feat: system admin blocklist backend (#25077)
* feat: admin blocklist backend * chore: * refactor: use DI * fix: tests * refactor; improve error * refactor; improve error * perf: use bulk * chore: some more * refactor: feedback * test: update test * refactor: improvements * refactor: improvements * fix: remove * refactor: move to service * refactor: move to service * chore: add logs * refactor: remove default
This commit is contained in:
1 parent
e1324bd9c3
commit
f007fe8407
44 files changed
+2062
-1179
No files matched your search
@@ -5,6 +5,14 @@ export const WATCHLIST_DI_TOKENS = {
|
||||
ORGANIZATION_BLOCKING_SERVICE: Symbol("OrganizationBlockingService"),
|
||||
AUDIT_SERVICE: Symbol("WatchlistAuditService"),
|
||||
|
||||
// Operations services
|
||||
ADMIN_WATCHLIST_OPERATIONS_SERVICE: Symbol("AdminWatchlistOperationsService"),
|
||||
ORGANIZATION_WATCHLIST_OPERATIONS_SERVICE: Symbol("OrganizationWatchlistOperationsService"),
|
||||
|
||||
// Query services
|
||||
ADMIN_WATCHLIST_QUERY_SERVICE: Symbol("AdminWatchlistQueryService"),
|
||||
ORGANIZATION_WATCHLIST_QUERY_SERVICE: Symbol("OrganizationWatchlistQueryService"),
|
||||
|
||||
// Repositories
|
||||
GLOBAL_WATCHLIST_REPOSITORY: Symbol("GlobalWatchlistRepository"),
|
||||
ORGANIZATION_WATCHLIST_REPOSITORY: Symbol("OrganizationWatchlistRepository"),
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
import { createContainer } from "@evyweb/ioctopus";
|
||||
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { moduleLoader as loggerModuleLoader } from "@calcom/features/di/shared/services/logger.service";
|
||||
import { taskerServiceModule } from "@calcom/features/di/shared/services/tasker.service";
|
||||
import { SHARED_TOKENS } from "@calcom/features/di/shared/shared.tokens";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import {
|
||||
createWatchlistFeature,
|
||||
type WatchlistFeature,
|
||||
} from "@calcom/features/watchlist/lib/facade/WatchlistFeature";
|
||||
import type { IGlobalWatchlistRepository } from "@calcom/features/watchlist/lib/interface/IWatchlistRepositories";
|
||||
import type { IOrganizationWatchlistRepository } from "@calcom/features/watchlist/lib/interface/IWatchlistRepositories";
|
||||
import { AdminWatchlistOperationsService } from "@calcom/features/watchlist/lib/service/AdminWatchlistOperationsService";
|
||||
import { AdminWatchlistQueryService } from "@calcom/features/watchlist/lib/service/AdminWatchlistQueryService";
|
||||
import type { GlobalBlockingService } from "@calcom/features/watchlist/lib/service/GlobalBlockingService";
|
||||
import type { OrganizationBlockingService } from "@calcom/features/watchlist/lib/service/OrganizationBlockingService";
|
||||
import { OrganizationWatchlistOperationsService } from "@calcom/features/watchlist/lib/service/OrganizationWatchlistOperationsService";
|
||||
import { OrganizationWatchlistQueryService } from "@calcom/features/watchlist/lib/service/OrganizationWatchlistQueryService";
|
||||
import type { WatchlistAuditService } from "@calcom/features/watchlist/lib/service/WatchlistAuditService";
|
||||
import type { WatchlistService } from "@calcom/features/watchlist/lib/service/WatchlistService";
|
||||
import { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
|
||||
import { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
|
||||
|
||||
import { WATCHLIST_DI_TOKENS } from "../Watchlist.tokens";
|
||||
@@ -64,3 +73,53 @@ export function getOrganizationWatchlistRepository() {
|
||||
export async function getWatchlistFeature(): Promise<WatchlistFeature> {
|
||||
return createWatchlistFeature(watchlistContainer);
|
||||
}
|
||||
|
||||
export function getAdminWatchlistOperationsService(): AdminWatchlistOperationsService {
|
||||
const watchlistRepo = new WatchlistRepository(prisma);
|
||||
const bookingReportRepo = new PrismaBookingReportRepository(prisma);
|
||||
|
||||
return new AdminWatchlistOperationsService({
|
||||
watchlistRepo,
|
||||
bookingReportRepo,
|
||||
});
|
||||
}
|
||||
|
||||
export function getOrganizationWatchlistOperationsService(
|
||||
organizationId: number
|
||||
): OrganizationWatchlistOperationsService {
|
||||
const watchlistRepo = new WatchlistRepository(prisma);
|
||||
const bookingReportRepo = new PrismaBookingReportRepository(prisma);
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
|
||||
return new OrganizationWatchlistOperationsService({
|
||||
watchlistRepo,
|
||||
bookingReportRepo,
|
||||
permissionCheckService,
|
||||
organizationId,
|
||||
});
|
||||
}
|
||||
|
||||
export function getAdminWatchlistQueryService(): AdminWatchlistQueryService {
|
||||
const watchlistRepo = new WatchlistRepository(prisma);
|
||||
const bookingReportRepo = new PrismaBookingReportRepository(prisma);
|
||||
const userRepo = new UserRepository(prisma);
|
||||
|
||||
return new AdminWatchlistQueryService({
|
||||
watchlistRepo,
|
||||
bookingReportRepo,
|
||||
userRepo,
|
||||
prisma,
|
||||
});
|
||||
}
|
||||
|
||||
export function getOrganizationWatchlistQueryService(): OrganizationWatchlistQueryService {
|
||||
const watchlistRepo = new WatchlistRepository(prisma);
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
|
||||
return new OrganizationWatchlistQueryService({
|
||||
watchlistRepo,
|
||||
userRepo,
|
||||
permissionCheckService,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
export enum WatchlistErrorCode {
|
||||
NOT_FOUND = "NOT_FOUND",
|
||||
UNAUTHORIZED = "UNAUTHORIZED",
|
||||
ALREADY_IN_WATCHLIST = "ALREADY_IN_WATCHLIST",
|
||||
INVALID_EMAIL = "INVALID_EMAIL",
|
||||
INVALID_DOMAIN = "INVALID_DOMAIN",
|
||||
INVALID_IP = "INVALID_IP",
|
||||
VALIDATION_ERROR = "VALIDATION_ERROR",
|
||||
PERMISSION_DENIED = "PERMISSION_DENIED",
|
||||
DUPLICATE_ENTRY = "DUPLICATE_ENTRY",
|
||||
BULK_DELETE_PARTIAL_FAILURE = "BULK_DELETE_PARTIAL_FAILURE",
|
||||
}
|
||||
|
||||
export class WatchlistError extends Error {
|
||||
constructor(
|
||||
public readonly code: WatchlistErrorCode,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
this.name = "WatchlistError";
|
||||
}
|
||||
}
|
||||
|
||||
export const WatchlistErrors = {
|
||||
notFound: (message: string) => new WatchlistError(WatchlistErrorCode.NOT_FOUND, message),
|
||||
|
||||
unauthorized: (message: string) => new WatchlistError(WatchlistErrorCode.UNAUTHORIZED, message),
|
||||
|
||||
alreadyInWatchlist: (message: string) =>
|
||||
new WatchlistError(WatchlistErrorCode.ALREADY_IN_WATCHLIST, message),
|
||||
|
||||
invalidEmail: (message: string) => new WatchlistError(WatchlistErrorCode.INVALID_EMAIL, message),
|
||||
|
||||
invalidDomain: (message: string) => new WatchlistError(WatchlistErrorCode.INVALID_DOMAIN, message),
|
||||
|
||||
invalidIp: (message: string) => new WatchlistError(WatchlistErrorCode.INVALID_IP, message),
|
||||
|
||||
validationError: (message: string) =>
|
||||
new WatchlistError(WatchlistErrorCode.VALIDATION_ERROR, message),
|
||||
|
||||
permissionDenied: (message: string) =>
|
||||
new WatchlistError(WatchlistErrorCode.PERMISSION_DENIED, message),
|
||||
|
||||
duplicateEntry: (message: string) =>
|
||||
new WatchlistError(WatchlistErrorCode.DUPLICATE_ENTRY, message),
|
||||
|
||||
bulkDeletePartialFailure: (message: string) =>
|
||||
new WatchlistError(WatchlistErrorCode.BULK_DELETE_PARTIAL_FAILURE, message),
|
||||
};
|
||||
@@ -0,0 +1,214 @@
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
|
||||
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
|
||||
import { BookingReportStatus } from "@calcom/prisma/enums";
|
||||
|
||||
import { WatchlistErrors } from "../errors/WatchlistErrors";
|
||||
import type {
|
||||
DeleteWatchlistEntryInput,
|
||||
DeleteWatchlistEntryResult,
|
||||
WatchlistOperationsScope,
|
||||
} from "./WatchlistOperationsService";
|
||||
import { WatchlistOperationsService } from "./WatchlistOperationsService";
|
||||
|
||||
export interface BulkDeleteWatchlistEntriesInput {
|
||||
entryIds: string[];
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface BulkDeleteWatchlistEntriesResult {
|
||||
success: number;
|
||||
failed: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface DismissReportInput {
|
||||
reportId: string;
|
||||
}
|
||||
|
||||
export interface DismissReportResult {
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export interface BulkDismissReportsInput {
|
||||
reportIds: string[];
|
||||
}
|
||||
|
||||
export interface BulkDismissReportsResult {
|
||||
success: number;
|
||||
failed: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
type Deps = {
|
||||
watchlistRepo: WatchlistRepository;
|
||||
bookingReportRepo: PrismaBookingReportRepository;
|
||||
};
|
||||
|
||||
export class AdminWatchlistOperationsService extends WatchlistOperationsService {
|
||||
private adminLog = logger.getSubLogger({ prefix: ["AdminWatchlistOperationsService"] });
|
||||
|
||||
constructor(deps: Deps) {
|
||||
super(deps);
|
||||
}
|
||||
|
||||
protected getScope(): WatchlistOperationsScope {
|
||||
return {
|
||||
organizationId: null,
|
||||
isGlobal: true,
|
||||
};
|
||||
}
|
||||
|
||||
protected async findReports(
|
||||
reportIds: string[]
|
||||
): Promise<Array<{ id: string; bookerEmail: string; watchlistId: string | null }>> {
|
||||
const reports = await this.deps.bookingReportRepo.findReportsByIds({
|
||||
reportIds,
|
||||
});
|
||||
|
||||
return reports;
|
||||
}
|
||||
|
||||
async bulkDeleteWatchlistEntries(
|
||||
input: BulkDeleteWatchlistEntriesInput
|
||||
): Promise<BulkDeleteWatchlistEntriesResult> {
|
||||
const entries = await this.deps.watchlistRepo.findEntriesByIds(input.entryIds);
|
||||
|
||||
const entryMap = new Map(entries.map((e) => [e.id, e]));
|
||||
const validIds: string[] = [];
|
||||
const failed: Array<{ id: string; reason: string }> = [];
|
||||
|
||||
for (const id of input.entryIds) {
|
||||
const entry = entryMap.get(id);
|
||||
|
||||
if (!entry) {
|
||||
failed.push({ id, reason: "Entry not found" });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!entry.isGlobal || entry.organizationId !== null) {
|
||||
failed.push({ id, reason: "Can only delete system blocklist entries" });
|
||||
continue;
|
||||
}
|
||||
|
||||
validIds.push(id);
|
||||
}
|
||||
|
||||
let successCount = 0;
|
||||
if (validIds.length > 0) {
|
||||
const result = await this.deps.watchlistRepo.bulkDeleteEntries({
|
||||
ids: validIds,
|
||||
userId: input.userId,
|
||||
});
|
||||
successCount = result.deleted;
|
||||
}
|
||||
|
||||
if (successCount === 0 && failed.length > 0) {
|
||||
this.adminLog.error("Bulk delete watchlist entries failures", { failed });
|
||||
throw WatchlistErrors.bulkDeletePartialFailure(`Failed to delete all entries: ${failed[0].reason}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: successCount,
|
||||
failed: failed.length,
|
||||
// TODO: use translate keys in follow up frontend PR
|
||||
message:
|
||||
failed.length === 0
|
||||
? "All entries deleted successfully"
|
||||
: `Deleted ${successCount} entries, ${failed.length} failed`,
|
||||
};
|
||||
}
|
||||
|
||||
async deleteWatchlistEntry(input: DeleteWatchlistEntryInput): Promise<DeleteWatchlistEntryResult> {
|
||||
const { entry } = await this.deps.watchlistRepo.findEntryWithAuditAndReports(input.entryId);
|
||||
|
||||
if (!entry) {
|
||||
throw WatchlistErrors.notFound("Blocklist entry not found");
|
||||
}
|
||||
|
||||
if (!entry.isGlobal || entry.organizationId !== null) {
|
||||
throw WatchlistErrors.permissionDenied("You can only delete system blocklist entries");
|
||||
}
|
||||
|
||||
await this.deps.watchlistRepo.deleteEntry(input.entryId, input.userId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Entry deleted successfully",
|
||||
};
|
||||
}
|
||||
|
||||
async dismissReport(input: DismissReportInput): Promise<DismissReportResult> {
|
||||
const reports = await this.deps.bookingReportRepo.findReportsByIds({
|
||||
reportIds: [input.reportId],
|
||||
});
|
||||
|
||||
if (reports.length === 0) {
|
||||
throw WatchlistErrors.notFound("Report not found");
|
||||
}
|
||||
|
||||
const report = reports[0];
|
||||
|
||||
if (report.watchlistId) {
|
||||
throw WatchlistErrors.validationError(
|
||||
"Cannot dismiss a report that has already been added to the blocklist"
|
||||
);
|
||||
}
|
||||
|
||||
await this.deps.bookingReportRepo.updateReportStatus({
|
||||
reportId: input.reportId,
|
||||
status: BookingReportStatus.DISMISSED,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async bulkDismissReports(input: BulkDismissReportsInput): Promise<BulkDismissReportsResult> {
|
||||
const reports = await this.deps.bookingReportRepo.findReportsByIds({
|
||||
reportIds: input.reportIds,
|
||||
});
|
||||
|
||||
const reportMap = new Map(reports.map((r) => [r.id, r]));
|
||||
const validReportIds: string[] = [];
|
||||
const failed: Array<{ id: string; reason: string }> = [];
|
||||
|
||||
for (const reportId of input.reportIds) {
|
||||
const report = reportMap.get(reportId);
|
||||
|
||||
if (!report) {
|
||||
failed.push({ id: reportId, reason: "Report not found" });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (report.watchlistId) {
|
||||
failed.push({ id: reportId, reason: "Already added to blocklist" });
|
||||
continue;
|
||||
}
|
||||
|
||||
validReportIds.push(reportId);
|
||||
}
|
||||
|
||||
let successCount = 0;
|
||||
if (validReportIds.length > 0) {
|
||||
const result = await this.deps.bookingReportRepo.bulkUpdateReportStatus({
|
||||
reportIds: validReportIds,
|
||||
status: BookingReportStatus.DISMISSED,
|
||||
});
|
||||
successCount = result.updated;
|
||||
}
|
||||
|
||||
if (successCount === 0 && failed.length > 0) {
|
||||
this.adminLog.error("Bulk dismiss reports failures", { failed });
|
||||
throw WatchlistErrors.bulkDeletePartialFailure(`Failed to dismiss all reports: ${failed[0].reason}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: successCount,
|
||||
failed: failed.length,
|
||||
message:
|
||||
failed.length === 0
|
||||
? "All reports dismissed successfully"
|
||||
: `Dismissed ${successCount} reports, ${failed.length} failed`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import type { ListBookingReportsFilters } from "@calcom/lib/server/repository/bookingReport.interface";
|
||||
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
|
||||
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { WatchlistType, WatchlistSource } from "@calcom/prisma/enums";
|
||||
|
||||
import { WatchlistErrors } from "../errors/WatchlistErrors";
|
||||
|
||||
export interface ListWatchlistEntriesInput {
|
||||
limit: number;
|
||||
offset: number;
|
||||
searchTerm?: string;
|
||||
filters?: {
|
||||
type?: WatchlistType;
|
||||
source?: WatchlistSource;
|
||||
};
|
||||
}
|
||||
|
||||
export interface GetWatchlistEntryDetailsInput {
|
||||
entryId: string;
|
||||
}
|
||||
|
||||
export interface ListBookingReportsInput {
|
||||
limit: number;
|
||||
offset: number;
|
||||
searchTerm?: string;
|
||||
filters?: ListBookingReportsFilters;
|
||||
}
|
||||
|
||||
type Deps = {
|
||||
watchlistRepo: WatchlistRepository;
|
||||
bookingReportRepo: PrismaBookingReportRepository;
|
||||
userRepo: UserRepository;
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
|
||||
export class AdminWatchlistQueryService {
|
||||
constructor(private readonly deps: Deps) {}
|
||||
|
||||
async listWatchlistEntries(input: ListWatchlistEntriesInput) {
|
||||
const { rows, meta } = await this.deps.watchlistRepo.findAllEntriesWithLatestAudit({
|
||||
organizationId: null,
|
||||
isGlobal: true,
|
||||
limit: input.limit,
|
||||
offset: input.offset,
|
||||
searchTerm: input.searchTerm,
|
||||
filters: input.filters,
|
||||
});
|
||||
|
||||
const userIds = rows
|
||||
.map((entry) => entry.latestAudit?.changedByUserId)
|
||||
.filter((id): id is number => id !== null && id !== undefined);
|
||||
|
||||
const uniqueUserIds = Array.from(new Set(userIds));
|
||||
|
||||
const users = uniqueUserIds.length > 0 ? await this.deps.userRepo.findUsersByIds(uniqueUserIds) : [];
|
||||
|
||||
const userMap = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
const rowsWithCreators = rows.map((entry) => {
|
||||
if (entry.latestAudit?.changedByUserId) {
|
||||
const changedByUser = userMap.get(entry.latestAudit.changedByUserId);
|
||||
return {
|
||||
...entry,
|
||||
latestAudit: {
|
||||
...entry.latestAudit,
|
||||
changedByUser,
|
||||
},
|
||||
};
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
|
||||
return {
|
||||
rows: rowsWithCreators,
|
||||
meta,
|
||||
};
|
||||
}
|
||||
|
||||
async getWatchlistEntryDetails(input: GetWatchlistEntryDetailsInput) {
|
||||
const result = await this.deps.watchlistRepo.findEntryWithAuditAndReports(input.entryId);
|
||||
|
||||
if (!result.entry) {
|
||||
throw WatchlistErrors.notFound("Blocklist entry not found");
|
||||
}
|
||||
|
||||
if (!result.entry.isGlobal || result.entry.organizationId !== null) {
|
||||
throw WatchlistErrors.permissionDenied("You can only view system blocklist entries");
|
||||
}
|
||||
|
||||
const userIds = result.auditHistory
|
||||
.map((audit) => audit.changedByUserId)
|
||||
.filter((id): id is number => id !== null && id !== undefined);
|
||||
|
||||
const uniqueUserIds = Array.from(new Set(userIds));
|
||||
|
||||
const users = uniqueUserIds.length > 0 ? await this.deps.userRepo.findUsersByIds(uniqueUserIds) : [];
|
||||
|
||||
const userMap = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
const auditHistoryWithUsers = result.auditHistory.map((audit) => ({
|
||||
...audit,
|
||||
changedByUser: audit.changedByUserId ? userMap.get(audit.changedByUserId) : undefined,
|
||||
}));
|
||||
|
||||
return {
|
||||
entry: result.entry,
|
||||
auditHistory: auditHistoryWithUsers,
|
||||
};
|
||||
}
|
||||
|
||||
async listBookingReports(input: ListBookingReportsInput) {
|
||||
const result = await this.deps.bookingReportRepo.findAllReportedBookings({
|
||||
skip: input.offset,
|
||||
take: input.limit,
|
||||
searchTerm: input.searchTerm,
|
||||
filters: input.filters,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getPendingReportsCount(): Promise<number> {
|
||||
return this.deps.prisma.bookingReport.count({
|
||||
where: {
|
||||
status: "PENDING",
|
||||
watchlistId: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { PermissionString } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
|
||||
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { WatchlistErrors } from "../errors/WatchlistErrors";
|
||||
import type {
|
||||
AddReportsToWatchlistInput,
|
||||
AddReportsToWatchlistResult,
|
||||
CreateWatchlistEntryInput,
|
||||
CreateWatchlistEntryResult,
|
||||
DeleteWatchlistEntryInput,
|
||||
DeleteWatchlistEntryResult,
|
||||
WatchlistOperationsScope,
|
||||
} from "./WatchlistOperationsService";
|
||||
import { WatchlistOperationsService } from "./WatchlistOperationsService";
|
||||
|
||||
type Deps = {
|
||||
watchlistRepo: WatchlistRepository;
|
||||
bookingReportRepo: PrismaBookingReportRepository;
|
||||
permissionCheckService: PermissionCheckService;
|
||||
organizationId: number;
|
||||
};
|
||||
|
||||
export class OrganizationWatchlistOperationsService extends WatchlistOperationsService {
|
||||
private readonly permissionCheckService: PermissionCheckService;
|
||||
private readonly organizationId: number;
|
||||
|
||||
constructor(deps: Deps) {
|
||||
super(deps);
|
||||
this.permissionCheckService = deps.permissionCheckService;
|
||||
this.organizationId = deps.organizationId;
|
||||
}
|
||||
|
||||
protected getScope(): WatchlistOperationsScope {
|
||||
return {
|
||||
organizationId: this.organizationId,
|
||||
isGlobal: false,
|
||||
};
|
||||
}
|
||||
|
||||
protected async findReports(
|
||||
reportIds: string[]
|
||||
): Promise<Array<{ id: string; bookerEmail: string; watchlistId: string | null }>> {
|
||||
const reports = await this.deps.bookingReportRepo.findReportsByIds({
|
||||
reportIds,
|
||||
organizationId: this.organizationId,
|
||||
});
|
||||
|
||||
return reports;
|
||||
}
|
||||
|
||||
private async checkPermission(userId: number, permission: PermissionString): Promise<void> {
|
||||
const hasPermission = await this.permissionCheckService.checkPermission({
|
||||
userId,
|
||||
teamId: this.organizationId,
|
||||
permission,
|
||||
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
});
|
||||
|
||||
if (!hasPermission) {
|
||||
throw WatchlistErrors.permissionDenied(`You are not authorized to ${permission.split(".")[1]} watchlist entries`);
|
||||
}
|
||||
}
|
||||
|
||||
async addReportsToWatchlist(input: AddReportsToWatchlistInput): Promise<AddReportsToWatchlistResult> {
|
||||
await this.checkPermission(input.userId, "watchlist.create");
|
||||
return super.addReportsToWatchlist(input);
|
||||
}
|
||||
|
||||
async createWatchlistEntry(input: CreateWatchlistEntryInput): Promise<CreateWatchlistEntryResult> {
|
||||
await this.checkPermission(input.userId, "watchlist.create");
|
||||
return super.createWatchlistEntry(input);
|
||||
}
|
||||
|
||||
async deleteWatchlistEntry(input: DeleteWatchlistEntryInput): Promise<DeleteWatchlistEntryResult> {
|
||||
await this.checkPermission(input.userId, "watchlist.delete");
|
||||
return super.deleteWatchlistEntry(input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
|
||||
import { MembershipRole, WatchlistType, WatchlistSource } from "@calcom/prisma/enums";
|
||||
|
||||
import { WatchlistErrors } from "../errors/WatchlistErrors";
|
||||
|
||||
export interface ListWatchlistEntriesInput {
|
||||
organizationId: number;
|
||||
userId: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
searchTerm?: string;
|
||||
filters?: {
|
||||
type?: WatchlistType;
|
||||
source?: WatchlistSource;
|
||||
};
|
||||
}
|
||||
|
||||
export interface GetWatchlistEntryDetailsInput {
|
||||
organizationId: number;
|
||||
userId: number;
|
||||
entryId: string;
|
||||
}
|
||||
|
||||
type Deps = {
|
||||
watchlistRepo: WatchlistRepository;
|
||||
userRepo: UserRepository;
|
||||
permissionCheckService: PermissionCheckService;
|
||||
};
|
||||
|
||||
export class OrganizationWatchlistQueryService {
|
||||
constructor(private readonly deps: Deps) {}
|
||||
|
||||
private async checkReadPermission(userId: number, organizationId: number): Promise<void> {
|
||||
const hasPermission = await this.deps.permissionCheckService.checkPermission({
|
||||
userId,
|
||||
teamId: organizationId,
|
||||
permission: "watchlist.read",
|
||||
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
});
|
||||
|
||||
if (!hasPermission) {
|
||||
throw WatchlistErrors.permissionDenied("You are not authorized to view watchlist entries");
|
||||
}
|
||||
}
|
||||
|
||||
async listWatchlistEntries(input: ListWatchlistEntriesInput) {
|
||||
await this.checkReadPermission(input.userId, input.organizationId);
|
||||
|
||||
const result = await this.deps.watchlistRepo.findAllEntriesWithLatestAudit({
|
||||
organizationId: input.organizationId,
|
||||
limit: input.limit,
|
||||
offset: input.offset,
|
||||
searchTerm: input.searchTerm,
|
||||
filters: input.filters,
|
||||
});
|
||||
|
||||
const userIds = result.rows
|
||||
.map((entry) => entry.latestAudit?.changedByUserId)
|
||||
.filter((id): id is number => id !== null && id !== undefined);
|
||||
|
||||
const uniqueUserIds = Array.from(new Set(userIds));
|
||||
|
||||
const users = uniqueUserIds.length > 0 ? await this.deps.userRepo.findUsersByIds(uniqueUserIds) : [];
|
||||
|
||||
const userMap = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
const rowsWithCreators = result.rows.map((entry) => {
|
||||
if (entry.latestAudit?.changedByUserId) {
|
||||
const changedByUser = userMap.get(entry.latestAudit.changedByUserId);
|
||||
return {
|
||||
...entry,
|
||||
latestAudit: {
|
||||
...entry.latestAudit,
|
||||
changedByUser,
|
||||
},
|
||||
};
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
|
||||
return {
|
||||
rows: rowsWithCreators,
|
||||
meta: result.meta,
|
||||
};
|
||||
}
|
||||
|
||||
async getWatchlistEntryDetails(input: GetWatchlistEntryDetailsInput) {
|
||||
await this.checkReadPermission(input.userId, input.organizationId);
|
||||
|
||||
const result = await this.deps.watchlistRepo.findEntryWithAuditAndReports(input.entryId);
|
||||
|
||||
if (!result.entry) {
|
||||
throw WatchlistErrors.notFound("Blocklist entry not found");
|
||||
}
|
||||
|
||||
if (result.entry.organizationId !== input.organizationId) {
|
||||
throw WatchlistErrors.permissionDenied("You can only view blocklist entries from your organization");
|
||||
}
|
||||
|
||||
const userIds = result.auditHistory
|
||||
.map((audit) => audit.changedByUserId)
|
||||
.filter((id): id is number => id !== null && id !== undefined);
|
||||
|
||||
const uniqueUserIds = Array.from(new Set(userIds));
|
||||
|
||||
const users = uniqueUserIds.length > 0 ? await this.deps.userRepo.findUsersByIds(uniqueUserIds) : [];
|
||||
|
||||
const userMap = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
const auditHistoryWithUsers = result.auditHistory.map((audit) => ({
|
||||
...audit,
|
||||
changedByUser: audit.changedByUserId ? userMap.get(audit.changedByUserId) : undefined,
|
||||
}));
|
||||
|
||||
return {
|
||||
entry: result.entry,
|
||||
auditHistory: auditHistoryWithUsers,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { domainRegex, emailRegex } from "@calcom/lib/emailSchema";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
|
||||
import type { WatchlistEntry } from "@calcom/lib/server/repository/watchlist.interface";
|
||||
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
|
||||
import { WatchlistAction, WatchlistType } from "@calcom/prisma/enums";
|
||||
|
||||
import { WatchlistErrors } from "../errors/WatchlistErrors";
|
||||
import { extractDomainFromEmail, normalizeEmail } from "../utils/normalization";
|
||||
|
||||
export interface AddReportsToWatchlistInput {
|
||||
reportIds: string[];
|
||||
type: WatchlistType;
|
||||
description?: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface AddReportsToWatchlistResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
addedCount: number;
|
||||
skippedCount: number;
|
||||
results: Array<{ reportId: string; watchlistId: string }>;
|
||||
}
|
||||
|
||||
export interface CreateWatchlistEntryInput {
|
||||
type: WatchlistType;
|
||||
value: string;
|
||||
description?: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface CreateWatchlistEntryResult {
|
||||
success: boolean;
|
||||
entry: WatchlistEntry;
|
||||
}
|
||||
|
||||
export interface DeleteWatchlistEntryInput {
|
||||
entryId: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface DeleteWatchlistEntryResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WatchlistOperationsScope {
|
||||
organizationId: number | null;
|
||||
isGlobal: boolean;
|
||||
}
|
||||
|
||||
type Deps = {
|
||||
watchlistRepo: WatchlistRepository;
|
||||
bookingReportRepo: PrismaBookingReportRepository;
|
||||
};
|
||||
|
||||
export abstract class WatchlistOperationsService {
|
||||
private log = logger.getSubLogger({ prefix: ["WatchlistOperationsService"] });
|
||||
|
||||
constructor(protected readonly deps: Deps) {}
|
||||
|
||||
protected abstract getScope(): WatchlistOperationsScope;
|
||||
|
||||
protected abstract findReports(
|
||||
reportIds: string[]
|
||||
): Promise<Array<{ id: string; bookerEmail: string; watchlistId: string | null }>>;
|
||||
|
||||
validateEmailOrDomain(type: WatchlistType, value: string): void {
|
||||
if (type === WatchlistType.EMAIL && !emailRegex.test(value)) {
|
||||
throw WatchlistErrors.invalidEmail("Invalid email address format");
|
||||
}
|
||||
|
||||
if (type === WatchlistType.DOMAIN && !domainRegex.test(value)) {
|
||||
throw WatchlistErrors.invalidDomain("Invalid domain format (e.g., example.com)");
|
||||
}
|
||||
}
|
||||
|
||||
async addReportsToWatchlist(input: AddReportsToWatchlistInput): Promise<AddReportsToWatchlistResult> {
|
||||
const scope = this.getScope();
|
||||
|
||||
const validReports = await this.findReports(input.reportIds);
|
||||
|
||||
if (validReports.length !== input.reportIds.length) {
|
||||
const foundIds = new Set(validReports.map((r) => r.id));
|
||||
const missingIds = input.reportIds.filter((id) => !foundIds.has(id));
|
||||
throw WatchlistErrors.notFound(`Report(s) not found: ${missingIds.join(", ")}`);
|
||||
}
|
||||
|
||||
const reportsToAdd = validReports.filter((report) => !report.watchlistId);
|
||||
|
||||
if (reportsToAdd.length === 0) {
|
||||
throw WatchlistErrors.alreadyInWatchlist("All selected reports are already in the watchlist");
|
||||
}
|
||||
|
||||
const normalizedValues = new Map<string, string>();
|
||||
try {
|
||||
for (const report of reportsToAdd) {
|
||||
const value =
|
||||
input.type === WatchlistType.EMAIL
|
||||
? normalizeEmail(report.bookerEmail)
|
||||
: extractDomainFromEmail(report.bookerEmail);
|
||||
normalizedValues.set(report.id, value);
|
||||
}
|
||||
} catch (error) {
|
||||
this.log.error("Email normalization failed", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
reportIds: reportsToAdd.map((r) => r.id),
|
||||
});
|
||||
throw WatchlistErrors.invalidEmail(error instanceof Error ? error.message : "Invalid email format");
|
||||
}
|
||||
|
||||
const results = await Promise.all(
|
||||
reportsToAdd.map(async (report) => {
|
||||
const normalizedValue = normalizedValues.get(report.id);
|
||||
if (!normalizedValue) {
|
||||
throw new Error("Unable to process the selected report. Please try again.");
|
||||
}
|
||||
|
||||
const { watchlistEntry } = await this.deps.watchlistRepo.createEntryFromReport({
|
||||
type: input.type,
|
||||
value: normalizedValue,
|
||||
organizationId: scope.organizationId,
|
||||
isGlobal: scope.isGlobal,
|
||||
userId: input.userId,
|
||||
description: input.description,
|
||||
});
|
||||
|
||||
return {
|
||||
reportId: report.id,
|
||||
watchlistId: watchlistEntry.id,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
await this.deps.bookingReportRepo.bulkLinkWatchlistWithStatus({
|
||||
links: results.map((r) => ({ reportId: r.reportId, watchlistId: r.watchlistId })),
|
||||
status: "BLOCKED",
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Successfully added ${results.length} report(s) to watchlist`,
|
||||
addedCount: results.length,
|
||||
skippedCount: validReports.length - reportsToAdd.length,
|
||||
results,
|
||||
};
|
||||
}
|
||||
|
||||
async createWatchlistEntry(input: CreateWatchlistEntryInput): Promise<CreateWatchlistEntryResult> {
|
||||
const scope = this.getScope();
|
||||
|
||||
this.validateEmailOrDomain(input.type, input.value);
|
||||
|
||||
const entry = await this.deps.watchlistRepo.createEntryIfNotExists({
|
||||
type: input.type,
|
||||
value: input.value.toLowerCase(),
|
||||
organizationId: scope.organizationId,
|
||||
action: WatchlistAction.BLOCK,
|
||||
description: input.description,
|
||||
userId: input.userId,
|
||||
isGlobal: scope.isGlobal,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
entry,
|
||||
};
|
||||
}
|
||||
|
||||
async deleteWatchlistEntry(input: DeleteWatchlistEntryInput): Promise<DeleteWatchlistEntryResult> {
|
||||
await this.deps.watchlistRepo.deleteEntry(input.entryId, input.userId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Entry deleted successfully",
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user