Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+16
@@ -0,0 +1,16 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildRfc3161TimestampRequest } from "./padesSeal.server";
|
||||
|
||||
describe("buildRfc3161TimestampRequest", () => {
|
||||
it("builds a DER encoded RFC3161 request for a SHA-256 message imprint", () => {
|
||||
const digest = createHash("sha256").update("pdf bytes").digest();
|
||||
const request = buildRfc3161TimestampRequest(digest, Buffer.from("0102030405060708", "hex"));
|
||||
|
||||
expect(request.byteLength).toBeGreaterThan(40);
|
||||
expect(request[0]).toBe(0x30);
|
||||
expect(request.includes(Buffer.from("608648016503040201", "hex"))).toBe(true);
|
||||
expect(request.includes(digest)).toBe(true);
|
||||
});
|
||||
});
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { plainAddPlaceholder } from "@signpdf/placeholder-plain";
|
||||
import { P12Signer } from "@signpdf/signer-p12";
|
||||
import { SignPdf } from "@signpdf/signpdf";
|
||||
|
||||
const requireNode = createRequire(import.meta.url);
|
||||
const SUBFILTER_ETSI_CADES_DETACHED = "ETSI.CAdES.detached";
|
||||
|
||||
export type PadesSealResult = {
|
||||
readonly bytes: Uint8Array;
|
||||
readonly mode: "pades_cades_detached" | "unsigned_dev_fallback";
|
||||
readonly signedPdfSha256: string;
|
||||
readonly certificateConfigured: boolean;
|
||||
readonly tsa: null | {
|
||||
readonly url: string;
|
||||
readonly requestSha256: string;
|
||||
readonly responseSha256: string;
|
||||
readonly responseBase64: string;
|
||||
};
|
||||
};
|
||||
|
||||
type PadesSealConfig = {
|
||||
readonly p12Base64?: string;
|
||||
readonly p12Path?: string;
|
||||
readonly p12Passphrase?: string;
|
||||
readonly tsaUrl?: string;
|
||||
readonly tsaAuthorizationHeader?: string;
|
||||
readonly requirePades: boolean;
|
||||
readonly signatureLength: number;
|
||||
};
|
||||
|
||||
type ForgeModule = {
|
||||
readonly asn1: {
|
||||
readonly Class: { readonly UNIVERSAL: number };
|
||||
readonly Type: { readonly SEQUENCE: number; readonly INTEGER: number; readonly OCTETSTRING: number; readonly OID: number; readonly NULL: number; readonly BOOLEAN: number };
|
||||
create(tagClass: number, type: number, constructed: boolean, value: string | readonly unknown[]): unknown;
|
||||
oidToDer(oid: string): { getBytes(): string };
|
||||
toDer(node: unknown): { getBytes(): string };
|
||||
};
|
||||
};
|
||||
|
||||
function getEnv(name: string): string | undefined {
|
||||
const value = process.env[name]?.trim();
|
||||
return value ? value : undefined;
|
||||
}
|
||||
|
||||
function resolvePadesSealConfig(): PadesSealConfig {
|
||||
return {
|
||||
p12Base64: getEnv("SIGNATURE_P12_BASE64"),
|
||||
p12Path: getEnv("SIGNATURE_P12_PATH"),
|
||||
p12Passphrase: process.env.SIGNATURE_P12_PASSPHRASE ?? "",
|
||||
tsaUrl: getEnv("SIGNATURE_TSA_URL"),
|
||||
tsaAuthorizationHeader: getEnv("SIGNATURE_TSA_AUTHORIZATION"),
|
||||
requirePades: getEnv("SIGNATURE_REQUIRE_PADES") === "true",
|
||||
signatureLength: Number(getEnv("SIGNATURE_PLACEHOLDER_LENGTH") ?? "32768"),
|
||||
};
|
||||
}
|
||||
|
||||
function sha256Hex(bytes: Uint8Array): string {
|
||||
return createHash("sha256").update(bytes).digest("hex");
|
||||
}
|
||||
|
||||
function binaryString(bytes: Uint8Array): string {
|
||||
return Buffer.from(bytes).toString("binary");
|
||||
}
|
||||
|
||||
async function loadP12Buffer(config: PadesSealConfig): Promise<Buffer | null> {
|
||||
if (config.p12Base64) return Buffer.from(config.p12Base64, "base64");
|
||||
if (config.p12Path) return readFile(config.p12Path);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function buildRfc3161TimestampRequest(messageHash: Uint8Array, nonce: Uint8Array = randomBytes(16)): Buffer {
|
||||
const forge = requireNode("node-forge") as ForgeModule;
|
||||
const asn1 = forge.asn1;
|
||||
const positiveNonce = nonce[0] && nonce[0] >= 0x80 ? Buffer.concat([Buffer.from([0]), Buffer.from(nonce)]) : Buffer.from(nonce);
|
||||
const sha256Algorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
|
||||
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer("2.16.840.1.101.3.4.2.1").getBytes()),
|
||||
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""),
|
||||
]);
|
||||
const messageImprint = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
|
||||
sha256Algorithm,
|
||||
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, binaryString(messageHash)),
|
||||
]);
|
||||
const request = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
|
||||
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, binaryString(Buffer.from([1]))),
|
||||
messageImprint,
|
||||
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, binaryString(positiveNonce)),
|
||||
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, binaryString(Buffer.from([0xff]))),
|
||||
]);
|
||||
return Buffer.from(asn1.toDer(request).getBytes(), "binary");
|
||||
}
|
||||
|
||||
async function requestTimestampToken(input: { tsaUrl: string; authorizationHeader?: string; pdfBytes: Uint8Array }) {
|
||||
const messageHash = createHash("sha256").update(input.pdfBytes).digest();
|
||||
const requestBody = buildRfc3161TimestampRequest(messageHash);
|
||||
const requestArrayBuffer = requestBody.buffer.slice(requestBody.byteOffset, requestBody.byteOffset + requestBody.byteLength) as ArrayBuffer;
|
||||
const response = await fetch(input.tsaUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/timestamp-query",
|
||||
Accept: "application/timestamp-reply",
|
||||
...(input.authorizationHeader ? { Authorization: input.authorizationHeader } : {}),
|
||||
},
|
||||
body: requestArrayBuffer,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`TSA request failed with status ${response.status}`);
|
||||
}
|
||||
const responseBytes = new Uint8Array(await response.arrayBuffer());
|
||||
return {
|
||||
url: input.tsaUrl,
|
||||
requestSha256: sha256Hex(requestBody),
|
||||
responseSha256: sha256Hex(responseBytes),
|
||||
responseBase64: Buffer.from(responseBytes).toString("base64"),
|
||||
};
|
||||
}
|
||||
|
||||
export async function sealPdfWithPades(input: {
|
||||
readonly pdfBytes: Uint8Array;
|
||||
readonly title: string;
|
||||
readonly signerName: string;
|
||||
readonly contactInfo: string;
|
||||
readonly location: string;
|
||||
readonly reason: string;
|
||||
readonly signingTime?: Date;
|
||||
}): Promise<PadesSealResult> {
|
||||
const config = resolvePadesSealConfig();
|
||||
const p12Buffer = await loadP12Buffer(config);
|
||||
if (!p12Buffer) {
|
||||
if (config.requirePades) throw new Error("SIGNATURE_P12_BASE64 or SIGNATURE_P12_PATH is required when SIGNATURE_REQUIRE_PADES=true.");
|
||||
return {
|
||||
bytes: input.pdfBytes,
|
||||
mode: "unsigned_dev_fallback",
|
||||
signedPdfSha256: sha256Hex(input.pdfBytes),
|
||||
certificateConfigured: false,
|
||||
tsa: null,
|
||||
};
|
||||
}
|
||||
|
||||
const signingTime = input.signingTime ?? new Date();
|
||||
const pdfWithPlaceholder = plainAddPlaceholder({
|
||||
pdfBuffer: Buffer.from(input.pdfBytes),
|
||||
reason: input.reason,
|
||||
contactInfo: input.contactInfo,
|
||||
name: input.signerName,
|
||||
location: input.location,
|
||||
signingTime,
|
||||
signatureLength: Number.isFinite(config.signatureLength) && config.signatureLength > 0 ? config.signatureLength : 32768,
|
||||
subFilter: SUBFILTER_ETSI_CADES_DETACHED,
|
||||
appName: "HiveGrid",
|
||||
});
|
||||
const signer = new P12Signer(p12Buffer, { passphrase: config.p12Passphrase, asn1StrictParsing: false });
|
||||
const signed = await new SignPdf().sign(pdfWithPlaceholder, signer, signingTime);
|
||||
const tsa = config.tsaUrl ? await requestTimestampToken({ tsaUrl: config.tsaUrl, authorizationHeader: config.tsaAuthorizationHeader, pdfBytes: signed }) : null;
|
||||
return {
|
||||
bytes: signed,
|
||||
mode: "pades_cades_detached",
|
||||
signedPdfSha256: sha256Hex(signed),
|
||||
certificateConfigured: true,
|
||||
tsa,
|
||||
};
|
||||
}
|
||||
+821
@@ -0,0 +1,821 @@
|
||||
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
||||
import i18next from "i18next";
|
||||
import { buildFileStorageKeys } from "@hivegrid/storage";
|
||||
import { buildPdfExportArtifact } from "@hivegrid/exports/pdf";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import {
|
||||
buildProjectSignaturePanelVM,
|
||||
signatureDocumentStatusKey,
|
||||
signatureProviderKey,
|
||||
signatureSignerStatusKey,
|
||||
type ProjectSignatureDocumentRow,
|
||||
type ProjectSignaturePanelVM,
|
||||
type SignatureSignerRole,
|
||||
} from "@hivegrid/view-models";
|
||||
import { ensureServerGlobalI18n } from "~/locale/i18next.global.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import type { ProjectRouteContext } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import { linkFile, getVisibleFileOrThrow } from "~/utils/integrations/fileService.server";
|
||||
import { putBufferAsFile, resolveStorageBucket } from "~/utils/integrations/storageService";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
|
||||
import { sealPdfWithPades, type PadesSealResult } from "./padesSeal.server";
|
||||
|
||||
export class SignatureServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "SignatureServiceError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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 requireSignatureRead(ctx: ProjectRouteContext): void {
|
||||
if (!canReadSignatures(ctx)) throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
|
||||
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<boolean> {
|
||||
return tenantHasModule({ tenantId, userId, moduleKey: SIGNATURE_MODULE_KEY });
|
||||
}
|
||||
|
||||
async function requireSignatureModule(tenantId: string, userId: string): Promise<void> {
|
||||
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(Number.parseInt(randomBytes(4).toString("hex"), 16) % max).padStart(OTP_DIGITS, "0");
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function requireVisibleProjectWithTx(tx: TenantRlsClient, input: { tenantId: string; projectId: string; ctx: ProjectRouteContext }) {
|
||||
const project = await tx.projekt.findFirst({ where: { id: input.projectId, tenantId: input.tenantId, archivedAt: null } });
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
if (hasPermission(input.ctx, "projects.read_all") || hasPermission(input.ctx, "signature.admin")) return project;
|
||||
const isOwner =
|
||||
project.createdByUserId === input.ctx.userId || project.zustaendigePersonId === input.ctx.userId || project.projektleiterId === input.ctx.userId;
|
||||
if (!isOwner) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
return project;
|
||||
}
|
||||
|
||||
function toDocumentRow(row: any): ProjectSignatureDocumentRow {
|
||||
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,
|
||||
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<ProjectSignaturePanelVM> {
|
||||
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 rows = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireVisibleProjectWithTx(tx, input);
|
||||
return tx.projektSignatureDocument.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
include: { signers: { orderBy: [{ signingOrder: "asc" }, { createdAt: "asc" }] } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
});
|
||||
return buildProjectSignaturePanelVM({
|
||||
rows: rows.map(toDocumentRow),
|
||||
canRead: true,
|
||||
canSend: canSendSignatures(input.ctx),
|
||||
canRevoke: canRevokeSignatures(input.ctx),
|
||||
canAdmin: hasPermission(input.ctx, "signature.admin"),
|
||||
});
|
||||
}
|
||||
|
||||
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<void> {
|
||||
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<ProjectSignatureDocumentRow> {
|
||||
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);
|
||||
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",
|
||||
}).catch(() => undefined);
|
||||
await linkFile({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
fileId: sourcePdfFileId,
|
||||
entityType: "project",
|
||||
entityId: input.projectId,
|
||||
linkRole: "signature_source_pdf",
|
||||
}).catch(() => undefined);
|
||||
await logSignatureActivity({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
projectId: input.projectId,
|
||||
documentId: document.id,
|
||||
summaryText: "Signatur-Dokument wurde vorbereitet.",
|
||||
});
|
||||
return toDocumentRow(document);
|
||||
}
|
||||
|
||||
export async function sendSignatureDocument(input: {
|
||||
tenantId: string;
|
||||
documentId: string;
|
||||
userId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
publicBaseUrl: string;
|
||||
}): Promise<SendSignatureDocumentResult> {
|
||||
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 });
|
||||
if (document.status === "signed" || document.status === "revoked") throw new SignatureServiceError("signature.error.documentTerminal");
|
||||
const now = new Date();
|
||||
const links: Array<SendSignatureDocumentResult["signerLinks"][number]> = [];
|
||||
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 body = [
|
||||
`<p>${i18next.t("signature.email.intro")}</p>`,
|
||||
`<p><a href="${signatureLink}">${i18next.t("signature.email.linkLabel")}</a></p>`,
|
||||
`<p>${i18next.t("signature.email.otpLabel")}: <strong>${link.otp}</strong></p>`,
|
||||
].join("");
|
||||
return queueTransactionalEmail({
|
||||
to: link.signerEmail,
|
||||
subject: i18next.t("signature.email.subject"),
|
||||
body,
|
||||
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,
|
||||
summaryText: "Signatur-Dokument wurde versendet.",
|
||||
});
|
||||
return { documentId: input.documentId, signerLinks };
|
||||
}
|
||||
|
||||
async function loadDocumentProjectId(tenantId: string, documentId: string): Promise<string> {
|
||||
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;
|
||||
summaryText: string;
|
||||
}): Promise<void> {
|
||||
await logActivity({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.actorUserId,
|
||||
actorKind: input.actorUserId ? "user" : "system",
|
||||
activityType: "project_signature_changed",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: input.summaryText,
|
||||
metadata: { signatureDocumentId: input.documentId },
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function storeGeneratedSignaturePdf(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
projectId: string;
|
||||
documentId: string;
|
||||
displayName: string;
|
||||
artifactKind: "signed_pdf" | "completion_certificate";
|
||||
rows: readonly Record<string, string>[];
|
||||
pades?: {
|
||||
signerName: string;
|
||||
contactInfo: string;
|
||||
location: string;
|
||||
reason: string;
|
||||
signingTime: Date;
|
||||
};
|
||||
}): Promise<{ fileId: string; sha256: string; seal: PadesSealResult | null }> {
|
||||
await ensureServerGlobalI18n();
|
||||
const pdf = await buildPdfExportArtifact(
|
||||
{
|
||||
columns: [
|
||||
{ key: "field", label: i18next.t("signature.certificate.columns.field") },
|
||||
{ key: "value", label: i18next.t("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);
|
||||
await putBufferAsFile({ bucket: resolveStorageBucket(), key: original, body: bytes, contentType: pdf.contentType });
|
||||
await withTenantRLS(input.tenantId, 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",
|
||||
scanStatus: "skipped",
|
||||
previewStatus: "pending",
|
||||
},
|
||||
});
|
||||
});
|
||||
await linkFile({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
fileId,
|
||||
entityType: "signature_document",
|
||||
entityId: input.documentId,
|
||||
linkRole: input.artifactKind,
|
||||
}).catch(() => undefined);
|
||||
await linkFile({
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
fileId,
|
||||
entityType: "project",
|
||||
entityId: input.projectId,
|
||||
linkRole: `signature_${input.artifactKind}`,
|
||||
}).catch(() => undefined);
|
||||
return { fileId, sha256: seal?.signedPdfSha256 ?? hashSecret(Buffer.from(bytes).toString("base64")), seal };
|
||||
}
|
||||
|
||||
async function sealDocumentIfComplete(input: { tenantId: string; documentId: string; actorUserId: string | null }): Promise<void> {
|
||||
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.signers.length === 0 || document.signers.some((signer) => signer.status !== "signed")) return null;
|
||||
return document;
|
||||
});
|
||||
if (!snapshot) 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,
|
||||
},
|
||||
});
|
||||
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],
|
||||
});
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await tx.projektSignatureDocument.update({
|
||||
where: { id: snapshot.id },
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
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 },
|
||||
});
|
||||
});
|
||||
await logSignatureActivity({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.actorUserId,
|
||||
projectId: snapshot.projektId,
|
||||
documentId: snapshot.id,
|
||||
summaryText: "Signatur-Dokument wurde abgeschlossen.",
|
||||
});
|
||||
}
|
||||
|
||||
export async function recordSignatureLinkOpened(input: { token: string; ipAddress?: string | null; userAgent?: string | null }) {
|
||||
const tokenHash = hashSecret(input.token);
|
||||
const tenantId = await loadSignerTenantIdByTokenHash(tokenHash);
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const signer = await tx.projektSignatureSigner.findUnique({
|
||||
where: { accessTokenHash: tokenHash },
|
||||
include: { document: true },
|
||||
});
|
||||
if (!signer || signer.document.archivedAt || signer.document.status === "revoked") 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;
|
||||
}) {
|
||||
const tokenHash = hashSecret(input.token);
|
||||
const tenantId = await loadSignerTenantIdByTokenHash(tokenHash);
|
||||
const result = await withTenantRLS(tenantId, async (tx) => {
|
||||
const signer = await tx.projektSignatureSigner.findUnique({ where: { accessTokenHash: tokenHash }, include: { document: true } });
|
||||
if (!signer || signer.document.archivedAt || signer.document.status === "revoked") throw new CatalogError(foundationErrors.notFound);
|
||||
if (!input.intentAccepted) throw new SignatureServiceError("signature.error.intentRequired");
|
||||
const otp = normalizeText(input.otp);
|
||||
if (!otp || !constantTimeEqualHash(otp, signer.otpHash)) throw new SignatureServiceError("signature.error.otpInvalid");
|
||||
if (signer.otpExpiresAt && signer.otpExpiresAt.getTime() < Date.now()) throw new SignatureServiceError("signature.error.otpExpired");
|
||||
const signatureSvg = normalizeText(input.signatureSvg);
|
||||
if (!signatureSvg) throw new SignatureServiceError("signature.error.signatureRequired");
|
||||
const now = new Date();
|
||||
await tx.projektSignatureSigner.update({
|
||||
where: { id: signer.id },
|
||||
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.",
|
||||
},
|
||||
});
|
||||
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 loadSignerTenantIdByTokenHash(tokenHash: string): Promise<string> {
|
||||
const signer = await db.projektSignatureSigner.findUnique({
|
||||
where: { accessTokenHash: tokenHash },
|
||||
select: { tenantId: true },
|
||||
});
|
||||
if (!signer) throw new CatalogError(foundationErrors.notFound);
|
||||
return signer.tenantId;
|
||||
}
|
||||
|
||||
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 });
|
||||
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 });
|
||||
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,
|
||||
summaryText: "Signatur-Dokument wurde widerrufen.",
|
||||
});
|
||||
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 };
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const document = await tx.projektSignatureDocument.findFirst({
|
||||
where: { tenantId: input.tenantId, provider: SIGNATURE_PROVIDER_PANDADOC, providerDocumentId },
|
||||
});
|
||||
if (!document) return;
|
||||
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 { ok: true };
|
||||
}
|
||||
Reference in new issue
Block a user