import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto"; import { requestScopedT as i18nT } from "~/locale/request-scoped-t"; import { buildFileStorageKeys } from "@hivegrid/storage"; import { withTenantStorageWriteReservation } from "@hivegrid/db/storage-capacity.server"; import { createIdempotencyStore, type IdempotencyStore } from "@hivegrid/shared-store"; import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { resolveSignatureSignerRlsIdentity } from "@hivegrid/db/rls-resolvers.server"; import { logActivity } from "@hivegrid/activity"; import { buildProjectSignaturePanelVM, signatureDocumentStatusKey, signatureProviderKey, signatureSignerStatusKey, type ProjectSignatureDocumentRow, type ProjectSignatureKontaktSuggestion, type ProjectSignaturePanelVM, type ProjectSignaturePdfFileOption, type SignatureSignerRole, } from "@hivegrid/view-models"; import { ensureServerGlobalI18n } from "~/locale/i18next.global.server"; import { getSharedStore } from "~/shared-store.server"; import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server"; import type { ProjectRouteContext } from "~/utils/integrations/projects/projectAccess.server"; import { projectEditScopeWhere, projectReadScopeWhere, type ProjectVisibilityContext } from "~/utils/integrations/projects/projectService.server"; import { linkFile, getVisibleFileOrThrow, listFilesForBrowser } from "~/utils/integrations/fileService.server"; import { mediaVariantPath } from "~/utils/integrations/fileRoutePaths"; import { deleteFile as deleteStoredFile, putBufferAsFile, resolveStorageBucket } from "~/utils/integrations/storageService"; import { tenantHasModule } from "~/utils/connector/tenantConnector.server"; import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server"; import { renderSystemMessageEmail } from "@hivegrid/mail"; import { sealPdfWithPades, type PadesSealResult } from "./padesSeal.server"; import { reserveSignatureOtpAttempt } from "./signature-otp-rate-limit.server"; import { sanitizeIconSvg } from "~/utils/html-sanitizer"; export class SignatureServiceError extends Error { readonly messageKey: string; readonly status: number; readonly retryAfterSeconds: number | null; constructor(messageKey: string, options: { status?: number; retryAfterSeconds?: number } = {}) { super(messageKey); this.name = "SignatureServiceError"; this.messageKey = messageKey; this.status = options.status ?? 400; this.retryAfterSeconds = options.retryAfterSeconds ?? null; } } export type ParsedSignatureSignerInput = { readonly signerName: string; readonly signerEmail: string; readonly signerRole: SignatureSignerRole; }; export type SendSignatureDocumentResult = { readonly documentId: string; readonly signerLinks: readonly { readonly signerId: string; readonly signerEmail: string; readonly accessToken: string; readonly otp: string; }[]; }; const SIGNATURE_PROVIDER_SES = "ses_selfhosted"; const SIGNATURE_PROVIDER_PANDADOC = "pandadoc_byok"; const SIGNATURE_MODULE_KEY = "signature"; const TOKEN_BYTES = 32; const OTP_DIGITS = 6; const MAX_SIGNATURE_SVG_BYTES = 64 * 1024; const SIGNATURE_SEAL_CLAIM_TTL_SECONDS = 30 * 60; let signatureSealingClaimStore: IdempotencyStore | null = null; function getSignatureSealingClaimStore(): IdempotencyStore { signatureSealingClaimStore ??= createIdempotencyStore({ store: getSharedStore(), prefix: "signature-seal-v1", ttlSeconds: SIGNATURE_SEAL_CLAIM_TTL_SECONDS, }); return signatureSealingClaimStore; } export function __setSignatureSealingClaimStoreForTests(store: IdempotencyStore): void { signatureSealingClaimStore = store; } export function __resetSignatureSealingClaimStoreForTests(): void { signatureSealingClaimStore = null; } function hasPermission(ctx: ProjectRouteContext, permission: string): boolean { return ctx.permissions.includes(permission); } export function canReadSignatures(ctx: ProjectRouteContext): boolean { return hasPermission(ctx, "signature.read") || hasPermission(ctx, "signature.send") || hasPermission(ctx, "signature.admin"); } export function canSendSignatures(ctx: ProjectRouteContext): boolean { return hasPermission(ctx, "signature.send") || hasPermission(ctx, "signature.admin"); } export function canRevokeSignatures(ctx: ProjectRouteContext): boolean { return hasPermission(ctx, "signature.revoke") || hasPermission(ctx, "signature.admin"); } function requireSignatureSend(ctx: ProjectRouteContext): void { if (!canSendSignatures(ctx)) throw new CatalogError(foundationErrors.notFound); } function requireSignatureRevoke(ctx: ProjectRouteContext): void { if (!canRevokeSignatures(ctx)) throw new CatalogError(foundationErrors.notFound); } async function hasSignatureModule(tenantId: string, userId: string): Promise { return tenantHasModule({ tenantId, userId, moduleKey: SIGNATURE_MODULE_KEY }); } async function requireSignatureModule(tenantId: string, userId: string): Promise { if (!(await hasSignatureModule(tenantId, userId))) { throw new CatalogError(foundationErrors.notFound, { module: SIGNATURE_MODULE_KEY }); } } function normalizeText(value?: string | null): string | null { const normalized = value?.trim(); return normalized || null; } function hashSecret(value: string): string { return createHash("sha256").update(value).digest("hex"); } function hashRequestPart(value?: string | null): string | null { const normalized = normalizeText(value); return normalized ? hashSecret(normalized) : null; } function constantTimeEqualHash(plain: string, expectedHash: string | null): boolean { if (!expectedHash) return false; const actual = Buffer.from(hashSecret(plain), "hex"); const expected = Buffer.from(expectedHash, "hex"); return actual.length === expected.length && timingSafeEqual(actual, expected); } function createAccessToken(): string { return randomBytes(TOKEN_BYTES).toString("base64url"); } function createOtp(): string { const max = 10 ** OTP_DIGITS; return String(randomInt(0, max)).padStart(OTP_DIGITS, "0"); } export function normalizeSignatureSvg(value: string | null | undefined): string { const normalized = normalizeText(value); if (!normalized) throw new SignatureServiceError("signature.error.signatureRequired"); if (Buffer.byteLength(normalized, "utf8") > MAX_SIGNATURE_SVG_BYTES) { throw new SignatureServiceError("signature.error.signatureInvalid"); } const sanitized = sanitizeIconSvg(normalized); if (!sanitized || Buffer.byteLength(sanitized, "utf8") > MAX_SIGNATURE_SVG_BYTES) { throw new SignatureServiceError("signature.error.signatureInvalid"); } return sanitized; } function iso(date: Date | null | undefined): string | null { return date ? date.toISOString() : null; } function parseSignerRole(value: string | null | undefined): SignatureSignerRole { if (value === "bauherr" || value === "auftraggeber" || value === "rechnungsempfaenger" || value === "intern") return value; return "kunde"; } export function parseSignatureSigners(text: string | null | undefined): ParsedSignatureSignerInput[] { const rows = (text ?? "") .split(/\r?\n/) .map((line) => line.trim()) .filter(Boolean); return rows.map((line) => { const [namePart, emailPart, rolePart] = line.split(";").map((part) => part.trim()); const signerEmail = emailPart ?? ""; if (!namePart || !signerEmail || !signerEmail.includes("@")) { throw new SignatureServiceError("signature.error.signerInvalid"); } return { signerName: namePart.slice(0, 160), signerEmail: signerEmail.toLowerCase().slice(0, 190), signerRole: parseSignerRole(rolePart), }; }); } function signatureProjectContext(ctx: ProjectRouteContext): ProjectVisibilityContext { if (!hasPermission(ctx, "signature.admin") || hasPermission(ctx, "projects.read_all")) return ctx; return { ...ctx, permissions: [...ctx.permissions, "projects.read_all"] }; } async function requireVisibleProjectWithTx(tx: TenantRlsClient, input: { tenantId: string; projectId: string; ctx: ProjectRouteContext; editable?: boolean }) { const visibility = signatureProjectContext(input.ctx); const scope = input.editable ? projectEditScopeWhere(input.tenantId, visibility) : projectReadScopeWhere(input.tenantId, visibility); const project = await tx.projekt.findFirst({ where: { id: input.projectId, tenantId: input.tenantId, archivedAt: null, ...scope }, }); if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId }); return project; } function toDocumentRow(row: any, tenantSlug?: string | null): ProjectSignatureDocumentRow { // Download URLs go through the auth-proxy media route (AD-23); they are only // available when the caller knows the tenant slug (loader path). const fileUrl = (fileId: string | null): string | null => (tenantSlug && fileId ? mediaVariantPath(tenantSlug, fileId, "original") : null); return { id: row.id, title: row.title, provider: row.provider, providerKey: signatureProviderKey(row.provider), status: row.status, statusKey: signatureDocumentStatusKey(row.status), sourcePdfFileId: row.sourcePdfFileId, signedPdfFileId: row.signedPdfFileId, completionCertFileId: row.completionCertFileId, sourcePdfUrl: fileUrl(row.sourcePdfFileId), signedPdfUrl: fileUrl(row.signedPdfFileId), completionCertUrl: fileUrl(row.completionCertFileId), sentAtIso: iso(row.sentAt), completedAtIso: iso(row.completedAt), expiresAtIso: iso(row.expiresAt), signers: (row.signers ?? []).map((signer: any) => ({ id: signer.id, signerName: signer.signerName, signerEmail: signer.signerEmail, signerRole: signer.signerRole, status: signer.status, statusKey: signatureSignerStatusKey(signer.status), signedAtIso: iso(signer.signedAt), lastReminderAtIso: iso(signer.lastReminderAt), })), }; } export async function loadProjectSignaturePanel(input: { tenantId: string; projectId: string; tenantSlug: string; ctx: ProjectRouteContext; }): Promise { if (!canReadSignatures(input.ctx)) { return buildProjectSignaturePanelVM({ rows: [], canRead: false, canSend: false, canRevoke: false, canAdmin: false }); } if (!(await hasSignatureModule(input.tenantId, input.ctx.userId))) { return buildProjectSignaturePanelVM({ rows: [], canRead: false, canSend: false, canRevoke: false, canAdmin: false }); } const canSend = canSendSignatures(input.ctx); const { rows, kontaktSuggestions } = await withTenantRLS(input.tenantId, async (tx) => { await requireVisibleProjectWithTx(tx, input); const documents = await tx.projektSignatureDocument.findMany({ where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null }, include: { signers: { orderBy: [{ signingOrder: "asc" }, { createdAt: "asc" }] } }, orderBy: { createdAt: "desc" }, }); const suggestions = canSend ? await loadKontaktSuggestionsWithTx(tx, input.tenantId, input.projectId) : []; return { rows: documents, kontaktSuggestions: suggestions }; }); const pdfFileOptions = canSend ? await loadPdfFileOptions(input.tenantId, input.ctx) : []; return buildProjectSignaturePanelVM({ rows: rows.map((row) => toDocumentRow(row, input.tenantSlug)), pdfFileOptions, kontaktSuggestions, canRead: true, canSend, canRevoke: canRevokeSignatures(input.ctx), canAdmin: hasPermission(input.ctx, "signature.admin"), }); } async function loadKontaktSuggestionsWithTx(tx: TenantRlsClient, tenantId: string, projectId: string): Promise { const links = await tx.projektKontakt.findMany({ where: { tenantId, projektId: projectId }, select: { kontaktId: true, primaer: true }, orderBy: [{ primaer: "desc" }, { createdAt: "asc" }], }); if (links.length === 0) return []; const kontaktIds = [...new Set(links.map((link) => link.kontaktId))]; const kontakte = await tx.kontakt.findMany({ where: { tenantId, id: { in: kontaktIds } }, select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true }, }); const byId = new Map(kontakte.map((kontakt) => [kontakt.id, kontakt])); const seen = new Set(); const suggestions: ProjectSignatureKontaktSuggestion[] = []; for (const link of links) { if (seen.has(link.kontaktId)) continue; seen.add(link.kontaktId); const kontakt = byId.get(link.kontaktId); if (!kontakt) continue; const personName = [kontakt.vorname, kontakt.nachname].filter(Boolean).join(" ").trim(); suggestions.push({ kontaktId: kontakt.id, name: personName || kontakt.orgName || kontakt.id, email: kontakt.primaerEmail ?? null, primaer: link.primaer, }); } return suggestions; } async function loadPdfFileOptions(tenantId: string, ctx: ProjectRouteContext): Promise { try { const { rows } = await listFilesForBrowser({ tenantId, ctx, filter: { mimeGroup: "pdf" }, limit: 50 }); return rows.map((file) => ({ id: file.id, displayName: file.displayName, createdAtIso: iso(file.createdAt) })); } catch { // Files module unavailable / no visibility: the wizard falls back to upload-only. return []; } } async function ensureSesProviderConnectionWithTx(tx: TenantRlsClient, tenantId: string) { const existing = await tx.signatureProviderConnection.findFirst({ where: { tenantId, provider: SIGNATURE_PROVIDER_SES, archivedAt: null }, orderBy: [{ isDefault: "desc" }, { createdAt: "asc" }], }); if (existing) return existing; return tx.signatureProviderConnection.create({ data: { tenantId, provider: SIGNATURE_PROVIDER_SES, label: SIGNATURE_PROVIDER_SES, isDefault: true, healthMessageKey: "integrations.health.active", }, }); } async function addSignatureEventWithTx( tx: TenantRlsClient, input: { tenantId: string; documentId: string; signerId?: string | null; eventType: string; actorUserId?: string | null; ipAddress?: string | null; userAgent?: string | null; metadata?: unknown; providerEventId?: string | null; } ): Promise { await tx.signatureEvent.create({ data: { tenantId: input.tenantId, documentId: input.documentId, signerId: input.signerId ?? null, eventType: input.eventType as never, actorUserId: input.actorUserId ?? null, providerEventId: normalizeText(input.providerEventId), ipHash: hashRequestPart(input.ipAddress), userAgent: normalizeText(input.userAgent), metadata: input.metadata ?? undefined, }, }); } export async function createSignatureDraft(input: { tenantId: string; projectId: string; userId: string; ctx: ProjectRouteContext; title: string | null; sourcePdfFileId: string | null; signers: readonly ParsedSignatureSignerInput[]; subject?: string | null; message?: string | null; }): Promise { await requireSignatureModule(input.tenantId, input.userId); requireSignatureSend(input.ctx); const title = normalizeText(input.title); const sourcePdfFileId = normalizeText(input.sourcePdfFileId); if (!title) throw new SignatureServiceError("signature.error.titleRequired"); if (!sourcePdfFileId) throw new SignatureServiceError("signature.error.sourcePdfRequired"); if (input.signers.length === 0) throw new SignatureServiceError("signature.error.signerRequired"); const sourceFile = await getVisibleFileOrThrow(input.tenantId, sourcePdfFileId, input.ctx); if (sourceFile.mimeType !== "application/pdf") throw new SignatureServiceError("signature.error.sourcePdfRequired"); const document = await withTenantRLS(input.tenantId, async (tx) => { await requireVisibleProjectWithTx(tx, { ...input, editable: true }); const providerConnection = await ensureSesProviderConnectionWithTx(tx, input.tenantId); const sourceHash = hashSecret(`${sourceFile.id}:${sourceFile.storageKey}:${sourceFile.sizeBytes}`); const created = await tx.projektSignatureDocument.create({ data: { tenantId: input.tenantId, projektId: input.projectId, providerConnectionId: providerConnection.id, provider: SIGNATURE_PROVIDER_SES, title: title.slice(0, 180), subject: normalizeText(input.subject), message: normalizeText(input.message), sourcePdfFileId, documentHashSha256: sourceHash, createdByUserId: input.userId, signers: { create: input.signers.map((signer, index) => ({ tenantId: input.tenantId, signerName: signer.signerName, signerEmail: signer.signerEmail, signerRole: signer.signerRole, signingOrder: index, })), }, }, include: { signers: { orderBy: [{ signingOrder: "asc" }, { createdAt: "asc" }] } }, }); await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: created.id, eventType: "link_created", actorUserId: input.userId, metadata: { signerCount: input.signers.length }, }); return created; }); await linkFile({ tenantId: input.tenantId, userId: input.userId, fileId: sourcePdfFileId, entityType: "signature_document", entityId: document.id, linkRole: "source_pdf", ctx: signatureProjectContext(input.ctx), }).catch(() => undefined); await linkFile({ tenantId: input.tenantId, userId: input.userId, fileId: sourcePdfFileId, entityType: "project", entityId: input.projectId, linkRole: "signature_source_pdf", ctx: signatureProjectContext(input.ctx), }).catch(() => undefined); await logSignatureActivity({ tenantId: input.tenantId, actorUserId: input.userId, projectId: input.projectId, documentId: document.id, summaryKey: "activity.runtime.signature.documentPrepared", }); return toDocumentRow(document); } export async function sendSignatureDocument(input: { tenantId: string; documentId: string; userId: string; ctx: ProjectRouteContext; publicBaseUrl: string; }): Promise { await requireSignatureModule(input.tenantId, input.userId); requireSignatureSend(input.ctx); const signerLinks = await withTenantRLS(input.tenantId, async (tx) => { const document = await tx.projektSignatureDocument.findFirst({ where: { id: input.documentId, tenantId: input.tenantId, archivedAt: null }, include: { signers: { orderBy: [{ signingOrder: "asc" }, { createdAt: "asc" }] } }, }); if (!document) throw new CatalogError(foundationErrors.notFound, { documentId: input.documentId }); await requireVisibleProjectWithTx(tx, { tenantId: input.tenantId, projectId: document.projektId, ctx: input.ctx, editable: true, }); if (document.status === "signed" || document.status === "revoked") throw new SignatureServiceError("signature.error.documentTerminal"); const now = new Date(); const links: Array = []; for (const signer of document.signers) { const accessToken = createAccessToken(); const otp = createOtp(); links.push({ signerId: signer.id, signerEmail: signer.signerEmail, accessToken, otp }); await tx.projektSignatureSigner.update({ where: { id: signer.id }, data: { status: "sent", accessTokenHash: hashSecret(accessToken), otpHash: hashSecret(otp), otpExpiresAt: new Date(now.getTime() + 30 * 60 * 1000), }, }); await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: document.id, signerId: signer.id, eventType: "otp_requested", actorUserId: input.userId, metadata: { delivery: "email", otpTtlMinutes: 30 }, }); } await tx.projektSignatureDocument.update({ where: { id: document.id }, data: { status: "sent", sentAt: now, expiresAt: document.expiresAt ?? new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000) }, }); await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: document.id, eventType: "document_sent", actorUserId: input.userId, metadata: { signerCount: links.length }, }); return links; }); const projectId = await loadDocumentProjectId(input.tenantId, input.documentId); await ensureServerGlobalI18n(); await Promise.all( signerLinks.map((link) => { const signatureLink = `${input.publicBaseUrl}/sign/${link.accessToken}`; const subject = i18nT("signature.email.subject"); const rendered = renderSystemMessageEmail({ locale: "de", subject, eyebrow: i18nT("signature.email.eyebrow"), title: i18nT("signature.email.title"), intro: i18nT("signature.email.intro"), actionUrl: signatureLink, actionLabel: i18nT("signature.email.linkLabel"), notice: `${i18nT("signature.email.otpLabel")}: ${link.otp}`, noticeTone: "info", outro: i18nT("signature.email.outro"), }); return queueTransactionalEmail({ to: link.signerEmail, subject, body: rendered.html, text: rendered.text, alias: "signature-otp", tenantId: input.tenantId, userId: input.userId, priorityOverride: "high", data: { signatureDocumentId: input.documentId, signatureSignerId: link.signerId, projectId }, }).catch(() => undefined); }) ); await logSignatureActivity({ tenantId: input.tenantId, actorUserId: input.userId, projectId, documentId: input.documentId, summaryKey: "activity.runtime.signature.documentSent", }); return { documentId: input.documentId, signerLinks }; } async function loadDocumentProjectId(tenantId: string, documentId: string): Promise { const row = await withTenantRLS(tenantId, (tx) => tx.projektSignatureDocument.findFirst({ where: { tenantId, id: documentId }, select: { projektId: true } }) ); if (!row) throw new CatalogError(foundationErrors.notFound, { documentId }); return row.projektId; } async function logSignatureActivity(input: { tenantId: string; actorUserId: string | null; projectId: string; documentId: string; summaryKey: string; }): Promise { await logActivity({ tenantId: input.tenantId, actorUserId: input.actorUserId, actorKind: input.actorUserId ? "user" : "system", activityType: "project_signature_changed", subjectType: "project", subjectId: input.projectId, summaryText: input.summaryKey, metadata: { signatureDocumentId: input.documentId }, }).catch(() => undefined); } type GeneratedSignatureArtifact = { fileId: string; storageKey: string; sha256: string; seal: PadesSealResult | null; }; async function cleanupGeneratedSignatureArtifacts(tenantId: string, artifacts: readonly GeneratedSignatureArtifact[]): Promise { if (artifacts.length === 0) return; const fileIds = artifacts.map(({ fileId }) => fileId); await withTenantRLS(tenantId, (tx) => tx.file.deleteMany({ where: { tenantId, id: { in: fileIds } } })).catch(() => undefined); const bucket = resolveStorageBucket(); await Promise.allSettled(artifacts.map(({ storageKey }) => deleteStoredFile({ bucket, key: storageKey }))); } async function storeGeneratedSignaturePdf(input: { tenantId: string; userId: string; projectId: string; documentId: string; displayName: string; artifactKind: "signed_pdf" | "completion_certificate"; rows: readonly Record[]; pades?: { signerName: string; contactInfo: string; location: string; reason: string; signingTime: Date; }; }): Promise { await ensureServerGlobalI18n(); const { buildPdfExportArtifact } = await import("@hivegrid/exports/pdf"); const pdf = await buildPdfExportArtifact( { columns: [ { key: "field", label: i18nT("signature.certificate.columns.field") }, { key: "value", label: i18nT("signature.certificate.columns.value") }, ], rows: input.rows, }, { title: input.displayName } ); const seal = input.pades ? await sealPdfWithPades({ pdfBytes: pdf.bytes, title: input.displayName, signerName: input.pades.signerName, contactInfo: input.pades.contactInfo, location: input.pades.location, reason: input.pades.reason, signingTime: input.pades.signingTime, }) : null; const bytes = seal?.bytes ?? pdf.bytes; const byteLength = bytes.byteLength; const fileId = `file_${randomUUID()}`; const { original } = buildFileStorageKeys(input.tenantId, fileId); const bucket = resolveStorageBucket(); try { await withTenantStorageWriteReservation({ reservation: { tenantId: input.tenantId, actorUserId: input.userId, targetFileId: fileId, originalFilename: input.displayName.slice(0, 255), mimeType: pdf.contentType, sizeBytes: byteLength, }, runTransaction: (operation) => withTenantRLS(input.tenantId, operation), upload: () => putBufferAsFile({ bucket, key: original, body: bytes, contentType: pdf.contentType }), commit: async (tx) => { await tx.file.create({ data: { id: fileId, tenantId: input.tenantId, createdByUserId: input.userId, displayName: input.displayName.slice(0, 255), mimeType: pdf.contentType, sizeBytes: byteLength, storageKey: original, checksumSha256: seal?.signedPdfSha256 ?? hashSecret(Buffer.from(bytes).toString("base64")), source: "automation", // The signed PDF is generated inside HiveGrid from an already accepted // source document, so the resulting artifact is trusted at creation. scanStatus: "clean", previewStatus: "pending", }, }); }, rollbackUpload: () => deleteStoredFile({ bucket, key: original }), }); } catch (error) { let persisted: { id: string } | null; try { persisted = await withTenantRLS(input.tenantId, (tx) => tx.file.findFirst({ where: { id: fileId, tenantId: input.tenantId }, select: { id: true } })); } catch { // The transaction outcome is unknown. Keep the object rather than risk // deleting bytes that a committed File row already references. throw error; } if (!persisted) { throw error; } } // This path is reached by the public signer after the document and project // were resolved from a verified signing token. Keep target existence and // tenant scoping enabled while using a narrow internal read context. const linkContext = { userId: input.userId, permissions: ["files.read_own", "projects.read_all", "signature.read"], roleIds: [], groupIds: [], }; await linkFile({ tenantId: input.tenantId, userId: input.userId, fileId, entityType: "signature_document", entityId: input.documentId, linkRole: input.artifactKind, ctx: linkContext, }).catch(() => undefined); await linkFile({ tenantId: input.tenantId, userId: input.userId, fileId, entityType: "project", entityId: input.projectId, linkRole: `signature_${input.artifactKind}`, ctx: linkContext, }).catch(() => undefined); return { fileId, storageKey: original, sha256: seal?.signedPdfSha256 ?? hashSecret(Buffer.from(bytes).toString("base64")), seal }; } async function sealDocumentIfComplete(input: { tenantId: string; documentId: string; actorUserId: string | null }): Promise { const current = await withTenantRLS(input.tenantId, (tx) => tx.projektSignatureDocument.findFirst({ where: { tenantId: input.tenantId, id: input.documentId, archivedAt: null }, select: { status: true }, }) ); if (!current || current.status === "signed" || ["declined", "revoked", "expired"].includes(current.status)) return; const claimKey = hashSecret(`${input.tenantId}:${input.documentId}`); let claims: IdempotencyStore; let ownsClaim: boolean; try { claims = getSignatureSealingClaimStore(); ownsClaim = await claims.claim(claimKey); } catch { throw new SignatureServiceError("signature.error.rateLimitUnavailable", { status: 503, retryAfterSeconds: 60 }); } if (!ownsClaim) return; const generatedArtifacts: GeneratedSignatureArtifact[] = []; let finalized = false; try { const snapshot = await withTenantRLS(input.tenantId, async (tx) => { const document = await tx.projektSignatureDocument.findFirst({ where: { tenantId: input.tenantId, id: input.documentId, archivedAt: null }, include: { signers: { orderBy: [{ signingOrder: "asc" }, { createdAt: "asc" }] } }, }); if (!document || document.status === "signed") return null; if (document.status !== "sent" && document.status !== "viewed") return null; if (document.signers.length === 0 || document.signers.some((signer) => signer.status !== "signed")) return null; return document; }); if (!snapshot) { await claims.forget(claimKey); return; } const completedAt = new Date(); const fileActorUserId = input.actorUserId ?? snapshot.createdByUserId ?? "system"; const rows = [ { field: "Dokument", value: snapshot.title }, { field: "Provider", value: SIGNATURE_PROVIDER_SES }, { field: "Quell-PDF SHA-256", value: snapshot.documentHashSha256 ?? "" }, { field: "Abgeschlossen", value: completedAt.toISOString() }, { field: "Unterzeichner", value: snapshot.signers.map((signer) => `${signer.signerName} <${signer.signerEmail}> ${signer.signedAt?.toISOString() ?? ""}`).join("\n"), }, ]; const signedPdf = await storeGeneratedSignaturePdf({ tenantId: input.tenantId, userId: fileActorUserId, projectId: snapshot.projektId, documentId: snapshot.id, displayName: `${snapshot.title}-signed.pdf`, artifactKind: "signed_pdf", rows, pades: { signerName: "HiveGrid SES", contactInfo: snapshot.signers.map((signer) => signer.signerEmail).join(", "), location: "HiveGrid", reason: `Electronic signature completion for ${snapshot.title}`, signingTime: completedAt, }, }); generatedArtifacts.push(signedPdf); const sealRows = [ { field: "PAdES-Modus", value: signedPdf.seal?.mode ?? "not_requested" }, { field: "PAdES-Zertifikat konfiguriert", value: signedPdf.seal?.certificateConfigured ? "true" : "false" }, { field: "TSA-URL", value: signedPdf.seal?.tsa?.url ?? "" }, { field: "TSA-Request SHA-256", value: signedPdf.seal?.tsa?.requestSha256 ?? "" }, { field: "TSA-Response SHA-256", value: signedPdf.seal?.tsa?.responseSha256 ?? "" }, ]; const certificate = await storeGeneratedSignaturePdf({ tenantId: input.tenantId, userId: fileActorUserId, projectId: snapshot.projektId, documentId: snapshot.id, displayName: `${snapshot.title}-completion-certificate.pdf`, artifactKind: "completion_certificate", rows: [...rows, ...sealRows], }); generatedArtifacts.push(certificate); const finalization = await withTenantRLS(input.tenantId, async (tx) => { const claimed = await tx.projektSignatureDocument.updateMany({ where: { id: snapshot.id, tenantId: input.tenantId, archivedAt: null, status: { in: ["sent", "viewed"] }, signedPdfFileId: null, completionCertFileId: null, }, data: { status: "signed", completedAt, signedPdfFileId: signedPdf.fileId, completionCertFileId: certificate.fileId, sealedPdfHashSha256: signedPdf.sha256, completionCertHashSha256: certificate.sha256, externalStatusPayload: { pades: { mode: signedPdf.seal?.mode ?? "not_requested", certificateConfigured: signedPdf.seal?.certificateConfigured ?? false, tsa: signedPdf.seal?.tsa ? { url: signedPdf.seal.tsa.url, requestSha256: signedPdf.seal.tsa.requestSha256, responseSha256: signedPdf.seal.tsa.responseSha256, } : null, }, }, }, }); if (claimed.count !== 1) { const document = await tx.projektSignatureDocument.findFirst({ where: { id: snapshot.id, tenantId: input.tenantId }, select: { status: true }, }); return { finalized: false as const, status: document?.status ?? null }; } await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: snapshot.id, eventType: "pdf_sealed", actorUserId: input.actorUserId, metadata: { signedPdfFileId: signedPdf.fileId }, }); await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: snapshot.id, eventType: "certificate_created", actorUserId: input.actorUserId, metadata: { completionCertFileId: certificate.fileId }, }); return { finalized: true as const, status: "signed" as const }; }); if (!finalization.finalized) { await cleanupGeneratedSignatureArtifacts(input.tenantId, generatedArtifacts); generatedArtifacts.length = 0; if (finalization.status === "signed" || ["declined", "revoked", "expired"].includes(finalization.status ?? "")) { await claims.complete(claimKey, { status: finalization.status }).catch(() => undefined); return; } throw new SignatureServiceError("signature.error.rateLimitUnavailable", { status: 503, retryAfterSeconds: 60 }); } finalized = true; await claims.complete(claimKey, { status: "signed" }).catch(() => undefined); await logSignatureActivity({ tenantId: input.tenantId, actorUserId: input.actorUserId, projectId: snapshot.projektId, documentId: snapshot.id, summaryKey: "activity.runtime.signature.documentCompleted", }); } catch (error) { if (!finalized) { let persisted: { status: string; signedPdfFileId: string | null; completionCertFileId: string | null } | null; try { persisted = await withTenantRLS(input.tenantId, (tx) => tx.projektSignatureDocument.findFirst({ where: { id: input.documentId, tenantId: input.tenantId }, select: { status: true, signedPdfFileId: true, completionCertFileId: true }, }) ); } catch { // An ambiguous commit must keep its claim and artifacts until the TTL; // deleting them could corrupt a document that did finalize. throw error; } if (persisted?.status === "signed") { const referencedFileIds = new Set([persisted.signedPdfFileId, persisted.completionCertFileId].filter((id): id is string => Boolean(id))); await cleanupGeneratedSignatureArtifacts( input.tenantId, generatedArtifacts.filter(({ fileId }) => !referencedFileIds.has(fileId)) ); await claims.complete(claimKey, { status: "signed" }).catch(() => undefined); return; } await cleanupGeneratedSignatureArtifacts(input.tenantId, generatedArtifacts); await claims.forget(claimKey).catch(() => undefined); } throw error; } } export async function __sealDocumentIfCompleteForTests(input: { tenantId: string; documentId: string; actorUserId: string | null }): Promise { return sealDocumentIfComplete(input); } export async function recordSignatureLinkOpened(input: { token: string; ipAddress?: string | null; userAgent?: string | null }) { const tokenHash = hashSecret(input.token); const identity = await loadSignerRlsIdentityByTokenHash(tokenHash); return withTenantRLS(identity.tenantId, async (tx) => { const signer = await tx.projektSignatureSigner.findFirst({ where: { id: identity.resourceId, tenantId: identity.tenantId, accessTokenHash: tokenHash }, include: { document: true }, }); if ( !signer || signer.document.archivedAt || signer.document.status === "revoked" || (signer.document.expiresAt && signer.document.expiresAt.getTime() <= Date.now()) ) { throw new CatalogError(foundationErrors.notFound); } const now = new Date(); if (signer.status === "sent") { await tx.projektSignatureSigner.update({ where: { id: signer.id }, data: { status: "viewed", viewedAt: now, lastLinkOpenedAt: now, signerIpHash: hashRequestPart(input.ipAddress), signerUserAgent: normalizeText(input.userAgent), }, }); await tx.projektSignatureDocument.update({ where: { id: signer.documentId }, data: { status: signer.document.status === "sent" ? "viewed" : signer.document.status }, }); await addSignatureEventWithTx(tx, { tenantId: signer.tenantId, documentId: signer.documentId, signerId: signer.id, eventType: "link_opened", ipAddress: input.ipAddress, userAgent: input.userAgent, }); } return { tenantId: signer.tenantId, documentId: signer.documentId, title: signer.document.title, signerName: signer.signerName, signerEmail: signer.signerEmail, status: signer.status, }; }); } export async function signWithOtp(input: { token: string; otp: string | null; signatureSvg: string | null; intentAccepted: boolean; ipAddress?: string | null; userAgent?: string | null; trustedClientIp?: string | null; }) { const tokenHash = hashSecret(input.token); const identity = await loadSignerRlsIdentityByTokenHash(tokenHash); const result = await withTenantRLS(identity.tenantId, async (tx) => { const signer = await tx.projektSignatureSigner.findFirst({ where: { id: identity.resourceId, tenantId: identity.tenantId, accessTokenHash: tokenHash }, include: { document: true }, }); if ( !signer || signer.document.archivedAt || signer.document.status === "revoked" || (signer.document.expiresAt && signer.document.expiresAt.getTime() <= Date.now()) ) { throw new CatalogError(foundationErrors.notFound); } // A previous request may have persisted the signer before sealing failed. // The verified access token may retry only the idempotent document seal. if (signer.status === "signed") { return { tenantId: signer.tenantId, documentId: signer.documentId, signerId: signer.id }; } if (!input.intentAccepted) throw new SignatureServiceError("signature.error.intentRequired"); const signatureSvg = normalizeSignatureSvg(input.signatureSvg); const otp = normalizeText(input.otp); if (signer.otpExpiresAt && signer.otpExpiresAt.getTime() < Date.now()) throw new SignatureServiceError("signature.error.otpExpired"); if (!otp) throw new SignatureServiceError("signature.error.otpInvalid"); let rateLimit; try { rateLimit = await reserveSignatureOtpAttempt({ tokenHash, trustedClientIp: input.trustedClientIp || "unknown", }); } catch { throw new SignatureServiceError("signature.error.rateLimitUnavailable", { status: 503, retryAfterSeconds: 60, }); } if (!rateLimit.allowed) { throw new SignatureServiceError("signature.error.tooManyAttempts", { status: 429, retryAfterSeconds: rateLimit.retryAfterSeconds, }); } if (!constantTimeEqualHash(otp, signer.otpHash)) throw new SignatureServiceError("signature.error.otpInvalid"); const now = new Date(); const claimed = await tx.projektSignatureSigner.updateMany({ where: { id: signer.id, otpHash: signer.otpHash, otpExpiresAt: { gte: now }, status: { in: ["sent", "viewed", "otp_verified"] }, }, data: { status: "signed", signedAt: now, otpHash: null, otpExpiresAt: null, signatureSvg, signerIpHash: hashRequestPart(input.ipAddress), signerUserAgent: normalizeText(input.userAgent), intentText: "Ich stimme zu und unterschreibe dieses Dokument elektronisch.", }, }); if (claimed.count !== 1) throw new SignatureServiceError("signature.error.otpInvalid"); await addSignatureEventWithTx(tx, { tenantId: signer.tenantId, documentId: signer.documentId, signerId: signer.id, eventType: "otp_verified", ipAddress: input.ipAddress, userAgent: input.userAgent, }); await addSignatureEventWithTx(tx, { tenantId: signer.tenantId, documentId: signer.documentId, signerId: signer.id, eventType: "signer_signed", ipAddress: input.ipAddress, userAgent: input.userAgent, }); return { tenantId: signer.tenantId, documentId: signer.documentId, signerId: signer.id }; }); await sealDocumentIfComplete({ tenantId: result.tenantId, documentId: result.documentId, actorUserId: null }); return result; } async function loadSignerRlsIdentityByTokenHash(tokenHash: string): Promise<{ tenantId: string; resourceId: string }> { const identity = await resolveSignatureSignerRlsIdentity(tokenHash); if (!identity) throw new CatalogError(foundationErrors.notFound); return identity; } export async function remindSignatureSigner(input: { tenantId: string; signerId: string; userId: string; ctx: ProjectRouteContext }) { await requireSignatureModule(input.tenantId, input.userId); requireSignatureSend(input.ctx); return withTenantRLS(input.tenantId, async (tx) => { const signer = await tx.projektSignatureSigner.findFirst({ where: { id: input.signerId, tenantId: input.tenantId }, include: { document: true } }); if (!signer) throw new CatalogError(foundationErrors.notFound, { signerId: input.signerId }); await requireVisibleProjectWithTx(tx, { tenantId: input.tenantId, projectId: signer.document.projektId, ctx: input.ctx, editable: true, }); await tx.projektSignatureSigner.update({ where: { id: signer.id }, data: { lastReminderAt: new Date() } }); await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: signer.documentId, signerId: signer.id, eventType: "reminder_sent", actorUserId: input.userId, }); return { ok: true }; }); } export async function revokeSignatureDocument(input: { tenantId: string; documentId: string; userId: string; ctx: ProjectRouteContext }) { await requireSignatureModule(input.tenantId, input.userId); requireSignatureRevoke(input.ctx); const document = await withTenantRLS(input.tenantId, async (tx) => { const existing = await tx.projektSignatureDocument.findFirst({ where: { id: input.documentId, tenantId: input.tenantId, archivedAt: null } }); if (!existing) throw new CatalogError(foundationErrors.notFound, { documentId: input.documentId }); await requireVisibleProjectWithTx(tx, { tenantId: input.tenantId, projectId: existing.projektId, ctx: input.ctx, editable: true, }); await tx.projektSignatureSigner.updateMany({ where: { tenantId: input.tenantId, documentId: existing.id, status: { not: "signed" } }, data: { status: "revoked", revokedAt: new Date() }, }); const updated = await tx.projektSignatureDocument.update({ where: { id: existing.id }, data: { status: "revoked", revokedAt: new Date() } }); await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: existing.id, eventType: "document_revoked", actorUserId: input.userId }); return updated; }); await logSignatureActivity({ tenantId: input.tenantId, actorUserId: input.userId, projectId: document.projektId, documentId: document.id, summaryKey: "activity.runtime.signature.documentRevoked", }); return { ok: true }; } export async function handlePandaDocWebhook(input: { tenantId: string; rawBody: string; verified: boolean }) { if (!input.verified) throw new CatalogError(foundationErrors.notFound); const payload = JSON.parse(input.rawBody) as { event?: string; data?: { id?: string; status?: string } }; const providerDocumentId = normalizeText(payload.data?.id); if (!providerDocumentId) return { ok: true, ignored: true }; const completed = await withTenantRLS(input.tenantId, async (tx) => { const document = await tx.projektSignatureDocument.findFirst({ where: { tenantId: input.tenantId, provider: SIGNATURE_PROVIDER_PANDADOC, providerDocumentId }, }); if (!document) return null; await addSignatureEventWithTx(tx, { tenantId: input.tenantId, documentId: document.id, eventType: "provider_webhook", providerEventId: payload.event ?? null, metadata: payload, }); if (payload.event === "document.completed" || payload.data?.status === "document.completed") { await tx.projektSignatureDocument.update({ where: { id: document.id }, data: { status: "signed", completedAt: new Date() } }); return { documentId: document.id, projektId: document.projektId }; } return null; }); if (completed) { // Provider-driven status transition still lands in the activity stream // (DoD C.14); actorUserId null renders as a system actor. await logSignatureActivity({ tenantId: input.tenantId, actorUserId: null, projectId: completed.projektId, documentId: completed.documentId, summaryKey: "activity.runtime.signature.providerCompleted", }); } return { ok: true }; }