import { getDbClient, type DbClient } from "./client.server.js"; export const GDPR_EXPORT_URL_TTL_HOURS = 72; export const GDPR_USER_SELF_EXPORT_LIMIT_PER_24H = 3; export const GDPR_TENANT_DELETION_GRACE_DAYS = 30; export type GdprExportScope = "user_self" | "tenant_full"; export type GdprExportStatus = "queued" | "processing" | "ready" | "failed" | "expired"; export type TenantDeletionRequestStatus = "pending" | "cancelled" | "executing" | "completed" | "failed"; export type TenantDeletionReason = "voluntary" | "non_payment" | "suspended_violation" | "admin_initiated"; type GdprExportJobRecord = { id: string; tenantId: string; requestedByUserId: string; targetUserId: string | null; scope: GdprExportScope; status: GdprExportStatus; progressPercent: number; resultFileId: string | null; resultBucket: string | null; resultKey: string | null; resultSizeBytes: number | null; resultExpiresAt: Date | null; downloadCount: number; createdAt: Date; updatedAt: Date; }; type TenantDeletionRequestRecord = { id: string; tenantId: string; requestedByUserId: string; reason: TenantDeletionReason; reasonText: string | null; slugConfirmPhrase: string; status: TenantDeletionRequestStatus; gracePeriodEndsAt: Date; createdAt: Date; updatedAt: Date; }; type AvvAcceptanceRecord = { id: string; tenantId: string; acceptedByUserId: string; avvVersion: string; pdfFileId: string | null; signerName: string; signerRole: string | null; createdAt: Date; }; type SubprocessorRecord = { id: string; name: string; purposeText: string; country: string; isEuEea: boolean; dataCategories: string[]; dpaUrl: string | null; activeSince: Date | null; archivedAt: Date | null; }; type GdprExportJobCreateData = { tenantId: string; requestedByUserId: string; targetUserId: string | null; scope: GdprExportScope; status: Extract; progressPercent: number; }; type GdprExportJobUpdateData = Partial<{ status: GdprExportStatus; progressPercent: number; resultFileId: string | null; resultBucket: string | null; resultKey: string | null; resultSizeBytes: number | null; resultExpiresAt: Date | null; downloadCount: { increment: number } | number; lastDownloadedAt: Date | null; errorMessage: string | null; processingStartedAt: Date | null; processingFinishedAt: Date | null; }>; type TenantDeletionRequestCreateData = { tenantId: string; requestedByUserId: string; reason: TenantDeletionReason; reasonText: string | null; slugConfirmPhrase: string; status: Extract; gracePeriodEndsAt: Date; }; type TenantDeletionRequestUpdateData = Partial<{ status: TenantDeletionRequestStatus; cancelledAt: Date | null; cancelledByUserId: string | null; hardDeleteStartedAt: Date | null; hardDeleteEndedAt: Date | null; errorMessage: string | null; }>; type AvvAcceptanceCreateData = { tenantId: string; acceptedByUserId: string; acceptedIp: string | null; acceptedUserAgent: string | null; avvVersion: string; pdfFileId: string | null; signerName: string; signerRole: string | null; }; export type PrivacyGdprClient = { gdprExportJob: { count(args: { where: Record }): Promise; create(args: { data: GdprExportJobCreateData }): Promise; findMany(args: { where: Record; orderBy: Record; take?: number; skip?: number }): Promise; updateMany(args: { where: Record; data: GdprExportJobUpdateData }): Promise<{ count?: number }>; }; tenantDeletionRequest: { count(args: { where: Record }): Promise; create(args: { data: TenantDeletionRequestCreateData }): Promise; findMany(args: { where: Record; orderBy: Record | Array>; take?: number; }): Promise; updateMany(args: { where: Record; data: TenantDeletionRequestUpdateData }): Promise<{ count?: number }>; }; avvAcceptance: { create(args: { data: AvvAcceptanceCreateData }): Promise; findMany(args: { where: Record; orderBy: Record }): Promise; }; subprocessor: { findMany(args: { where: Record; orderBy: Record }): Promise; }; }; export type CreateGdprExportJobInput = { tenantId: string; requestedByUserId: string; scope: GdprExportScope; targetUserId?: string | null; now?: Date; }; export type MarkGdprExportReadyInput = { id: string; tenantId: string; resultFileId?: string | null; resultBucket: string; resultKey: string; resultSizeBytes?: number | null; resultExpiresAt?: Date; now?: Date; }; export type MarkGdprExportProcessingInput = { id: string; tenantId: string; now?: Date; }; export type MarkGdprExportFailedInput = { id: string; tenantId: string; errorMessage?: string | null; now?: Date; }; export type CreateTenantDeletionRequestInput = { tenantId: string; requestedByUserId: string; tenantSlug: string; slugConfirmPhrase: string; reason: TenantDeletionReason; reasonText?: string | null; now?: Date; }; export type AcceptAvvInput = { tenantId: string; acceptedByUserId: string; avvVersion: string; signerName: string; signerRole?: string | null; pdfFileId?: string | null; acceptedIp?: string | null; acceptedUserAgent?: string | null; }; function requireText(value: string, fieldName: string): string { const trimmed = value.trim(); if (!trimmed) { throw new Error(`${fieldName} is required.`); } return trimmed; } function hoursBefore(date: Date, hours: number): Date { return new Date(date.getTime() - hours * 60 * 60 * 1_000); } function hoursAfter(date: Date, hours: number): Date { return new Date(date.getTime() + hours * 60 * 60 * 1_000); } function daysAfter(date: Date, days: number): Date { return new Date(date.getTime() + days * 24 * 60 * 60 * 1_000); } function clampProgress(value: number): number { if (!Number.isFinite(value)) { return 0; } return Math.max(0, Math.min(100, Math.floor(value))); } function redactDiagnosticText(value: string): string { return value .replace(/(authorization)\s*=\s*Bearer\s+\S+/gi, "$1=Bearer [REDACTED]") .replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]") .replace(/(password|secret|token|api[-_]?key)=\S+/gi, "$1=[REDACTED]"); } function clientOrDefault(client?: PrivacyGdprClient): PrivacyGdprClient { return client ?? (getDbClient() as DbClient & PrivacyGdprClient); } async function updateOneTenantScoped( operation: Promise<{ count?: number }>, errorMessage: string, ): Promise { const result = await operation; if (typeof result.count === "number" && result.count !== 1) { throw new Error(errorMessage); } } export async function createGdprExportJob(input: CreateGdprExportJobInput, client?: PrivacyGdprClient): Promise { const db = clientOrDefault(client); const tenantId = requireText(input.tenantId, "tenantId"); const requestedByUserId = requireText(input.requestedByUserId, "requestedByUserId"); const targetUserId = input.scope === "user_self" ? requireText(input.targetUserId ?? requestedByUserId, "targetUserId") : (input.targetUserId?.trim() || null); const now = input.now ?? new Date(); if (input.scope === "user_self") { const recentSelfExports = await db.gdprExportJob.count({ where: { tenantId, scope: "user_self", targetUserId, createdAt: { gte: hoursBefore(now, 24) }, }, }); if (recentSelfExports >= GDPR_USER_SELF_EXPORT_LIMIT_PER_24H) { throw new Error("GDPR user self export limit reached."); } } else { const activeTenantExports = await db.gdprExportJob.count({ where: { tenantId, scope: "tenant_full", status: { in: ["queued", "processing"] }, }, }); if (activeTenantExports > 0) { throw new Error("A tenant GDPR export is already active."); } } return db.gdprExportJob.create({ data: { tenantId, requestedByUserId, targetUserId, scope: input.scope, status: "queued", progressPercent: 0, }, }); } export async function listGdprExportJobs( input: { tenantId: string; requestedByUserId?: string | null; take?: number; skip?: number }, client?: PrivacyGdprClient, ): Promise { const tenantId = requireText(input.tenantId, "tenantId"); return clientOrDefault(client).gdprExportJob.findMany({ where: { tenantId, ...(input.requestedByUserId ? { requestedByUserId: input.requestedByUserId } : {}), }, orderBy: { createdAt: "desc" }, take: input.take, skip: input.skip, }); } export async function markGdprExportProcessing(input: MarkGdprExportProcessingInput, client?: PrivacyGdprClient): Promise { const now = input.now ?? new Date(); await updateOneTenantScoped( clientOrDefault(client).gdprExportJob.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") }, data: { status: "processing", progressPercent: 5, processingStartedAt: now, processingFinishedAt: null, errorMessage: null, }, }), "GDPR export job tenant scope did not match exactly one job.", ); } export async function markGdprExportProgress(input: { id: string; tenantId: string; progressPercent: number }, client?: PrivacyGdprClient): Promise { await updateOneTenantScoped( clientOrDefault(client).gdprExportJob.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") }, data: { progressPercent: clampProgress(input.progressPercent) }, }), "GDPR export job tenant scope did not match exactly one job.", ); } export async function markGdprExportReady(input: MarkGdprExportReadyInput, client?: PrivacyGdprClient): Promise { const now = input.now ?? new Date(); await updateOneTenantScoped( clientOrDefault(client).gdprExportJob.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") }, data: { status: "ready", progressPercent: 100, resultFileId: input.resultFileId ?? null, resultBucket: requireText(input.resultBucket, "resultBucket"), resultKey: requireText(input.resultKey, "resultKey"), resultSizeBytes: input.resultSizeBytes ?? null, resultExpiresAt: input.resultExpiresAt ?? hoursAfter(now, GDPR_EXPORT_URL_TTL_HOURS), processingFinishedAt: now, errorMessage: null, }, }), "GDPR export job tenant scope did not match exactly one job.", ); } export async function markGdprExportFailed(input: MarkGdprExportFailedInput, client?: PrivacyGdprClient): Promise { await updateOneTenantScoped( clientOrDefault(client).gdprExportJob.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") }, data: { status: "failed", errorMessage: redactDiagnosticText(input.errorMessage ?? "GDPR export failed.").slice(0, 2_000), processingFinishedAt: input.now ?? new Date(), }, }), "GDPR export job tenant scope did not match exactly one job.", ); } export async function markGdprExportDownloaded(input: { id: string; tenantId: string; now?: Date }, client?: PrivacyGdprClient): Promise { await updateOneTenantScoped( clientOrDefault(client).gdprExportJob.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId"), status: "ready", resultExpiresAt: { gt: input.now ?? new Date() }, }, data: { downloadCount: { increment: 1 }, lastDownloadedAt: input.now ?? new Date(), }, }), "GDPR export job is not ready for download or has expired.", ); } export async function createTenantDeletionRequest(input: CreateTenantDeletionRequestInput, client?: PrivacyGdprClient): Promise { const tenantId = requireText(input.tenantId, "tenantId"); const requestedByUserId = requireText(input.requestedByUserId, "requestedByUserId"); const tenantSlug = requireText(input.tenantSlug, "tenantSlug"); const slugConfirmPhrase = requireText(input.slugConfirmPhrase, "slugConfirmPhrase"); if (slugConfirmPhrase !== tenantSlug) { throw new Error("Tenant deletion confirmation phrase does not match the tenant slug."); } const db = clientOrDefault(client); const activeRequests = await db.tenantDeletionRequest.count({ where: { tenantId, status: { in: ["pending", "executing"] } }, }); if (activeRequests > 0) { throw new Error("A tenant deletion request is already active."); } const now = input.now ?? new Date(); return db.tenantDeletionRequest.create({ data: { tenantId, requestedByUserId, reason: input.reason, reasonText: input.reasonText?.trim() || null, slugConfirmPhrase, status: "pending", gracePeriodEndsAt: daysAfter(now, GDPR_TENANT_DELETION_GRACE_DAYS), }, }); } export async function cancelTenantDeletionRequest(input: { id: string; tenantId: string; cancelledByUserId: string; now?: Date }, client?: PrivacyGdprClient): Promise { await updateOneTenantScoped( clientOrDefault(client).tenantDeletionRequest.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId"), status: "pending", }, data: { status: "cancelled", cancelledAt: input.now ?? new Date(), cancelledByUserId: requireText(input.cancelledByUserId, "cancelledByUserId"), }, }), "Tenant deletion request is not pending or does not belong to the tenant.", ); } export async function listDueTenantDeletionRequests(input: { now?: Date; take?: number }, client?: PrivacyGdprClient): Promise { return clientOrDefault(client).tenantDeletionRequest.findMany({ where: { status: "pending", gracePeriodEndsAt: { lte: input.now ?? new Date() }, }, orderBy: [{ gracePeriodEndsAt: "asc" }, { id: "asc" }], take: Math.max(1, Math.min(input.take ?? 50, 200)), }); } export async function markTenantDeletionExecuting(input: { id: string; tenantId: string; now?: Date }, client?: PrivacyGdprClient): Promise { await updateOneTenantScoped( clientOrDefault(client).tenantDeletionRequest.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId"), status: "pending" }, data: { status: "executing", hardDeleteStartedAt: input.now ?? new Date(), errorMessage: null }, }), "Tenant deletion request tenant scope did not match exactly one pending request.", ); } export async function markTenantDeletionCompleted(input: { id: string; tenantId: string; now?: Date }, client?: PrivacyGdprClient): Promise { await updateOneTenantScoped( clientOrDefault(client).tenantDeletionRequest.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId"), status: "executing" }, data: { status: "completed", hardDeleteEndedAt: input.now ?? new Date(), errorMessage: null }, }), "Tenant deletion request tenant scope did not match exactly one executing request.", ); } export async function markTenantDeletionFailed(input: { id: string; tenantId: string; errorMessage?: string | null }, client?: PrivacyGdprClient): Promise { await updateOneTenantScoped( clientOrDefault(client).tenantDeletionRequest.updateMany({ where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") }, data: { status: "failed", errorMessage: redactDiagnosticText(input.errorMessage ?? "Tenant deletion failed.").slice(0, 2_000) }, }), "Tenant deletion request tenant scope did not match exactly one request.", ); } export async function acceptAvv(input: AcceptAvvInput, client?: PrivacyGdprClient): Promise { return clientOrDefault(client).avvAcceptance.create({ data: { tenantId: requireText(input.tenantId, "tenantId"), acceptedByUserId: requireText(input.acceptedByUserId, "acceptedByUserId"), acceptedIp: input.acceptedIp?.trim() || null, acceptedUserAgent: input.acceptedUserAgent?.trim() || null, avvVersion: requireText(input.avvVersion, "avvVersion"), pdfFileId: input.pdfFileId?.trim() || null, signerName: requireText(input.signerName, "signerName"), signerRole: input.signerRole?.trim() || null, }, }); } export async function listAvvAcceptances(input: { tenantId: string }, client?: PrivacyGdprClient): Promise { return clientOrDefault(client).avvAcceptance.findMany({ where: { tenantId: requireText(input.tenantId, "tenantId") }, orderBy: { createdAt: "desc" }, }); } export async function listActiveSubprocessors(client?: PrivacyGdprClient): Promise { return clientOrDefault(client).subprocessor.findMany({ where: { archivedAt: null }, orderBy: { name: "asc" }, }); }