Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,7 +1,29 @@
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { serializeExportTableToPdf } from "@hivegrid/exports";
import { describe, expect, it } from "vitest";
import { buildRfc3161TimestampRequest } from "./padesSeal.server";
import { buildRfc3161TimestampRequest, readTimestampResponseBytes, sealPdfWithPades } from "./padesSeal.server";
const requireNode = createRequire(import.meta.url);
function createTestPkcs12(passphrase: string): Buffer {
const forge = requireNode("node-forge");
const keys = forge.pki.rsa.generateKeyPair(1024);
const certificate = forge.pki.createCertificate();
certificate.publicKey = keys.publicKey;
certificate.serialNumber = "01";
certificate.validity.notBefore = new Date("2025-01-01T00:00:00.000Z");
certificate.validity.notAfter = new Date("2030-01-01T00:00:00.000Z");
const attributes = [{ name: "commonName", value: "HiveGrid test signer" }];
certificate.setSubject(attributes);
certificate.setIssuer(attributes);
certificate.sign(keys.privateKey, forge.md.sha256.create());
const p12 = forge.pkcs12.toPkcs12Asn1(keys.privateKey, [certificate], passphrase, {
algorithm: "3des",
});
return Buffer.from(forge.asn1.toDer(p12).getBytes(), "binary");
}
describe("buildRfc3161TimestampRequest", () => {
it("builds a DER encoded RFC3161 request for a SHA-256 message imprint", () => {
@@ -14,3 +36,65 @@ describe("buildRfc3161TimestampRequest", () => {
expect(request.includes(digest)).toBe(true);
});
});
describe("readTimestampResponseBytes", () => {
it("bounds both declared and actual response bytes", async () => {
const valid = new Response(new Uint8Array([1, 2, 3]), { headers: { "content-length": "3" } });
await expect(readTimestampResponseBytes(valid, 3)).resolves.toEqual(new Uint8Array([1, 2, 3]));
const declaredTooLarge = new Response(new Uint8Array([1]), { headers: { "content-length": "4" } });
await expect(readTimestampResponseBytes(declaredTooLarge, 3)).rejects.toThrow("size limit");
const understated = new Response(new Uint8Array([1, 2, 3, 4]), { headers: { "content-length": "2" } });
await expect(readTimestampResponseBytes(understated, 3)).rejects.toThrow("size limit");
});
});
describe("sealPdfWithPades", () => {
it("signs a generated PDF with the supported PKCS#12 and PDF dependency graph", async () => {
const passphrase = "test-passphrase";
const original = {
p12: process.env.SIGNATURE_P12_BASE64,
passphrase: process.env.SIGNATURE_P12_PASSPHRASE,
requirePades: process.env.SIGNATURE_REQUIRE_PADES,
tsaUrl: process.env.SIGNATURE_TSA_URL,
};
process.env.SIGNATURE_P12_BASE64 = createTestPkcs12(passphrase).toString("base64");
process.env.SIGNATURE_P12_PASSPHRASE = passphrase;
process.env.SIGNATURE_REQUIRE_PADES = "true";
delete process.env.SIGNATURE_TSA_URL;
try {
const pdfBytes = await serializeExportTableToPdf(
{ columns: [{ key: "value", label: "Value" }], rows: [{ value: "signed" }] },
{ title: "Dependency compatibility" },
);
const result = await sealPdfWithPades({
pdfBytes,
title: "Dependency compatibility",
signerName: "HiveGrid test signer",
contactInfo: "security@example.invalid",
location: "Test",
reason: "Dependency compatibility",
signingTime: new Date("2026-01-01T00:00:00.000Z"),
});
const signedPdf = Buffer.from(result.bytes).toString("latin1");
expect(result.mode).toBe("pades_cades_detached");
expect(result.certificateConfigured).toBe(true);
expect(result.bytes.byteLength).toBeGreaterThan(pdfBytes.byteLength);
expect(signedPdf).toContain("/ByteRange");
expect(signedPdf).toContain("/SubFilter /ETSI.CAdES.detached");
} finally {
for (const [key, value] of Object.entries({
SIGNATURE_P12_BASE64: original.p12,
SIGNATURE_P12_PASSPHRASE: original.passphrase,
SIGNATURE_REQUIRE_PADES: original.requirePades,
SIGNATURE_TSA_URL: original.tsaUrl,
})) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
});
});
@@ -7,6 +7,8 @@ import { SignPdf } from "@signpdf/signpdf";
const requireNode = createRequire(import.meta.url);
const SUBFILTER_ETSI_CADES_DETACHED = "ETSI.CAdES.detached";
export const TSA_RESPONSE_MAX_BYTES = 1024 * 1024;
export const TSA_REQUEST_TIMEOUT_MS = 10_000;
export type PadesSealResult = {
readonly bytes: Uint8Array;
@@ -93,6 +95,40 @@ export function buildRfc3161TimestampRequest(messageHash: Uint8Array, nonce: Uin
return Buffer.from(asn1.toDer(request).getBytes(), "binary");
}
export async function readTimestampResponseBytes(response: Response, maxBytes = TSA_RESPONSE_MAX_BYTES): Promise<Uint8Array> {
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
throw new TypeError("Timestamp response limit must be a positive safe integer.");
}
const contentLength = response.headers.get("content-length");
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
await response.body?.cancel().catch(() => undefined);
throw new Error("TSA response exceeds the configured size limit.");
}
if (!response.body) return new Uint8Array();
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let totalBytes = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
totalBytes += chunk.value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel().catch(() => undefined);
throw new Error("TSA response exceeds the configured size limit.");
}
chunks.push(chunk.value);
}
const bytes = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return bytes;
}
async function requestTimestampToken(input: { tsaUrl: string; authorizationHeader?: string; pdfBytes: Uint8Array }) {
const messageHash = createHash("sha256").update(input.pdfBytes).digest();
const requestBody = buildRfc3161TimestampRequest(messageHash);
@@ -105,11 +141,13 @@ async function requestTimestampToken(input: { tsaUrl: string; authorizationHeade
...(input.authorizationHeader ? { Authorization: input.authorizationHeader } : {}),
},
body: requestArrayBuffer,
redirect: "error",
signal: AbortSignal.timeout(TSA_REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`TSA request failed with status ${response.status}`);
}
const responseBytes = new Uint8Array(await response.arrayBuffer());
const responseBytes = await readTimestampResponseBytes(response);
return {
url: input.tsaUrl,
requestSha256: sha256Hex(requestBody),
@@ -0,0 +1,23 @@
// @vitest-environment node
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const SOURCE = readFileSync("apps/web/app/modules/signature/services/signatureService.server.ts", "utf8");
describe("signature activity i18n contract", () => {
it("persists semantic keys for every machine-authored signature summary", () => {
const summaries = [...SOURCE.matchAll(/summaryKey:\s*"([^"]+)"/gu)].map((match) => match[1]);
expect(summaries).toEqual(
expect.arrayContaining([
"activity.runtime.signature.documentPrepared",
"activity.runtime.signature.documentSent",
"activity.runtime.signature.documentCompleted",
"activity.runtime.signature.documentRevoked",
"activity.runtime.signature.providerCompleted",
]),
);
expect(summaries.every((summary) => summary.startsWith("activity.runtime.signature."))).toBe(true);
});
});
@@ -0,0 +1,44 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
import {
__resetSignatureOtpRateLimitStoreForTests,
__setSignatureOtpRateLimitStoreForTests,
reserveSignatureOtpAttempt,
} from "./signature-otp-rate-limit.server";
describe("signature OTP rate limit", () => {
beforeEach(() => {
__setSignatureOtpRateLimitStoreForTests(createSharedStore({ namespace: "signature-otp-test", adapter: new MemoryAdapter() }));
});
afterEach(() => {
__resetSignatureOtpRateLimitStoreForTests();
});
it("blocks the sixth attempt for the same signing token", async () => {
for (let attempt = 0; attempt < 5; attempt += 1) {
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" })).resolves.toMatchObject({ allowed: true });
}
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 1800,
});
});
it("keeps the authoritative attempt budget isolated per token", async () => {
for (let attempt = 0; attempt < 5; attempt += 1) {
await reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" });
}
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-b", trustedClientIp: "203.0.113.10" })).resolves.toMatchObject({ allowed: true });
});
it("propagates shared-store failures so callers fail closed", async () => {
const adapter = new MemoryAdapter();
await adapter.close();
__setSignatureOtpRateLimitStoreForTests(createSharedStore({ namespace: "signature-otp-closed", adapter }));
await expect(reserveSignatureOtpAttempt({ tokenHash: "token-a", trustedClientIp: "203.0.113.10" })).rejects.toThrow(/closed/i);
});
});
@@ -0,0 +1,76 @@
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
const TOKEN_ATTEMPT_LIMIT = 5;
const TOKEN_WINDOW_SECONDS = 30 * 60;
const IP_ATTEMPT_LIMIT = 30;
const IP_WINDOW_SECONDS = 15 * 60;
type Limiters = {
readonly perToken: FixedWindowRateLimiter;
readonly perIp: FixedWindowRateLimiter;
};
export type SignatureOtpRateLimitDecision =
| { readonly allowed: true; readonly remaining: number }
| { readonly allowed: false; readonly retryAfterSeconds: number };
let cached: Limiters | null = null;
let storeFactory: () => SharedStore = () => getSharedStore();
function getLimiters(): Limiters {
if (cached) return cached;
const store = storeFactory();
cached = {
perToken: createFixedWindowRateLimiter({
store,
prefix: "signature-otp-token",
max: TOKEN_ATTEMPT_LIMIT,
windowSeconds: TOKEN_WINDOW_SECONDS,
}),
perIp: createFixedWindowRateLimiter({
store,
prefix: "signature-otp-ip",
max: IP_ATTEMPT_LIMIT,
windowSeconds: IP_WINDOW_SECONDS,
}),
};
return cached;
}
/**
* Reserves an OTP attempt before verification. The token bucket is the
* authoritative brute-force bound; the trusted-IP bucket additionally slows
* broad attacks across many leaked links. Store failures propagate so the
* signing endpoint fails closed instead of silently losing its protection.
*/
export async function reserveSignatureOtpAttempt(input: {
readonly tokenHash: string;
readonly trustedClientIp: string;
}): Promise<SignatureOtpRateLimitDecision> {
const { perToken, perIp } = getLimiters();
const tokenDecision = await perToken.consume(input.tokenHash);
if (!tokenDecision.allowed) {
return { allowed: false, retryAfterSeconds: TOKEN_WINDOW_SECONDS };
}
const ipDecision = await perIp.consume(input.trustedClientIp);
if (!ipDecision.allowed) {
return { allowed: false, retryAfterSeconds: IP_WINDOW_SECONDS };
}
return {
allowed: true,
remaining: Math.min(tokenDecision.remaining, ipDecision.remaining),
};
}
export function __setSignatureOtpRateLimitStoreForTests(store: SharedStore): void {
cached = null;
storeFactory = () => store;
}
export function __resetSignatureOtpRateLimitStoreForTests(): void {
cached = null;
storeFactory = () => getSharedStore();
}
@@ -0,0 +1,13 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
describe("public signature RLS bootstrap", () => {
it("uses the narrow resolver and re-reads the exact signer in tenant context", () => {
const source = readFileSync(resolveRepoPath("apps/web/app/modules/signature/services/signatureService.server.ts"), "utf8");
expect(source).toContain("resolveSignatureSignerRlsIdentity(tokenHash)");
expect(source).toContain("id: identity.resourceId, tenantId: identity.tenantId, accessTokenHash: tokenHash");
expect(source).not.toContain("loadSignerTenantIdByTokenHash");
});
});
@@ -0,0 +1,227 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createIdempotencyStore, createSharedStore, MemoryAdapter, type IdempotencyStore, type SharedStore } from "@hivegrid/shared-store";
const mocks = vi.hoisted(() => ({
buildPdfExportArtifact: vi.fn(),
deleteStoredFile: vi.fn(async () => undefined),
ensureServerGlobalI18n: vi.fn(async () => undefined),
linkFile: vi.fn(async () => undefined),
logActivity: vi.fn(async () => undefined),
putBufferAsFile: vi.fn(async () => undefined),
sealPdfWithPades: vi.fn(),
withTenantRLS: vi.fn(),
withStorageReservation: vi.fn(),
}));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
vi.mock("@hivegrid/exports/pdf", () => ({ buildPdfExportArtifact: mocks.buildPdfExportArtifact }));
vi.mock("@hivegrid/db/storage-capacity.server", () => ({
withTenantStorageWriteReservation: (...args: unknown[]) => mocks.withStorageReservation(...args),
}));
vi.mock("~/locale/i18next.global.server", () => ({ ensureServerGlobalI18n: mocks.ensureServerGlobalI18n }));
vi.mock("~/locale/request-scoped-t", () => ({ requestScopedT: (key: string) => key }));
vi.mock("~/shared-store.server", () => ({
getSharedStore: vi.fn(() => {
throw new Error("Unexpected singleton access in test");
}),
}));
vi.mock("~/utils/db.server", () => ({ db: {} }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
vi.mock("~/utils/integrations/fileService.server", () => ({
getVisibleFileOrThrow: vi.fn(),
linkFile: mocks.linkFile,
listFilesForBrowser: vi.fn(),
}));
vi.mock("~/utils/integrations/storageService", () => ({
deleteFile: mocks.deleteStoredFile,
putBufferAsFile: mocks.putBufferAsFile,
resolveStorageBucket: () => "signature-test-bucket",
}));
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: vi.fn() }));
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({ queueTransactionalEmail: vi.fn() }));
vi.mock("./padesSeal.server", () => ({ sealPdfWithPades: mocks.sealPdfWithPades }));
vi.mock("./signature-otp-rate-limit.server", () => ({ reserveSignatureOtpAttempt: vi.fn() }));
import {
__resetSignatureSealingClaimStoreForTests,
__sealDocumentIfCompleteForTests,
__setSignatureSealingClaimStoreForTests,
} from "./signatureService.server";
type SignatureDocumentStatus = "sent" | "signed";
function createDeferred(): { promise: Promise<void>; resolve: () => void } {
let resolve!: () => void;
const promise = new Promise<void>((done) => {
resolve = done;
});
return { promise, resolve };
}
describe("signature document sealing claim", () => {
let sharedStore: SharedStore;
let documentStatus: SignatureDocumentStatus;
let transaction: ReturnType<typeof createTransaction>;
function createTransaction() {
const snapshot = {
id: "document_1",
tenantId: "tenant_1",
projektId: "project_1",
createdByUserId: "creator_1",
title: "Abnahmeprotokoll",
documentHashSha256: "source-hash",
status: documentStatus,
signers: [
{
id: "signer_1",
signerName: "Erika Muster",
signerEmail: "erika@example.test",
status: "signed",
signedAt: new Date("2026-07-13T10:00:00.000Z"),
signingOrder: 0,
createdAt: new Date("2026-07-13T09:00:00.000Z"),
},
],
};
return {
projektSignatureDocument: {
findFirst: vi.fn(async (args: { select?: { status?: boolean } }) =>
args.select?.status ? { status: documentStatus } : { ...snapshot, status: documentStatus }
),
updateMany: vi.fn(async () => {
if (documentStatus !== "sent") return { count: 0 };
documentStatus = "signed";
return { count: 1 };
}),
},
file: {
create: vi.fn(async () => undefined),
deleteMany: vi.fn(async () => ({ count: 1 })),
},
signatureEvent: {
create: vi.fn(async () => undefined),
},
};
}
beforeEach(() => {
vi.clearAllMocks();
documentStatus = "sent";
transaction = createTransaction();
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (tx: typeof transaction) => unknown) => callback(transaction));
mocks.withStorageReservation.mockImplementation(async (input) => {
const stored = await input.upload();
return input.runTransaction((tx) => input.commit(tx, stored));
});
mocks.buildPdfExportArtifact.mockResolvedValue({
bytes: new Uint8Array([1, 2, 3]),
contentType: "application/pdf",
});
mocks.sealPdfWithPades.mockResolvedValue({
bytes: new Uint8Array([4, 5, 6]),
mode: "unsigned_dev_fallback",
signedPdfSha256: "signed-hash",
certificateConfigured: false,
tsa: null,
});
sharedStore = createSharedStore({ namespace: "signature-sealing-test", adapter: new MemoryAdapter() });
__setSignatureSealingClaimStoreForTests(createIdempotencyStore({ store: sharedStore, prefix: "test-seal", ttlSeconds: 60 }));
});
afterEach(async () => {
__resetSignatureSealingClaimStoreForTests();
await sharedStore.close();
});
it("lets only the first parallel claimant generate and finalize artifacts", async () => {
const firstBuildStarted = createDeferred();
const releaseFirstBuild = createDeferred();
mocks.buildPdfExportArtifact.mockImplementationOnce(async () => {
firstBuildStarted.resolve();
await releaseFirstBuild.promise;
return { bytes: new Uint8Array([1, 2, 3]), contentType: "application/pdf" };
});
const input = { tenantId: "tenant_1", documentId: "document_1", actorUserId: null };
const first = __sealDocumentIfCompleteForTests(input);
await firstBuildStarted.promise;
await expect(__sealDocumentIfCompleteForTests(input)).resolves.toBeUndefined();
expect(mocks.buildPdfExportArtifact).toHaveBeenCalledTimes(1);
expect(mocks.putBufferAsFile).not.toHaveBeenCalled();
releaseFirstBuild.resolve();
await first;
expect(mocks.buildPdfExportArtifact).toHaveBeenCalledTimes(2);
expect(mocks.putBufferAsFile).toHaveBeenCalledTimes(2);
expect(transaction.file.create).toHaveBeenCalledTimes(2);
expect(transaction.projektSignatureDocument.updateMany).toHaveBeenCalledTimes(1);
expect(transaction.projektSignatureDocument.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
id: "document_1",
tenantId: "tenant_1",
status: { in: ["sent", "viewed"] },
signedPdfFileId: null,
completionCertFileId: null,
}),
})
);
expect(transaction.signatureEvent.create).toHaveBeenCalledTimes(2);
expect(mocks.logActivity).toHaveBeenCalledTimes(1);
expect(documentStatus).toBe("signed");
});
it("returns an already signed document without generating new artifacts", async () => {
documentStatus = "signed";
await expect(__sealDocumentIfCompleteForTests({ tenantId: "tenant_1", documentId: "document_1", actorUserId: null })).resolves.toBeUndefined();
expect(mocks.buildPdfExportArtifact).not.toHaveBeenCalled();
expect(mocks.putBufferAsFile).not.toHaveBeenCalled();
expect(transaction.file.create).not.toHaveBeenCalled();
expect(transaction.projektSignatureDocument.updateMany).not.toHaveBeenCalled();
expect(transaction.signatureEvent.create).not.toHaveBeenCalled();
});
it("cleans a partial artifact and releases the claim so sealing can retry", async () => {
let buildCall = 0;
mocks.buildPdfExportArtifact.mockImplementation(async () => {
buildCall += 1;
if (buildCall === 2) throw new Error("certificate generation failed");
return { bytes: new Uint8Array([1, 2, 3]), contentType: "application/pdf" };
});
const input = { tenantId: "tenant_1", documentId: "document_1", actorUserId: null };
await expect(__sealDocumentIfCompleteForTests(input)).rejects.toThrow("certificate generation failed");
expect(transaction.file.deleteMany).toHaveBeenCalledTimes(1);
expect(mocks.deleteStoredFile).toHaveBeenCalledTimes(1);
expect(documentStatus).toBe("sent");
await expect(__sealDocumentIfCompleteForTests(input)).resolves.toBeUndefined();
expect(transaction.projektSignatureDocument.updateMany).toHaveBeenCalledTimes(1);
expect(transaction.signatureEvent.create).toHaveBeenCalledTimes(2);
expect(documentStatus).toBe("signed");
});
it("fails closed before artifact generation when the shared claim is unavailable", async () => {
const unavailableClaims: IdempotencyStore = {
claim: vi.fn(async () => {
throw new Error("shared store unavailable");
}),
complete: vi.fn(async () => undefined),
get: vi.fn(async () => null),
forget: vi.fn(async () => undefined),
};
__setSignatureSealingClaimStoreForTests(unavailableClaims);
await expect(__sealDocumentIfCompleteForTests({ tenantId: "tenant_1", documentId: "document_1", actorUserId: null })).rejects.toMatchObject({
status: 503,
messageKey: "signature.error.rateLimitUnavailable",
});
expect(mocks.buildPdfExportArtifact).not.toHaveBeenCalled();
expect(mocks.putBufferAsFile).not.toHaveBeenCalled();
expect(transaction.file.create).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,30 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
import { normalizeSignatureSvg, SignatureServiceError } from "./signatureService.server";
describe("signature payload security", () => {
it("removes scriptable SVG elements and event handlers before persistence", () => {
const sanitized = normalizeSignatureSvg('<svg onload="alert(1)"><script>alert(1)</script><foreignObject>bad</foreignObject><path d="M0 0" /></svg>');
expect(sanitized).toContain("<svg");
expect(sanitized).toContain("<path");
expect(sanitized).not.toMatch(/script|foreignObject|onload/iu);
});
it("rejects non-SVG and oversized signature payloads", () => {
expect(() => normalizeSignatureSvg("plain text")).toThrowError(
expect.objectContaining<Partial<SignatureServiceError>>({ messageKey: "signature.error.signatureInvalid" })
);
expect(() => normalizeSignatureSvg(`<svg>${"x".repeat(65 * 1024)}</svg>`)).toThrowError(
expect.objectContaining<Partial<SignatureServiceError>>({ messageKey: "signature.error.signatureInvalid" })
);
});
it("gives generated signature artifacts the narrow own-file scope needed for linking", () => {
const source = readFileSync(resolveRepoPath("apps/web/app/modules/signature/services/signatureService.server.ts"), "utf8");
expect(source).toContain('permissions: ["files.read_own", "projects.read_all", "signature.read"]');
});
});
@@ -1,8 +1,10 @@
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
import i18next from "i18next";
import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { buildFileStorageKeys } from "@hivegrid/storage";
import { buildPdfExportArtifact } from "@hivegrid/exports/pdf";
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,
@@ -10,25 +12,36 @@ import {
signatureProviderKey,
signatureSignerStatusKey,
type ProjectSignatureDocumentRow,
type ProjectSignatureKontaktSuggestion,
type ProjectSignaturePanelVM,
type ProjectSignaturePdfFileOption,
type SignatureSignerRole,
} from "@hivegrid/view-models";
import { ensureServerGlobalI18n } from "~/locale/i18next.global.server";
import { db } from "~/utils/db.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 { linkFile, getVisibleFileOrThrow } from "~/utils/integrations/fileService.server";
import { putBufferAsFile, resolveStorageBucket } from "~/utils/integrations/storageService";
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;
constructor(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;
}
}
@@ -53,6 +66,27 @@ 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);
@@ -70,10 +104,6 @@ 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);
}
@@ -119,7 +149,20 @@ function createAccessToken(): string {
function createOtp(): string {
const max = 10 ** OTP_DIGITS;
return String(Number.parseInt(randomBytes(4).toString("hex"), 16) % max).padStart(OTP_DIGITS, "0");
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 {
@@ -150,17 +193,25 @@ export function parseSignatureSigners(text: string | null | undefined): ParsedSi
});
}
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 } });
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 });
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 {
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,
@@ -171,6 +222,9 @@ function toDocumentRow(row: any): ProjectSignatureDocumentRow {
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),
@@ -199,23 +253,70 @@ export async function loadProjectSignaturePanel(input: {
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) => {
const canSend = canSendSignatures(input.ctx);
const { rows, kontaktSuggestions } = await withTenantRLS(input.tenantId, async (tx) => {
await requireVisibleProjectWithTx(tx, input);
return tx.projektSignatureDocument.findMany({
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(toDocumentRow),
rows: rows.map((row) => toDocumentRow(row, input.tenantSlug)),
pdfFileOptions,
kontaktSuggestions,
canRead: true,
canSend: canSendSignatures(input.ctx),
canSend,
canRevoke: canRevokeSignatures(input.ctx),
canAdmin: hasPermission(input.ctx, "signature.admin"),
});
}
async function loadKontaktSuggestionsWithTx(tx: TenantRlsClient, tenantId: string, projectId: string): Promise<ProjectSignatureKontaktSuggestion[]> {
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<string>();
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<ProjectSignaturePdfFileOption[]> {
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 },
@@ -284,7 +385,7 @@ export async function createSignatureDraft(input: {
if (sourceFile.mimeType !== "application/pdf") throw new SignatureServiceError("signature.error.sourcePdfRequired");
const document = await withTenantRLS(input.tenantId, async (tx) => {
await requireVisibleProjectWithTx(tx, input);
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({
@@ -327,6 +428,7 @@ export async function createSignatureDraft(input: {
entityType: "signature_document",
entityId: document.id,
linkRole: "source_pdf",
ctx: signatureProjectContext(input.ctx),
}).catch(() => undefined);
await linkFile({
tenantId: input.tenantId,
@@ -335,13 +437,14 @@ export async function createSignatureDraft(input: {
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,
summaryText: "Signatur-Dokument wurde vorbereitet.",
summaryKey: "activity.runtime.signature.documentPrepared",
});
return toDocumentRow(document);
}
@@ -361,7 +464,12 @@ export async function sendSignatureDocument(input: {
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 });
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<SendSignatureDocumentResult["signerLinks"][number]> = [];
@@ -405,15 +513,24 @@ export async function sendSignatureDocument(input: {
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("");
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: i18next.t("signature.email.subject"),
body,
subject,
body: rendered.html,
text: rendered.text,
alias: "signature-otp",
tenantId: input.tenantId,
userId: input.userId,
@@ -427,7 +544,7 @@ export async function sendSignatureDocument(input: {
actorUserId: input.userId,
projectId,
documentId: input.documentId,
summaryText: "Signatur-Dokument wurde versendet.",
summaryKey: "activity.runtime.signature.documentSent",
});
return { documentId: input.documentId, signerLinks };
}
@@ -445,7 +562,7 @@ async function logSignatureActivity(input: {
actorUserId: string | null;
projectId: string;
documentId: string;
summaryText: string;
summaryKey: string;
}): Promise<void> {
await logActivity({
tenantId: input.tenantId,
@@ -454,11 +571,26 @@ async function logSignatureActivity(input: {
activityType: "project_signature_changed",
subjectType: "project",
subjectId: input.projectId,
summaryText: input.summaryText,
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<void> {
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;
@@ -474,13 +606,14 @@ async function storeGeneratedSignaturePdf(input: {
reason: string;
signingTime: Date;
};
}): Promise<{ fileId: string; sha256: string; seal: PadesSealResult | null }> {
}): Promise<GeneratedSignatureArtifact> {
await ensureServerGlobalI18n();
const { buildPdfExportArtifact } = await import("@hivegrid/exports/pdf");
const pdf = await buildPdfExportArtifact(
{
columns: [
{ key: "field", label: i18next.t("signature.certificate.columns.field") },
{ key: "value", label: i18next.t("signature.certificate.columns.value") },
{ key: "field", label: i18nT("signature.certificate.columns.field") },
{ key: "value", label: i18nT("signature.certificate.columns.value") },
],
rows: input.rows,
},
@@ -501,24 +634,62 @@ async function storeGeneratedSignaturePdf(input: {
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,
const bucket = resolveStorageBucket();
try {
await withTenantStorageWriteReservation({
reservation: {
tenantId: input.tenantId,
createdByUserId: input.userId,
displayName: input.displayName.slice(0, 255),
actorUserId: input.userId,
targetFileId: fileId,
originalFilename: 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",
},
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,
@@ -526,6 +697,7 @@ async function storeGeneratedSignaturePdf(input: {
entityType: "signature_document",
entityId: input.documentId,
linkRole: input.artifactKind,
ctx: linkContext,
}).catch(() => undefined);
await linkFile({
tenantId: input.tenantId,
@@ -534,124 +706,222 @@ async function storeGeneratedSignaturePdf(input: {
entityType: "project",
entityId: input.projectId,
linkRole: `signature_${input.artifactKind}`,
ctx: linkContext,
}).catch(() => undefined);
return { fileId, sha256: seal?.signedPdfSha256 ?? hashSecret(Buffer.from(bytes).toString("base64")), seal };
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<void> {
const snapshot = await withTenantRLS(input.tenantId, async (tx) => {
const document = await tx.projektSignatureDocument.findFirst({
const current = await withTenantRLS(input.tenantId, (tx) =>
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;
select: { status: true },
})
);
if (!current || current.status === "signed" || ["declined", "revoked", "expired"].includes(current.status)) 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,
},
},
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,
},
});
await addSignatureEventWithTx(tx, {
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,
eventType: "pdf_sealed",
actorUserId: input.actorUserId,
metadata: { signedPdfFileId: signedPdf.fileId },
displayName: `${snapshot.title}-completion-certificate.pdf`,
artifactKind: "completion_certificate",
rows: [...rows, ...sealRows],
});
await addSignatureEventWithTx(tx, {
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,
documentId: snapshot.id,
eventType: "certificate_created",
actorUserId: input.actorUserId,
metadata: { completionCertFileId: certificate.fileId },
projectId: snapshot.projektId,
documentId: snapshot.id,
summaryKey: "activity.runtime.signature.documentCompleted",
});
});
await logSignatureActivity({
tenantId: input.tenantId,
actorUserId: input.actorUserId,
projectId: snapshot.projektId,
documentId: snapshot.id,
summaryText: "Signatur-Dokument wurde abgeschlossen.",
});
} 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<void> {
return sealDocumentIfComplete(input);
}
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 },
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") throw new CatalogError(foundationErrors.notFound);
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({
@@ -695,21 +965,60 @@ export async function signWithOtp(input: {
intentAccepted: boolean;
ipAddress?: string | null;
userAgent?: string | null;
trustedClientIp?: 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);
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 (!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");
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();
await tx.projektSignatureSigner.update({
where: { id: signer.id },
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,
@@ -721,6 +1030,7 @@ export async function signWithOtp(input: {
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,
@@ -743,13 +1053,10 @@ export async function signWithOtp(input: {
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;
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 }) {
@@ -758,7 +1065,12 @@ export async function remindSignatureSigner(input: { tenantId: string; signerId:
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 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,
@@ -777,7 +1089,12 @@ export async function revokeSignatureDocument(input: { tenantId: string; documen
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 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() },
@@ -791,7 +1108,7 @@ export async function revokeSignatureDocument(input: { tenantId: string; documen
actorUserId: input.userId,
projectId: document.projektId,
documentId: document.id,
summaryText: "Signatur-Dokument wurde widerrufen.",
summaryKey: "activity.runtime.signature.documentRevoked",
});
return { ok: true };
}
@@ -801,11 +1118,11 @@ export async function handlePandaDocWebhook(input: { tenantId: string; rawBody:
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 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;
if (!document) return null;
await addSignatureEventWithTx(tx, {
tenantId: input.tenantId,
documentId: document.id,
@@ -815,7 +1132,20 @@ export async function handlePandaDocWebhook(input: { tenantId: string; rawBody:
});
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 };
}