Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(verify): match deleted envelopes via envelope_deleted audit records (#218)
Kevin Rose3c6b90a7cfa8
diff --git a/src/components/verify/verify-form.tsx b/src/components/verify/verify-form.tsxindex 179e3cb..6f87b0a 100644--- a/src/components/verify/verify-form.tsx+++ b/src/components/verify/verify-form.tsx@@ -2,30 +2,7 @@import { useState, type ChangeEvent } from "react";-type VerifyAnswer =- | { match: false }- | {- envelopeId: string;- fileKind: "signed-document" | "certificate";- finishedAt: number | null;- match: true;- approverCount?: number;- signerCount: number;- status: "completed" | "declined" | "voided";- title: string;- };--const dateFormatter = new Intl.DateTimeFormat("en-US", {- dateStyle: "long",- timeStyle: "short",- timeZone: "UTC",-});--const STATUS_WORDS = {- completed: "completed",- declined: "declined",- voided: "voided",-} as const;+import { formatVerifyVerdict, type VerifyResult } from "@/lib/verify-result";async function sha256OfFile(file: File): Promise<string> {const digest = await crypto.subtle.digest(@@ -41,10 +18,12 @@ async function sha256OfFile(file: File): Promise<string> {export function VerifyForm() {const [fileName, setFileName] = useState<string | null>(null);const [hash, setHash] = useState<string | null>(null);- const [answer, setAnswer] = useState<VerifyAnswer | null>(null);+ const [answer, setAnswer] = useState<VerifyResult | null>(null);const [error, setError] = useState<string | null>(null);const [isChecking, setIsChecking] = useState(false);+ const verdict = answer ? formatVerifyVerdict(answer) : null;+async function handleFile(event: ChangeEvent<HTMLInputElement>) {const file = event.target.files?.[0];@@ -71,9 +50,9 @@ export function VerifyForm() {method: "POST",});const payload = (await response.json().catch(() => null)) as- (VerifyAnswer & { error?: string }) | null;+ (VerifyResult & { error?: string }) | null;- if (!response.ok || !payload) {+ if (!response.ok || !payload || typeof payload.match !== "boolean") {setError(payload?.error ?? "The file could not be checked right now.");return;}@@ -109,37 +88,24 @@ export function VerifyForm() {<div aria-live="polite" className="space-y-3" role="status">{isChecking ? <p>Checking {fileName}...</p> : null}{error ? <p className="notice notice-danger">{error}</p> : null}- {answer?.match === true ? (- <div className="rounded-2xl bg-(--success-soft) px-5 py-4">- <p className="font-bold text-(--success)">- This file is unchanged. It is the{" "}- {answer.fileKind === "signed-document"- ? "signed document"- : "audit certificate"}{" "}- this site produced for “{answer.title}”.- </p>- <p className="mt-2 text-sm text-(--secondary)">- The envelope was {STATUS_WORDS[answer.status]}- {answer.finishedAt- ? ` on ${dateFormatter.format(new Date(answer.finishedAt * 1000))} UTC`- : ""}{" "}- with {answer.signerCount} signer- {answer.signerCount === 1 ? "" : "s"}- {answer.approverCount- ? ` and ${answer.approverCount} approver${answer.approverCount === 1 ? "" : "s"}`- : ""}- . Envelope ID {answer.envelopeId}.- </p>- </div>- ) : null}- {answer?.match === false ? (- <div className="rounded-2xl bg-(--danger-soft) px-5 py-4">- <p className="font-bold text-(--danger)">No match.</p>- <p className="mt-2 text-sm text-(--secondary)">- This site did not produce this exact file. It may have been- changed, saved again by another program, or come from somewhere- else. Ask the sender for the copy kept on this site.+ {verdict ? (+ <div+ className={`rounded-2xl px-5 py-4 ${+ verdict.tone === "success"+ ? "bg-(--success-soft)"+ : "bg-(--danger-soft)"+ }`}+ >+ <p+ className={`font-bold ${+ verdict.tone === "success"+ ? "text-(--success)"+ : "text-(--danger)"+ }`}+ >+ {verdict.heading}</p>+ <p className="mt-2 text-sm text-(--secondary)">{verdict.detail}</p></div>) : null}{hash ? (diff --git a/src/lib/verify-result.ts b/src/lib/verify-result.tsnew file mode 100644index 0000000..eb59b41--- /dev/null+++ b/src/lib/verify-result.ts@@ -0,0 +1,117 @@+// Shared public result types and verdict formatting for /verify. Kept free of+// database imports so the Verify form can format verdicts directly on the+// client while unit tests cover the exact wording in Node.++export type VerifyFileKind = "signed-document" | "certificate";++export type VerifyEnvelopeStatus = "completed" | "declined" | "voided";++export type VerifyResult =+ | { match: false }+ | {+ /** People who approved or rejected instead of signing. */+ approverCount: number;+ envelopeDeleted: false;+ envelopeId: string;+ fileKind: VerifyFileKind;+ finishedAt: number | null;+ match: true;+ signerCount: number;+ status: VerifyEnvelopeStatus;+ title: string;+ }+ | {+ deletedAt: number | null;+ envelopeDeleted: true;+ envelopeId: string | null;+ fileKind: VerifyFileKind;+ finishedAt: number | null;+ match: true;+ status: VerifyEnvelopeStatus | null;+ title: string | null;+ };++export type VerifyVerdict = {+ detail: string;+ heading: string;+ tone: "danger" | "success";+};++const dateFormatter = new Intl.DateTimeFormat("en-US", {+ dateStyle: "long",+ timeStyle: "short",+ timeZone: "UTC",+});++const STATUS_WORDS: Record<VerifyEnvelopeStatus, string> = {+ completed: "completed",+ declined: "declined",+ voided: "voided",+};++function formatUtcTimestamp(timestamp: number): string {+ return `${dateFormatter.format(new Date(timestamp * 1000))} UTC`;+}++export function formatVerifyVerdict(result: VerifyResult): VerifyVerdict {+ if (!result.match) {+ return {+ detail:+ "This site has no record of this exact file. It may be an unsigned copy, have been changed or saved again by another program, come from somewhere else, or belong to a record that has been removed. Check the digital seal in a PDF reader, or ask the sender for their copy.",+ heading: "No match.",+ tone: "danger",+ };+ }++ const fileLabel =+ result.fileKind === "signed-document"+ ? "signed document"+ : "audit certificate";++ if (result.envelopeDeleted) {+ const heading = result.title+ ? `This file is unchanged. It is the ${fileLabel} this site produced for \u201c${result.title}\u201d.`+ : `This file is unchanged. It is the ${fileLabel} this site produced.`;+ const details: string[] = [];++ if (result.status) {+ details.push(+ `The envelope was ${STATUS_WORDS[result.status]}${+ result.finishedAt !== null+ ? ` on ${formatUtcTimestamp(result.finishedAt)}`+ : ""+ }.`,+ );+ }++ details.push(+ result.deletedAt !== null+ ? `Its record and files were deleted from this site on ${formatUtcTimestamp(result.deletedAt)}.`+ : "Its record and files have since been deleted from this site.",+ );++ if (result.envelopeId) {+ details.push(`Envelope ID ${result.envelopeId}.`);+ }++ return {+ detail: details.join(" "),+ heading,+ tone: "success",+ };+ }++ return {+ detail: `The envelope was ${STATUS_WORDS[result.status]}${+ result.finishedAt !== null+ ? ` on ${formatUtcTimestamp(result.finishedAt)}`+ : ""+ } with ${result.signerCount} signer${result.signerCount === 1 ? "" : "s"}${+ result.approverCount+ ? ` and ${result.approverCount} approver${result.approverCount === 1 ? "" : "s"}`+ : ""+ }. Envelope ID ${result.envelopeId}.`,+ heading: `This file is unchanged. It is the ${fileLabel} this site produced for \u201c${result.title}\u201d.`,+ tone: "success",+ };+}diff --git a/src/lib/verify.dbtest.ts b/src/lib/verify.dbtest.tsnew file mode 100644index 0000000..9a8d165--- /dev/null+++ b/src/lib/verify.dbtest.ts@@ -0,0 +1,349 @@+import assert from "node:assert/strict";+import { randomBytes, randomUUID } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, before, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import {+ deleteScheduledEnvelope,+ ENVELOPE_DELETION_WAIT_DAYS,+ scheduleEnvelopeDeletion,+} from "./envelope-deletion.ts";+import { deleteEnvelopesAndFiles } from "./retention.ts";+import type { EmailService } from "./services/email.ts";+import { getRecipientCertificateKey } from "./services/storage-keys.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import {+ listSystemAuditEvents,+ verifySystemAuditChain,+} from "./services/system-audit.ts";+import { verifyDocumentHash } from "./verify.ts";++// Verifying unchanged signed PDFs and audit certificates before and after an+// administrator's scheduled deletion, against a real Postgres. Run with+// `npm run test:db`.++const DAY = 24 * 60 * 60;+const WAIT = ENVELOPE_DELETION_WAIT_DAYS * DAY;++let database: pg.Pool;+let storageDir: string;+let storageService: StorageService;+const createdUsers: string[] = [];++before(async () => {+ database = await openTestDatabase();+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-verify-"));+ Object.assign(process.env, {+ STORAGE_DRIVER: "local",+ STORAGE_LOCAL_DIR: storageDir,+ });+ storageService = createStorageService();+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();+ await rm(storageDir, { force: true, recursive: true });+});++function randomSha256(): string {+ return randomBytes(32).toString("hex");+}++function createNoopOutbox(): EmailService {+ return {+ async send(message) {+ return { accepted: [message.to], rejected: [] };+ },+ async sendBatch(messages) {+ return Promise.all(messages.map((message) => this.send(message)));+ },+ };+}++async function createUser(role: "admin" | "user") {+ const id = randomUUID();+ const email = `${id}@example.test`;++ createdUsers.push(id);+ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, 'Avery Admin', $2, $3)`,+ [id, email, role],+ );++ return { email, userId: id };+}++async function createFinishedEnvelope(+ userId: string,+ {+ status,+ title = "Lease Agreement",+ }: {+ status: "completed" | "declined" | "voided";+ title?: string;+ },+) {+ const envelopeId = randomUUID();+ const base = `users/${userId}/envelopes/${envelopeId}`;+ const keys = {+ evidence: `${base}/evidence/internal.pdf`,+ signed: `${base}/signed.pdf`,+ source: `${base}/source.pdf`,+ };+ const stored = [+ keys.source,+ keys.evidence,+ getRecipientCertificateKey(keys.evidence),+ ...(status === "completed" ? [keys.signed] : []),+ ];++ for (const key of stored) {+ await storageService.putObject({+ body: new Uint8Array([37, 80, 68, 70]),+ contentType: "application/pdf",+ key,+ });+ }++ const finishedAt = Math.floor(Date.now() / 1000) - 60;+ const sourcePdfHash = randomSha256();+ const signedPdfSha256 = status === "completed" ? randomSha256() : null;+ const evidenceSha256 = randomSha256();+ const recipientEvidenceSha256 = randomSha256();++ await database.query(+ `+ insert into envelopes (+ id, user_id, title, status, source_pdf_key, source_pdf_filename,+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at,+ completed_at, declined_at, voided_at, signed_pdf_key, evidence_key,+ signed_pdf_sha256, evidence_sha256, part11, recipient_evidence_sha256+ ) values (+ $1, $2, $3, $4, $5, 'lease.pdf', 4, 1, $6, $7,+ $8, $9, $10, $11, $12, $13, $14, false, $15+ )+ `,+ [+ envelopeId,+ userId,+ title,+ status,+ keys.source,+ sourcePdfHash,+ finishedAt - 100,+ status === "completed" ? finishedAt : null,+ status === "declined" ? finishedAt : null,+ status === "voided" ? finishedAt : null,+ status === "completed" ? keys.signed : null,+ keys.evidence,+ signedPdfSha256,+ evidenceSha256,+ recipientEvidenceSha256,+ ],+ );+ await database.query(+ `+ insert into signers (id, envelope_id, name, email, sign_order, role, status)+ values ($1, $2, 'Riley Recipient', '[email protected]', 1, 'signer', $3)+ `,+ [randomUUID(), envelopeId, status === "completed" ? "signed" : "declined"],+ );++ return {+ envelopeId,+ evidenceSha256,+ finishedAt,+ recipientEvidenceSha256,+ signedPdfSha256,+ sourcePdfHash,+ title,+ };+}++for (const status of ["completed", "declined", "voided"] as const) {+ test(`unchanged ${status} files still verify after scheduled deletion without leaking private deletion details`, async () => {+ const owner = await createUser("user");+ const admin = await createUser("admin");+ const envelope = await createFinishedEnvelope(owner.userId, { status });+ const now = Math.floor(Date.now() / 1000);++ // Before deletion: live envelope matches, unsigned original and altered files do not.+ if (envelope.signedPdfSha256) {+ assert.deepEqual(+ await verifyDocumentHash(envelope.signedPdfSha256, database),+ {+ approverCount: 0,+ envelopeDeleted: false,+ envelopeId: envelope.envelopeId,+ fileKind: "signed-document",+ finishedAt: envelope.finishedAt,+ match: true,+ signerCount: 1,+ status,+ title: envelope.title,+ },+ );+ }++ assert.deepEqual(+ await verifyDocumentHash(envelope.evidenceSha256, database),+ {+ approverCount: 0,+ envelopeDeleted: false,+ envelopeId: envelope.envelopeId,+ fileKind: "certificate",+ finishedAt: envelope.finishedAt,+ match: true,+ signerCount: 1,+ status,+ title: envelope.title,+ },+ );+ assert.deepEqual(+ await verifyDocumentHash(envelope.recipientEvidenceSha256, database),+ {+ approverCount: 0,+ envelopeDeleted: false,+ envelopeId: envelope.envelopeId,+ fileKind: "certificate",+ finishedAt: envelope.finishedAt,+ match: true,+ signerCount: 1,+ status,+ title: envelope.title,+ },+ );+ assert.deepEqual(+ await verifyDocumentHash(envelope.sourcePdfHash, database),+ { match: false },+ );++ // Schedule and execute deletion.+ await scheduleEnvelopeDeletion(+ envelope.envelopeId,+ {+ actor: admin,+ ipAddress: "203.0.113.10",+ reason: "Confidential HR cleanup",+ userAgent: "Test browser",+ },+ { database, emailService: createNoopOutbox(), now },+ );+ assert.equal(+ await deleteScheduledEnvelope(envelope.envelopeId, {+ database,+ now: now + WAIT,+ storageService,+ }),+ true,+ );++ const [auditEvent] = await listSystemAuditEvents({ limit: 1 }, database);++ assert.equal(auditEvent?.event, "envelope_deleted");+ assert.equal(auditEvent?.metadata?.envelopeId, envelope.envelopeId);+ assert.equal(+ auditEvent?.metadata?.signedPdfSha256,+ envelope.signedPdfSha256,+ );+ assert.equal(auditEvent?.metadata?.evidenceSha256, envelope.evidenceSha256);+ assert.equal(+ auditEvent?.metadata?.recipientEvidenceSha256,+ envelope.recipientEvidenceSha256,+ );+ assert.equal((await verifySystemAuditChain(database)).ok, true);++ // After deletion: signed PDF (if completed) and both certificates match as deleted.+ if (envelope.signedPdfSha256) {+ const signedResult = await verifyDocumentHash(+ envelope.signedPdfSha256,+ database,+ );++ assert.deepEqual(signedResult, {+ deletedAt: auditEvent.createdAt,+ envelopeDeleted: true,+ envelopeId: envelope.envelopeId,+ fileKind: "signed-document",+ finishedAt: envelope.finishedAt,+ match: true,+ status,+ title: envelope.title,+ });++ const serialized = JSON.stringify(signedResult);++ assert.equal(serialized.includes(admin.email), false);+ assert.equal(serialized.includes(owner.email), false);+ assert.equal(serialized.includes("Confidential HR cleanup"), false);+ assert.equal(serialized.includes(envelope.sourcePdfHash), false);+ assert.equal(serialized.includes(envelope.evidenceSha256), false);+ }++ for (const certHash of [+ envelope.evidenceSha256,+ envelope.recipientEvidenceSha256,+ ]) {+ assert.deepEqual(await verifyDocumentHash(certHash, database), {+ deletedAt: auditEvent.createdAt,+ envelopeDeleted: true,+ envelopeId: envelope.envelopeId,+ fileKind: "certificate",+ finishedAt: envelope.finishedAt,+ match: true,+ status,+ title: envelope.title,+ });+ }++ // Unsigned source PDF and tampered/unknown files still return no match.+ assert.deepEqual(+ await verifyDocumentHash(envelope.sourcePdfHash, database),+ { match: false },+ );+ assert.deepEqual(await verifyDocumentHash(randomSha256(), database), {+ match: false,+ });+ });+}++test("envelopes deleted without an envelope_deleted audit event return no match", async () => {+ const owner = await createUser("user");+ const envelope = await createFinishedEnvelope(owner.userId, {+ status: "completed",+ });++ assert.equal(+ await deleteEnvelopesAndFiles(+ [envelope.envelopeId],+ database,+ storageService,+ ),+ 1,+ );+ assert.deepEqual(+ await verifyDocumentHash(envelope.signedPdfSha256 ?? "", database),+ { match: false },+ );+ assert.deepEqual(+ await verifyDocumentHash(envelope.evidenceSha256, database),+ {+ match: false,+ },+ );+ assert.deepEqual(+ await verifyDocumentHash(envelope.recipientEvidenceSha256, database),+ { match: false },+ );+});diff --git a/src/lib/verify.test.ts b/src/lib/verify.test.tsnew file mode 100644index 0000000..ddd34dd--- /dev/null+++ b/src/lib/verify.test.ts@@ -0,0 +1,411 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import type { DbExecutor } from "./db/connection.ts";+import { verifyDocumentHash, verifyRequestSchema } from "./verify.ts";+import { formatVerifyVerdict } from "./verify-result.ts";++const SIGNED_HASH = "1".repeat(64);+const EVIDENCE_HASH = "2".repeat(64);+const RECIPIENT_EVIDENCE_HASH = "3".repeat(64);+const SOURCE_HASH = "4".repeat(64);+const UNKNOWN_HASH = "f".repeat(64);++type RecordedQuery = { text: string; values: readonly unknown[] };++function createMockDb(+ handler: (text: string, values: readonly unknown[]) => unknown[],+): { db: DbExecutor; queries: RecordedQuery[] } {+ const queries: RecordedQuery[] = [];+ const db = {+ async query(text: string, values: readonly unknown[] = []) {+ queries.push({ text, values });+ const rows = handler(text, values);++ return { rowCount: rows.length, rows };+ },+ } as unknown as DbExecutor;++ return { db, queries };+}++test("verifyRequestSchema accepts and normalizes 64-character hex hashes", () => {+ const upper = "ABCDEF0123456789".repeat(4);+ const parsed = verifyRequestSchema.safeParse({ sha256: ` ${upper} ` });++ assert.equal(parsed.success, true);+ assert.equal(parsed.data?.sha256, upper.toLowerCase());++ assert.equal(verifyRequestSchema.safeParse({ sha256: "" }).success, false);+ assert.equal(+ verifyRequestSchema.safeParse({ sha256: "a".repeat(63) }).success,+ false,+ );+ assert.equal(+ verifyRequestSchema.safeParse({ sha256: "g".repeat(64) }).success,+ false,+ );+});++test("verifyDocumentHash rejects non-SHA-256 values without querying the database", async () => {+ const { db, queries } = createMockDb(() => {+ throw new Error("should not query");+ });++ assert.deepEqual(await verifyDocumentHash("", db), { match: false });+ assert.deepEqual(await verifyDocumentHash("not-a-hash", db), {+ match: false,+ });+ assert.equal(queries.length, 0);+});++test("verifyDocumentHash returns a live signed-document match without hitting system_audit_events", async () => {+ const { db, queries } = createMockDb((text) => {+ if (text.includes("FROM envelopes")) {+ return [+ {+ approverCount: 1,+ completedAt: 1_764_000_000,+ declinedAt: null,+ envelopeId: "env-live-1",+ evidenceSha256: EVIDENCE_HASH,+ recipientEvidenceSha256: RECIPIENT_EVIDENCE_HASH,+ signedPdfSha256: SIGNED_HASH,+ signerCount: 2,+ status: "completed",+ title: "Master Services Agreement",+ voidedAt: null,+ },+ ];+ }++ throw new Error("system_audit_events should not be queried for live match");+ });++ const result = await verifyDocumentHash(+ ` ${SIGNED_HASH.toUpperCase()} `,+ db,+ );++ assert.deepEqual(result, {+ approverCount: 1,+ envelopeDeleted: false,+ envelopeId: "env-live-1",+ fileKind: "signed-document",+ finishedAt: 1_764_000_000,+ match: true,+ signerCount: 2,+ status: "completed",+ title: "Master Services Agreement",+ });+ assert.equal(queries.length, 1);+ assert.deepEqual(queries[0]?.values, [SIGNED_HASH]);+});++test("verifyDocumentHash identifies both sender and recipient certificates for live envelopes", async () => {+ for (const hash of [EVIDENCE_HASH, RECIPIENT_EVIDENCE_HASH]) {+ const { db } = createMockDb(() => [+ {+ approverCount: 0,+ completedAt: null,+ declinedAt: 1_764_000_500,+ envelopeId: "env-declined-1",+ evidenceSha256: EVIDENCE_HASH,+ recipientEvidenceSha256: RECIPIENT_EVIDENCE_HASH,+ signedPdfSha256: null,+ signerCount: 1,+ status: "declined",+ title: "NDA",+ voidedAt: null,+ },+ ]);++ const result = await verifyDocumentHash(hash, db);++ assert.deepEqual(result, {+ approverCount: 0,+ envelopeDeleted: false,+ envelopeId: "env-declined-1",+ fileKind: "certificate",+ finishedAt: 1_764_000_500,+ match: true,+ signerCount: 1,+ status: "declined",+ title: "NDA",+ });+ }+});++test("verifyDocumentHash falls back to envelope_deleted audit events for deleted signed PDFs and certificates", async () => {+ const cases = [+ {+ expectedFileKind: "signed-document" as const,+ hash: SIGNED_HASH,+ isSignedDocument: true,+ status: "completed" as const,+ },+ {+ expectedFileKind: "certificate" as const,+ hash: EVIDENCE_HASH,+ isSignedDocument: false,+ status: "completed" as const,+ },+ {+ expectedFileKind: "certificate" as const,+ hash: RECIPIENT_EVIDENCE_HASH,+ isSignedDocument: false,+ status: "declined" as const,+ },+ {+ expectedFileKind: "certificate" as const,+ hash: EVIDENCE_HASH,+ isSignedDocument: false,+ status: "voided" as const,+ },+ ];++ for (const testCase of cases) {+ const { db, queries } = createMockDb((text) => {+ if (text.includes("FROM envelopes")) {+ return [];+ }++ if (text.includes("FROM system_audit_events")) {+ return [+ {+ deletedAt: 1_765_209_600,+ envelopeId: "env-deleted-1",+ finishedAt: 1_764_000_000,+ isSignedDocument: testCase.isSignedDocument,+ status: testCase.status,+ title: "Consulting Agreement",+ },+ ];+ }++ return [];+ });++ const result = await verifyDocumentHash(testCase.hash, db);++ assert.deepEqual(result, {+ deletedAt: 1_765_209_600,+ envelopeDeleted: true,+ envelopeId: "env-deleted-1",+ fileKind: testCase.expectedFileKind,+ finishedAt: 1_764_000_000,+ match: true,+ status: testCase.status,+ title: "Consulting Agreement",+ });+ assert.equal(queries.length, 2);+ assert.deepEqual(queries[1]?.values, [testCase.hash]);+ }+});++test("deleted-envelope lookup never selects PII, admin-only fields, or sourcePdfHash", async () => {+ const { db, queries } = createMockDb((text) => {+ if (text.includes("FROM system_audit_events")) {+ // Simulate extra columns to verify the return object is strictly allowlisted.+ return [+ {+ actorEmail: "[email protected]",+ actorUserId: "admin-1",+ deletedAt: 1_765_209_600,+ envelopeId: "env-deleted-privacy",+ finishedAt: 1_764_000_000,+ isSignedDocument: true,+ ownerEmail: "[email protected]",+ ownerUserId: "user-1",+ part11: true,+ reason: "Sensitive legal settlement",+ requestedAt: 1_764_500_000,+ senderNotifiedAt: 1_764_500_010,+ sourcePdfHash: SOURCE_HASH,+ status: "completed",+ title: "Agreement",+ },+ ];+ }++ return [];+ });++ const result = await verifyDocumentHash(SIGNED_HASH, db);+ const auditSql = queries[1]?.text ?? "";++ assert.match(auditSql, /event = 'envelope_deleted'/);+ assert.match(auditSql, /metadata->>'signedPdfSha256' = \$1/);+ assert.match(auditSql, /metadata->>'evidenceSha256' = \$1/);+ assert.match(auditSql, /metadata->>'recipientEvidenceSha256' = \$1/);+ assert.match(auditSql, /ORDER BY sequence DESC/);++ for (const forbidden of [+ "sourcePdfHash",+ "actor_email",+ "actor_user_id",+ "target_user_id",+ "ip_address",+ "user_agent",+ "ownerEmail",+ "ownerUserId",+ "reason",+ "part11",+ "requestedAt",+ "senderNotifiedAt",+ ]) {+ assert.equal(+ auditSql.includes(forbidden),+ false,+ `SQL must not reference ${forbidden}`,+ );+ }++ assert.deepEqual(Object.keys(result).sort(), [+ "deletedAt",+ "envelopeDeleted",+ "envelopeId",+ "fileKind",+ "finishedAt",+ "match",+ "status",+ "title",+ ]);+ const serialized = JSON.stringify(result);++ assert.equal(serialized.includes("[email protected]"), false);+ assert.equal(serialized.includes("[email protected]"), false);+ assert.equal(serialized.includes("Sensitive legal settlement"), false);+ assert.equal(serialized.includes(SOURCE_HASH), false);+});++test("verifyDocumentHash handles partial or legacy envelope_deleted metadata cleanly", async () => {+ const { db } = createMockDb((text) => {+ if (text.includes("FROM system_audit_events")) {+ return [+ {+ deletedAt: "1765209600",+ envelopeId: " ",+ finishedAt: "not-a-timestamp",+ isSignedDocument: false,+ status: "unexpected",+ title: null,+ },+ ];+ }++ return [];+ });++ const result = await verifyDocumentHash(EVIDENCE_HASH, db);++ assert.deepEqual(result, {+ deletedAt: 1_765_209_600,+ envelopeDeleted: true,+ envelopeId: null,+ fileKind: "certificate",+ finishedAt: null,+ match: true,+ status: null,+ title: null,+ });+});++test("verifyDocumentHash returns match false when neither envelopes nor envelope_deleted matches", async () => {+ const { db, queries } = createMockDb(() => []);++ assert.deepEqual(await verifyDocumentHash(UNKNOWN_HASH, db), {+ match: false,+ });+ assert.equal(queries.length, 2);+});++test("formatVerifyVerdict formats live matches with signer and approver counts", () => {+ const verdict = formatVerifyVerdict({+ approverCount: 2,+ envelopeDeleted: false,+ envelopeId: "env-1",+ fileKind: "signed-document",+ finishedAt: 1_764_000_000,+ match: true,+ signerCount: 1,+ status: "completed",+ title: "Lease",+ });++ assert.equal(verdict.tone, "success");+ assert.equal(+ verdict.heading,+ "This file is unchanged. It is the signed document this site produced for \u201cLease\u201d.",+ );+ assert.match(+ verdict.detail,+ /^The envelope was completed on .+ UTC with 1 signer and 2 approvers\. Envelope ID env-1\.$/,+ );+});++test("formatVerifyVerdict confirms origin and notes deletion for deleted envelopes without false claims", () => {+ const signedVerdict = formatVerifyVerdict({+ deletedAt: 1_765_209_600,+ envelopeDeleted: true,+ envelopeId: "env-deleted-2",+ fileKind: "signed-document",+ finishedAt: 1_764_000_000,+ match: true,+ status: "completed",+ title: "Lease",+ });++ assert.equal(signedVerdict.tone, "success");+ assert.equal(+ signedVerdict.heading,+ "This file is unchanged. It is the signed document this site produced for \u201cLease\u201d.",+ );+ assert.match(signedVerdict.detail, /The envelope was completed on .+ UTC\./);+ assert.match(+ signedVerdict.detail,+ /Its record and files were deleted from this site on .+ UTC\./,+ );+ assert.match(signedVerdict.detail, /Envelope ID env-deleted-2\.$/);+ assert.doesNotMatch(+ signedVerdict.detail,+ /0 signers|kept on this site|did not produce/i,+ );++ const minimalCertVerdict = formatVerifyVerdict({+ deletedAt: null,+ envelopeDeleted: true,+ envelopeId: null,+ fileKind: "certificate",+ finishedAt: null,+ match: true,+ status: null,+ title: null,+ });++ assert.equal(minimalCertVerdict.tone, "success");+ assert.equal(+ minimalCertVerdict.heading,+ "This file is unchanged. It is the audit certificate this site produced.",+ );+ assert.equal(+ minimalCertVerdict.detail,+ "Its record and files have since been deleted from this site.",+ );+});++test("formatVerifyVerdict gives an accurate no-match message without a false negative origin claim", () => {+ const verdict = formatVerifyVerdict({ match: false });++ assert.equal(verdict.tone, "danger");+ assert.equal(verdict.heading, "No match.");+ assert.doesNotMatch(+ verdict.detail,+ /This site did not produce this exact file/i,+ );+ assert.doesNotMatch(verdict.detail, /copy kept on this site/i);+ assert.match(verdict.detail, /no record of this exact file/i);+ assert.match(verdict.detail, /unsigned copy/i);+ assert.match(verdict.detail, /record that has been removed/i);+ assert.match(verdict.detail, /digital seal in a PDF reader/i);+});diff --git a/src/lib/verify.ts b/src/lib/verify.tsindex 95363ff..82c051e 100644--- a/src/lib/verify.ts+++ b/src/lib/verify.ts@@ -1,34 +1,36 @@import { z } from "zod";import { getDb, queryOne, type DbExecutor } from "./db/connection.ts";+import type {+ VerifyEnvelopeStatus,+ VerifyFileKind,+ VerifyResult,+} from "./verify-result.ts";++export type { VerifyEnvelopeStatus, VerifyFileKind, VerifyResult };// The Verify page: anyone holding a copy of a finished document or// certificate can check that it is exactly the file this install produced.// The browser hashes the file; only the hash is sent. A match says nothing// the holder could not already read in the file itself.+//+// When an administrator deletes a finished envelope after the waiting period,+// its row leaves `envelopes` while `system_audit_events` keeps the+// `envelope_deleted` event with the finished file fingerprints. Checking that+// event as a fallback prevents a false negative on an unchanged file while+// reading only non-PII record fields (never sender/admin emails, deletion+// reason, or the unsigned source PDF hash).++const SHA256_PATTERN = /^[a-f0-9]{64}$/;export const verifyRequestSchema = z.object({sha256: z.string().trim().toLowerCase()- .regex(/^[a-f0-9]{64}$/, "Expected a SHA-256 value."),+ .regex(SHA256_PATTERN, "Expected a SHA-256 value."),});-export type VerifyResult =- | { match: false }- | {- envelopeId: string;- fileKind: "signed-document" | "certificate";- finishedAt: number | null;- match: true;- /** People who approved or rejected instead of signing. */- approverCount: number;- signerCount: number;- status: "completed" | "declined" | "voided";- title: string;- };-type VerifyRow = {approverCount: number;completedAt: number | null;@@ -38,15 +40,60 @@ type VerifyRow = {recipientEvidenceSha256: string | null;signedPdfSha256: string | null;signerCount: number;- status: "completed" | "declined" | "voided";+ status: VerifyEnvelopeStatus;title: string;voidedAt: number | null;};+type DeletedVerifyRow = {+ deletedAt: unknown;+ envelopeId: unknown;+ finishedAt: unknown;+ isSignedDocument: unknown;+ status: unknown;+ title: unknown;+};++function parseFinishedStatus(value: unknown): VerifyEnvelopeStatus | null {+ return value === "completed" || value === "declined" || value === "voided"+ ? value+ : null;+}++function parseTimestamp(value: unknown): number | null {+ if (typeof value === "number" && Number.isFinite(value)) {+ return Math.trunc(value);+ }++ if (typeof value === "string" && /^-?\d+$/.test(value.trim())) {+ const parsed = Number.parseInt(value, 10);++ return Number.isSafeInteger(parsed) ? parsed : null;+ }++ return null;+}++function parseNonEmptyString(value: unknown): string | null {+ if (typeof value !== "string") {+ return null;+ }++ const trimmed = value.trim();++ return trimmed.length > 0 ? trimmed : null;+}+export async function verifyDocumentHash(sha256: string,database: DbExecutor = getDb(),): Promise<VerifyResult> {+ const normalizedSha256 = sha256.trim().toLowerCase();++ if (!SHA256_PATTERN.test(normalizedSha256)) {+ return { match: false };+ }+const row = await queryOne<VerifyRow>(database,`@@ -68,22 +115,65 @@ export async function verifyDocumentHash(OR e.recipient_evidence_sha256 = $1LIMIT 1`,- [sha256],+ [normalizedSha256],+ );++ if (row) {+ return {+ approverCount: row.approverCount,+ envelopeDeleted: false,+ envelopeId: row.envelopeId,+ fileKind:+ row.signedPdfSha256 === normalizedSha256+ ? "signed-document"+ : "certificate",+ finishedAt: row.completedAt ?? row.declinedAt ?? row.voidedAt,+ match: true,+ signerCount: row.signerCount,+ status: row.status,+ title: row.title,+ };+ }++ // Only select the public fields that live /verify already returns plus when+ // the record was deleted — never actor/owner emails, deletion reason, or+ // sibling file hashes, and never match the unsigned sourcePdfHash.+ const deletedRow = await queryOne<DeletedVerifyRow>(+ database,+ `+ SELECT+ created_at AS "deletedAt",+ metadata->>'envelopeId' AS "envelopeId",+ metadata->>'title' AS "title",+ metadata->>'status' AS "status",+ metadata->'finishedAt' AS "finishedAt",+ COALESCE(metadata->>'signedPdfSha256' = $1, false) AS "isSignedDocument"+ FROM system_audit_events+ WHERE event = 'envelope_deleted'+ AND (+ metadata->>'signedPdfSha256' = $1+ OR metadata->>'evidenceSha256' = $1+ OR metadata->>'recipientEvidenceSha256' = $1+ )+ ORDER BY sequence DESC+ LIMIT 1+ `,+ [normalizedSha256],);- if (!row) {+ if (!deletedRow) {return { match: false };}return {- approverCount: row.approverCount,- envelopeId: row.envelopeId,+ deletedAt: parseTimestamp(deletedRow.deletedAt),+ envelopeDeleted: true,+ envelopeId: parseNonEmptyString(deletedRow.envelopeId),fileKind:- row.signedPdfSha256 === sha256 ? "signed-document" : "certificate",- finishedAt: row.completedAt ?? row.declinedAt ?? row.voidedAt,+ deletedRow.isSignedDocument === true ? "signed-document" : "certificate",+ finishedAt: parseTimestamp(deletedRow.finishedAt),match: true,- signerCount: row.signerCount,- status: row.status,- title: row.title,+ status: parseFinishedStatus(deletedRow.status),+ title: parseNonEmptyString(deletedRow.title),};}