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; resolve: () => void } { let resolve!: () => void; const promise = new Promise((done) => { resolve = done; }); return { promise, resolve }; } describe("signature document sealing claim", () => { let sharedStore: SharedStore; let documentStatus: SignatureDocumentStatus; let transaction: ReturnType; 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(); }); });