Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Close the e-signature compliance gaps from the legal review

Claudec47507bde796
diff --git a/.env.example b/.env.example
index bd784a2..ad59946 100644
--- a/.env.example
+++ b/.env.example
@@ -69,3 +69,21 @@ EMAIL_DRIVER=capture
# STORAGE_DRIVER=blob or =local forces one.
# STORAGE_DRIVER=local
# STORAGE_LOCAL_DIR=
+
+# Resend region for the sending domain the app adds for you: us-east-1
+# (default), eu-west-1, sa-east-1 or ap-northeast-1. Use eu-west-1 to send
+# from the EU. See "Running in the EU" in the README.
+# RESEND_REGION=
+
+# The seal on finished PDFs. Unset, the install makes its own key and
+# self-signed certificate on first use (kept encrypted in the database with
+# a key derived from BETTER_AUTH_SECRET, so keep that secret stable). To
+# seal with a certificate from a certificate authority instead, give it as
+# a base64 PKCS#12 (.p12) file and its password.
+# SEAL_P12_BASE64=
+# SEAL_P12_PASSWORD=
+
+# An RFC 3161 timestamp server, to add a trusted time to each seal, for
+# example http://timestamp.digicert.com. If the server cannot be reached,
+# the PDF is sealed without a timestamp.
+# SEAL_TIMESTAMP_URL=
diff --git a/README.md b/README.md
index ed5ce86..594726a 100644
--- a/README.md
+++ b/README.md
@@ -67,21 +67,57 @@ After that first time, `git merge upstream/main` works as above.
A deployment made with the button needs no environment variables. These are there if you want them, under Settings, Environment Variables in the Vercel project. Deploy again after changing one.
-| Variable | What it does |
-| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
-| `SETUP_TOKEN` | A secret the setup page asks for. See [Lock down a new install](#lock-down-a-new-install). |
-| `CRON_SECRET` | Closes the daily cleanup route to everyone but Vercel's own cron call. See [Daily cleanup](#daily-cleanup). |
-| `BOTID` | `1` turns on Vercel BotID for sign-in, sign-up and setup. See [Bot protection](#bot-protection). |
-| `RESEND_FROM_EMAIL`, `SUPPORT_EMAIL` | Fix the sender and support addresses from the environment instead of in Settings. |
-| `BETTER_AUTH_SECRET` | Your own secret for signing sessions. Without it one is derived from the database password, so changing that password signs everyone out. |
-| `APP_URL` | The site's public address, if it should not be the project's production domain. |
-| `HOSTED_MODE` | `1` runs SignuDoc as a public service under its own name. See [Hosted mode](#hosted-mode). |
+| Variable | What it does |
+| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `SETUP_TOKEN` | A secret the setup page asks for. See [Lock down a new install](#lock-down-a-new-install). |
+| `CRON_SECRET` | Closes the daily cleanup route to everyone but Vercel's own cron call. See [Daily cleanup](#daily-cleanup). |
+| `BOTID` | `1` turns on Vercel BotID for sign-in, sign-up and setup. See [Bot protection](#bot-protection). |
+| `RESEND_FROM_EMAIL`, `SUPPORT_EMAIL` | Fix the sender and support addresses from the environment instead of in Settings. |
+| `BETTER_AUTH_SECRET` | Your own secret for signing sessions. Without it one is derived from the database password, so changing that password signs everyone out. |
+| `APP_URL` | The site's public address, if it should not be the project's production domain. |
+| `HOSTED_MODE` | `1` runs SignuDoc as a public service under its own name. See [Hosted mode](#hosted-mode). |
+| `RESEND_REGION` | Where Resend sends from when the app adds your domain, for example `eu-west-1`. See [Running in the EU](#running-in-the-eu). |
+| `SEAL_P12_BASE64`, `SEAL_P12_PASSWORD` | Seal finished PDFs with a certificate from a certificate authority instead of the install's own. See [Signed PDFs and the seal](#signed-pdfs-and-the-seal). |
+| `SEAL_TIMESTAMP_URL` | An RFC 3161 timestamp server that adds a trusted time to each seal. |
## Important notes
-- SignuDoc is designed for U.S. small businesses and ordinary business agreements such as NDAs, SOWs, and vendor contracts.
-- SignuDoc is not a law firm and does not provide legal advice. It does not determine whether a particular document is legally suitable for electronic signing.
-- If you self-host SignuDoc, your install carries your organization's name, not SignuDoc's, and does not show SignuDoc's own terms, privacy, contact or accessibility pages. You are responsible for linking to your own terms and privacy policy (in Settings), setting your own support address, and making sure your deployment meets any applicable compliance, retention, or consent requirements.
+SignuDoc is not a law firm and does not give legal advice. Whoever runs an install decides what it may be used for. Every install has a page at `/electronic-signatures` that says what follows, and senders confirm it before each send.
+
+### What SignuDoc is for
+
+- Ordinary business agreements: sales and service contracts, NDAs, statements of work, offer letters, purchase orders, approvals.
+- In the US, signatures made with it are electronic signatures under the federal ESIGN Act and the state UETA laws (New York: ESRA). Each signer first agrees to use electronic records, and that agreement is recorded.
+- In the EU and UK, they are **simple electronic signatures (SES)** under eIDAS. A court cannot reject them only for being electronic, but you may have to show who signed. The sealed PDF, the audit certificate and the optional access code or emailed code help.
+
+### What SignuDoc is not
+
+- **Not an advanced or qualified electronic signature (AdES or QES)** under eIDAS. Where a law asks for a QES, use a qualified trust service.
+- **Not built for FDA 21 CFR Part 11** records.
+- **Not HIPAA-ready.** Do not send protected health information without your own agreements with every service the install runs on.
+- **Not for documents the law keeps out of electronic signature**, such as wills, family-law matters, court orders, and notices of foreclosure, eviction, utility shut-off or insurance cancellation (ESIGN section 103, UETA section 3), and in most EU countries real estate transfers and documents that need a notary.
+
+### Your responsibilities when you self-host
+
+Your install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), set a support address, and choose how long finished documents are kept. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.
+
+## Signed PDFs and the seal
+
+Every finished PDF and audit certificate is sealed with a PAdES signature, so any change after signing shows in Adobe Acrobat and other PDF readers, and its SHA-256 is recorded. Anyone can check a copy at `/verify`. The audit trail in the database is a hash chain, so an edited or deleted row shows too.
+
+By default each install makes its own seal key and self-signed certificate the first time it seals, and keeps the key encrypted in the database with a key derived from `BETTER_AUTH_SECRET` (or the database password, when that is unset). Keep that secret stable: a new one makes a new seal key, and old PDFs still verify but under the old certificate. Readers show a self-signed seal as "validity unknown" until the certificate is trusted. For a seal readers trust on sight, buy a document-signing certificate and set `SEAL_P12_BASE64` and `SEAL_P12_PASSWORD`. `SEAL_TIMESTAMP_URL` adds a trusted time from a timestamp server.
+
+## Running in the EU
+
+By default the parts of an install run in the US. To keep signers' data in the EU:
+
+1. **Functions.** Add `"regions": ["fra1"]` to `vercel.json` (or pick Frankfurt under Settings, Functions in the Vercel project).
+2. **Database.** Create the Neon database in an EU region (Frankfurt) when you connect it.
+3. **Files.** Create the Vercel Blob store in an EU region (Frankfurt).
+4. **Email.** Set `RESEND_REGION=eu-west-1` before you add your domain in Settings, or create the domain in Resend's dashboard with the Ireland region. Resend still keeps account data and email logs in the US.
+5. **Agreements.** Accept the data processing agreements of Vercel, Neon and Resend, which include the EU standard contractual clauses, and list them in your privacy policy.
+
+Some data still leaves the EU: Vercel's and Resend's account metadata and logs, for example. The processors' agreements and the EU-US Data Privacy Framework cover that, but check it against your own obligations.
## What it does
diff --git a/db/migrations/20261113090000_signature_evidence.sql b/db/migrations/20261113090000_signature_evidence.sql
new file mode 100644
index 0000000..c1bc83d
--- /dev/null
+++ b/db/migrations/20261113090000_signature_evidence.sql
@@ -0,0 +1,91 @@
+-- Evidence and record-keeping for signed documents.
+--
+-- * envelopes: the SHA-256 of each finished file, so a copy can be checked
+-- against the original later, and when the owner was last warned that the
+-- retention period is about to remove the envelope.
+-- * seal_keys: the key this install seals finished PDFs with. The private
+-- key is stored encrypted with a key derived from the auth secret.
+-- * signers: optional extra checks before signing (an access code the sender
+-- shares, a one-time code sent by email), and when the signer agreed to
+-- use electronic records.
+-- * audit_events: new event kinds, and a hash chain so that a changed or
+-- removed row can be detected.
+-- * app_settings: how long finished envelopes are kept.
+
+alter table public.envelopes
+ add column if not exists signed_pdf_sha256 text
+ check (signed_pdf_sha256 is null or length(signed_pdf_sha256) = 64),
+ add column if not exists evidence_sha256 text
+ check (evidence_sha256 is null or length(evidence_sha256) = 64),
+ add column if not exists recipient_evidence_sha256 text
+ check (
+ recipient_evidence_sha256 is null
+ or length(recipient_evidence_sha256) = 64
+ ),
+ add column if not exists retention_warned_at bigint;
+
+create index if not exists idx_envelopes_signed_pdf_sha256
+ on public.envelopes(signed_pdf_sha256)
+ where signed_pdf_sha256 is not null;
+
+create index if not exists idx_envelopes_evidence_sha256
+ on public.envelopes(evidence_sha256)
+ where evidence_sha256 is not null;
+
+create index if not exists idx_envelopes_recipient_evidence_sha256
+ on public.envelopes(recipient_evidence_sha256)
+ where recipient_evidence_sha256 is not null;
+
+create table if not exists public.seal_keys (
+ id text primary key,
+ certificate_pem text not null,
+ encrypted_private_key text not null,
+ created_at bigint not null,
+ retired_at bigint
+);
+
+create unique index if not exists idx_seal_keys_single_active
+ on public.seal_keys ((true))
+ where retired_at is null;
+
+alter table public.signers
+ add column if not exists access_code_hash text,
+ add column if not exists require_email_code boolean not null default false,
+ add column if not exists email_code_hash text,
+ add column if not exists email_code_expires_at bigint,
+ add column if not exists email_code_attempts integer not null default 0,
+ add column if not exists email_code_sent_at bigint,
+ add column if not exists consented_at bigint;
+
+alter table public.audit_events
+ drop constraint if exists audit_events_event_check;
+
+alter table public.audit_events
+ add constraint audit_events_event_check
+ check (event in (
+ 'created',
+ 'sent',
+ 'viewed',
+ 'consented',
+ 'verified',
+ 'verification_failed',
+ 'signed',
+ 'declined',
+ 'reminded_manual',
+ 'email_sent',
+ 'completed',
+ 'voided'
+ ));
+
+alter table public.audit_events
+ add column if not exists sequence integer,
+ add column if not exists prev_hash text,
+ add column if not exists row_hash text;
+
+create unique index if not exists idx_audit_events_envelope_sequence
+ on public.audit_events(envelope_id, sequence)
+ where sequence is not null;
+
+alter table public.app_settings
+ add column if not exists retention_days integer
+ check (retention_days is null or retention_days >= 30);
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index c07d4a9..f5d6ed1 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -313,6 +313,22 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a
watchForContentSecurityPolicyViolations(recipientPage, cspViolations);
await recipientPage.goto(signingLink);
+
+ // Agreement to electronic records comes before anything else.
+ const consent = recipientPage.getByRole("dialog", {
+ name: "Before you sign",
+ });
+
+ await expect(
+ consent.getByRole("button", { name: "Agree and continue" }),
+ ).toBeDisabled();
+ await consent
+ .getByRole("checkbox", {
+ name: "I agree to use electronic records and signatures",
+ })
+ .check();
+ await consent.getByRole("button", { name: "Agree and continue" }).click();
+ await expect(consent).toBeHidden();
await expect(
recipientPage.getByRole("img", { name: "Rendered PDF page 1" }),
).toBeVisible();
@@ -345,6 +361,21 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a
await expectPdfResponse(await recipientContext.request.get(downloadLink));
}
+ // The signer's copy comes attached, and the Verify page knows it.
+ const signedAttachment = completionEmail.attachments?.find(
+ (attachment) => !attachment.filename.includes("certificate"),
+ );
+
+ expect(completionEmail.attachments?.length).toBe(2);
+ expect(signedAttachment).toBeDefined();
+
+ const verification = await recipientContext.request.post("/api/verify", {
+ data: { sha256: signedAttachment?.sha256 },
+ });
+
+ expect(verification.ok()).toBe(true);
+ expect(await verification.json()).toMatchObject({ match: true });
+
await recipientContext.close();
});
diff --git a/e2e/support/outbox.ts b/e2e/support/outbox.ts
index ad0af9b..07f3ae8 100644
--- a/e2e/support/outbox.ts
+++ b/e2e/support/outbox.ts
@@ -4,6 +4,7 @@ import path from "node:path";
import { e2eOutboxDir } from "../../playwright.config";
export type CapturedEmail = {
+ attachments?: { filename: string; sha256: string }[];
subject: string;
template: string;
text: string;
diff --git a/package-lock.json b/package-lock.json
index 603293c..8bf53db 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,6 +10,10 @@
"license": "MIT",
"dependencies": {
"@pdf-lib/fontkit": "^1.1.1",
+ "@signpdf/placeholder-pdf-lib": "3.3.0",
+ "@signpdf/signer-p12": "3.3.0",
+ "@signpdf/signpdf": "3.3.0",
+ "@signpdf/utils": "3.3.0",
"@vercel/blob": "^2.9.0",
"@vercel/functions": "^3.11.1",
"better-auth": "^1.7.21",
@@ -18,6 +22,7 @@
"clsx": "^2.1.1",
"lucide-react": "^0.577.0",
"next": "16.4.6",
+ "node-forge": "1.4.2",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "5.5.207",
"pg": "^8.23.1",
@@ -33,6 +38,7 @@
"@playwright/test": "1.63.0",
"@tailwindcss/postcss": "^4.3.5",
"@types/node": "^24",
+ "@types/node-forge": "1.3.14",
"@types/pg": "^8.23.1",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
@@ -3352,6 +3358,84 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@signpdf/placeholder-pdf-lib": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/@signpdf/placeholder-pdf-lib/-/placeholder-pdf-lib-3.3.0.tgz",
+ "integrity": "sha512-DT1s617z88NvvCmo+z8jaz7lNzy7b7/fwo/movJGukpfSkl4FaLNRXIHNBCTRCP9TUb6F/axK1JulES/jY7mLQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://buymeacoffee.com/vbuch?utm_source=npm-funding-signpdf"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@signpdf/utils": "^3.3.0"
+ },
+ "engines": {
+ "node": ">=12",
+ "yarn": ">=1.22.18"
+ },
+ "peerDependencies": {
+ "pdf-lib": "^1.17.1"
+ }
+ },
+ "node_modules/@signpdf/signer-p12": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/@signpdf/signer-p12/-/signer-p12-3.3.0.tgz",
+ "integrity": "sha512-MLynYKgUBu29ojIueIDV34sIOFDFpP0s1gQORxCc0zhs1jfy0juqU2xQpjUayMbhzB4L0zS9dPwgHtok1f89Cg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://buymeacoffee.com/vbuch?utm_source=npm-funding-signpdf"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@signpdf/utils": "^3.3.0"
+ },
+ "engines": {
+ "node": ">=12",
+ "yarn": ">=1.22.18"
+ },
+ "peerDependencies": {
+ "node-forge": "^1.3.3"
+ }
+ },
+ "node_modules/@signpdf/signpdf": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/@signpdf/signpdf/-/signpdf-3.3.0.tgz",
+ "integrity": "sha512-/vy3dPTsTbLHdsKRarPQw8++UqN8GXxjEVnl4ZRl+o/zMWFqVb861RM5bxoRMGGMuPSvb1Rgt2lmVobEc0YUpw==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://buymeacoffee.com/vbuch?utm_source=npm-funding-signpdf"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@signpdf/utils": "^3.3.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@signpdf/utils": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/@signpdf/utils/-/utils-3.3.0.tgz",
+ "integrity": "sha512-ArOP0MIhCfdChh1oZkog81TPeSY2e5TvHQmXJ682T4+SKb6Z609uAZhqMQZ9xm+YenEf/eNMSE5KVwU+EudXug==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://buymeacoffee.com/vbuch?utm_source=npm-funding-signpdf"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12",
+ "yarn": ">=1.22.18"
+ }
+ },
"node_modules/@stablelib/base64": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
@@ -3793,6 +3877,16 @@
"undici-types": ">=7.24.0 <7.24.7"
}
},
+ "node_modules/@types/node-forge": {
+ "version": "1.3.14",
+ "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz",
+ "integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/pg": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz",
@@ -7795,6 +7889,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/node-forge": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.2.tgz",
+ "integrity": "sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==",
+ "license": "(BSD-3-Clause OR GPL-2.0)",
+ "engines": {
+ "node": ">= 6.13.0"
+ }
+ },
"node_modules/node-readable-to-web-readable-stream": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/node-readable-to-web-readable-stream/-/node-readable-to-web-readable-stream-0.4.2.tgz",
diff --git a/package.json b/package.json
index 8300863..f4f6f78 100644
--- a/package.json
+++ b/package.json
@@ -25,6 +25,10 @@
},
"dependencies": {
"@pdf-lib/fontkit": "^1.1.1",
+ "@signpdf/placeholder-pdf-lib": "3.3.0",
+ "@signpdf/signer-p12": "3.3.0",
+ "@signpdf/signpdf": "3.3.0",
+ "@signpdf/utils": "3.3.0",
"@vercel/blob": "^2.9.0",
"@vercel/functions": "^3.11.1",
"better-auth": "^1.7.21",
@@ -33,6 +37,7 @@
"clsx": "^2.1.1",
"lucide-react": "^0.577.0",
"next": "16.4.6",
+ "node-forge": "1.4.2",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "5.5.207",
"pg": "^8.23.1",
@@ -48,6 +53,7 @@
"@playwright/test": "1.63.0",
"@tailwindcss/postcss": "^4.3.5",
"@types/node": "^24",
+ "@types/node-forge": "1.3.14",
"@types/pg": "^8.23.1",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
diff --git a/src/app/api/admin/signer-data/route.ts b/src/app/api/admin/signer-data/route.ts
new file mode 100644
index 0000000..ec3b7f0
--- /dev/null
+++ b/src/app/api/admin/signer-data/route.ts
@@ -0,0 +1,103 @@
+import { NextResponse } from "next/server";
+
+import { requireAdminSession } from "@/lib/auth/admin";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ SignerDataError,
+ eraseSignerData,
+ exportSignerData,
+} from "@/lib/signer-data";
+
+// Signer data requests (access, portability, erasure). Administrators only.
+
+async function guard(request: Request, action: "erase" | "export") {
+ const sessionResult = await requireAdminSession(request);
+
+ if (sessionResult instanceof Response) {
+ return { response: sessionResult };
+ }
+
+ const rateLimitResponse = await applyRateLimit({
+ category: `signer_data_${action}`,
+ key: buildRateLimitKey(["signer-data", action, sessionResult.user.id]),
+ limit: action === "erase" ? 10 : 30,
+ request,
+ userId: sessionResult.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ return rateLimitResponse
+ ? { response: rateLimitResponse }
+ : { response: null };
+}
+
+function errorResponse(error: unknown, request: Request) {
+ if (error instanceof SignerDataError) {
+ return NextResponse.json(
+ { error: error.message },
+ { status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "signer_data_failure",
+ message: "Unexpected failure while handling a signer data request.",
+ path: request.url,
+ });
+
+ return NextResponse.json(
+ { error: "That request could not be completed." },
+ { status: 500 },
+ );
+}
+
+/** GET ?email=...: a JSON file of everything stored about that signer. */
+export async function GET(request: Request) {
+ const { response } = await guard(request, "export");
+
+ if (response) {
+ return response;
+ }
+
+ try {
+ const data = await exportSignerData(
+ new URL(request.url).searchParams.get("email"),
+ );
+
+ return new Response(JSON.stringify(data, null, 2), {
+ headers: {
+ "cache-control": "private, no-store",
+ "content-disposition": `attachment; filename="signer-data.json"`,
+ "content-type": "application/json; charset=utf-8",
+ },
+ });
+ } catch (error) {
+ return errorResponse(error, request);
+ }
+}
+
+/** DELETE {email, confirmation}: erases that signer's records. */
+export async function DELETE(request: Request) {
+ const { response } = await guard(request, "erase");
+
+ if (response) {
+ return response;
+ }
+
+ const body = (await request.json().catch(() => null)) as {
+ confirmation?: unknown;
+ email?: unknown;
+ } | null;
+
+ try {
+ return NextResponse.json(
+ await eraseSignerData(body?.email, body?.confirmation),
+ );
+ } catch (error) {
+ return errorResponse(error, request);
+ }
+}
diff --git a/src/app/api/download/[token]/renew/route.ts b/src/app/api/download/[token]/renew/route.ts
new file mode 100644
index 0000000..74608a4
--- /dev/null
+++ b/src/app/api/download/[token]/renew/route.ts
@@ -0,0 +1,61 @@
+import { NextResponse } from "next/server";
+
+import { getDb } from "@/lib/db/connection";
+import { sendFreshDownloadLinks } from "@/lib/download-renewal";
+import { DownloadAccessError } from "@/lib/downloads";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress } from "@/lib/security/request";
+
+type RenewRouteContext = {
+ params: Promise<{
+ token: string;
+ }>;
+};
+
+const NO_STORE = { "cache-control": "private, no-store" };
+
+export async function POST(request: Request, context: RenewRouteContext) {
+ const { token } = await context.params;
+ const rateLimitResponse = await applyRateLimit({
+ category: "download_link_renewal",
+ // Per link, not per address: each request sends an email.
+ key: buildRateLimitKey(["download-renew", token]),
+ limit: 3,
+ message: "A new link was sent recently. Check your email.",
+ request,
+ windowMs: 60 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ try {
+ const result = await sendFreshDownloadLinks(token, { database: getDb() });
+
+ return NextResponse.json(result, { headers: NO_STORE });
+ } catch (error) {
+ if (error instanceof DownloadAccessError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "download_link_renewal_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while sending new download links.",
+ path: "/api/download/[token]/renew",
+ });
+
+ return NextResponse.json(
+ { error: "New links could not be sent right now." },
+ { headers: NO_STORE, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/download/[token]/route.ts b/src/app/api/download/[token]/route.ts
index 9f495b2..0de4709 100644
--- a/src/app/api/download/[token]/route.ts
+++ b/src/app/api/download/[token]/route.ts
@@ -4,6 +4,7 @@ import { getDb } from "@/lib/db/connection";
import { createDownloadResponse } from "@/lib/download-response";
import {
DownloadAccessError,
+ ExpiredDownloadLinkError,
getPublicEnvelopeDownloadForToken,
} from "@/lib/downloads";
import { logRouteError } from "@/lib/security/logging";
@@ -12,6 +13,7 @@ import {
buildRateLimitKey,
} from "@/lib/security/route-controls";
import { getClientIpAddress } from "@/lib/security/request";
+import { resolveAppUrl } from "@/lib/utils/env";
// Public download route for recipient email links only.
// Sender downloads must go through the authenticated /api/envelopes/[id]/download route.
@@ -56,6 +58,17 @@ export async function GET(
return await createDownloadResponse(download);
} catch (error) {
+ // The page there offers to email fresh links to the signer.
+ if (error instanceof ExpiredDownloadLinkError) {
+ return NextResponse.redirect(
+ new URL(
+ `/download/${encodeURIComponent(token)}`,
+ resolveAppUrl() ?? request.url,
+ ),
+ { headers: { "cache-control": "private, no-store" }, status: 303 },
+ );
+ }
+
if (error instanceof DownloadAccessError) {
return new NextResponse(error.message, {
headers: {
diff --git a/src/app/api/signing/[token]/consent/route.ts b/src/app/api/signing/[token]/consent/route.ts
new file mode 100644
index 0000000..03f85c8
--- /dev/null
+++ b/src/app/api/signing/[token]/consent/route.ts
@@ -0,0 +1,101 @@
+import { NextResponse } from "next/server";
+import { ZodError } from "zod";
+
+import { getDb } from "@/lib/db/connection";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+import {
+ recordSignerConsent,
+ SigningAccessError,
+ SigningMutationError,
+ SigningVerificationRequiredError,
+} from "@/lib/signing";
+import {
+ verificationRequiredResponse,
+ verifiedMethodsForRequest,
+} from "@/lib/signing-route";
+
+type ConsentRouteContext = {
+ params: Promise<{
+ token: string;
+ }>;
+};
+
+const NO_STORE = { "cache-control": "private, no-store" };
+
+export async function POST(request: Request, context: ConsentRouteContext) {
+ const { token } = await context.params;
+ const rateLimitResponse = await applyRateLimit({
+ category: "signing_consent",
+ key: buildRateLimitKey([
+ "signing-consent",
+ token,
+ getClientIpAddress(request.headers) ?? "unknown",
+ ]),
+ limit: 10,
+ request,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ try {
+ return NextResponse.json(
+ await recordSignerConsent(token, await request.json().catch(() => null), {
+ database: getDb(),
+ requestMeta: {
+ ipAddress: getClientIpAddress(request.headers),
+ userAgent: getRequestUserAgent(request.headers),
+ },
+ verifiedMethods: verifiedMethodsForRequest(token, request),
+ }),
+ { headers: NO_STORE },
+ );
+ } catch (error) {
+ if (error instanceof ZodError) {
+ return NextResponse.json(
+ { error: "Invalid request." },
+ { headers: NO_STORE, status: 400 },
+ );
+ }
+
+ if (error instanceof SigningVerificationRequiredError) {
+ return verificationRequiredResponse(error);
+ }
+
+ if (error instanceof SigningMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ if (error instanceof SigningAccessError) {
+ return NextResponse.json(
+ { error: error.message, state: error.state },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "signing_consent_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while recording consent.",
+ path: request.url,
+ });
+
+ return NextResponse.json(
+ { error: "Your agreement could not be saved right now." },
+ { headers: NO_STORE, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/signing/[token]/decline/route.ts b/src/app/api/signing/[token]/decline/route.ts
index 1eb3f43..e67b2b7 100644
--- a/src/app/api/signing/[token]/decline/route.ts
+++ b/src/app/api/signing/[token]/decline/route.ts
@@ -2,14 +2,25 @@ import { NextResponse } from "next/server";
import { ZodError } from "zod";
import { getDb } from "@/lib/db/connection";
+import {
+ verificationRequiredResponse,
+ verifiedMethodsForRequest,
+} from "@/lib/signing-route";
import {
SigningAccessError,
+ SigningVerificationRequiredError,
SigningMutationError,
declineSigningForToken,
} from "@/lib/signing";
import { logRouteError } from "@/lib/security/logging";
-import { applyRateLimit, buildRateLimitKey } from "@/lib/security/route-controls";
-import { getClientIpAddress, getRequestUserAgent } from "@/lib/security/request";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestUserAgent,
+} from "@/lib/security/request";
type SigningDeclineRouteContext = {
params: Promise<{
@@ -42,6 +53,7 @@ export async function POST(
try {
const payload = await declineSigningForToken(token, body, {
database: getDb(),
+ verifiedMethods: verifiedMethodsForRequest(token, request),
requestMeta: {
ipAddress: getClientIpAddress(request.headers),
userAgent: getRequestUserAgent(request.headers),
@@ -71,6 +83,10 @@ export async function POST(
);
}
+ if (error instanceof SigningVerificationRequiredError) {
+ return verificationRequiredResponse(error);
+ }
+
if (error instanceof SigningAccessError) {
return NextResponse.json(
{
diff --git a/src/app/api/signing/[token]/document/route.ts b/src/app/api/signing/[token]/document/route.ts
index 6a54eb0..d7c68fb 100644
--- a/src/app/api/signing/[token]/document/route.ts
+++ b/src/app/api/signing/[token]/document/route.ts
@@ -1,9 +1,20 @@
import { NextResponse } from "next/server";
import { getDb } from "@/lib/db/connection";
-import { SigningAccessError, getSigningDocumentForToken } from "@/lib/signing";
+import {
+ verificationRequiredResponse,
+ verifiedMethodsForRequest,
+} from "@/lib/signing-route";
+import {
+ SigningAccessError,
+ SigningVerificationRequiredError,
+ getSigningDocumentForToken,
+} from "@/lib/signing";
import { logRouteError } from "@/lib/security/logging";
-import { applyRateLimit, buildRateLimitKey } from "@/lib/security/route-controls";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
import { getClientIpAddress } from "@/lib/security/request";
type SigningDocumentRouteContext = {
@@ -36,13 +47,20 @@ export async function GET(
try {
const documentObject = await getSigningDocumentForToken(token, {
database: getDb(),
+ verifiedMethods: verifiedMethodsForRequest(token, request),
});
const responseBody = documentObject.body.slice().buffer as ArrayBuffer;
return new Response(responseBody, {
headers: {
"cache-control": "private, no-store",
- "content-disposition": 'inline; filename="document.pdf"',
+ // ?download=1 saves the file instead of showing it, for the
+ // signer's own copy before signing.
+ "content-disposition": `${
+ new URL(request.url).searchParams.get("download") === "1"
+ ? "attachment"
+ : "inline"
+ }; filename="document.pdf"`,
"content-length": String(
documentObject.contentLength ?? documentObject.body.length,
),
@@ -51,6 +69,10 @@ export async function GET(
status: 200,
});
} catch (error) {
+ if (error instanceof SigningVerificationRequiredError) {
+ return verificationRequiredResponse(error);
+ }
+
if (error instanceof SigningAccessError) {
return NextResponse.json(
{
diff --git a/src/app/api/signing/[token]/route.ts b/src/app/api/signing/[token]/route.ts
index 55e550b..89ccd08 100644
--- a/src/app/api/signing/[token]/route.ts
+++ b/src/app/api/signing/[token]/route.ts
@@ -1,10 +1,24 @@
import { NextResponse } from "next/server";
import { getDb } from "@/lib/db/connection";
-import { SigningAccessError, getSigningPayloadForToken } from "@/lib/signing";
+import {
+ verificationRequiredResponse,
+ verifiedMethodsForRequest,
+} from "@/lib/signing-route";
+import {
+ SigningAccessError,
+ SigningVerificationRequiredError,
+ getSigningPayloadForToken,
+} from "@/lib/signing";
import { logRouteError } from "@/lib/security/logging";
-import { applyRateLimit, buildRateLimitKey } from "@/lib/security/route-controls";
-import { getClientIpAddress, getRequestUserAgent } from "@/lib/security/request";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestUserAgent,
+} from "@/lib/security/request";
type SigningRouteContext = {
params: Promise<{
@@ -33,6 +47,7 @@ export async function GET(request: Request, context: SigningRouteContext) {
try {
const payload = await getSigningPayloadForToken(token, {
database: getDb(),
+ verifiedMethods: verifiedMethodsForRequest(token, request),
requestMeta: {
ipAddress: getClientIpAddress(request.headers),
userAgent: getRequestUserAgent(request.headers),
@@ -46,6 +61,10 @@ export async function GET(request: Request, context: SigningRouteContext) {
status: 200,
});
} catch (error) {
+ if (error instanceof SigningVerificationRequiredError) {
+ return verificationRequiredResponse(error);
+ }
+
if (error instanceof SigningAccessError) {
return NextResponse.json(
{
diff --git a/src/app/api/signing/[token]/submit/route.ts b/src/app/api/signing/[token]/submit/route.ts
index ac1c9a6..02da1bc 100644
--- a/src/app/api/signing/[token]/submit/route.ts
+++ b/src/app/api/signing/[token]/submit/route.ts
@@ -2,14 +2,25 @@ import { NextResponse } from "next/server";
import { ZodError } from "zod";
import { getDb } from "@/lib/db/connection";
+import {
+ verificationRequiredResponse,
+ verifiedMethodsForRequest,
+} from "@/lib/signing-route";
import {
SigningAccessError,
+ SigningVerificationRequiredError,
SigningMutationError,
submitSigningForToken,
} from "@/lib/signing";
import { logRouteError } from "@/lib/security/logging";
-import { applyRateLimit, buildRateLimitKey } from "@/lib/security/route-controls";
-import { getClientIpAddress, getRequestUserAgent } from "@/lib/security/request";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestUserAgent,
+} from "@/lib/security/request";
type SigningSubmitRouteContext = {
params: Promise<{
@@ -42,6 +53,7 @@ export async function POST(
try {
const payload = await submitSigningForToken(token, body, {
database: getDb(),
+ verifiedMethods: verifiedMethodsForRequest(token, request),
requestMeta: {
ipAddress: getClientIpAddress(request.headers),
userAgent: getRequestUserAgent(request.headers),
@@ -71,6 +83,10 @@ export async function POST(
);
}
+ if (error instanceof SigningVerificationRequiredError) {
+ return verificationRequiredResponse(error);
+ }
+
if (error instanceof SigningAccessError) {
return NextResponse.json(
{
diff --git a/src/app/api/signing/[token]/verify/email-code/route.ts b/src/app/api/signing/[token]/verify/email-code/route.ts
new file mode 100644
index 0000000..9625f78
--- /dev/null
+++ b/src/app/api/signing/[token]/verify/email-code/route.ts
@@ -0,0 +1,71 @@
+import { NextResponse } from "next/server";
+
+import { getDb } from "@/lib/db/connection";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress } from "@/lib/security/request";
+import {
+ SigningAccessError,
+ SigningMutationError,
+ sendSignerEmailCode,
+} from "@/lib/signing";
+
+type EmailCodeRouteContext = {
+ params: Promise<{
+ token: string;
+ }>;
+};
+
+const NO_STORE = { "cache-control": "private, no-store" };
+
+export async function POST(request: Request, context: EmailCodeRouteContext) {
+ const { token } = await context.params;
+ const rateLimitResponse = await applyRateLimit({
+ category: "signing_email_code",
+ key: buildRateLimitKey(["signing-email-code", token]),
+ limit: 5,
+ message: "Several codes were sent already. Check your email.",
+ request,
+ windowMs: 60 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ try {
+ return NextResponse.json(
+ await sendSignerEmailCode(token, { database: getDb() }),
+ { headers: NO_STORE },
+ );
+ } catch (error) {
+ if (error instanceof SigningMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ if (error instanceof SigningAccessError) {
+ return NextResponse.json(
+ { error: error.message, state: error.state },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "signing_email_code_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while sending a signer code.",
+ path: request.url,
+ });
+
+ return NextResponse.json(
+ { error: "The code could not be sent right now." },
+ { headers: NO_STORE, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/signing/[token]/verify/route.ts b/src/app/api/signing/[token]/verify/route.ts
new file mode 100644
index 0000000..2ff033a
--- /dev/null
+++ b/src/app/api/signing/[token]/verify/route.ts
@@ -0,0 +1,114 @@
+import { NextResponse } from "next/server";
+import { ZodError } from "zod";
+
+import { getDb } from "@/lib/db/connection";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+import { hashOpaqueToken } from "@/lib/services/opaque-tokens";
+import {
+ buildVerificationCookieValue,
+ verificationCookieName,
+} from "@/lib/signer-checks";
+import {
+ SigningAccessError,
+ SigningMutationError,
+ verifySignerCheck,
+} from "@/lib/signing";
+import { verifiedMethodsForRequest } from "@/lib/signing-route";
+import { resolveAppUrl } from "@/lib/utils/env";
+
+type VerifyRouteContext = {
+ params: Promise<{
+ token: string;
+ }>;
+};
+
+const NO_STORE = { "cache-control": "private, no-store" };
+
+export async function POST(request: Request, context: VerifyRouteContext) {
+ const { token } = await context.params;
+ // Codes are short: few tries per link, whatever address they come from.
+ const rateLimitResponse = await applyRateLimit({
+ category: "signing_verify",
+ key: buildRateLimitKey(["signing-verify", token]),
+ limit: 10,
+ message: "Too many tries. Wait a few minutes and try again.",
+ request,
+ windowMs: 15 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ try {
+ const methods = await verifySignerCheck(
+ token,
+ await request.json().catch(() => null),
+ {
+ database: getDb(),
+ requestMeta: {
+ ipAddress: getClientIpAddress(request.headers),
+ userAgent: getRequestUserAgent(request.headers),
+ },
+ verifiedMethods: verifiedMethodsForRequest(token, request),
+ },
+ );
+ const tokenHash = hashOpaqueToken(token);
+ const cookie = buildVerificationCookieValue(tokenHash, methods);
+ const response = NextResponse.json(
+ { verified: methods },
+ { headers: NO_STORE },
+ );
+
+ response.cookies.set(verificationCookieName(tokenHash), cookie.value, {
+ httpOnly: true,
+ maxAge: cookie.maxAge,
+ path: "/",
+ sameSite: "lax",
+ secure: resolveAppUrl()?.startsWith("https://") ?? false,
+ });
+
+ return response;
+ } catch (error) {
+ if (error instanceof ZodError) {
+ return NextResponse.json(
+ { error: "Enter the code." },
+ { headers: NO_STORE, status: 400 },
+ );
+ }
+
+ if (error instanceof SigningMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ if (error instanceof SigningAccessError) {
+ return NextResponse.json(
+ { error: error.message, state: error.state },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "signing_verify_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while checking a signer code.",
+ path: request.url,
+ });
+
+ return NextResponse.json(
+ { error: "The code could not be checked right now." },
+ { headers: NO_STORE, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/verify/route.ts b/src/app/api/verify/route.ts
new file mode 100644
index 0000000..29c762b
--- /dev/null
+++ b/src/app/api/verify/route.ts
@@ -0,0 +1,60 @@
+import { NextResponse } from "next/server";
+
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+import { verifyDocumentHash, verifyRequestSchema } from "@/lib/verify";
+
+export async function POST(request: Request) {
+ const rateLimitResponse = await applyRateLimit({
+ category: "document_verify",
+ key: buildRateLimitKey([
+ "document-verify",
+ getClientIpAddress(request.headers) ??
+ getRequestUserAgent(request.headers) ??
+ "unknown",
+ ]),
+ limit: 30,
+ request,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ const parsed = verifyRequestSchema.safeParse(
+ await request.json().catch(() => null),
+ );
+
+ if (!parsed.success) {
+ return NextResponse.json(
+ { error: "Send the file's SHA-256 value." },
+ { status: 400 },
+ );
+ }
+
+ try {
+ return NextResponse.json(await verifyDocumentHash(parsed.data.sha256), {
+ headers: { "cache-control": "no-store" },
+ });
+ } catch (error) {
+ logRouteError(error, {
+ category: "document_verify_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while checking a document.",
+ path: getRequestPathname(request),
+ });
+ return NextResponse.json(
+ { error: "The file could not be checked right now." },
+ { status: 500 },
+ );
+ }
+}
diff --git a/src/app/download/[token]/page.tsx b/src/app/download/[token]/page.tsx
new file mode 100644
index 0000000..339158d
--- /dev/null
+++ b/src/app/download/[token]/page.tsx
@@ -0,0 +1,31 @@
+import type { Metadata } from "next";
+
+import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import { RenewDownloadButton } from "@/components/downloads/renew-download-button";
+
+export const metadata: Metadata = {
+ robots: { follow: false, index: false },
+ title: "Download link expired",
+};
+
+type ExpiredDownloadPageProps = {
+ params: Promise<{ token: string }>;
+};
+
+export default async function ExpiredDownloadPage({
+ params,
+}: ExpiredDownloadPageProps) {
+ const { token } = await params;
+
+ return (
+ <PublicDocumentShell
+ description="Download links work for a limited time. You can have new ones sent to the email address this document was sent to."
+ lastUpdated="November 13, 2026"
+ title="This download link has expired"
+ >
+ <div className="mx-auto w-full max-w-[52rem]">
+ <RenewDownloadButton token={token} />
+ </div>
+ </PublicDocumentShell>
+ );
+}
diff --git a/src/app/electronic-signatures/page.tsx b/src/app/electronic-signatures/page.tsx
new file mode 100644
index 0000000..ce3b9dc
--- /dev/null
+++ b/src/app/electronic-signatures/page.tsx
@@ -0,0 +1,92 @@
+import type { Metadata } from "next";
+import { connection } from "next/server";
+
+import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import {
+ EU_LIMITS,
+ PERMITTED_USE_VERSION,
+ US_EXCLUDED_DOCUMENTS,
+ WHAT_IT_IS,
+ WHAT_IT_IS_NOT,
+} from "@/lib/permitted-uses";
+import { getBranding } from "@/lib/settings";
+
+export const metadata: Metadata = {
+ description:
+ "Which documents can be signed here, and what kind of electronic signature this is.",
+ title: "Electronic signatures: what this is for",
+};
+
+function List({ items }: { items: string[] }) {
+ return (
+ <ul className="list-disc space-y-2 pl-6">
+ {items.map((item) => (
+ <li key={item}>{item}</li>
+ ))}
+ </ul>
+ );
+}
+
+// On every install, hosted or not: senders confirm this list before each
+// send, and signers can read it.
+export default async function ElectronicSignaturesPage() {
+ await connection();
+
+ const { productName } = await getBranding();
+
+ return (
+ <PublicDocumentShell
+ description={`${productName} uses Signudoc to collect electronic signatures. This page says which documents that is meant for, and which it is not.`}
+ lastUpdated={PERMITTED_USE_VERSION}
+ title="What this is for"
+ >
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ {WHAT_IT_IS.heading}
+ </h2>
+ <List items={WHAT_IT_IS.items} />
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ {WHAT_IT_IS_NOT.heading}
+ </h2>
+ <List items={WHAT_IT_IS_NOT.items} />
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Do not send these documents (United States)
+ </h2>
+ <p>
+ The federal ESIGN Act (15 U.S.C. 7003) and the Uniform Electronic
+ Transactions Act adopted by the states leave these out, so an
+ electronic signature may not make them valid:
+ </p>
+ <List items={US_EXCLUDED_DOCUMENTS} />
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Take care with these (European Union)
+ </h2>
+ <p>
+ eIDAS lets member states decide which documents need a stronger form.
+ Commonly these do:
+ </p>
+ <List items={EU_LIMITS} />
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Who decides
+ </h2>
+ <p>
+ {productName} runs this site and decides what it may be used for.
+ Before each send, the sender confirms the document is not one of the
+ kinds listed here. This page is general information, not legal advice.
+ </p>
+ </section>
+ </PublicDocumentShell>
+ );
+}
diff --git a/src/app/sign/[token]/page.tsx b/src/app/sign/[token]/page.tsx
index 869a1ab..91e51e0 100644
--- a/src/app/sign/[token]/page.tsx
+++ b/src/app/sign/[token]/page.tsx
@@ -1,9 +1,15 @@
-import { headers } from "next/headers";
+import { cookies, headers } from "next/headers";
import { SigningShell } from "@/components/signing/signing-shell";
import { getDb } from "@/lib/db/connection";
import { getClientIpAddress } from "@/lib/security/request";
-import { SigningAccessError, getSigningPayloadForToken } from "@/lib/signing";
+import type { SigningVerificationState } from "@/lib/schemas/signing";
+import { verifiedMethodsFromCookies } from "@/lib/signer-checks";
+import {
+ SigningAccessError,
+ SigningVerificationRequiredError,
+ getSigningPayloadForToken,
+} from "@/lib/signing";
type SignPageProps = {
params: Promise<{
@@ -11,22 +17,17 @@ type SignPageProps = {
}>;
};
-export default async function SignPage({
- params,
-}: SignPageProps) {
+export default async function SignPage({ params }: SignPageProps) {
const { token } = await params;
let initialState:
- | "already-signed"
- | "declined"
- | "error"
- | "expired"
- | "voided"
- | undefined;
+ "already-signed" | "declined" | "error" | "expired" | "voided" | undefined;
let record: Awaited<ReturnType<typeof getSigningPayloadForToken>> | null =
null;
+ let verification: SigningVerificationState | null = null;
try {
const requestHeaders = await headers();
+ const cookieStore = await cookies();
record = await getSigningPayloadForToken(token, {
database: getDb(),
@@ -34,9 +35,15 @@ export default async function SignPage({
ipAddress: getClientIpAddress(requestHeaders),
userAgent: requestHeaders.get("user-agent")?.trim() ?? null,
},
+ verifiedMethods: verifiedMethodsFromCookies(
+ token,
+ (name) => cookieStore.get(name)?.value,
+ ),
});
} catch (error) {
- if (error instanceof SigningAccessError) {
+ if (error instanceof SigningVerificationRequiredError) {
+ verification = error.details;
+ } else if (error instanceof SigningAccessError) {
initialState = error.state;
} else {
initialState = "error";
@@ -48,6 +55,8 @@ export default async function SignPage({
initialState={initialState}
key={token}
record={record ?? undefined}
+ token={token}
+ verification={verification ?? undefined}
/>
);
}
diff --git a/src/app/signer-privacy/page.tsx b/src/app/signer-privacy/page.tsx
new file mode 100644
index 0000000..63354c0
--- /dev/null
+++ b/src/app/signer-privacy/page.tsx
@@ -0,0 +1,136 @@
+import type { Metadata } from "next";
+import { redirect } from "next/navigation";
+import { connection } from "next/server";
+
+import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import { getSettings } from "@/lib/settings";
+import { STALE_DRAFT_RETENTION_DAYS } from "@/lib/retention";
+
+export const metadata: Metadata = {
+ description: "How your information is used when you sign a document here.",
+ title: "Privacy notice for signers",
+};
+
+// A GDPR Article 13 notice for signers, built from the install's settings.
+// Shown in the footer when the organization has not linked its own privacy
+// policy. The organization remains the controller and should check it.
+export default async function SignerPrivacyPage() {
+ await connection();
+
+ const settings = await getSettings();
+
+ if (settings.hosted) {
+ redirect("/privacy");
+ }
+
+ if (settings.privacyUrl) {
+ redirect(settings.privacyUrl);
+ }
+
+ const organization =
+ settings.organizationName?.trim() || "The organization that runs this site";
+ const contact = settings.supportAddress;
+ const retention = settings.retentionDays
+ ? `Finished documents and their audit trails are deleted ${String(settings.retentionDays)} days after they are finished.`
+ : "Finished documents and their audit trails are kept until the organization deletes them, because they are evidence of an agreement and many must be kept for years by law.";
+
+ return (
+ <PublicDocumentShell
+ description={`${organization} uses this site to send documents for electronic signature. This notice says what is collected about you when you sign, why, and what you can do about it.`}
+ lastUpdated="2026-11-13"
+ title="Privacy notice for signers"
+ >
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Who is responsible
+ </h2>
+ <p>
+ {organization} is responsible for your information (the
+ &ldquo;controller&rdquo;).{" "}
+ {contact ? (
+ <>
+ Contact them at{" "}
+ <a className="underline" href={`mailto:${contact}`}>
+ {contact}
+ </a>
+ .
+ </>
+ ) : (
+ "Contact them through the person who sent you the document."
+ )}
+ </p>
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ What is collected
+ </h2>
+ <ul className="list-disc space-y-2 pl-6">
+ <li>Your name and email address, given by the sender.</li>
+ <li>
+ What you enter: your signature or initials (typed or drawn), dates,
+ text and checkboxes, or your reason for declining.
+ </li>
+ <li>
+ Evidence of signing: when you opened, agreed and signed, your IP
+ address, your browser&apos;s description of itself, and the checks
+ you passed (such as an emailed code).
+ </li>
+ <li>Records of the emails sent to you about the document.</li>
+ </ul>
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Why, and on what basis
+ </h2>
+ <p>
+ To let you review and sign the document, to deliver copies, and to
+ keep evidence of who signed what and when. The basis is taking steps
+ for or performing a contract you are part of (GDPR Article 6(1)(b)),
+ the organization&apos;s legitimate interest in being able to prove the
+ agreement (Article 6(1)(f)), and any legal duty to keep records
+ (Article 6(1)(c)).
+ </p>
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Who else handles it
+ </h2>
+ <p>
+ The other parties to the document see your name, email and signature.
+ The services that run this site process it for {organization}: the
+ hosting provider (Vercel), the database provider (such as Neon), file
+ storage (Vercel Blob) and the email provider (Resend). Some are based
+ in the United States; where information leaves the European Economic
+ Area, it is protected by the EU-US Data Privacy Framework or by
+ standard contractual clauses.
+ </p>
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ How long it is kept
+ </h2>
+ <p>
+ {retention} Unsent drafts are deleted after{" "}
+ {String(STALE_DRAFT_RETENTION_DAYS)} days without changes.
+ </p>
+ </section>
+
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Your rights
+ </h2>
+ <p>
+ You can ask {organization} for a copy of your information, to correct
+ it, to restrict or object to its use, or to erase it. A signed record
+ may be kept despite a request to erase it while it is needed as
+ evidence or by law (GDPR Article 17(3)). You can also complain to the
+ data protection authority where you live or work.
+ </p>
+ </section>
+ </PublicDocumentShell>
+ );
+}
diff --git a/src/app/verify/page.tsx b/src/app/verify/page.tsx
new file mode 100644
index 0000000..12708f6
--- /dev/null
+++ b/src/app/verify/page.tsx
@@ -0,0 +1,38 @@
+import type { Metadata } from "next";
+
+import { PublicDocumentShell } from "@/components/layout/public-document-shell";
+import { VerifyForm } from "@/components/verify/verify-form";
+
+export const metadata: Metadata = {
+ description:
+ "Check that a signed PDF or audit certificate is exactly the file this site produced.",
+ title: "Verify a document",
+};
+
+export default function VerifyPage() {
+ return (
+ <PublicDocumentShell
+ description="Check that a signed PDF or audit certificate is exactly the file this site produced when signing finished. Any change to the file, however small, gives a different fingerprint."
+ lastUpdated="November 13, 2026"
+ title="Verify a document"
+ >
+ <div className="mx-auto w-full max-w-[52rem] space-y-8">
+ <VerifyForm />
+ <section className="space-y-3">
+ <h2 className="text-xl font-semibold tracking-[-0.03em] text-(--fg)">
+ Checking the seal in a PDF reader
+ </h2>
+ <p>
+ Finished documents and certificates also carry a digital seal. Open
+ the file in Adobe Acrobat Reader or another PDF reader and look at
+ its signature panel. The reader says whether the document has been
+ changed since it was sealed. Unless the organization has installed a
+ certificate from a certificate authority, the reader will also say
+ the signer&apos;s identity is unknown; that is expected and does not
+ affect the check for changes.
+ </p>
+ </section>
+ </div>
+ </PublicDocumentShell>
+ );
+}
diff --git a/src/components/downloads/renew-download-button.tsx b/src/components/downloads/renew-download-button.tsx
new file mode 100644
index 0000000..a3f19f8
--- /dev/null
+++ b/src/components/downloads/renew-download-button.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { useState } from "react";
+
+import { ShellButton } from "@/components/shared/form-shell";
+
+export function RenewDownloadButton({ token }: { token: string }) {
+ const [state, setState] = useState<
+ | { kind: "idle" }
+ | { kind: "sending" }
+ | { kind: "sent"; maskedEmail: string }
+ | { kind: "error"; message: string }
+ >({ kind: "idle" });
+
+ async function handleClick() {
+ setState({ kind: "sending" });
+
+ try {
+ const response = await fetch(
+ `/api/download/${encodeURIComponent(token)}/renew`,
+ { method: "POST" },
+ );
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ maskedEmail?: string;
+ } | null;
+
+ if (!response.ok || !payload?.maskedEmail) {
+ setState({
+ kind: "error",
+ message: payload?.error ?? "New links could not be sent right now.",
+ });
+ return;
+ }
+
+ setState({ kind: "sent", maskedEmail: payload.maskedEmail });
+ } catch {
+ setState({
+ kind: "error",
+ message: "New links could not be sent right now.",
+ });
+ }
+ }
+
+ return (
+ <div className="space-y-4">
+ {state.kind === "sent" ? (
+ <p role="status" className="font-semibold text-(--fg)">
+ New links are on their way to {state.maskedEmail}.
+ </p>
+ ) : (
+ <ShellButton loading={state.kind === "sending"} onClick={handleClick}>
+ {state.kind === "sending"
+ ? "Sending..."
+ : "Email me new download links"}
+ </ShellButton>
+ )}
+ {state.kind === "error" ? (
+ <p role="alert" className="text-(--accent)">
+ {state.message}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsx
index 75b3f4f..d11adf9 100644
--- a/src/components/envelopes/review-shell.tsx
+++ b/src/components/envelopes/review-shell.tsx
@@ -2,7 +2,6 @@
import { useEffect, useRef, useState } from "react";
-import { useBranding } from "@/components/layout/branding-provider";
import { ShellButton } from "@/components/shared/form-shell";
import { PageHeader } from "@/components/shared/page-header";
import { StatusPanel } from "@/components/shared/status-panel";
@@ -16,6 +15,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import type { ReviewEnvelopeData } from "@/lib/envelopes";
+import { PERMITTED_USE_PATH } from "@/lib/permitted-uses";
import { getSignerPalette } from "./signer-palette";
const envelopeSteps = ["Upload", "Signers", "Place fields", "Review"];
@@ -37,11 +37,7 @@ type ReviewRecordView = {
};
type ReviewFieldSummaryLabel =
- | "Checkbox"
- | "Date"
- | "Initials"
- | "Signature"
- | "Text";
+ "Checkbox" | "Date" | "Initials" | "Signature" | "Text";
type ReviewSigner = {
color?: string;
@@ -390,7 +386,6 @@ function SendConfirmationDialog({
title,
}: SendConfirmationDialogProps) {
const [isPermittedUseConfirmed, setIsPermittedUseConfirmed] = useState(false);
- const { termsUrl } = useBranding();
return (
<Dialog
@@ -437,30 +432,22 @@ function SendConfirmationDialog({
<span className="text-sm leading-6 text-muted-foreground">
By sending, you confirm this document is an ordinary business
agreement and not a will, court order, legally required consumer
- disclosure, or other
- {termsUrl ? (
- <>
- {" "}
- excluded document type described in the{" "}
- <a
- className="font-semibold text-(--fg)"
- href={termsUrl}
- rel="noreferrer"
- style={{
- textDecorationColor: "rgba(17,17,17,0.35)",
- textDecorationLine: "underline",
- textDecorationThickness: "1px",
- textUnderlineOffset: "4px",
- }}
- target="_blank"
- >
- Terms of Service
- </a>
- .
- </>
- ) : (
- " document that cannot be signed electronically."
- )}
+ disclosure, or other{" "}
+ <a
+ className="font-semibold text-(--fg)"
+ href={PERMITTED_USE_PATH}
+ rel="noreferrer"
+ style={{
+ textDecorationColor: "rgba(17,17,17,0.35)",
+ textDecorationLine: "underline",
+ textDecorationThickness: "1px",
+ textUnderlineOffset: "4px",
+ }}
+ target="_blank"
+ >
+ document that cannot be signed electronically
+ </a>
+ .
</span>
</span>
</label>
diff --git a/src/components/envelopes/signers-shell.tsx b/src/components/envelopes/signers-shell.tsx
index 094f03f..8577abd 100644
--- a/src/components/envelopes/signers-shell.tsx
+++ b/src/components/envelopes/signers-shell.tsx
@@ -30,7 +30,16 @@ type SignersShellProps = {
type SignerField = "email" | "name";
-type ShellSigner = {
+type SignerChecks = {
+ /** A new code typed by the sender. Empty means "no change". */
+ accessCode: string;
+ /** A code is saved on the server. */
+ hasAccessCode: boolean;
+ removeAccessCode: boolean;
+ requireEmailCode: boolean;
+};
+
+type ShellSigner = SignerChecks & {
email: string;
localId: string;
name: string;
@@ -39,6 +48,7 @@ type ShellSigner = {
};
type SignerErrors = {
+ accessCode?: string;
email?: string;
name?: string;
};
@@ -55,8 +65,12 @@ function createSigner(
},
): ShellSigner {
return {
+ accessCode: "",
email: overrides?.email ?? "",
+ hasAccessCode: overrides?.hasAccessCode ?? false,
localId,
+ removeAccessCode: false,
+ requireEmailCode: overrides?.requireEmailCode ?? false,
name: overrides?.name ?? "",
signerId: overrides?.signerId,
touched: {
@@ -74,7 +88,9 @@ function buildInitialModel(record?: DraftSignerStepData): InitialModel {
.map((signer) =>
createSigner(signer.id, {
email: signer.email,
+ hasAccessCode: signer.hasAccessCode,
name: signer.name,
+ requireEmailCode: signer.requireEmailCode,
signerId: signer.id,
touched: { email: true, name: true },
}),
@@ -119,6 +135,15 @@ function buildSignerErrors(signers: readonly ShellSigner[]) {
signerErrors.email = duplicateSignerEmailMessage;
}
+ const accessCode = signer.accessCode.trim();
+
+ if (
+ accessCode.length > 0 &&
+ (accessCode.length < 4 || accessCode.length > 64)
+ ) {
+ signerErrors.accessCode = "Use 4 to 64 characters";
+ }
+
errorsBySignerId[signer.localId] = signerErrors;
}
@@ -126,7 +151,7 @@ function buildSignerErrors(signers: readonly ShellSigner[]) {
}
function hasSignerErrors(errors: SignerErrors) {
- return Boolean(errors.name || errors.email);
+ return Boolean(errors.name || errors.email || errors.accessCode);
}
function reorderSigners(
@@ -158,9 +183,16 @@ function reorderSigners(
function buildSignerRequest(signers: readonly ShellSigner[]) {
return {
signers: signers.map((signer, index) => ({
+ accessCode:
+ signer.accessCode.trim().length > 0
+ ? signer.accessCode.trim()
+ : signer.removeAccessCode
+ ? null
+ : undefined,
email: signer.email,
id: signer.signerId,
name: signer.name,
+ requireEmailCode: signer.requireEmailCode,
signOrder: index + 1,
})),
};
@@ -170,9 +202,7 @@ async function parseJsonResponse<T>(
response: Response,
): Promise<{ data: T | null; error: string | null }> {
const payload = (await response.json().catch(() => null)) as
- | { error?: string }
- | T
- | null;
+ { error?: string } | T | null;
if (!response.ok) {
return {
@@ -203,10 +233,14 @@ function SignerCard({
nameError,
onChange,
onBlur,
+ onChecksChange,
onMove,
onRemove,
+ accessCodeError,
signer,
}: {
+ accessCodeError?: string;
+ onChecksChange: (patch: Partial<SignerChecks>) => void;
canMoveEarlier: boolean;
canMoveLater: boolean;
canRemove: boolean;
@@ -345,6 +379,84 @@ function SignerCard({
</span>
</label>
</div>
+
+ <fieldset className="grid gap-3 border-t border-(--border) pt-4 text-sm">
+ <legend className="sr-only">Extra check before signing</legend>
+ <p className="font-semibold text-(--fg)">
+ Extra check before signing{" "}
+ <span className="font-normal text-muted-foreground">
+ (optional)
+ </span>
+ </p>
+ <p className="text-xs leading-5 text-muted-foreground">
+ By default anyone holding the emailed link can sign. Add a check
+ when the signer&apos;s identity matters.
+ </p>
+ <label className="flex items-start gap-3">
+ <input
+ aria-label={`Email signer ${order} a one-time code`}
+ checked={signer.requireEmailCode}
+ className="mt-1 size-4"
+ disabled={disabled}
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ onChecksChange({ requireEmailCode: event.target.checked })
+ }
+ type="checkbox"
+ />
+ <span>Email a one-time code when they open the link</span>
+ </label>
+ <label className="grid gap-2">
+ <span>
+ Access code you will give them yourself, for example by phone
+ {signer.hasAccessCode && !signer.removeAccessCode
+ ? " (a code is set; type a new one to change it)"
+ : ""}
+ </span>
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <input
+ aria-invalid={accessCodeError ? true : undefined}
+ aria-label={`Signer ${order} access code`}
+ autoComplete="off"
+ className="min-h-11 flex-1 rounded-none border border-(--border) bg-popover px-4 text-(--fg) outline-none placeholder:text-(--placeholder)"
+ disabled={disabled}
+ maxLength={64}
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ onChecksChange({
+ accessCode: event.target.value,
+ removeAccessCode: false,
+ })
+ }
+ placeholder={
+ signer.hasAccessCode && !signer.removeAccessCode
+ ? "••••••"
+ : "No access code"
+ }
+ type="text"
+ value={signer.accessCode}
+ />
+ {signer.hasAccessCode && !signer.removeAccessCode ? (
+ <button
+ className="min-h-11 border border-(--border) px-4 text-xs font-semibold text-muted-foreground hover:border-black hover:text-(--fg)"
+ disabled={disabled}
+ onClick={() =>
+ onChecksChange({ accessCode: "", removeAccessCode: true })
+ }
+ type="button"
+ >
+ Remove code
+ </button>
+ ) : null}
+ </div>
+ {accessCodeError ? (
+ <span
+ className="text-xs font-semibold text-(--accent)"
+ role="alert"
+ >
+ {accessCodeError}
+ </span>
+ ) : null}
+ </label>
+ </fieldset>
</div>
</li>
);
@@ -395,6 +507,18 @@ export function SignersShell({
);
}
+ function handleSignerChecksChange(
+ signerLocalId: string,
+ patch: Partial<SignerChecks>,
+ ) {
+ clearSubmitError();
+ setSigners((currentSigners) =>
+ currentSigners.map((signer) =>
+ signer.localId === signerLocalId ? { ...signer, ...patch } : signer,
+ ),
+ );
+ }
+
function handleSignerBlur(signerLocalId: string, field: SignerField) {
setSigners((currentSigners) =>
currentSigners.map((signer) =>
@@ -568,6 +692,10 @@ export function SignersShell({
handleSignerChange(signer.localId, field, value)
}
onBlur={(field) => handleSignerBlur(signer.localId, field)}
+ accessCodeError={errorsBySignerId[signer.localId]?.accessCode}
+ onChecksChange={(patch) =>
+ handleSignerChecksChange(signer.localId, patch)
+ }
onMove={(direction) =>
handleMoveSigner(signer.localId, direction)
}
diff --git a/src/components/layout/public-legal-links.tsx b/src/components/layout/public-legal-links.tsx
index 8228c6e..6a8b797 100644
--- a/src/components/layout/public-legal-links.tsx
+++ b/src/components/layout/public-legal-links.tsx
@@ -7,6 +7,7 @@ import { useBranding } from "@/components/layout/branding-provider";
import { SIGNUDOC_NAME, SIGNUDOC_URL } from "@/lib/branding";
import { PUBLIC_COPYRIGHT_YEAR, publicFooterLinks } from "@/lib/legal";
import { cn } from "@/lib/cn";
+import { PERMITTED_USE_PATH } from "@/lib/permitted-uses";
const ibmPlexMono = IBM_Plex_Mono({
display: "swap",
@@ -56,17 +57,28 @@ export function PublicLegalFooter({
},
]
: []),
- ...(branding.privacyUrl
- ? [
- {
- external: true,
- href: branding.privacyUrl,
- label: labelVariant === "long" ? "Privacy Policy" : "Privacy",
- },
- ]
- : []),
+ // Without the organization's own policy, signers still get a
+ // notice, built from the install's settings.
+ branding.privacyUrl
+ ? {
+ external: true,
+ href: branding.privacyUrl,
+ label: labelVariant === "long" ? "Privacy Policy" : "Privacy",
+ }
+ : {
+ external: false,
+ href: "/signer-privacy",
+ label: labelVariant === "long" ? "Privacy notice" : "Privacy",
+ },
];
+ // Which documents may be signed here: on every install.
+ links.push({
+ external: false,
+ href: PERMITTED_USE_PATH,
+ label: labelVariant === "long" ? "What this is for" : "E-signatures",
+ });
+
return (
<footer
className={cn(
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
index 5b3e515..936041d 100644
--- a/src/components/settings/organization-settings.tsx
+++ b/src/components/settings/organization-settings.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
+import { SignerDataPanel } from "@/components/settings/signer-data-panel";
import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";
import type {
OrganizationSettingsField,
@@ -112,6 +113,7 @@ export function OrganizationSettings({
allowedEmailDomains: values.allowedEmailDomains,
organizationName: values.organizationName,
privacyUrl: values.privacyUrl,
+ retentionDays: values.retentionDays,
senderAddress: values.senderAddress,
signupMode: values.signupMode,
supportAddress: values.supportAddress,
@@ -313,15 +315,51 @@ export function OrganizationSettings({
value={values.privacyUrl}
/>
</div>
+ <p className="max-w-2xl text-sm leading-6 text-muted-foreground">
+ Without a privacy policy link, signers see{" "}
+ <a className="underline" href="/signer-privacy" target="_blank">
+ a notice built from these settings
+ </a>
+ . Check that it is right for your organization.
+ </p>
</div>
) : null}
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <div className="space-y-2">
+ <h3 className="text-xl font-bold tracking-[-0.03em] text-(--fg)">
+ How long to keep finished documents
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-muted-foreground">
+ Optional. After this many days a completed, declined or voided
+ envelope is deleted with its audit trail. Its sender is emailed
+ 30 days before. Leave empty to keep them until someone deletes
+ them. Many records must be kept for years, so check what applies
+ to you before setting this.
+ </p>
+ </div>
+ <div className="max-w-xs">
+ <FieldShell
+ disabled={isSaving}
+ error={errors.retentionDays}
+ label="Days to keep"
+ name="retention-days"
+ onChange={handleChange("retentionDays")}
+ placeholder="Keep until deleted"
+ readOnly={false}
+ value={values.retentionDays}
+ />
+ </div>
+ </div>
+
<ShellButton className="w-fit" loading={isSaving} type="submit">
{isSaving ? "Saving..." : "Save organization settings"}
</ShellButton>
</form>
<EmailSetupPanel key={emailRevision} />
+
+ <SignerDataPanel />
</div>
</section>
);
diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsx
index 401c139..cdb37e6 100644
--- a/src/components/settings/settings-shell.tsx
+++ b/src/components/settings/settings-shell.tsx
@@ -161,7 +161,7 @@ function isNoOpEmailChangeMessage(message: string) {
export function SettingsShell({
initialProfile = defaultProfileValues,
}: SettingsShellProps) {
- const { productName } = useBranding();
+ const closureCopy = useClosureCopy();
const [profileValues, setProfileValues] = useState(initialProfile);
const [savedProfileValues, setSavedProfileValues] = useState(initialProfile);
const [profileErrors, setProfileErrors] = useState<ProfileErrors>({});
@@ -665,10 +665,7 @@ export function SettingsShell({
<div className="space-y-5">
<SectionHeading title="Danger zone" />
<p className="max-w-2xl text-sm leading-6 text-muted-foreground">
- Before closing your account, download any documents you want to
- keep. After closure, {productName} may provide a 30-day export window
- and then delete stored document files and related envelope
- records.
+ {closureCopy}
</p>
<ShellButton
className="w-fit"
@@ -734,6 +731,14 @@ type AccountClosureDialogProps = {
onConfirm: () => void;
};
+function useClosureCopy(): string {
+ const { hosted, productName } = useBranding();
+
+ return hosted
+ ? `Before closing your account, download any documents you want to keep. After closure, ${productName} keeps a 30-day export window and then deletes your stored documents and envelope records. Signers keep the copies they were emailed.`
+ : `Before closing your account, download any documents you want to keep. After 30 days your drafts and unfinished envelopes are deleted. Finished documents and their audit trails stay with ${productName}: they move to an administrator, because they are the organization's records.`;
+}
+
function AccountClosureDialog({
confirmationValue,
isReady,
@@ -742,7 +747,7 @@ function AccountClosureDialog({
onChange,
onConfirm,
}: AccountClosureDialogProps) {
- const { productName } = useBranding();
+ const closureCopy = useClosureCopy();
return (
<Dialog
@@ -763,10 +768,7 @@ function AccountClosureDialog({
Request account closure?
</DialogTitle>
<DialogDescription className="text-sm leading-6 text-muted-foreground">
- Before closing your account, download any documents you want to
- keep. After closure, {productName} may provide a 30-day export window
- and then delete stored document files and related envelope
- records.
+ {closureCopy}
</DialogDescription>
</DialogHeader>
diff --git a/src/components/settings/signer-data-panel.tsx b/src/components/settings/signer-data-panel.tsx
new file mode 100644
index 0000000..252c7a1
--- /dev/null
+++ b/src/components/settings/signer-data-panel.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { useState } from "react";
+
+import { FieldShell, ShellButton } from "@/components/shared/form-shell";
+
+// Answers a signer who asks what is stored about them, or for it to be
+// erased. Administrators only.
+
+type ErasureResult = {
+ deletedEnvelopes: number;
+ removedFromDrafts: number;
+ skippedInProgress: { id: string; title: string }[];
+};
+
+export function SignerDataPanel() {
+ const [email, setEmail] = useState("");
+ const [confirmation, setConfirmation] = useState("");
+ const [isErasing, setIsErasing] = useState(false);
+ const [message, setMessage] = useState<{
+ text: string;
+ tone: "error" | "success";
+ } | null>(null);
+ const trimmed = email.trim();
+ const exportHref = `/api/admin/signer-data?email=${encodeURIComponent(trimmed)}`;
+
+ async function erase() {
+ setIsErasing(true);
+ setMessage(null);
+
+ try {
+ const response = await fetch("/api/admin/signer-data", {
+ body: JSON.stringify({ confirmation, email: trimmed }),
+ headers: { "content-type": "application/json" },
+ method: "DELETE",
+ });
+ const payload = (await response.json().catch(() => null)) as
+ (ErasureResult & { error?: string }) | null;
+
+ if (!response.ok || !payload) {
+ setMessage({
+ text: payload?.error ?? "That request could not be completed.",
+ tone: "error",
+ });
+ return;
+ }
+
+ const skipped = payload.skippedInProgress.length
+ ? ` ${String(payload.skippedInProgress.length)} envelope(s) still out for signature were left alone: void them first, then erase again.`
+ : "";
+
+ setMessage({
+ text: `Deleted ${String(payload.deletedEnvelopes)} finished envelope(s) and removed the signer from ${String(payload.removedFromDrafts)} draft(s).${skipped}`,
+ tone: "success",
+ });
+ setConfirmation("");
+ } catch {
+ setMessage({
+ text: "That request could not be completed.",
+ tone: "error",
+ });
+ } finally {
+ setIsErasing(false);
+ }
+ }
+
+ return (
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <div className="space-y-2">
+ <h3 className="text-xl font-bold tracking-[-0.03em] text-(--fg)">
+ Signer data requests
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-muted-foreground">
+ When a signer asks what you hold about them, download it here. When
+ they ask for it to be erased, you can delete every finished envelope
+ they signed, with its files and audit trail. Signed records are often
+ ones you must keep, so erase only when no law or open dispute requires
+ them.
+ </p>
+ </div>
+ <div className="grid max-w-xl gap-4">
+ <FieldShell
+ label="Signer's email"
+ name="signer-data-email"
+ onChange={(event) => setEmail(event.target.value)}
+ placeholder="[email protected]"
+ readOnly={false}
+ type="email"
+ value={email}
+ />
+ <a
+ aria-disabled={trimmed.length === 0}
+ className={`w-fit border border-(--border) px-5 py-3 text-sm font-semibold ${
+ trimmed.length === 0
+ ? "pointer-events-none text-(--placeholder)"
+ : "text-(--fg) hover:border-black"
+ }`}
+ download
+ href={exportHref}
+ >
+ Download their data (JSON)
+ </a>
+ <FieldShell
+ helper="Type the email again to confirm erasure. This cannot be undone."
+ label="Confirm erasure"
+ name="signer-data-confirm"
+ onChange={(event) => setConfirmation(event.target.value)}
+ readOnly={false}
+ value={confirmation}
+ />
+ <ShellButton
+ className="w-fit"
+ disabled={
+ trimmed.length === 0 ||
+ confirmation.trim().toLowerCase() !== trimmed.toLowerCase()
+ }
+ loading={isErasing}
+ onClick={erase}
+ variant="secondary"
+ >
+ Erase this signer&apos;s records
+ </ShellButton>
+ {message ? (
+ <p
+ className={`text-sm ${message.tone === "error" ? "text-(--accent)" : "text-muted-foreground"}`}
+ role={message.tone === "error" ? "alert" : "status"}
+ >
+ {message.text}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/signing/signer-verification-screen.tsx b/src/components/signing/signer-verification-screen.tsx
new file mode 100644
index 0000000..5aec733
--- /dev/null
+++ b/src/components/signing/signer-verification-screen.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import { useState, type FormEvent } from "react";
+
+import { Brand } from "@/components/layout/brand";
+import { PublicLegalFooter } from "@/components/layout/public-legal-links";
+import { FieldShell, ShellButton } from "@/components/shared/form-shell";
+import type { SigningVerificationState } from "@/lib/schemas/signing";
+
+type Method = SigningVerificationState["required"][number];
+
+const METHOD_COPY: Record<Method, { helper: string; label: string }> = {
+ access_code: {
+ helper: "The sender gave you this code separately, for example by phone.",
+ label: "Access code",
+ },
+ email_code: {
+ helper: "We email a 6-digit code to the address this document was sent to.",
+ label: "Code from your email",
+ },
+};
+
+export function SignerVerificationScreen({
+ state,
+ token,
+}: {
+ state: SigningVerificationState;
+ token: string;
+}) {
+ const method = state.pending[0]!;
+ const [code, setCode] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(
+ state.emailCodeSentAt && method === "email_code"
+ ? `A code was sent to ${state.maskedEmail}.`
+ : null,
+ );
+ const [isChecking, setIsChecking] = useState(false);
+ const [isSending, setIsSending] = useState(false);
+ const base = `/api/signing/${encodeURIComponent(token)}`;
+
+ async function sendCode() {
+ setIsSending(true);
+ setError(null);
+
+ try {
+ const response = await fetch(`${base}/verify/email-code`, {
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ maskedEmail?: string;
+ } | null;
+
+ if (!response.ok) {
+ setError(payload?.error ?? "The code could not be sent right now.");
+ return;
+ }
+
+ setNotice(
+ `A code was sent to ${payload?.maskedEmail ?? state.maskedEmail}.`,
+ );
+ } catch {
+ setError("The code could not be sent right now.");
+ } finally {
+ setIsSending(false);
+ }
+ }
+
+ async function handleSubmit(event: FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ setIsChecking(true);
+ setError(null);
+
+ try {
+ const response = await fetch(`${base}/verify`, {
+ body: JSON.stringify({ code, method }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+
+ if (!response.ok) {
+ setError(payload?.error ?? "The code could not be checked right now.");
+ return;
+ }
+
+ // The page reads the new cookie and shows the next check or the
+ // document.
+ window.location.reload();
+ } catch {
+ setError("The code could not be checked right now.");
+ } finally {
+ setIsChecking(false);
+ }
+ }
+
+ const copy = METHOD_COPY[method];
+ const step = state.required.indexOf(method) + 1;
+
+ return (
+ <div className="flex min-h-screen flex-col bg-white">
+ <header className="border-b border-(--border) bg-white">
+ <div className="mx-auto flex max-w-[1360px] items-center px-4 py-5 sm:px-6 lg:px-8">
+ <Brand href="/" />
+ </div>
+ </header>
+ <main className="mx-auto flex w-full max-w-[1360px] flex-1 items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
+ <section className="editorial-panel w-full max-w-[560px] px-6 py-10 sm:px-10">
+ <h1 className="text-[28px] font-extrabold tracking-[-0.04em] text-(--fg)">
+ Confirm it&apos;s you
+ </h1>
+ <p className="mt-3 text-base leading-7 text-muted-foreground">
+ {state.senderName} asked for a check before you open &ldquo;
+ {state.envelopeTitle}&rdquo;.
+ {state.required.length > 1
+ ? ` Step ${String(step)} of ${String(state.required.length)}.`
+ : ""}
+ </p>
+ <form className="mt-8 grid gap-5" onSubmit={handleSubmit}>
+ <FieldShell
+ autoComplete="one-time-code"
+ helper={copy.helper}
+ label={copy.label}
+ name="signer-code"
+ onChange={(event) => setCode(event.target.value)}
+ readOnly={false}
+ value={code}
+ />
+ {notice ? (
+ <p className="text-sm text-muted-foreground" role="status">
+ {notice}
+ </p>
+ ) : null}
+ {error ? (
+ <p className="text-sm text-(--accent)" role="alert">
+ {error}
+ </p>
+ ) : null}
+ <div className="flex flex-col gap-3 sm:flex-row">
+ <ShellButton
+ disabled={code.trim().length === 0}
+ loading={isChecking}
+ type="submit"
+ >
+ Continue
+ </ShellButton>
+ {method === "email_code" ? (
+ <ShellButton
+ loading={isSending}
+ onClick={sendCode}
+ variant="secondary"
+ >
+ {notice ? "Send a new code" : "Email me a code"}
+ </ShellButton>
+ ) : null}
+ </div>
+ </form>
+ </section>
+ </main>
+ <PublicLegalFooter />
+ </div>
+ );
+}
diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsx
index 88ef69b..fff2526 100644
--- a/src/components/signing/signing-live-shell.tsx
+++ b/src/components/signing/signing-live-shell.tsx
@@ -37,6 +37,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { Checkbox } from "@/components/ui/checkbox";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import {
@@ -355,6 +356,10 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
const [checkboxValues, setCheckboxValues] = useState<Record<string, boolean>>(
{},
);
+ const [consentedAt, setConsentedAt] = useState(record.consentedAt);
+ const [isConsentChecked, setIsConsentChecked] = useState(false);
+ const [isSavingConsent, setIsSavingConsent] = useState(false);
+ const [consentError, setConsentError] = useState<string | null>(null);
const [declineError, setDeclineError] = useState<string | null>(null);
const [declineReason, setDeclineReason] = useState("");
const [isDeclineDialogOpen, setIsDeclineDialogOpen] = useState(false);
@@ -397,9 +402,8 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
const pageVisibleFields = record.visibleFields.filter(
(field) => field.page === activePage,
);
- const actionSummaryFields = record.currentSignerFields.filter(
- isActionSummaryField,
- );
+ const actionSummaryFields =
+ record.currentSignerFields.filter(isActionSummaryField);
const remainingFields = record.currentSignerFields.filter(
(field) =>
field.required &&
@@ -500,6 +504,36 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
}
}
+ async function handleConsent() {
+ setIsSavingConsent(true);
+ setConsentError(null);
+
+ try {
+ const response = await fetch(record.consentUrl, {
+ body: JSON.stringify({ disclosureVersion: record.disclosure.version }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ consentedAt?: number;
+ error?: string;
+ } | null;
+
+ if (!response.ok || typeof payload?.consentedAt !== "number") {
+ setConsentError(
+ payload?.error ?? "Your agreement could not be saved right now.",
+ );
+ return;
+ }
+
+ setConsentedAt(payload.consentedAt);
+ } catch {
+ setConsentError("Your agreement could not be saved right now.");
+ } finally {
+ setIsSavingConsent(false);
+ }
+ }
+
async function handleDeclineSigning() {
if (isDeclining) {
return;
@@ -588,17 +622,26 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
</p>
</div>
</div>
- <ShellButton
- className="min-h-11 px-4"
- disabled={isSubmitting || isDeclining}
- onClick={() => {
- setDeclineError(null);
- setIsDeclineDialogOpen(true);
- }}
- variant="secondary"
- >
- Decline
- </ShellButton>
+ <div className="flex items-center gap-3">
+ <a
+ className="inline-flex min-h-11 items-center px-2 text-sm font-semibold text-(--fg) underline decoration-[rgba(17,17,17,0.35)] underline-offset-4"
+ download="document.pdf"
+ href={`${record.documentUrl}?download=1`}
+ >
+ Download PDF
+ </a>
+ <ShellButton
+ className="min-h-11 px-4"
+ disabled={isSubmitting || isDeclining}
+ onClick={() => {
+ setDeclineError(null);
+ setIsDeclineDialogOpen(true);
+ }}
+ variant="secondary"
+ >
+ Decline
+ </ShellButton>
+ </div>
</div>
</header>
@@ -844,7 +887,6 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
))}
</div>
</section>
-
</aside>
</section>
</main>
@@ -931,6 +973,59 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {
</DialogFrame>
) : null}
+ {consentedAt === null && !isDeclineDialogOpen ? (
+ <DialogFrame
+ description={`${record.senderName} sent you "${record.envelopeTitle}" to sign electronically.`}
+ onClose={() => undefined}
+ title="Before you sign"
+ >
+ <div className="max-h-[45vh] space-y-4 overflow-y-auto border border-(--border) bg-(--surface) px-4 py-4 text-sm leading-6 text-muted-foreground">
+ {record.disclosure.sections.map((section) => (
+ <section key={section.heading}>
+ <h3 className="font-semibold text-(--fg)">{section.heading}</h3>
+ <p className="mt-1">{section.text}</p>
+ </section>
+ ))}
+ </div>
+ <label className="flex items-start gap-3 text-sm leading-6 text-(--fg)">
+ <Checkbox
+ aria-label="I agree to use electronic records and signatures"
+ checked={isConsentChecked}
+ className="mt-1"
+ disabled={isSavingConsent}
+ onCheckedChange={(checked) =>
+ setIsConsentChecked(checked === true)
+ }
+ />
+ <span>{record.disclosure.statement}</span>
+ </label>
+ {consentError ? (
+ <div className="border border-[rgba(180,35,53,0.18)] bg-[rgba(180,35,53,0.08)] px-4 py-3 text-sm text-(--accent)">
+ {consentError}
+ </div>
+ ) : null}
+ <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
+ <ShellButton
+ disabled={isSavingConsent}
+ onClick={() => {
+ setDeclineError(null);
+ setIsDeclineDialogOpen(true);
+ }}
+ variant="secondary"
+ >
+ Decline
+ </ShellButton>
+ <ShellButton
+ disabled={!isConsentChecked}
+ loading={isSavingConsent}
+ onClick={handleConsent}
+ >
+ Agree and continue
+ </ShellButton>
+ </div>
+ </DialogFrame>
+ ) : null}
+
{isDeclineDialogOpen ? (
<DialogFrame
description={`The sender (${record.senderName}) will be notified that you declined. This cannot be undone.`}
@@ -1075,7 +1170,8 @@ function CurrentSignerField({
type="button"
>
<span className="pointer-events-none flex h-full w-full items-center justify-center overflow-hidden px-1 text-center">
- {signatureEntry?.inputMethod === "drawn" && signatureEntry.imageDataUrl ? (
+ {signatureEntry?.inputMethod === "drawn" &&
+ signatureEntry.imageDataUrl ? (
<span className="relative block h-full w-full">
<Image
alt={`${field.type === "initials" ? "Initials" : "Signature"} preview`}
@@ -1094,7 +1190,9 @@ function CurrentSignerField({
? typedSignatureFont
: undefined,
fontSize:
- signatureEntry.inputMethod === "typed" ? "1.05rem" : undefined,
+ signatureEntry.inputMethod === "typed"
+ ? "1.05rem"
+ : undefined,
}}
>
{signatureEntry.value}
diff --git a/src/components/signing/signing-shell.tsx b/src/components/signing/signing-shell.tsx
index 457d190..7c9209f 100644
--- a/src/components/signing/signing-shell.tsx
+++ b/src/components/signing/signing-shell.tsx
@@ -2,19 +2,21 @@
import { Brand } from "@/components/layout/brand";
import { PublicLegalFooter } from "@/components/layout/public-legal-links";
-import type { SigningPayload } from "@/lib/schemas/signing";
+import type {
+ SigningPayload,
+ SigningVerificationState,
+} from "@/lib/schemas/signing";
+import { SignerVerificationScreen } from "./signer-verification-screen";
import { SigningLiveShell } from "./signing-live-shell";
type SigningUnavailableState =
- | "already-signed"
- | "declined"
- | "error"
- | "expired"
- | "voided";
+ "already-signed" | "declined" | "error" | "expired" | "voided";
type SigningShellProps = {
initialState?: SigningUnavailableState;
record?: SigningPayload;
+ token: string;
+ verification?: SigningVerificationState;
};
const tokenStateCopy: Record<
@@ -46,11 +48,20 @@ const tokenStateCopy: Record<
},
};
-export function SigningShell({ initialState, record }: SigningShellProps) {
+export function SigningShell({
+ initialState,
+ record,
+ token,
+ verification,
+}: SigningShellProps) {
if (record) {
return <SigningLiveShell record={record} />;
}
+ if (verification) {
+ return <SignerVerificationScreen state={verification} token={token} />;
+ }
+
const tokenState = tokenStateCopy[initialState ?? "error"];
return (
diff --git a/src/components/verify/verify-form.tsx b/src/components/verify/verify-form.tsx
new file mode 100644
index 0000000..662d87e
--- /dev/null
+++ b/src/components/verify/verify-form.tsx
@@ -0,0 +1,147 @@
+"use client";
+
+import { useState, type ChangeEvent } from "react";
+
+type VerifyAnswer =
+ | { match: false }
+ | {
+ envelopeId: string;
+ fileKind: "signed-document" | "certificate";
+ finishedAt: number | null;
+ match: true;
+ 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;
+
+async function sha256OfFile(file: File): Promise<string> {
+ const digest = await crypto.subtle.digest(
+ "SHA-256",
+ await file.arrayBuffer(),
+ );
+
+ return Array.from(new Uint8Array(digest))
+ .map((byte) => byte.toString(16).padStart(2, "0"))
+ .join("");
+}
+
+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 [error, setError] = useState<string | null>(null);
+ const [isChecking, setIsChecking] = useState(false);
+
+ async function handleFile(event: ChangeEvent<HTMLInputElement>) {
+ const file = event.target.files?.[0];
+
+ setAnswer(null);
+ setError(null);
+ setHash(null);
+
+ if (!file) {
+ setFileName(null);
+ return;
+ }
+
+ setFileName(file.name);
+ setIsChecking(true);
+
+ try {
+ const sha256 = await sha256OfFile(file);
+
+ setHash(sha256);
+
+ const response = await fetch("/api/verify", {
+ body: JSON.stringify({ sha256 }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as
+ (VerifyAnswer & { error?: string }) | null;
+
+ if (!response.ok || !payload) {
+ setError(payload?.error ?? "The file could not be checked right now.");
+ return;
+ }
+
+ setAnswer(payload);
+ } catch {
+ setError("The file could not be read.");
+ } finally {
+ setIsChecking(false);
+ }
+ }
+
+ return (
+ <div className="space-y-6">
+ <label className="block border border-dashed border-(--border) bg-(--surface) px-6 py-8 text-center">
+ <span className="block text-sm font-semibold text-(--fg)">
+ Choose a signed PDF or audit certificate
+ </span>
+ <span className="mt-1 block text-sm text-muted-foreground">
+ The file stays on your device. Only its SHA-256 fingerprint is sent.
+ </span>
+ <input
+ accept="application/pdf,.pdf"
+ aria-label="PDF to verify"
+ className="mx-auto mt-4 block text-sm"
+ onChange={handleFile}
+ type="file"
+ />
+ </label>
+
+ <div aria-live="polite" className="space-y-3" role="status">
+ {isChecking ? <p>Checking {fileName}...</p> : null}
+ {error ? <p className="text-(--accent)">{error}</p> : null}
+ {answer?.match === true ? (
+ <div className="border border-[rgba(24,132,74,0.3)] bg-[rgba(24,132,74,0.06)] px-5 py-4 text-(--fg)">
+ <p className="font-semibold">
+ This file is unchanged. It is the{" "}
+ {answer.fileKind === "signed-document"
+ ? "signed document"
+ : "audit certificate"}{" "}
+ this site produced for &ldquo;{answer.title}&rdquo;.
+ </p>
+ <p className="mt-2 text-sm text-muted-foreground">
+ 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"}. Envelope ID{" "}
+ {answer.envelopeId}.
+ </p>
+ </div>
+ ) : null}
+ {answer?.match === false ? (
+ <div className="border border-[rgba(180,35,53,0.18)] bg-[rgba(180,35,53,0.06)] px-5 py-4 text-(--fg)">
+ <p className="font-semibold">No match.</p>
+ <p className="mt-2 text-sm text-muted-foreground">
+ 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.
+ </p>
+ </div>
+ ) : null}
+ {hash ? (
+ <p className="break-all font-mono text-xs text-muted-foreground">
+ SHA-256: {hash}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/src/lib/download-renewal.ts b/src/lib/download-renewal.ts
new file mode 100644
index 0000000..ca9353f
--- /dev/null
+++ b/src/lib/download-renewal.ts
@@ -0,0 +1,70 @@
+import { type DbExecutor, getDb } from "./db/connection.ts";
+import {
+ renewRecipientDownloadLinks,
+ type RenewedDownloadLinks,
+} from "./downloads.ts";
+import { getBranding } from "./settings.ts";
+import { recordEmailSent } from "./services/audit.ts";
+import { createEmailService, type EmailService } from "./services/email.ts";
+import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
+import { RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS } from "./types/domain.ts";
+import { escapeHtml } from "./utils/html.ts";
+
+const TTL_DAYS = RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS / (24 * 60 * 60);
+
+/** Sends fresh download links to the signer an expired link belonged to. */
+export async function sendFreshDownloadLinks(
+ token: string,
+ {
+ database = getDb(),
+ emailService = createEmailService(),
+ }: { database?: DbExecutor; emailService?: EmailService } = {},
+): Promise<RenewedDownloadLinks> {
+ const branding = await getBranding();
+
+ return renewRecipientDownloadLinks(token, {
+ database,
+ async sendLinks({ envelope, evidenceUrl, signedUrl, signer }) {
+ const subject = `New download links for "${envelope.title}"`;
+ const textBody = [
+ `Hi ${signer.name},`,
+ "",
+ `Here are new download links for "${envelope.title}" in ${branding.productName}. They work for ${String(TTL_DAYS)} days.`,
+ "",
+ ...(signedUrl ? [`Signed PDF: ${signedUrl}`] : []),
+ `Certificate: ${evidenceUrl}`,
+ "",
+ "Download and keep the files: they are your copy of the record.",
+ ].join("\n");
+ const htmlBody = [
+ `<p>Hi ${escapeHtml(signer.name)},</p>`,
+ `<p>Here are new download links for &ldquo;${escapeHtml(envelope.title)}&rdquo; in ${escapeHtml(branding.productName)}. They work for ${String(TTL_DAYS)} days.</p>`,
+ "<p>",
+ signedUrl
+ ? `<a href="${escapeHtml(signedUrl)}">Download signed PDF</a><br />`
+ : "",
+ `<a href="${escapeHtml(evidenceUrl)}">Download certificate</a></p>`,
+ "<p>Download and keep the files: they are your copy of the record.</p>",
+ ].join("");
+ const body = withUserEmailLegalFooter({ htmlBody, textBody }, branding);
+ const delivery = await emailService.send({
+ htmlBody: body.htmlBody,
+ subject,
+ template: "download_links",
+ textBody: body.textBody,
+ to: signer.email,
+ });
+
+ await recordEmailSent(
+ {
+ envelopeId: envelope.id,
+ messageId: delivery.messageId,
+ recipient: signer.email,
+ signerId: signer.id,
+ template: "download_links",
+ },
+ database,
+ );
+ },
+ });
+}
diff --git a/src/lib/downloads.ts b/src/lib/downloads.ts
index 741a187..6a13262 100644
--- a/src/lib/downloads.ts
+++ b/src/lib/downloads.ts
@@ -42,6 +42,9 @@ type EnvelopeRow = {
sourcePdfHash: string;
sourcePdfKey: string;
sourcePdfSizeBytes: number;
+ evidenceSha256: string | null;
+ recipientEvidenceSha256: string | null;
+ signedPdfSha256: string | null;
status: EnvelopeRecord["status"];
title: string;
updatedAt: number;
@@ -123,6 +126,14 @@ export class DownloadAccessError extends Error {
}
}
+/** A link this site issued whose time is up. A new one can be sent. */
+export class ExpiredDownloadLinkError extends DownloadAccessError {
+ constructor() {
+ super("This download link has expired.", 410);
+ this.name = "ExpiredDownloadLinkError";
+ }
+}
+
function mapEnvelopeRow(row: EnvelopeRow): EnvelopeRecord {
return envelopeRecordSchema.parse(row);
}
@@ -190,6 +201,9 @@ async function getEnvelopeById(
signed_pdf_key AS "signedPdfKey",
evidence_key AS "evidenceKey",
source_pdf_hash AS "sourcePdfHash",
+ signed_pdf_sha256 AS "signedPdfSha256",
+ evidence_sha256 AS "evidenceSha256",
+ recipient_evidence_sha256 AS "recipientEvidenceSha256",
sent_at AS "sentAt",
completed_at AS "completedAt",
declined_at AS "declinedAt",
@@ -225,6 +239,9 @@ async function getEnvelopeByIdForUser(
signed_pdf_key AS "signedPdfKey",
evidence_key AS "evidenceKey",
source_pdf_hash AS "sourcePdfHash",
+ signed_pdf_sha256 AS "signedPdfSha256",
+ evidence_sha256 AS "evidenceSha256",
+ recipient_evidence_sha256 AS "recipientEvidenceSha256",
sent_at AS "sentAt",
completed_at AS "completedAt",
declined_at AS "declinedAt",
@@ -443,7 +460,7 @@ async function listFieldsForEnvelope(
return rows.map(mapFieldRow);
}
-function sanitizeFileNameSegment(value: string): string {
+export function sanitizeFileNameSegment(value: string): string {
return value
.trim()
.replace(/[<>:"/\\|?*\u0000-\u001F]+/g, " ")
@@ -512,6 +529,12 @@ async function buildSignedPdfDownload(
}
}
+ // A file whose fingerprint was recorded cannot be made again: a rebuilt
+ // copy would not match it, and handing one out would undo the point.
+ if (envelope.signedPdfSha256) {
+ throw new DownloadAccessError("This file is no longer available.", 404);
+ }
+
const [auditEvents, fields, signers] = await Promise.all([
listAuditEventsForEnvelope(envelope.id, database),
listFieldsForEnvelope(envelope.id, database),
@@ -612,6 +635,14 @@ async function buildCertificateDownload(
}
}
+ if (
+ redactForRecipients
+ ? envelope.recipientEvidenceSha256
+ : envelope.evidenceSha256
+ ) {
+ throw new DownloadAccessError("This file is no longer available.", 404);
+ }
+
const [auditEvents, signers] = await Promise.all([
listAuditEventsForEnvelope(envelope.id, database),
listSignersForEnvelope(envelope.id, database),
@@ -620,6 +651,7 @@ async function buildCertificateDownload(
auditEvents,
envelope,
redactForRecipients,
+ signedPdfSha256: envelope.signedPdfSha256,
signers,
});
@@ -698,13 +730,17 @@ export async function getPublicEnvelopeDownloadForToken(
);
const now = Math.floor(Date.now() / 1000);
- if (!tokenRow || tokenRow.expiresAt <= now) {
+ if (!tokenRow) {
throw new DownloadAccessError(
"This download link is invalid or has expired.",
410,
);
}
+ if (tokenRow.expiresAt <= now) {
+ throw new ExpiredDownloadLinkError();
+ }
+
const envelope = await getEnvelopeById(tokenRow.envelopeId, database);
if (!envelope) {
@@ -737,3 +773,94 @@ export async function getPublicEnvelopeDownloadForToken(
redactForRecipients: true,
});
}
+
+export type RenewedDownloadLinks = {
+ /** The signer's address with most of it hidden, to show on the page. */
+ maskedEmail: string;
+};
+
+function maskEmail(email: string): string {
+ const [local = "", domain = ""] = email.split("@");
+
+ return `${local.slice(0, 1)}${"*".repeat(Math.max(1, local.length - 1))}@${domain}`;
+}
+
+/**
+ * Someone holding an expired download link asks for a new one. The new links
+ * go only to the signer's own address on record, never anywhere the request
+ * names, so holding an old link gains nothing a forwarded email did not.
+ */
+export async function renewRecipientDownloadLinks(
+ token: string,
+ {
+ database = getDb(),
+ sendLinks,
+ }: {
+ database?: DbExecutor;
+ sendLinks: (input: {
+ envelope: EnvelopeRecord;
+ evidenceUrl: string;
+ signedUrl: string | null;
+ signer: SignerRecord;
+ }) => Promise<void>;
+ },
+): Promise<RenewedDownloadLinks> {
+ const tokenRow = await getRecipientDownloadTokenByHash(
+ hashOpaqueToken(token),
+ database,
+ );
+ const envelope = tokenRow
+ ? await getEnvelopeById(tokenRow.envelopeId, database)
+ : null;
+ const signer =
+ tokenRow && envelope
+ ? await getSignerForEnvelope(tokenRow.signerId, envelope.id, database)
+ : null;
+
+ if (
+ !tokenRow ||
+ !envelope ||
+ !signer?.id ||
+ (envelope.status !== "completed" &&
+ envelope.status !== "declined" &&
+ envelope.status !== "voided")
+ ) {
+ throw new DownloadAccessError(
+ "This download link is invalid or has expired.",
+ 410,
+ );
+ }
+
+ const issuedAt = Math.floor(Date.now() / 1000);
+ const [signedLink, evidenceLink] = await Promise.all([
+ envelope.status === "completed"
+ ? createRecipientDownloadLink(
+ {
+ envelopeId: envelope.id,
+ fileType: "signed",
+ issuedAt,
+ signerId: signer.id,
+ },
+ { database },
+ )
+ : Promise.resolve(null),
+ createRecipientDownloadLink(
+ {
+ envelopeId: envelope.id,
+ fileType: "evidence",
+ issuedAt,
+ signerId: signer.id,
+ },
+ { database },
+ ),
+ ]);
+
+ await sendLinks({
+ envelope,
+ evidenceUrl: evidenceLink.url,
+ signedUrl: signedLink?.url ?? null,
+ signer,
+ });
+
+ return { maskedEmail: maskEmail(signer.email) };
+}
diff --git a/src/lib/electronic-records-disclosure.ts b/src/lib/electronic-records-disclosure.ts
new file mode 100644
index 0000000..b78dae2
--- /dev/null
+++ b/src/lib/electronic-records-disclosure.ts
@@ -0,0 +1,49 @@
+// What a signer is told, and agrees to, before signing: the disclosure the
+// US laws on electronic signatures expect (ESIGN 101(c), UETA 5) and that
+// works as a plain statement of terms elsewhere. Its version is stored with
+// each signer's agreement, so the record shows which words they saw. Change
+// the version whenever the words change.
+
+export const ELECTRONIC_RECORDS_DISCLOSURE_VERSION = "2026-11-13";
+
+export type DisclosureParty = {
+ /** Who to ask for a paper copy or to withdraw: the organization or sender. */
+ contactAddress: string | null;
+ senderName: string;
+};
+
+export type DisclosureSection = { heading: string; text: string };
+
+export function buildElectronicRecordsDisclosure(
+ party: DisclosureParty,
+): DisclosureSection[] {
+ const contact = party.contactAddress
+ ? `${party.senderName} at ${party.contactAddress}`
+ : party.senderName;
+
+ return [
+ {
+ heading: "Using electronic records and signatures",
+ text: `${party.senderName} asks you to receive this document and sign it electronically instead of on paper. If you agree, your electronic signature has the same effect as a handwritten one, and the documents you receive this way count as delivered to you in writing.`,
+ },
+ {
+ heading: "You can choose paper instead",
+ text: `You do not have to agree. To sign on paper instead, or to ask for a paper copy of any document after signing, contact ${contact}. A paper copy is free unless ${party.senderName} tells you otherwise before you ask.`,
+ },
+ {
+ heading: "Withdrawing your agreement",
+ text: `You can withdraw this agreement at any time before you sign by declining or by telling ${contact}. Withdrawing does not undo a signature you already gave.`,
+ },
+ {
+ heading: "What you need",
+ text: "A current web browser and a device that can open and save PDF files. You will receive the signed document by email, so keep your email address up to date with the sender. Download and keep the signed copy: it is your record.",
+ },
+ {
+ heading: "This agreement covers",
+ text: "This document and the notices about it that are sent to you through this site.",
+ },
+ ];
+}
+
+export const CONSENT_STATEMENT =
+ "I have read the disclosure above, I can open and save PDF files on this device, and I agree to use electronic records and signatures for this document.";
diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.ts
index 131e013..73c7f77 100644
--- a/src/lib/email-status.test.ts
+++ b/src/lib/email-status.test.ts
@@ -6,6 +6,7 @@ import {
emailNeedsAttention,
getEmailStatus,
recheckEmailDomain,
+ resendRegionOption,
type ResendDomainsClient,
} from "./email-status.ts";
import { resolveSettings, type AppSettings } from "./settings.ts";
@@ -15,6 +16,7 @@ const stored: AppSettings = {
emailReadyAt: null,
organizationName: "Acme Corp",
privacyUrl: null,
+ retentionDays: null,
senderAddress: "[email protected]",
setupCompletedAt: 1_800_000_000,
signupMode: "domains",
@@ -545,3 +547,11 @@ test("the administrator is told about email until it has been seen working", ()
false,
);
});
+
+test("RESEND_REGION picks a known Resend region and ignores anything else", () => {
+ assert.deepEqual(resendRegionOption({ RESEND_REGION: "EU-WEST-1" }), {
+ region: "eu-west-1",
+ });
+ assert.deepEqual(resendRegionOption({ RESEND_REGION: "mars-1" }), {});
+ assert.deepEqual(resendRegionOption({}), {});
+});
diff --git a/src/lib/email-status.ts b/src/lib/email-status.ts
index 92454c4..2e04230 100644
--- a/src/lib/email-status.ts
+++ b/src/lib/email-status.ts
@@ -12,7 +12,7 @@ import {
markEmailReady,
type ResolvedSettings,
} from "./settings.ts";
-import { getEnv, type EnvSource } from "./utils/env.ts";
+import { getEnv, readEnv, type EnvSource } from "./utils/env.ts";
// Whether this install can send email to anyone, and what is left to do if
// it cannot. Shown to the administrator in Settings.
@@ -63,6 +63,28 @@ export type EmailStatus =
| { state: "error"; message: string; senderAddress: string };
/** The parts of the Resend SDK used here. Replaced by a fake in tests. */
+const RESEND_REGIONS = [
+ "us-east-1",
+ "eu-west-1",
+ "sa-east-1",
+ "ap-northeast-1",
+] as const;
+
+/**
+ * RESEND_REGION picks where Resend sends a new domain's mail from, for
+ * example eu-west-1 to keep sending in the EU. Unset, Resend's default
+ * (us-east-1) is used. It only applies when the app adds the domain.
+ */
+export function resendRegionOption(env: EnvSource): {
+ region?: (typeof RESEND_REGIONS)[number];
+} {
+ const value = readEnv(env, "RESEND_REGION")?.toLowerCase();
+
+ return value && (RESEND_REGIONS as readonly string[]).includes(value)
+ ? { region: value as (typeof RESEND_REGIONS)[number] }
+ : {};
+}
+
export type ResendDomainsClient = Pick<
Resend["domains"],
"create" | "get" | "list" | "verify"
@@ -473,7 +495,10 @@ export async function addEmailDomain(
}
const created = await callResend(() =>
- client.create({ name: status.domain }),
+ client.create({
+ name: status.domain,
+ ...resendRegionOption(options.env ?? process.env),
+ }),
);
if (created.error) {
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index c1afa76..b679bc5 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -44,6 +44,7 @@ import { importPdfDocument } from "./services/document-import.ts";
import {
listAuditEventsForEnvelope,
recordAuditEvent,
+ recordEmailSent,
} from "./services/audit.ts";
import { createEmailService } from "./services/email.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
@@ -63,6 +64,8 @@ import {
getManualNudgeAvailableAt,
isManualNudgeAvailable,
} from "./services/reminders.ts";
+import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";
+import { hashAccessCode } from "./signer-checks.ts";
import { escapeHtml } from "./utils/html.ts";
type CreateDraftEnvelopeOptions = {
@@ -208,11 +211,7 @@ export type DashboardEnvelopeListItem = {
};
type ReviewFieldSummary =
- | "Checkbox"
- | "Date"
- | "Initials"
- | "Signature"
- | "Text";
+ "Checkbox" | "Date" | "Initials" | "Signature" | "Text";
export type ReviewSignerSummary = {
email: string;
@@ -237,9 +236,12 @@ export type ReviewEnvelopeData = {
export type DraftSignerStepSigner = {
email: string;
+ /** Set on the signers step only. */
+ hasAccessCode?: boolean;
id: string;
name: string;
order: number;
+ requireEmailCode?: boolean;
};
export type DraftSignerStepData = {
@@ -352,11 +354,15 @@ const TIMELINE_TONE_MAP: Record<
EnvelopeDetailTimelineItem["tone"]
> = {
completed: "success",
+ consented: "neutral",
created: "accent",
declined: "danger",
+ email_sent: "neutral",
reminded_manual: "neutral",
sent: "neutral",
signed: "success",
+ verification_failed: "danger",
+ verified: "neutral",
viewed: "neutral",
voided: "danger",
};
@@ -711,6 +717,38 @@ async function listSignersForEnvelopeId(
);
}
+async function listSignerCheckSettings(
+ envelopeId: string,
+ database: DbExecutor,
+): Promise<Map<string, { hasAccessCode: boolean; requireEmailCode: boolean }>> {
+ const rows = await queryMany<{
+ hasAccessCode: boolean;
+ id: string;
+ requireEmailCode: boolean;
+ }>(
+ database,
+ `
+ SELECT
+ id,
+ access_code_hash IS NOT NULL AS "hasAccessCode",
+ require_email_code AS "requireEmailCode"
+ FROM signers
+ WHERE envelope_id = $1
+ `,
+ [envelopeId],
+ );
+
+ return new Map(
+ rows.map((row) => [
+ row.id,
+ {
+ hasAccessCode: Boolean(row.hasAccessCode),
+ requireEmailCode: Boolean(row.requireEmailCode),
+ },
+ ]),
+ );
+}
+
async function listEnvelopePagesForEnvelopeId(
envelopeId: string,
database: DbExecutor,
@@ -917,6 +955,16 @@ function buildTimelineDescription(event: AuditEventRecord): string {
: `Declined by ${targetLabel}`;
case "reminded_manual":
return `Manual reminder sent to ${targetLabel}`;
+ case "consented":
+ return `${targetLabel} agreed to use electronic records and signatures`;
+ case "verified":
+ return `${targetLabel} confirmed their identity`;
+ case "verification_failed":
+ return `Wrong identity code entered for ${targetLabel}`;
+ case "email_sent":
+ return typeof event.metadata?.recipient === "string"
+ ? `Email accepted for delivery to ${event.metadata.recipient}`
+ : "Email accepted for delivery";
case "completed":
return "Final signed PDF and certificate generated";
case "voided":
@@ -1185,14 +1233,18 @@ export async function getDraftSignerStepDataForUser(
return null;
}
+ const checks = await listSignerCheckSettings(envelopeId, database);
+
return {
envelopeId,
signers: (await listSignersForEnvelopeId(envelopeId, database)).map(
(signer) => ({
email: signer.email,
+ hasAccessCode: checks.get(signer.id)?.hasAccessCode ?? false,
id: signer.id,
name: signer.name,
order: signer.signOrder,
+ requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,
}),
),
status: envelope.status,
@@ -1485,6 +1537,9 @@ export async function sendDraftEnvelope(
event: "sent",
ipAddress: input.ipAddress ?? null,
metadata: {
+ // The send route refuses a send without this confirmation.
+ permittedUseConfirmed: true,
+ permittedUseVersion: PERMITTED_USE_VERSION,
signerEmail: firstSigner.email,
signerId: firstSigner.id,
signerName: firstSigner.name,
@@ -1498,17 +1553,21 @@ export async function sendDraftEnvelope(
throw error;
}
+ let invitationMessageId: string | undefined;
+
try {
- await emailService.send(
- buildSigningInvitationEmail({
- branding: await getBranding(),
- envelopeTitle: envelope.title,
- senderName: input.senderName,
- signerEmail: firstSigner.email,
- signerName: firstSigner.name,
- signingUrl: issuedLink.url,
- }),
- );
+ invitationMessageId = (
+ await emailService.send(
+ buildSigningInvitationEmail({
+ branding: await getBranding(),
+ envelopeTitle: envelope.title,
+ senderName: input.senderName,
+ signerEmail: firstSigner.email,
+ signerName: firstSigner.name,
+ signingUrl: issuedLink.url,
+ }),
+ )
+ ).messageId;
} catch (error) {
await withTransaction(async (tx) => {
await tx.query(
@@ -1564,6 +1623,17 @@ export async function sendDraftEnvelope(
throw error;
}
+ await recordEmailSent(
+ {
+ envelopeId,
+ messageId: invitationMessageId,
+ recipient: firstSigner.email,
+ signerId: firstSigner.id,
+ template: "signing_invitation",
+ },
+ database,
+ );
+
return sendEnvelopeResponseSchema.parse({
envelopeId,
notifiedSignerName: firstSigner.name,
@@ -1656,7 +1726,8 @@ export async function voidSentEnvelope(
voidedAuditEvent,
];
const storedCertificateKeys: string[] = [];
- let certificate: { key: string };
+ let certificate: { key: string; sha256: string };
+ let recipientCertificateSha256: string;
try {
certificate = await storeEnvelopeCertificatePdf(
@@ -1690,6 +1761,7 @@ export async function voidSentEnvelope(
},
);
storedCertificateKeys.push(recipientCertificate.key);
+ recipientCertificateSha256 = recipientCertificate.sha256;
} catch (error) {
await Promise.all(
storedCertificateKeys.map((key) =>
@@ -1725,12 +1797,22 @@ export async function voidSentEnvelope(
status = 'voided',
evidence_key = $1,
voided_at = $2,
- updated_at = $3
+ updated_at = $3,
+ evidence_sha256 = $6,
+ recipient_evidence_sha256 = $7
WHERE id = $4
AND user_id = $5
AND status = 'sent'
`,
- [certificate.key, voidedAt, voidedAt, envelopeId, userId],
+ [
+ certificate.key,
+ voidedAt,
+ voidedAt,
+ envelopeId,
+ userId,
+ certificate.sha256,
+ recipientCertificateSha256,
+ ],
);
if (updatedEnvelope.rowCount !== 1) {
@@ -1757,6 +1839,7 @@ export async function voidSentEnvelope(
{
actorEmail: voidedAuditEvent.actorEmail,
actorType: voidedAuditEvent.actorType,
+ id: voidedAuditEvent.id,
createdAt: voidedAuditEvent.createdAt,
envelopeId: voidedAuditEvent.envelopeId,
event: voidedAuditEvent.event,
@@ -1782,10 +1865,12 @@ export async function voidSentEnvelope(
notifiedSigners.map(async (signer) => {
try {
if (!branding) {
- throw new Error("Could not load settings for the notification email.");
+ throw new Error(
+ "Could not load settings for the notification email.",
+ );
}
- await emailService.send(
+ const delivery = await emailService.send(
buildVoidNotificationEmail({
branding,
envelopeId,
@@ -1795,6 +1880,17 @@ export async function voidSentEnvelope(
signerName: signer.name,
}),
);
+
+ await recordEmailSent(
+ {
+ envelopeId,
+ messageId: delivery.messageId,
+ recipient: signer.email,
+ signerId: signer.id,
+ template: "void_notification",
+ },
+ database,
+ );
} catch (error) {
console.error(
`Failed to send void notification for envelope ${envelopeId} to ${signer.email}:`,
@@ -1986,9 +2082,17 @@ export async function replaceDraftEnvelopeSigners(
usedSignerIds.add(persistedSignerId);
return {
+ // undefined keeps the saved hash; null clears it.
+ accessCodeHash:
+ signer.accessCode === undefined
+ ? undefined
+ : signer.accessCode === null
+ ? null
+ : hashAccessCode(signer.accessCode),
email: signer.email,
id: persistedSignerId,
name: signer.name,
+ requireEmailCode: signer.requireEmailCode,
signOrder: index + 1,
};
});
@@ -2017,7 +2121,9 @@ export async function replaceDraftEnvelopeSigners(
name = $1,
email = $2,
sign_order = $3,
- updated_at = $4
+ updated_at = $4,
+ access_code_hash = CASE WHEN $7::boolean THEN $8 ELSE access_code_hash END,
+ require_email_code = COALESCE($9, require_email_code)
WHERE id = $5 AND envelope_id = $6
`,
[
@@ -2027,6 +2133,9 @@ export async function replaceDraftEnvelopeSigners(
updatedAt,
signer.id,
envelopeId,
+ signer.accessCodeHash !== undefined,
+ signer.accessCodeHash ?? null,
+ signer.requireEmailCode ?? null,
],
);
} else {
@@ -2048,9 +2157,11 @@ export async function replaceDraftEnvelopeSigners(
declined_at,
decline_reason,
created_at,
- updated_at
+ updated_at,
+ access_code_hash,
+ require_email_code
) VALUES (
- $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7
+ $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9
)
`,
[
@@ -2061,6 +2172,8 @@ export async function replaceDraftEnvelopeSigners(
signer.signOrder,
updatedAt,
updatedAt,
+ signer.accessCodeHash ?? null,
+ signer.requireEmailCode ?? false,
],
);
}
@@ -2085,14 +2198,18 @@ export async function replaceDraftEnvelopeSigners(
);
}, database);
+ const checks = await listSignerCheckSettings(envelopeId, database);
+
return replaceSignersResponseSchema.parse({
envelopeId,
redirectPath: `/envelopes/${envelopeId}/prepare`,
signers: (await listSignersForEnvelopeId(envelopeId, database)).map(
(signer) => ({
email: signer.email,
+ hasAccessCode: checks.get(signer.id)?.hasAccessCode ?? false,
id: signer.id,
name: signer.name,
+ requireEmailCode: checks.get(signer.id)?.requireEmailCode ?? false,
signOrder: signer.signOrder,
}),
),
diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.ts
index 98414a1..aabe214 100644
--- a/src/lib/organization-settings.test.ts
+++ b/src/lib/organization-settings.test.ts
@@ -13,6 +13,7 @@ const stored: AppSettings = {
emailReadyAt: null,
organizationName: "Acme Corp",
privacyUrl: null,
+ retentionDays: null,
senderAddress: "[email protected]",
setupCompletedAt: 1_800_000_000,
signupMode: "domains",
@@ -25,6 +26,7 @@ const storedRow = {
email_ready_at: stored.emailReadyAt,
organization_name: stored.organizationName,
privacy_url: stored.privacyUrl,
+ retention_days: stored.retentionDays,
sender_address: stored.senderAddress,
setup_completed_at: stored.setupCompletedAt,
signup_mode: stored.signupMode,
diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.ts
index bde036c..bd0b4d8 100644
--- a/src/lib/organization-settings.ts
+++ b/src/lib/organization-settings.ts
@@ -15,6 +15,7 @@ export type OrganizationSettingsField =
| "allowedEmailDomains"
| "organizationName"
| "privacyUrl"
+ | "retentionDays"
| "senderAddress"
| "signupMode"
| "supportAddress"
@@ -36,6 +37,8 @@ export type OrganizationSettingsView = {
hosted: boolean;
organizationName: string;
privacyUrl: string;
+ /** Days, as typed. Empty keeps finished envelopes until deleted by hand. */
+ retentionDays: string;
senderAddress: string;
senderAddressFromEnv: boolean;
signupMode: AppSettings["signupMode"];
@@ -52,6 +55,8 @@ export function toOrganizationSettingsView(
hosted: settings.hosted,
organizationName: settings.organizationName ?? "",
privacyUrl: settings.privacyUrl ?? "",
+ retentionDays:
+ settings.retentionDays === null ? "" : String(settings.retentionDays),
senderAddress: settings.senderAddress ?? "",
senderAddressFromEnv: settings.senderAddressFromEnv,
signupMode: settings.signupMode,
@@ -88,6 +93,13 @@ const organizationSettingsSchema = z.object({
allowedEmailDomains: z.string().max(4000).default(""),
organizationName: z.string().trim().min(1).max(120),
privacyUrl: optionalWebUrl.default(null),
+ retentionDays: z
+ .preprocess((value) => {
+ const blank = blankToNull(value);
+
+ return typeof blank === "string" ? Number(blank) : blank;
+ }, z.number().int().min(30).max(36_500).nullable())
+ .default(null),
senderAddress: optionalEmail.default(null),
signupMode: z.enum(SIGNUP_MODES),
supportAddress: optionalEmail.default(null),
@@ -98,6 +110,7 @@ const FIELD_MESSAGES: Record<OrganizationSettingsField, string> = {
allowedEmailDomains: "Enter one or more domains, such as yourcompany.com",
organizationName: "Enter the name of your organization",
privacyUrl: "Enter a full web address starting with https://",
+ retentionDays: "Enter a number of days, 30 or more, or leave this empty",
senderAddress: "Enter a valid email address, or leave this empty",
signupMode: "Choose who can create an account",
supportAddress: "Enter a valid email address, or leave this empty",
@@ -187,6 +200,7 @@ export async function updateOrganizationSettings(
{
...(domainRule ? { allowedEmailDomains: domains } : {}),
organizationName: input.organizationName,
+ retentionDays: input.retentionDays,
signupMode: input.signupMode,
...(current.hosted
? {}
diff --git a/src/lib/permitted-uses.ts b/src/lib/permitted-uses.ts
new file mode 100644
index 0000000..19195a9
--- /dev/null
+++ b/src/lib/permitted-uses.ts
@@ -0,0 +1,51 @@
+// What documents this software may be used for, shown on every install at
+// /electronic-signatures and confirmed by the sender before each send. The
+// version is stored with each send, so the record shows which list the
+// sender confirmed.
+
+export const PERMITTED_USE_VERSION = "2026-11-13";
+export const PERMITTED_USE_PATH = "/electronic-signatures";
+
+export type UseSection = { heading: string; items: string[] };
+
+/** Documents the US laws exclude from electronic signature (ESIGN 103, UETA 3). */
+export const US_EXCLUDED_DOCUMENTS: string[] = [
+ "Wills, codicils and testamentary trusts.",
+ "Adoption, divorce and other family-law matters.",
+ "Court orders, notices and official court documents such as briefs and pleadings.",
+ "Notices of default, foreclosure, eviction or repossession under a credit agreement or lease of a primary residence.",
+ "Notices that utility services (water, heat, power) will be cancelled or terminated.",
+ "Notices that health or life insurance benefits will be cancelled or terminated (not including annuities).",
+ "Product recall notices and notices of material failure that risk health or safety.",
+ "Documents required to accompany the transport or handling of hazardous materials, pesticides or other toxic or dangerous materials.",
+ "Most of the Uniform Commercial Code other than sales and leases (for example negotiable instruments such as promissory notes meant to be transferred).",
+ "Anything else your state or country requires on paper, notarized or witnessed in person, such as many real property deeds.",
+];
+
+/** Documents that the EU and member states commonly keep out of simple e-signatures. */
+export const EU_LIMITS: string[] = [
+ "Contracts creating or transferring rights in real estate (other than rental), which most member states require in notarial form.",
+ "Contracts that by law need a court, public authority or notary.",
+ "Suretyship and guarantee contracts given by consumers, and family or succession law matters, in many member states.",
+ "Anything your law requires to carry a qualified electronic signature (QES): Signudoc does not produce one.",
+];
+
+export const WHAT_IT_IS: UseSection = {
+ heading: "What Signudoc is",
+ items: [
+ "A tool for ordinary business agreements: sales and service contracts, NDAs, offer letters, purchase orders, consent and approval forms, and similar documents.",
+ "In the US, signatures made here are electronic signatures under ESIGN and UETA (and New York's ESRA).",
+ "In the EU and UK, they are simple electronic signatures (SES) under eIDAS. A court cannot refuse them only because they are electronic, but you may need to show who signed. The audit certificate, the sealed PDF and the optional access code or email code help with that.",
+ ],
+};
+
+export const WHAT_IT_IS_NOT: UseSection = {
+ heading: "What Signudoc is not",
+ items: [
+ "Not an advanced (AdES) or qualified (QES) electronic signature under eIDAS. The seal on finished PDFs is the install's own, not a qualified seal.",
+ "Not built for US FDA 21 CFR Part 11 records: it has no signature manifestation with meaning, no re-authentication at each signature, and no validated system documentation.",
+ "Not a HIPAA-covered service. Do not send protected health information unless your organization has its own agreements and controls for every service the install uses.",
+ "Not a consumer-disclosure system beyond the electronic-records agreement each signer gives. If a law requires you to deliver specific consumer notices electronically, check that its own rules are met.",
+ "Not legal advice. Whoever runs this install decides which documents it may be used for.",
+ ],
+};
diff --git a/src/lib/reminders.ts b/src/lib/reminders.ts
index ea0e1b7..db6559b 100644
--- a/src/lib/reminders.ts
+++ b/src/lib/reminders.ts
@@ -12,7 +12,7 @@ import {
} from "./schemas/envelope.ts";
import { type SignerRecord } from "./schemas/signer.ts";
import { getBranding } from "./settings.ts";
-import { recordAuditEvent } from "./services/audit.ts";
+import { recordAuditEvent, recordEmailSent } from "./services/audit.ts";
import { createEmailService } from "./services/email.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
import {
@@ -378,18 +378,22 @@ export async function sendManualEnvelopeNudge(
);
const emailService = createEmailService();
+ let reminderMessageId: string | undefined;
+
try {
- await emailService.send(
- buildReminderEmail({
- branding: await getBranding(),
- envelopeId: persisted.envelopeId,
- envelopeTitle: persisted.envelopeTitle,
- senderName: persisted.senderName,
- signerEmail: persisted.signerEmail,
- signerName: persisted.signerName,
- signingUrl: persisted.issuedLink.url,
- }),
- );
+ reminderMessageId = (
+ await emailService.send(
+ buildReminderEmail({
+ branding: await getBranding(),
+ envelopeId: persisted.envelopeId,
+ envelopeTitle: persisted.envelopeTitle,
+ senderName: persisted.senderName,
+ signerEmail: persisted.signerEmail,
+ signerName: persisted.signerName,
+ signingUrl: persisted.issuedLink.url,
+ }),
+ )
+ ).messageId;
} catch (error) {
await withTransaction(async (tx) => {
await tx.query(
@@ -447,6 +451,17 @@ export async function sendManualEnvelopeNudge(
throw error;
}
+ await recordEmailSent(
+ {
+ envelopeId: persisted.envelopeId,
+ messageId: reminderMessageId,
+ recipient: persisted.signerEmail,
+ signerId: persisted.signerId,
+ template: "manual_nudge",
+ },
+ database,
+ );
+
return manualNudgeResponseSchema.parse({
envelopeId: persisted.envelopeId,
nextAvailableAt: persisted.nextAvailableAt,
diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.ts
index 5cac5d0..11588a7 100644
--- a/src/lib/retention-job.ts
+++ b/src/lib/retention-job.ts
@@ -163,6 +163,7 @@ export async function runRetentionJob({
export function retentionSweepFailed(summary: RetentionSweepSummary): boolean {
return (
summary.accountPurgeFailures.length > 0 ||
- summary.draftDeletionFailures.length > 0
+ summary.draftDeletionFailures.length > 0 ||
+ summary.finishedEnvelopeDeletionFailures.length > 0
);
}
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index 66e09a2..a16aec4 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -9,6 +9,9 @@ import {
createStorageService,
type StorageService,
} from "./services/storage.ts";
+import { createEmailService, type EmailService } from "./services/email.ts";
+import { readStoredSettings } from "./settings.ts";
+import { type EnvSource, isHostedMode, resolveAppUrl } from "./utils/env.ts";
const DAY_IN_SECONDS = 24 * 60 * 60;
export const STALE_DRAFT_RETENTION_DAYS = 30;
@@ -51,9 +54,16 @@ export type RetentionSweepSummary = {
draftDeletionFailures: string[];
draftsDeleted: number;
expiredRecipientDownloadTokensDeleted: number;
+ finishedEnvelopeDeletionFailures: string[];
+ finishedEnvelopesDeleted: number;
+ finishedEnvelopeWarningsSent: number;
ranAt: number;
};
+/** How long before deletion a sender is told, and the shortest notice. */
+export const RETENTION_WARNING_DAYS = 30;
+const RETENTION_MIN_NOTICE_DAYS = 7;
+
function getCurrentUnixTimestamp() {
return Math.floor(Date.now() / 1000);
}
@@ -213,6 +223,10 @@ async function deleteStorageKeys(
}
}
+// An expired download link is kept for a year so the signer can still use
+// it to ask for a new one (see renewRecipientDownloadLinks).
+const EXPIRED_DOWNLOAD_TOKEN_GRACE_SECONDS = 365 * DAY_IN_SECONDS;
+
async function deleteExpiredRecipientDownloadTokens(
now: number,
database: DbExecutor,
@@ -222,7 +236,7 @@ async function deleteExpiredRecipientDownloadTokens(
DELETE FROM recipient_download_tokens
WHERE expires_at <= $1
`,
- [now],
+ [now - EXPIRED_DOWNLOAD_TOKEN_GRACE_SECONDS],
);
return result.rowCount ?? 0;
@@ -286,11 +300,88 @@ export async function scheduleAccountClosure(
};
}
+const FINISHED_ENVELOPE_STATUSES = ["completed", "declined", "voided"];
+
+/**
+ * On a self-hosted install the organization owns its signed records, so a
+ * person leaving must not take them along. Finished envelopes move to an
+ * administrator (or, failing that, any other active user) before the
+ * account is deleted. Returns false when there is nobody to keep them.
+ */
+async function handOverFinishedEnvelopes(
+ userId: string,
+ database: DbExecutor,
+): Promise<boolean> {
+ const finished = await queryOne<{ count: string }>(
+ database,
+ `
+ SELECT count(*)::text AS count
+ FROM envelopes
+ WHERE user_id = $1 AND status = ANY($2::text[])
+ `,
+ [userId, FINISHED_ENVELOPE_STATUSES],
+ );
+
+ if (Number(finished?.count ?? 0) === 0) {
+ return true;
+ }
+
+ const keeper = await queryOne<{ id: string }>(
+ database,
+ `
+ SELECT u.id
+ FROM "user" u
+ WHERE u.id <> $1
+ AND NOT EXISTS (
+ SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id
+ )
+ ORDER BY (u.role = 'admin') DESC, u."createdAt" ASC, u.id ASC
+ LIMIT 1
+ `,
+ [userId],
+ );
+
+ if (!keeper) {
+ return false;
+ }
+
+ await database.query(
+ `
+ UPDATE envelopes
+ SET user_id = $1
+ WHERE user_id = $2 AND status = ANY($3::text[])
+ `,
+ [keeper.id, userId, FINISHED_ENVELOPE_STATUSES],
+ );
+ console.info(
+ `Moved finished envelopes from closed account ${userId} to ${keeper.id}.`,
+ );
+
+ return true;
+}
+
+export class AccountPurgeDeferredError extends Error {
+ constructor(userId: string) {
+ super(
+ `Account ${userId} holds finished envelopes and no other user can keep them. Its purge is deferred until an administrator exists or the records are exported and deleted by hand.`,
+ );
+ this.name = "AccountPurgeDeferredError";
+ }
+}
+
async function purgeQueuedAccount(
userId: string,
database: DbExecutor,
storageService: StorageService,
+ env: EnvSource = process.env,
): Promise<boolean> {
+ if (
+ !isHostedMode(env) &&
+ !(await handOverFinishedEnvelopes(userId, database))
+ ) {
+ throw new AccountPurgeDeferredError(userId);
+ }
+
const envelopes = await listEnvelopeArtifactsForUser(userId, database);
const fieldImagesByEnvelopeId = await listFieldImagesForEnvelopeIds(
envelopes.map((envelope) => envelope.id),
@@ -361,12 +452,213 @@ async function purgeStaleDraftEnvelope(
return true;
}
+type FinishedEnvelopeRow = EnvelopeArtifactRow & {
+ finishedAt: number;
+ ownerEmail: string;
+ ownerName: string;
+ retentionWarnedAt: number | null;
+ title: string;
+};
+
+async function listFinishedEnvelopesOlderThan(
+ finishedBefore: number,
+ database: DbExecutor,
+): Promise<FinishedEnvelopeRow[]> {
+ return queryMany<FinishedEnvelopeRow>(
+ database,
+ `
+ SELECT
+ e.id,
+ e.user_id AS "userId",
+ e.status,
+ e.title,
+ e.source_pdf_key AS "sourcePdfKey",
+ e.signed_pdf_key AS "signedPdfKey",
+ e.evidence_key AS "evidenceKey",
+ e.updated_at AS "updatedAt",
+ e.retention_warned_at AS "retentionWarnedAt",
+ COALESCE(e.completed_at, e.declined_at, e.voided_at, e.updated_at) AS "finishedAt",
+ u.email AS "ownerEmail",
+ u.name AS "ownerName"
+ FROM envelopes e
+ JOIN "user" u ON u.id = e.user_id
+ WHERE e.status IN ('completed', 'declined', 'voided')
+ AND COALESCE(e.completed_at, e.declined_at, e.voided_at, e.updated_at) < $1
+ ORDER BY "finishedAt" ASC, e.id ASC
+ LIMIT 500
+ `,
+ [finishedBefore],
+ );
+}
+
+function formatDay(timestamp: number): string {
+ return new Date(timestamp * 1000).toISOString().slice(0, 10);
+}
+
+async function warnBeforeRetentionDeletion(
+ envelope: FinishedEnvelopeRow,
+ deleteOn: number,
+ now: number,
+ database: DbExecutor,
+ emailService: EmailService,
+) {
+ const appUrl = resolveAppUrl();
+ const link = appUrl ? `${appUrl}/envelopes/${envelope.id}` : null;
+
+ await emailService.send(
+ {
+ subject: `"${envelope.title}" will be deleted on ${formatDay(deleteOn)}`,
+ template: "retention_notice",
+ textBody: [
+ `Hello ${envelope.ownerName},`,
+ "",
+ `Your organization keeps finished documents for a set time. "${envelope.title}" and its audit trail will be deleted on or after ${formatDay(deleteOn)}.`,
+ "",
+ "Download the signed PDF and the certificate now if you need to keep them.",
+ ...(link ? ["", link] : []),
+ ].join("\n"),
+ to: envelope.ownerEmail,
+ },
+ { idempotencyKey: `retention-notice/${envelope.id}` },
+ );
+
+ await database.query(
+ `UPDATE envelopes SET retention_warned_at = $1 WHERE id = $2`,
+ [now, envelope.id],
+ );
+}
+
+/**
+ * Applies the install's retention period to finished envelopes: a warning to
+ * the sender first, deletion once the period has passed and the warning is
+ * at least a week old.
+ */
+async function applyRetentionPeriod(
+ retentionDays: number,
+ now: number,
+ database: DbExecutor,
+ storageService: StorageService,
+ emailService: () => EmailService,
+ summary: RetentionSweepSummary,
+) {
+ const warnBefore =
+ now - (retentionDays - RETENTION_WARNING_DAYS) * DAY_IN_SECONDS;
+ const candidates = await listFinishedEnvelopesOlderThan(warnBefore, database);
+ const fieldImagesByEnvelopeId = await listFieldImagesForEnvelopeIds(
+ candidates.map((envelope) => envelope.id),
+ database,
+ );
+
+ for (const envelope of candidates) {
+ const deleteOn = envelope.finishedAt + retentionDays * DAY_IN_SECONDS;
+
+ try {
+ if (envelope.retentionWarnedAt === null) {
+ await warnBeforeRetentionDeletion(
+ envelope,
+ Math.max(deleteOn, now + RETENTION_MIN_NOTICE_DAYS * DAY_IN_SECONDS),
+ now,
+ database,
+ emailService(),
+ );
+ summary.finishedEnvelopeWarningsSent += 1;
+ continue;
+ }
+
+ if (
+ deleteOn > now ||
+ envelope.retentionWarnedAt >
+ now - RETENTION_MIN_NOTICE_DAYS * DAY_IN_SECONDS
+ ) {
+ continue;
+ }
+
+ const deleted = await database.query(
+ `DELETE FROM envelopes WHERE id = $1 AND status = $2`,
+ [envelope.id, envelope.status],
+ );
+
+ if (deleted.rowCount === 1) {
+ await deleteStorageKeys(
+ buildEnvelopeStorageKeys(
+ envelope,
+ fieldImagesByEnvelopeId.get(envelope.id) ?? [],
+ ),
+ storageService,
+ );
+ summary.finishedEnvelopesDeleted += 1;
+ }
+ } catch (error) {
+ summary.finishedEnvelopeDeletionFailures.push(envelope.id);
+ console.error(
+ `Retention period handling failed for envelope ${envelope.id}:`,
+ error,
+ );
+ }
+ }
+}
+
+/** Deletes these envelopes and their stored files. Returns how many went. */
+export async function deleteEnvelopesAndFiles(
+ envelopeIds: readonly string[],
+ database: DbExecutor = getDb(),
+ storageService: StorageService = createStorageService(),
+): Promise<number> {
+ if (envelopeIds.length === 0) {
+ return 0;
+ }
+
+ const envelopes = await queryMany<EnvelopeArtifactRow>(
+ database,
+ `
+ SELECT
+ id,
+ user_id AS "userId",
+ status,
+ source_pdf_key AS "sourcePdfKey",
+ signed_pdf_key AS "signedPdfKey",
+ evidence_key AS "evidenceKey",
+ updated_at AS "updatedAt"
+ FROM envelopes
+ WHERE id = ANY($1::text[])
+ `,
+ [envelopeIds],
+ );
+ const fieldImagesByEnvelopeId = await listFieldImagesForEnvelopeIds(
+ envelopes.map((envelope) => envelope.id),
+ database,
+ );
+ const deleted = await database.query(
+ `DELETE FROM envelopes WHERE id = ANY($1::text[])`,
+ [envelopes.map((envelope) => envelope.id)],
+ );
+
+ for (const envelope of envelopes) {
+ await deleteStorageKeys(
+ buildEnvelopeStorageKeys(
+ envelope,
+ fieldImagesByEnvelopeId.get(envelope.id) ?? [],
+ ),
+ storageService,
+ ).catch((error) => {
+ console.error(
+ `Failed to delete files of envelope ${envelope.id}:`,
+ error,
+ );
+ });
+ }
+
+ return deleted.rowCount ?? 0;
+}
+
export async function runRetentionSweep({
database = getDb(),
+ emailService,
now = getCurrentUnixTimestamp(),
storageService = createStorageService(),
}: {
database?: DbExecutor;
+ emailService?: EmailService;
now?: number;
storageService?: StorageService;
} = {}): Promise<RetentionSweepSummary> {
@@ -383,6 +675,9 @@ export async function runRetentionSweep({
draftDeletionFailures: [],
draftsDeleted: 0,
expiredRecipientDownloadTokensDeleted: 0,
+ finishedEnvelopeDeletionFailures: [],
+ finishedEnvelopesDeleted: 0,
+ finishedEnvelopeWarningsSent: 0,
ranAt: now,
};
@@ -430,5 +725,20 @@ export async function runRetentionSweep({
}
}
+ const retentionDays = (await readStoredSettings(database))?.retentionDays;
+
+ if (retentionDays) {
+ let service = emailService;
+
+ await applyRetentionPeriod(
+ retentionDays,
+ now,
+ database,
+ storageService,
+ () => (service ??= createEmailService()),
+ summary,
+ );
+ }
+
return summary;
}
diff --git a/src/lib/schemas/envelope.ts b/src/lib/schemas/envelope.ts
index 084e7c1..8636f62 100644
--- a/src/lib/schemas/envelope.ts
+++ b/src/lib/schemas/envelope.ts
@@ -95,6 +95,9 @@ export const envelopeRecordSchema = z.object({
signedPdfKey: z.string().trim().min(1).nullable().optional(),
evidenceKey: z.string().trim().min(1).nullable().optional(),
sourcePdfHash: sourcePdfHashSchema,
+ signedPdfSha256: sourcePdfHashSchema.nullable().optional(),
+ evidenceSha256: sourcePdfHashSchema.nullable().optional(),
+ recipientEvidenceSha256: sourcePdfHashSchema.nullable().optional(),
sentAt: unixTimestampSchema.nullable().optional(),
completedAt: unixTimestampSchema.nullable().optional(),
declinedAt: unixTimestampSchema.nullable().optional(),
diff --git a/src/lib/schemas/signer.ts b/src/lib/schemas/signer.ts
index 808c757..8c99ca3 100644
--- a/src/lib/schemas/signer.ts
+++ b/src/lib/schemas/signer.ts
@@ -19,6 +19,10 @@ export const draftSignerSchema = z.object({
name: nameSchema,
email: emailSchema,
signOrder: z.number().int().positive().optional(),
+ // Extra checks before signing. accessCode: a string sets it, null removes
+ // it, and leaving it out keeps the code already saved.
+ accessCode: z.string().trim().min(4).max(64).nullable().optional(),
+ requireEmailCode: z.boolean().optional(),
});
export const signerListSchema = z
@@ -69,7 +73,9 @@ export const replaceSignersResponseSchema = z.object({
z.object({
email: emailSchema,
id: idSchema,
+ hasAccessCode: z.boolean(),
name: nameSchema,
+ requireEmailCode: z.boolean(),
signOrder: z.number().int().positive(),
}),
),
diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.ts
index f2ca2ed..4386259 100644
--- a/src/lib/schemas/signing.ts
+++ b/src/lib/schemas/signing.ts
@@ -46,8 +46,22 @@ export const signingVisibleFieldSchema = signingFieldBaseSchema.extend({
value: optionalTrimmedString(5000).nullable().optional(),
});
+export const signingDisclosureSchema = z.object({
+ sections: z.array(
+ z.object({
+ heading: z.string().trim().min(1),
+ text: z.string().trim().min(1),
+ }),
+ ),
+ statement: z.string().trim().min(1),
+ version: z.string().trim().min(1),
+});
+
export const signingPayloadSchema = z.object({
+ consentUrl: z.string().trim().min(1),
+ consentedAt: unixTimestampSchema.nullable(),
currentSignerFields: z.array(signingCurrentFieldSchema),
+ disclosure: signingDisclosureSchema,
declineUrl: z.string().trim().min(1),
documentUrl: z.string().trim().min(1),
envelopeId: idSchema,
@@ -91,6 +105,25 @@ export const signingRouteResponseSchema = z.union([
export type SigningCurrentField = z.infer<typeof signingCurrentFieldSchema>;
export type SigningVisibleField = z.infer<typeof signingVisibleFieldSchema>;
export type SigningPayload = z.infer<typeof signingPayloadSchema>;
+export type SigningDisclosure = z.infer<typeof signingDisclosureSchema>;
+
+export const signerCheckRequestSchema = z.object({
+ code: z.string().trim().min(1).max(64),
+ method: z.enum(["access_code", "email_code"]),
+});
+
+export const signerConsentRequestSchema = z.object({
+ disclosureVersion: z.string().trim().min(1).max(40),
+});
+
+export type SigningVerificationState = {
+ emailCodeSentAt: number | null;
+ envelopeTitle: string;
+ maskedEmail: string;
+ pending: Array<"access_code" | "email_code">;
+ required: Array<"access_code" | "email_code">;
+ senderName: string;
+};
export type SigningDeclineResponse = z.infer<
typeof signingDeclineResponseSchema
>;
diff --git a/src/lib/security/logging.ts b/src/lib/security/logging.ts
index df2db93..6cfa846 100644
--- a/src/lib/security/logging.ts
+++ b/src/lib/security/logging.ts
@@ -13,6 +13,7 @@ const TOKEN_PATH_PATTERNS = [
/^\/sign\/[^/]+/i,
/^\/api\/signing\/[^/]+/i,
/^\/api\/download\/[^/]+/i,
+ /^\/download\/[^/]+/i,
] as const;
function normalizeLoggedPath(path: string): string {
diff --git a/src/lib/services/audit.ts b/src/lib/services/audit.ts
index 319d3d4..dedae39 100644
--- a/src/lib/services/audit.ts
+++ b/src/lib/services/audit.ts
@@ -1,14 +1,21 @@
-import { randomUUID } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import {
auditEventRecordSchema,
type AuditEventRecord,
} from "../schemas/envelope.ts";
-import { type DbExecutor, getDb, queryMany } from "../db/connection.ts";
+import {
+ type DbExecutor,
+ getDb,
+ queryMany,
+ withTransaction,
+} from "../db/connection.ts";
export type AuditEventMetadata = Record<string, unknown> | null;
export type RecordAuditEventInput = {
+ /** Given when the event was already shown on a certificate under this id. */
+ id?: string;
envelopeId: string;
event: AuditEventRecord["event"];
actorType: AuditEventRecord["actorType"];
@@ -72,13 +79,102 @@ export async function listAuditEventsForEnvelope(
return rows.map(mapAuditRow);
}
-export async function recordAuditEvent(
+// Each envelope's audit events form a hash chain: every row stores the hash
+// of the row before it and a hash over its own content. Changing, removing or
+// reordering a row breaks the chain from that point on, which
+// verifyAuditChain reports. Rows written before the chain existed have no
+// sequence and are left out of it.
+
+type ChainedFields = {
+ actorEmail: string | null;
+ actorType: string;
+ createdAt: number;
+ envelopeId: string;
+ event: string;
+ id: string;
+ ipAddress: string | null;
+ metadata: Record<string, unknown> | null;
+ sequence: number;
+ userAgent: string | null;
+};
+
+/** Key order is fixed so the same row always hashes the same way. */
+function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map(canonicalJson).join(",")}]`;
+ }
+
+ if (value && typeof value === "object") {
+ return `{${Object.keys(value)
+ .sort()
+ .map(
+ (key) =>
+ `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`,
+ )
+ .join(",")}}`;
+ }
+
+ return JSON.stringify(value ?? null);
+}
+
+export function computeAuditRowHash(
+ previousHash: string | null,
+ fields: ChainedFields,
+): string {
+ return createHash("sha256")
+ .update(previousHash ?? "")
+ .update("\n")
+ .update(canonicalJson(fields))
+ .digest("hex");
+}
+
+function isPool(database: DbExecutor): database is ReturnType<typeof getDb> {
+ return "connect" in database && "totalCount" in database;
+}
+
+async function insertChainedAuditEvent(
input: RecordAuditEventInput,
- database: DbExecutor = getDb(),
+ database: DbExecutor,
): Promise<AuditEventRecord> {
- const id = randomUUID();
+ const id = input.id ?? randomUUID();
const createdAt = input.createdAt ?? Math.floor(Date.now() / 1000);
+ // Serializes writers for one envelope until the surrounding transaction
+ // ends, so two events cannot take the same place in the chain.
+ await database.query(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 7))",
+ [input.envelopeId],
+ );
+
+ const previous = await database.query<{
+ rowHash: string | null;
+ sequence: number;
+ }>(
+ `
+ SELECT sequence, row_hash AS "rowHash"
+ FROM audit_events
+ WHERE envelope_id = $1 AND sequence IS NOT NULL
+ ORDER BY sequence DESC
+ LIMIT 1
+ `,
+ [input.envelopeId],
+ );
+ const previousRow = previous.rows[0];
+ const sequence = (previousRow?.sequence ?? 0) + 1;
+ const previousHash = previousRow?.rowHash ?? null;
+ const fields: ChainedFields = {
+ actorEmail: input.actorEmail ?? null,
+ actorType: input.actorType,
+ createdAt,
+ envelopeId: input.envelopeId,
+ event: input.event,
+ id,
+ ipAddress: input.ipAddress ?? null,
+ metadata: input.metadata ?? null,
+ sequence,
+ userAgent: input.userAgent ?? null,
+ };
+
await database.query(
`
INSERT INTO audit_events (
@@ -90,31 +186,143 @@ export async function recordAuditEvent(
ip_address,
user_agent,
metadata,
- created_at
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
+ created_at,
+ sequence,
+ prev_hash,
+ row_hash
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
`,
[
id,
input.envelopeId,
input.event,
input.actorType,
- input.actorEmail ?? null,
- input.ipAddress ?? null,
- input.userAgent ?? null,
- input.metadata ?? null,
+ fields.actorEmail,
+ fields.ipAddress,
+ fields.userAgent,
+ fields.metadata,
createdAt,
+ sequence,
+ previousHash,
+ computeAuditRowHash(previousHash, fields),
],
);
return auditEventRecordSchema.parse({
- actorEmail: input.actorEmail ?? null,
+ actorEmail: fields.actorEmail,
actorType: input.actorType,
createdAt,
envelopeId: input.envelopeId,
event: input.event,
id,
- ipAddress: input.ipAddress ?? null,
- metadata: input.metadata ?? null,
- userAgent: input.userAgent ?? null,
+ ipAddress: fields.ipAddress,
+ metadata: fields.metadata,
+ userAgent: fields.userAgent,
});
}
+
+export async function recordAuditEvent(
+ input: RecordAuditEventInput,
+ database: DbExecutor = getDb(),
+): Promise<AuditEventRecord> {
+ if (isPool(database)) {
+ return withTransaction(
+ (client) => insertChainedAuditEvent(input, client),
+ database,
+ );
+ }
+
+ return insertChainedAuditEvent(input, database);
+}
+
+export type AuditChainCheck =
+ | { chainedEvents: number; ok: true }
+ | { brokenAtSequence: number; chainedEvents: number; ok: false };
+
+/** Recomputes an envelope's chain and reports the first row that disagrees. */
+export async function verifyAuditChain(
+ envelopeId: string,
+ database: DbExecutor = getDb(),
+): Promise<AuditChainCheck> {
+ const result = await database.query<
+ ChainedFields & { prevHash: string | null; rowHash: string | null }
+ >(
+ `
+ SELECT
+ id,
+ envelope_id AS "envelopeId",
+ event,
+ actor_type AS "actorType",
+ actor_email AS "actorEmail",
+ ip_address AS "ipAddress",
+ user_agent AS "userAgent",
+ metadata,
+ created_at AS "createdAt",
+ sequence,
+ prev_hash AS "prevHash",
+ row_hash AS "rowHash"
+ FROM audit_events
+ WHERE envelope_id = $1 AND sequence IS NOT NULL
+ ORDER BY sequence ASC
+ `,
+ [envelopeId],
+ );
+ let previousHash: string | null = null;
+ let expectedSequence = 1;
+
+ for (const row of result.rows) {
+ const { prevHash, rowHash, ...fields } = row;
+
+ if (
+ row.sequence !== expectedSequence ||
+ prevHash !== previousHash ||
+ rowHash !== computeAuditRowHash(previousHash, fields)
+ ) {
+ return {
+ brokenAtSequence: expectedSequence,
+ chainedEvents: result.rows.length,
+ ok: false,
+ };
+ }
+
+ previousHash = rowHash;
+ expectedSequence += 1;
+ }
+
+ return { chainedEvents: result.rows.length, ok: true };
+}
+
+/** Notes that the mail provider accepted a message about this envelope. */
+export async function recordEmailSent(
+ input: {
+ envelopeId: string;
+ messageId?: string | null;
+ recipient: string;
+ signerId?: string | null;
+ template: string;
+ },
+ database: DbExecutor = getDb(),
+): Promise<void> {
+ try {
+ await recordAuditEvent(
+ {
+ actorType: "system",
+ envelopeId: input.envelopeId,
+ event: "email_sent",
+ metadata: {
+ messageId: input.messageId ?? null,
+ recipient: input.recipient,
+ signerId: input.signerId ?? null,
+ template: input.template,
+ },
+ },
+ database,
+ );
+ } catch (error) {
+ // The email went out; failing to note it must not undo anything.
+ console.error(
+ `Failed to record email delivery for envelope ${input.envelopeId}:`,
+ error,
+ );
+ }
+}
diff --git a/src/lib/services/email-legal-footer.test.ts b/src/lib/services/email-legal-footer.test.ts
index d99b808..dfbd181 100644
--- a/src/lib/services/email-legal-footer.test.ts
+++ b/src/lib/services/email-legal-footer.test.ts
@@ -43,11 +43,20 @@ test("the hosted service links to its own terms, privacy and contact pages", ()
assert.doesNotMatch(result.textBody, /Sent by|Sent using/);
});
-test("a neutral install with nothing else set says only who sent the message", () => {
+test("a neutral install with nothing else set links its signer privacy notice and says who sent the message", () => {
const result = withUserEmailLegalFooter(body, neutral, env);
- assert.equal(result.textBody, "Hello\n\nSent by Acme Corp using SignuDoc.");
- assert.doesNotMatch(result.htmlBody, /<a /);
+ assert.equal(
+ result.textBody,
+ [
+ "Hello",
+ "",
+ "Privacy notice:",
+ "https://sign.acme.com/signer-privacy",
+ "",
+ "Sent by Acme Corp using SignuDoc.",
+ ].join("\n"),
+ );
});
test("a neutral install links to the organization's own pages and support address", () => {
@@ -91,7 +100,8 @@ test("an install that has not been named yet does not invent a name", () => {
env,
);
- assert.equal(result.textBody, "Hello\n\nSent using SignuDoc.");
+ assert.match(result.textBody, /\n\nSent using SignuDoc\.$/);
+ assert.doesNotMatch(result.textBody, /Acme/);
});
test("the organization's name and links are escaped in the HTML part", () => {
diff --git a/src/lib/services/email-legal-footer.ts b/src/lib/services/email-legal-footer.ts
index a40c8d0..2813dc6 100644
--- a/src/lib/services/email-legal-footer.ts
+++ b/src/lib/services/email-legal-footer.ts
@@ -18,7 +18,11 @@ type FooterLink = {
function buildFooterLinks(branding: Branding, env: EnvSource): FooterLink[] {
const candidates: Array<[label: string, url: string | null]> = [
["Terms of Service", branding.termsUrl],
- ["Privacy Policy", branding.privacyUrl],
+ // Without the organization's own policy, the notice built from the
+ // install's settings.
+ branding.privacyUrl || branding.hosted
+ ? ["Privacy Policy", branding.privacyUrl]
+ : ["Privacy notice", getEnv(env).appUrl ? "/signer-privacy" : null],
["Contact", branding.contactUrl],
];
const links = candidates.filter((candidate): candidate is [string, string] =>
diff --git a/src/lib/services/email.ts b/src/lib/services/email.ts
index 6d254a4..67b335d 100644
--- a/src/lib/services/email.ts
+++ b/src/lib/services/email.ts
@@ -1,4 +1,4 @@
-import { randomUUID } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import { mkdir, rename, writeFile } from "node:fs/promises";
import path from "node:path";
@@ -20,7 +20,31 @@ const DEFAULT_CAPTURE_SENDER_ADDRESS = "[email protected]";
export type EmailDriver = "capture" | "resend";
+export type EmailAttachment = {
+ content: Uint8Array;
+ contentType: string;
+ filename: string;
+};
+
+/**
+ * Resend accepts up to 40 MB per message once attachments are base64
+ * encoded, which makes them a third larger. Above this the message goes out
+ * with links only.
+ */
+export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
+
+export function fitsAsAttachments(
+ attachments: readonly EmailAttachment[],
+): boolean {
+ return (
+ attachments.reduce((total, item) => total + item.content.byteLength, 0) <=
+ MAX_ATTACHMENT_BYTES
+ );
+}
+
export type TransactionalEmailMessage = {
+ /** Not allowed in sendBatch: Resend's batch endpoint takes none. */
+ attachments?: EmailAttachment[];
htmlBody?: string;
replyTo?: string;
subject: string;
@@ -72,6 +96,15 @@ function buildResendPayload(
config: EmailAddresses,
) {
return {
+ ...(message.attachments?.length
+ ? {
+ attachments: message.attachments.map((attachment) => ({
+ content: Buffer.from(attachment.content),
+ contentType: attachment.contentType,
+ filename: attachment.filename,
+ })),
+ }
+ : {}),
from: config.senderAddress,
html: message.htmlBody,
replyTo: message.replyTo ?? config.supportAddress ?? undefined,
@@ -156,7 +189,17 @@ function createCaptureEmailService(
temporaryPath,
JSON.stringify(
{
- ...buildResendPayload(message, config),
+ ...buildResendPayload({ ...message, attachments: undefined }, config),
+ // The files themselves are not written out; their names, sizes
+ // and fingerprints are enough to check what would have been sent.
+ attachments: message.attachments?.map((attachment) => ({
+ bytes: attachment.content.byteLength,
+ contentType: attachment.contentType,
+ filename: attachment.filename,
+ sha256: createHash("sha256")
+ .update(attachment.content)
+ .digest("hex"),
+ })),
capturedAt: new Date().toISOString(),
messageId,
template: message.template,
@@ -241,6 +284,10 @@ export function createEmailService({
return [];
}
+ if (messages.some((message) => message.attachments?.length)) {
+ throw new Error("Messages with attachments must be sent one by one.");
+ }
+
const config = await resolveAddresses();
const { data, error } = await client.batch.send(
messages.map((message) => buildResendPayload(message, config)),
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index c9fd9be..c84a472 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -20,6 +20,8 @@ import {
import type { FieldRecord } from "../schemas/field.ts";
import type { SignerRecord } from "../schemas/signer.ts";
import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";
+import { sha256Hex } from "./pdf-seal.ts";
+import { saveInstallSealedPdf, type SealPurpose } from "./seal-identity.ts";
import {
buildEnvelopeCertificateKey,
buildEnvelopeSignedPdfKey,
@@ -44,12 +46,65 @@ const DEFAULT_AUDIT_PAGE_SIZE = {
let typedSignatureFontBytesPromise: Promise<Uint8Array> | null = null;
+export type StoredSealedPdf = StorageObjectRef & {
+ body: Uint8Array;
+ sha256: string;
+};
+
export type FinalizedEnvelopeArtifacts = {
- certificate: StorageObjectRef;
+ certificate: StoredSealedPdf;
generatedAt: number;
- signedPdf: StorageObjectRef;
+ recipientCertificate: StoredSealedPdf;
+ signedPdf: StoredSealedPdf;
};
+/** Saves a finished PDF. The default seals it with the install's key. */
+export type PdfSealer = (
+ pdfDocument: PDFDocument,
+ purpose: SealPurpose,
+) => Promise<Uint8Array>;
+
+const defaultSealer: PdfSealer = (pdfDocument, purpose) =>
+ saveInstallSealedPdf(pdfDocument, purpose);
+
+/**
+ * Standard PDF fonts can only draw Windows-1252 text. Evidence lines carry
+ * text from browsers and email providers, so anything outside Latin-1
+ * becomes "?".
+ */
+function toPrintable(value: string): string {
+ return value.replace(/[^\x20-\x7e\xa0-\xff]/g, "?");
+}
+
+const CERTIFICATE_FINGERPRINT_VERSION = 1;
+
+/**
+ * A SHA-256 over every audit event the certificate is built from, in order,
+ * unredacted. Printed on both certificates, so the record held by the sender
+ * can later be shown to be the one the certificate was made from.
+ */
+export function computeAuditFingerprint(
+ auditEvents: readonly AuditEventRecord[],
+): string {
+ return sha256Hex(
+ new TextEncoder().encode(
+ JSON.stringify({
+ events: auditEvents.map((event) => [
+ event.id,
+ event.createdAt,
+ event.event,
+ event.actorType,
+ event.actorEmail ?? null,
+ event.ipAddress ?? null,
+ event.userAgent ?? null,
+ event.metadata ?? null,
+ ]),
+ version: CERTIFICATE_FINGERPRINT_VERSION,
+ }),
+ ),
+ );
+}
+
export class PdfFinalizeError extends Error {
constructor(message: string) {
super(message);
@@ -467,6 +522,7 @@ async function stampFieldValue(
function buildAuditLines(input: {
auditEvents: AuditEventRecord[];
+ auditFingerprint?: string | null;
completedAt: number;
envelope: EnvelopeRecord;
fonts: {
@@ -475,6 +531,7 @@ function buildAuditLines(input: {
};
maxWidth: number;
redactForRecipients?: boolean;
+ signedPdfSha256?: string | null;
signers: SignerRecord[];
}) {
const titleFontSize = 18;
@@ -542,6 +599,22 @@ function buildAuditLines(input: {
input.fonts.regular,
bodyFontSize,
);
+ if (input.signedPdfSha256) {
+ pushParagraph(
+ `Signed document SHA-256: ${input.signedPdfSha256}`,
+ input.fonts.regular,
+ bodyFontSize,
+ );
+ }
+
+ if (input.auditFingerprint) {
+ pushParagraph(
+ `Audit trail fingerprint (SHA-256): ${input.auditFingerprint}`,
+ input.fonts.regular,
+ bodyFontSize,
+ );
+ }
+
pushParagraph(
`Status: ${getEnvelopeStatusLabel(input.envelope.status)}`,
input.fonts.regular,
@@ -561,15 +634,20 @@ function buildAuditLines(input: {
});
for (const signer of input.signers) {
- const actionLabel = getSignerCertificateActionLabel(
- input.envelope,
- signer,
- );
+ const actionLabel = getSignerCertificateActionLabel(input.envelope, signer);
const signerLabel = input.redactForRecipients
? `${signer.signOrder}. ${signer.name} | ${actionLabel}`
: `${signer.signOrder}. ${signer.name} <${signer.email}> | ${actionLabel}`;
pushParagraph(signerLabel, input.fonts.regular, bodyFontSize);
+
+ for (const detail of describeSignerEvidence(
+ signer,
+ input.auditEvents,
+ Boolean(input.redactForRecipients),
+ )) {
+ pushParagraph(` ${detail}`, input.fonts.regular, bodyFontSize);
+ }
}
pushParagraph("Audit events", input.fonts.bold, sectionFontSize, {
@@ -591,15 +669,155 @@ function buildAuditLines(input: {
signerName && actor !== signerName ? `${signerName} <${actor}>` : actor;
pushParagraph(
- `${formatAuditTimestamp(event.createdAt)} | ${event.event} | ${actorLabel}`,
+ toPrintable(
+ `${formatAuditTimestamp(event.createdAt)} | ${event.event} | ${actorLabel}`,
+ ),
input.fonts.regular,
bodyFontSize,
);
+
+ for (const detail of describeEventEvidence(event)) {
+ pushParagraph(
+ toPrintable(` ${detail}`),
+ input.fonts.regular,
+ bodyFontSize,
+ );
+ }
}
+ pushParagraph("How to check this record", input.fonts.bold, sectionFontSize, {
+ gapAfter: 4,
+ gapBefore: 10,
+ });
+ pushParagraph(
+ "The signed document and this certificate are each sealed with a digital signature. A PDF reader shows the seal as valid only if the file has not changed since it was sealed. The SHA-256 values above can also be checked on this site's Verify page.",
+ input.fonts.regular,
+ bodyFontSize,
+ );
+
return lines;
}
+const AUTHENTICATION_LABELS: Record<string, string> = {
+ access_code: "access code from the sender",
+ email_code: "one-time code sent by email",
+};
+
+function readStringArray(value: unknown): string[] {
+ return Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === "string")
+ : [];
+}
+
+/** What the record shows about how one signer was identified and agreed. */
+function describeSignerEvidence(
+ signer: SignerRecord,
+ auditEvents: readonly AuditEventRecord[],
+ redacted: boolean,
+): string[] {
+ const forSigner = auditEvents.filter(
+ (event) => event.metadata?.signerId === signer.id,
+ );
+ const details: string[] = [];
+ const signed = forSigner.find((event) => event.event === "signed");
+ const consented = forSigner.find((event) => event.event === "consented");
+ const checks = [
+ "possession of the emailed signing link",
+ ...readStringArray(signed?.metadata?.authMethods).map(
+ (method) => AUTHENTICATION_LABELS[method] ?? method,
+ ),
+ ];
+
+ if (signed || signer.status === "declined") {
+ details.push(`Identified by: ${checks.join(", ")}`);
+ }
+
+ if (consented) {
+ details.push(
+ `Agreed to use electronic records and signatures at ${formatAuditTimestamp(consented.createdAt)}${
+ typeof consented.metadata?.disclosureVersion === "string"
+ ? ` (disclosure ${consented.metadata.disclosureVersion})`
+ : ""
+ }`,
+ );
+ }
+
+ const methods = readStringArray(signed?.metadata?.signatureMethods);
+
+ if (methods.length > 0) {
+ details.push(`Signature adopted by: ${methods.join(", ")}`);
+ }
+
+ if (!redacted && signed?.ipAddress) {
+ details.push(`Signed from IP ${signed.ipAddress}`);
+ }
+
+ return details;
+}
+
+function describeEventEvidence(event: AuditEventRecord): string[] {
+ const details: string[] = [];
+ const metadata = event.metadata ?? {};
+
+ if (event.ipAddress || event.userAgent) {
+ details.push(
+ [
+ event.ipAddress ? `IP ${event.ipAddress}` : null,
+ event.userAgent ? `browser ${event.userAgent.slice(0, 160)}` : null,
+ ]
+ .filter(Boolean)
+ .join(" | "),
+ );
+ }
+
+ if (typeof metadata.timezoneOffsetMinutes === "number") {
+ const offset = -metadata.timezoneOffsetMinutes;
+ const sign = offset >= 0 ? "+" : "-";
+ const hours = Math.floor(Math.abs(offset) / 60);
+ const minutes = Math.abs(offset) % 60;
+
+ details.push(
+ `signer's clock: UTC${sign}${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`,
+ );
+ }
+
+ if (event.event === "email_sent") {
+ const recipient =
+ typeof metadata.recipient === "string" ? metadata.recipient : null;
+ const kind =
+ typeof metadata.template === "string" ? metadata.template : null;
+ const messageId =
+ typeof metadata.messageId === "string" ? metadata.messageId : null;
+
+ details.push(
+ [
+ kind ? `email ${kind.replaceAll("_", " ")}` : "email",
+ recipient ? `to ${recipient}` : null,
+ messageId ? `accepted by the mail provider as ${messageId}` : null,
+ ]
+ .filter(Boolean)
+ .join(" "),
+ );
+ }
+
+ if (event.event === "verified" && typeof metadata.method === "string") {
+ details.push(
+ `passed: ${AUTHENTICATION_LABELS[metadata.method] ?? metadata.method}`,
+ );
+ }
+
+ if (
+ event.event === "verification_failed" &&
+ typeof metadata.method === "string"
+ ) {
+ details.push(
+ `wrong ${AUTHENTICATION_LABELS[metadata.method] ?? metadata.method}`,
+ );
+ }
+
+ return details;
+}
+
function getSignerCertificateActionLabel(
envelope: EnvelopeRecord,
signer: SignerRecord,
@@ -630,6 +848,7 @@ function getSignerCertificateActionLabel(
function appendAuditTrailPages(input: {
auditEvents: AuditEventRecord[];
+ auditFingerprint?: string | null;
completedAt: number;
envelope: EnvelopeRecord;
fonts: {
@@ -638,6 +857,7 @@ function appendAuditTrailPages(input: {
};
pdfDocument: PDFDocument;
redactForRecipients?: boolean;
+ signedPdfSha256?: string | null;
signers: SignerRecord[];
}) {
const templatePage = input.pdfDocument.getPageCount()
@@ -654,11 +874,13 @@ function appendAuditTrailPages(input: {
const lineHeightMultiplier = 1.24;
const lines = buildAuditLines({
auditEvents: input.auditEvents,
+ auditFingerprint: input.auditFingerprint,
completedAt: input.completedAt,
envelope: input.envelope,
fonts: input.fonts,
maxWidth,
redactForRecipients: input.redactForRecipients,
+ signedPdfSha256: input.signedPdfSha256,
signers: input.signers,
});
@@ -688,65 +910,64 @@ function appendAuditTrailPages(input: {
}
}
-export async function storeEnvelopeCertificatePdf(input: {
+type CertificateInput = {
auditEvents: AuditEventRecord[];
envelope: EnvelopeRecord;
- certificate: StorageObjectRef;
redactForRecipients?: boolean;
+ /** The finished signed PDF's SHA-256, printed when there is one. */
+ signedPdfSha256?: string | null;
signers: SignerRecord[];
- },
- {
- storageService = createStorageService(),
- }: {
- storageService?: StorageService;
- } = {},
-): Promise<StorageObjectRef> {
+};
+
+type SealOption = {
+ seal?: PdfSealer;
+};
+
+function assertTerminalEnvelope(envelope: EnvelopeRecord, noun: string) {
if (
- input.envelope.status !== "completed" &&
- input.envelope.status !== "declined" &&
- input.envelope.status !== "voided"
+ envelope.status !== "completed" &&
+ envelope.status !== "declined" &&
+ envelope.status !== "voided"
) {
throw new PdfFinalizeError(
- "Certificates can only be generated for terminal envelopes.",
+ `${noun} can only be generated for terminal envelopes.`,
);
}
+}
- const body = await renderEnvelopeCertificatePdf({
- auditEvents: input.auditEvents,
- envelope: input.envelope,
- redactForRecipients: input.redactForRecipients,
- signers: input.signers,
- });
+export async function storeEnvelopeCertificatePdf(
+ input: CertificateInput & { certificate: StorageObjectRef },
+ {
+ seal,
+ storageService = createStorageService(),
+ }: SealOption & {
+ storageService?: StorageService;
+ } = {},
+): Promise<StoredSealedPdf> {
+ assertTerminalEnvelope(input.envelope, "Certificates");
- return storageService.putObject({
+ const body = await renderEnvelopeCertificatePdf(input, { seal });
+ const stored = await storageService.putObject({
body,
contentType: "application/pdf",
key: input.certificate.key,
});
+
+ return { ...stored, body, sha256: sha256Hex(body) };
}
export async function storeRecipientEnvelopeCertificatePdf(
- input: {
- auditEvents: AuditEventRecord[];
+ input: Omit<CertificateInput, "redactForRecipients"> & {
certificate: StorageObjectRef;
- envelope: EnvelopeRecord;
- signers: SignerRecord[];
},
{
+ seal,
storageService = createStorageService(),
- }: {
+ }: SealOption & {
storageService?: StorageService;
} = {},
-): Promise<StorageObjectRef> {
- if (
- input.envelope.status !== "completed" &&
- input.envelope.status !== "declined" &&
- input.envelope.status !== "voided"
- ) {
- throw new PdfFinalizeError(
- "Evidence bundles can only be generated for terminal envelopes.",
- );
- }
+): Promise<StoredSealedPdf> {
+ assertTerminalEnvelope(input.envelope, "Evidence bundles");
return storeEnvelopeCertificatePdf(
{
@@ -754,26 +975,17 @@ export async function storeRecipientEnvelopeCertificatePdf(
redactForRecipients: true,
},
{
+ seal,
storageService,
},
);
}
-export async function renderEnvelopeCertificatePdf(input: {
- auditEvents: AuditEventRecord[];
- envelope: EnvelopeRecord;
- redactForRecipients?: boolean;
- signers: SignerRecord[];
-}): Promise<Uint8Array> {
- if (
- input.envelope.status !== "completed" &&
- input.envelope.status !== "declined" &&
- input.envelope.status !== "voided"
- ) {
- throw new PdfFinalizeError(
- "Certificates can only be generated for terminal envelopes.",
- );
- }
+export async function renderEnvelopeCertificatePdf(
+ input: CertificateInput,
+ { seal = defaultSealer }: SealOption = {},
+): Promise<Uint8Array> {
+ assertTerminalEnvelope(input.envelope, "Certificates");
const pdfDocument = await PDFDocument.create();
const auditRegularFont = await pdfDocument.embedFont(StandardFonts.Helvetica);
@@ -789,6 +1001,9 @@ export async function renderEnvelopeCertificatePdf(input: {
auditEvents: input.redactForRecipients
? input.auditEvents.map(redactAuditEventForRecipients)
: input.auditEvents,
+ auditFingerprint: computeAuditFingerprint(
+ stripCompletedAuditEvents(input.auditEvents),
+ ),
completedAt: terminalTimestamp,
envelope: input.envelope,
fonts: {
@@ -797,12 +1012,24 @@ export async function renderEnvelopeCertificatePdf(input: {
},
pdfDocument,
redactForRecipients: input.redactForRecipients,
+ signedPdfSha256: input.signedPdfSha256,
signers: input.signers,
});
+ pdfDocument.setTitle(
+ `Audit certificate: ${toPrintable(input.envelope.title)}`,
+ );
+ pdfDocument.setProducer("SignuDoc");
- return pdfDocument.save({
- useObjectStreams: false,
- });
+ return seal(pdfDocument, "certificate");
+}
+
+export class SourceDocumentChangedError extends PdfFinalizeError {
+ constructor() {
+ super(
+ "The stored source document no longer matches the one that was sent for signing.",
+ );
+ this.name = "SourceDocumentChangedError";
+ }
}
export async function renderFinalizedEnvelopePdf(
@@ -816,12 +1043,20 @@ export async function renderFinalizedEnvelopePdf(
sourcePdfKey: string;
},
{
+ seal = defaultSealer,
storageService = createStorageService(),
- }: {
+ }: SealOption & {
storageService?: StorageService;
} = {},
): Promise<Uint8Array> {
const sourcePdfObject = await storageService.getObject(input.sourcePdfKey);
+
+ // The certificate states the source document's hash, so the stamped copy
+ // must be made from exactly that file.
+ if (sha256Hex(sourcePdfObject.body) !== input.envelope.sourcePdfHash) {
+ throw new SourceDocumentChangedError();
+ }
+
const pdfDocument = await PDFDocument.load(sourcePdfObject.body);
pdfDocument.registerFontkit(fontkit);
@@ -880,9 +1115,7 @@ export async function renderFinalizedEnvelopePdf(
});
}
- return pdfDocument.save({
- useObjectStreams: false,
- });
+ return seal(pdfDocument, "signed-document");
}
export async function finalizeEnvelope(
@@ -894,8 +1127,9 @@ export async function finalizeEnvelope(
sourcePdf: StorageObjectRef;
},
{
+ seal,
storageService = createStorageService(),
- }: {
+ }: SealOption & {
storageService?: StorageService;
} = {},
): Promise<FinalizedEnvelopeArtifacts> {
@@ -914,25 +1148,31 @@ export async function finalizeEnvelope(
sourcePdfKey: input.sourcePdf.key,
},
{
+ seal,
storageService,
},
);
+ const signedPdfSha256 = sha256Hex(signedPdfBytes);
const completedEnvelope = {
...input.envelope,
completedAt: generatedAt,
status: "completed" as const,
updatedAt: generatedAt,
};
- let signedPdf: StorageObjectRef | null = null;
- let certificate: StorageObjectRef | null = null;
- let recipientCertificate: StorageObjectRef | null = null;
+ let signedPdf: StoredSealedPdf | null = null;
+ let certificate: StoredSealedPdf | null = null;
+ let recipientCertificate: StoredSealedPdf | null = null;
try {
- signedPdf = await storageService.putObject({
+ signedPdf = {
+ ...(await storageService.putObject({
+ body: signedPdfBytes,
+ contentType: "application/pdf",
+ key: buildEnvelopeSignedPdfKey(storageIdentity),
+ })),
body: signedPdfBytes,
- contentType: "application/pdf",
- key: buildEnvelopeSignedPdfKey(storageIdentity),
- });
+ sha256: signedPdfSha256,
+ };
certificate = await storeEnvelopeCertificatePdf(
{
@@ -945,9 +1185,11 @@ export async function finalizeEnvelope(
}),
},
envelope: completedEnvelope,
+ signedPdfSha256,
signers: input.signers,
},
{
+ seal,
storageService,
},
);
@@ -962,9 +1204,11 @@ export async function finalizeEnvelope(
}),
},
envelope: completedEnvelope,
+ signedPdfSha256,
signers: input.signers,
},
{
+ seal,
storageService,
},
);
@@ -972,6 +1216,7 @@ export async function finalizeEnvelope(
return {
certificate,
generatedAt,
+ recipientCertificate,
signedPdf,
};
} catch (error) {
diff --git a/src/lib/services/pdf-seal.test.ts b/src/lib/services/pdf-seal.test.ts
new file mode 100644
index 0000000..ab9059f
--- /dev/null
+++ b/src/lib/services/pdf-seal.test.ts
@@ -0,0 +1,254 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { generateKeyPairSync } from "node:crypto";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { createServer } from "node:http";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { promisify } from "node:util";
+
+import forge from "node-forge";
+import { PDFDocument, StandardFonts } from "pdf-lib";
+
+import {
+ buildCadesSignature,
+ createSelfSignedSealIdentity,
+ saveSealedPdf,
+ SEAL_TEST_OIDS,
+ sealIdentityFromPkcs12,
+ type SealIdentity,
+} from "./pdf-seal.ts";
+
+const run = promisify(execFile);
+
+function makeIdentity(): SealIdentity {
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", {
+ modulusLength: 2048,
+ privateKeyEncoding: { format: "pem", type: "pkcs8" },
+ publicKeyEncoding: { format: "pem", type: "spki" },
+ });
+
+ return createSelfSignedSealIdentity({
+ commonName: "Test seal",
+ organization: "Harbour & Finch",
+ privateKeyPem: privateKey,
+ publicKeyPem: publicKey,
+ });
+}
+
+async function makePdf(): Promise<PDFDocument> {
+ const pdf = await PDFDocument.create();
+ const page = pdf.addPage([612, 792]);
+
+ page.drawText("Signed agreement", {
+ font: await pdf.embedFont(StandardFonts.Helvetica),
+ x: 72,
+ y: 700,
+ });
+
+ return pdf;
+}
+
+async function hasPdfsig(): Promise<boolean> {
+ try {
+ await run("pdfsig", ["-v"]);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Checks the CMS signature the way a reader would, without poppler. */
+function verifyByteRange(sealed: Uint8Array) {
+ const text = Buffer.from(sealed).toString("latin1");
+ const match = /\/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\]/.exec(
+ text,
+ );
+
+ assert.ok(match, "the seal has a byte range");
+
+ const [a, b, c, d] = match.slice(1).map(Number) as [
+ number,
+ number,
+ number,
+ number,
+ ];
+ const signedContent = Buffer.concat([
+ Buffer.from(sealed.subarray(a, a + b)),
+ Buffer.from(sealed.subarray(c, c + d)),
+ ]);
+ const hex = text.slice(a + b + 1, c - 1).replace(/0+$/, "");
+ const cms = forge.asn1.fromDer(Buffer.from(hex, "hex").toString("binary"));
+ const message = forge.pkcs7.messageFromAsn1(cms) as unknown as {
+ rawCapture: { authenticatedAttributes: forge.asn1.Asn1[] };
+ };
+ const digestAttribute = message.rawCapture.authenticatedAttributes.find(
+ (attribute) =>
+ forge.asn1.derToOid(
+ (attribute.value as forge.asn1.Asn1[])[0]!.value as string,
+ ) === SEAL_TEST_OIDS.messageDigest,
+ );
+ const digest = (
+ (digestAttribute!.value as forge.asn1.Asn1[])[1]!.value as forge.asn1.Asn1[]
+ )[0]!.value as string;
+
+ assert.equal(
+ Buffer.from(digest, "binary").toString("hex"),
+ forge.md.sha256
+ .create()
+ .update(signedContent.toString("binary"))
+ .digest()
+ .toHex(),
+ );
+
+ return { a, b, c, d };
+}
+
+test("a sealed PDF verifies, and any change to it is detected", async (t) => {
+ const identity = makeIdentity();
+ const sealed = await saveSealedPdf(await makePdf(), identity, {
+ name: "SignuDoc",
+ reason: "Signed with SignuDoc",
+ });
+
+ verifyByteRange(sealed);
+
+ if (!(await hasPdfsig())) {
+ t.diagnostic("pdfsig is not installed; skipped the poppler check");
+ return;
+ }
+
+ const directory = await mkdtemp(path.join(os.tmpdir(), "seal-"));
+
+ try {
+ const original = path.join(directory, "sealed.pdf");
+
+ await writeFile(original, sealed);
+
+ const { stdout } = await run("pdfsig", ["-nocert", original]);
+
+ assert.match(stdout, /Signature Validation: Signature is Valid\./);
+ assert.match(stdout, /Signature Type: ETSI\.CAdES\.detached/);
+ assert.match(stdout, /Total document signed/);
+
+ // Change one byte of the page text and the seal must fail.
+ const tampered = Buffer.from(sealed);
+ const position = tampered.indexOf("Signed agreement");
+ const changed = path.join(directory, "tampered.pdf");
+
+ if (position === -1) {
+ // The text sits in a compressed stream; change a byte in the header
+ // comment instead, which is inside the signed range too.
+ tampered[10] = tampered[10] === 0x41 ? 0x42 : 0x41;
+ } else {
+ tampered[position] = 0x58;
+ }
+
+ await writeFile(changed, tampered);
+
+ const result = await run("pdfsig", ["-nocert", changed]).catch(
+ (error: { stdout?: string }) => ({ stdout: error.stdout ?? "" }),
+ );
+
+ assert.doesNotMatch(
+ result.stdout,
+ /Signature Validation: Signature is Valid\./,
+ );
+ } finally {
+ await rm(directory, { force: true, recursive: true });
+ }
+});
+
+test("a timestamp token from the service is stored with the signature", async () => {
+ const identity = makeIdentity();
+ // A stand-in service: answers "granted" with a token that is just a
+ // recognisable ContentInfo. The real token's own signature is not checked
+ // here; only that it is requested and stored in the right place.
+ const marker = forge.asn1.create(
+ forge.asn1.Class.UNIVERSAL,
+ forge.asn1.Type.SEQUENCE,
+ true,
+ [
+ forge.asn1.create(
+ forge.asn1.Class.UNIVERSAL,
+ forge.asn1.Type.OID,
+ false,
+ forge.asn1.oidToDer(SEAL_TEST_OIDS.signedData).getBytes(),
+ ),
+ ],
+ );
+ let requestContentType: string | undefined;
+ const server = createServer((request, response) => {
+ requestContentType = request.headers["content-type"];
+ request.resume();
+ request.on("end", () => {
+ const answer = forge.asn1.create(
+ forge.asn1.Class.UNIVERSAL,
+ forge.asn1.Type.SEQUENCE,
+ true,
+ [
+ forge.asn1.create(
+ forge.asn1.Class.UNIVERSAL,
+ forge.asn1.Type.SEQUENCE,
+ true,
+ [
+ forge.asn1.create(
+ forge.asn1.Class.UNIVERSAL,
+ forge.asn1.Type.INTEGER,
+ false,
+ String.fromCharCode(0),
+ ),
+ ],
+ ),
+ marker,
+ ],
+ );
+
+ response.writeHead(200, {
+ "content-type": "application/timestamp-reply",
+ });
+ response.end(Buffer.from(forge.asn1.toDer(answer).getBytes(), "binary"));
+ });
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+
+ try {
+ const address = server.address();
+ const port = typeof address === "object" && address ? address.port : 0;
+ const cms = await buildCadesSignature(new Uint8Array([1, 2, 3]), identity, {
+ timestampUrl: `http://127.0.0.1:${String(port)}/`,
+ });
+ const der = Buffer.from(cms).toString("binary");
+
+ assert.equal(requestContentType, "application/timestamp-query");
+ assert.ok(
+ der.includes(
+ forge.asn1.oidToDer(SEAL_TEST_OIDS.timeStampToken).getBytes(),
+ ),
+ "the token attribute is present",
+ );
+ } finally {
+ server.close();
+ }
+});
+
+test("a PKCS#12 bundle from a certificate authority can be used", () => {
+ const identity = makeIdentity();
+ const key = forge.pki.privateKeyFromPem(identity.privateKeyPem);
+ const certificate = forge.pki.certificateFromPem(
+ identity.certificateChainPem[0]!,
+ );
+ const p12 = forge.pkcs12.toPkcs12Asn1(key, [certificate], "secret", {
+ algorithm: "3des",
+ });
+ const bytes = new Uint8Array(
+ Buffer.from(forge.asn1.toDer(p12).getBytes(), "binary"),
+ );
+ const parsed = sealIdentityFromPkcs12(bytes, "secret");
+
+ assert.equal(parsed.certificateChainPem.length, 1);
+ assert.match(parsed.privateKeyPem, /PRIVATE KEY/);
+ assert.throws(() => sealIdentityFromPkcs12(bytes, "wrong"));
+});
diff --git a/src/lib/services/pdf-seal.ts b/src/lib/services/pdf-seal.ts
new file mode 100644
index 0000000..84ea214
--- /dev/null
+++ b/src/lib/services/pdf-seal.ts
@@ -0,0 +1,442 @@
+import { createHash, createSign, randomBytes } from "node:crypto";
+
+import { SignPdf } from "@signpdf/signpdf";
+import { pdflibAddPlaceholder } from "@signpdf/placeholder-pdf-lib";
+import { Signer, SUBFILTER_ETSI_CADES_DETACHED } from "@signpdf/utils";
+import forge from "node-forge";
+import type { PDFDocument } from "pdf-lib";
+
+// A PAdES baseline (B-B, or B-T with a timestamp) seal on a finished PDF.
+//
+// The seal is a CMS signature over the whole file, made with this install's
+// own key. Any PDF reader then shows whether the file was changed after it
+// was sealed. With the install's self-made certificate a reader reports the
+// signer's identity as unknown, but still reports the document as unchanged;
+// an organization that wants its name verified can supply a certificate from
+// a certificate authority instead (SEAL_P12_BASE64).
+
+const asn1 = forge.asn1;
+const OID = {
+ contentType: "1.2.840.113549.1.9.3",
+ data: "1.2.840.113549.1.7.1",
+ messageDigest: "1.2.840.113549.1.9.4",
+ rsaEncryption: "1.2.840.113549.1.1.1",
+ sha256: "2.16.840.1.101.3.4.2.1",
+ sha256WithRsa: "1.2.840.113549.1.1.11",
+ signedData: "1.2.840.113549.1.7.2",
+ signingCertificateV2: "1.2.840.113549.1.9.16.2.47",
+ timeStampToken: "1.2.840.113549.1.9.16.2.14",
+} as const;
+
+// Room for the CMS structure, a certificate chain and a timestamp token.
+const SIGNATURE_PLACEHOLDER_BYTES = 24_576;
+const TIMESTAMP_TIMEOUT_MS = 10_000;
+
+export type SealIdentity = {
+ /** The signing certificate first, then any chain above it, as PEM. */
+ certificateChainPem: string[];
+ privateKeyPem: string;
+};
+
+export type SealOptions = {
+ contactInfo?: string;
+ location?: string;
+ name: string;
+ reason: string;
+ signingTime?: Date;
+ /** An RFC 3161 time-stamping service. Without one the seal is PAdES B-B. */
+ timestampUrl?: string | null;
+};
+
+export class PdfSealError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = "PdfSealError";
+ }
+}
+
+export function sha256Hex(bytes: Uint8Array): string {
+ return createHash("sha256").update(bytes).digest("hex");
+}
+
+function oid(value: string) {
+ return asn1.create(
+ asn1.Class.UNIVERSAL,
+ asn1.Type.OID,
+ false,
+ asn1.oidToDer(value).getBytes(),
+ );
+}
+
+function seq(values: forge.asn1.Asn1[]) {
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, values);
+}
+
+function set(values: forge.asn1.Asn1[]) {
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, values);
+}
+
+function octets(binary: string) {
+ return asn1.create(
+ asn1.Class.UNIVERSAL,
+ asn1.Type.OCTETSTRING,
+ false,
+ binary,
+ );
+}
+
+function integer(binary: string) {
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, binary);
+}
+
+function nullValue() {
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "");
+}
+
+function contextTag(tag: number, values: forge.asn1.Asn1[]) {
+ return asn1.create(asn1.Class.CONTEXT_SPECIFIC, tag, true, values);
+}
+
+function attribute(type: string, value: forge.asn1.Asn1) {
+ return seq([oid(type), set([value])]);
+}
+
+function toBinary(bytes: Uint8Array): string {
+ return Buffer.from(bytes).toString("binary");
+}
+
+function derOf(value: forge.asn1.Asn1): string {
+ return asn1.toDer(value).getBytes();
+}
+
+/** Builds the detached CMS SignedData that goes into the PDF. */
+export async function buildCadesSignature(
+ content: Uint8Array,
+ identity: SealIdentity,
+ { timestampUrl }: { timestampUrl?: string | null } = {},
+): Promise<Uint8Array> {
+ if (identity.certificateChainPem.length === 0) {
+ throw new PdfSealError("The seal identity has no certificate.");
+ }
+
+ const certificates = identity.certificateChainPem.map((pem) =>
+ forge.pki.certificateFromPem(pem),
+ );
+ const signingCertificate = certificates[0]!;
+ const signingCertificateDer = derOf(
+ forge.pki.certificateToAsn1(signingCertificate),
+ );
+ const contentDigest = createHash("sha256").update(content).digest();
+ const certificateDigest = createHash("sha256")
+ .update(Buffer.from(signingCertificateDer, "binary"))
+ .digest();
+ const signedAttributes = [
+ attribute(OID.contentType, oid(OID.data)),
+ attribute(OID.messageDigest, octets(contentDigest.toString("binary"))),
+ // ESSCertIDv2 with the default hash (SHA-256), so no algorithm is named.
+ attribute(
+ OID.signingCertificateV2,
+ seq([seq([seq([octets(certificateDigest.toString("binary"))])])]),
+ ),
+ ];
+ // The signature covers the attributes encoded as a SET (RFC 5652 5.4).
+ const signedAttributesDer = derOf(set(signedAttributes));
+ const signer = createSign("sha256");
+
+ signer.update(Buffer.from(signedAttributesDer, "binary"));
+
+ const signatureValue = signer.sign(identity.privateKeyPem);
+ const unsignedAttributes: forge.asn1.Asn1[] = [];
+
+ if (timestampUrl) {
+ const token = await requestTimestampToken(signatureValue, timestampUrl);
+
+ unsignedAttributes.push(attribute(OID.timeStampToken, token));
+ }
+
+ const issuerAndSerial = seq([
+ forge.pki.distinguishedNameToAsn1(signingCertificate.issuer),
+ integer(forge.util.hexToBytes(signingCertificate.serialNumber)),
+ ]);
+ const signerInfo = seq([
+ integer(String.fromCharCode(1)),
+ issuerAndSerial,
+ seq([oid(OID.sha256), nullValue()]),
+ contextTag(0, signedAttributes),
+ seq([oid(OID.sha256WithRsa), nullValue()]),
+ octets(signatureValue.toString("binary")),
+ ...(unsignedAttributes.length > 0
+ ? [contextTag(1, unsignedAttributes)]
+ : []),
+ ]);
+ const signedData = seq([
+ integer(String.fromCharCode(1)),
+ set([seq([oid(OID.sha256), nullValue()])]),
+ seq([oid(OID.data)]),
+ contextTag(
+ 0,
+ certificates.map((certificate) =>
+ forge.pki.certificateToAsn1(certificate),
+ ),
+ ),
+ set([signerInfo]),
+ ]);
+ const contentInfo = seq([oid(OID.signedData), contextTag(0, [signedData])]);
+
+ return new Uint8Array(Buffer.from(derOf(contentInfo), "binary"));
+}
+
+/**
+ * Asks an RFC 3161 service to timestamp the signature value, and returns the
+ * token (a CMS ContentInfo) to store beside it.
+ */
+async function requestTimestampToken(
+ signatureValue: Buffer,
+ timestampUrl: string,
+): Promise<forge.asn1.Asn1> {
+ const imprint = createHash("sha256").update(signatureValue).digest();
+ const nonce = randomBytes(8);
+
+ nonce[0] = nonce[0]! & 0x7f;
+
+ const request = seq([
+ integer(String.fromCharCode(1)),
+ seq([
+ seq([oid(OID.sha256), nullValue()]),
+ octets(imprint.toString("binary")),
+ ]),
+ integer(nonce.toString("binary")),
+ asn1.create(
+ asn1.Class.UNIVERSAL,
+ asn1.Type.BOOLEAN,
+ false,
+ String.fromCharCode(0xff),
+ ),
+ ]);
+ let response: Response;
+
+ try {
+ response = await fetch(timestampUrl, {
+ body: Buffer.from(derOf(request), "binary"),
+ headers: { "content-type": "application/timestamp-query" },
+ method: "POST",
+ signal: AbortSignal.timeout(TIMESTAMP_TIMEOUT_MS),
+ });
+ } catch (error) {
+ throw new PdfSealError("The time-stamping service could not be reached.", {
+ cause: error,
+ });
+ }
+
+ if (!response.ok) {
+ throw new PdfSealError(
+ `The time-stamping service answered ${String(response.status)}.`,
+ );
+ }
+
+ const body = Buffer.from(await response.arrayBuffer());
+ let parsed: forge.asn1.Asn1;
+
+ try {
+ parsed = asn1.fromDer(body.toString("binary"));
+ } catch (error) {
+ throw new PdfSealError(
+ "The time-stamping service sent an unreadable answer.",
+ {
+ cause: error,
+ },
+ );
+ }
+
+ // TimeStampResp ::= SEQUENCE { status PKIStatusInfo, timeStampToken OPTIONAL }
+ const parts = parsed.value as forge.asn1.Asn1[];
+ const statusInfo = parts[0]?.value as forge.asn1.Asn1[] | undefined;
+ const statusValue = statusInfo?.[0]?.value;
+ const status =
+ typeof statusValue === "string"
+ ? statusValue.charCodeAt(statusValue.length - 1)
+ : -1;
+
+ // 0 = granted, 1 = granted with modifications.
+ if ((status !== 0 && status !== 1) || !parts[1]) {
+ throw new PdfSealError("The time-stamping service refused the request.");
+ }
+
+ return parts[1];
+}
+
+class CadesSigner extends Signer {
+ readonly identity: SealIdentity;
+ readonly timestampUrl: string | null;
+
+ constructor(identity: SealIdentity, timestampUrl: string | null) {
+ super();
+ this.identity = identity;
+ this.timestampUrl = timestampUrl;
+ }
+
+ async sign(content: Buffer): Promise<Buffer> {
+ return Buffer.from(
+ await buildCadesSignature(new Uint8Array(content), this.identity, {
+ timestampUrl: this.timestampUrl,
+ }),
+ );
+ }
+}
+
+/**
+ * Saves the document with a seal over the whole file. Nothing may change the
+ * document after this, or the seal no longer verifies.
+ */
+export async function saveSealedPdf(
+ pdfDocument: PDFDocument,
+ identity: SealIdentity,
+ options: SealOptions,
+): Promise<Uint8Array> {
+ const signingTime = options.signingTime ?? new Date();
+
+ pdflibAddPlaceholder({
+ appName: "SignuDoc",
+ contactInfo: options.contactInfo ?? "",
+ location: options.location ?? "",
+ name: options.name,
+ pdfDoc: pdfDocument,
+ reason: options.reason,
+ signatureLength: SIGNATURE_PLACEHOLDER_BYTES,
+ signingTime,
+ subFilter: SUBFILTER_ETSI_CADES_DETACHED,
+ });
+
+ const unsigned = await pdfDocument.save({ useObjectStreams: false });
+ const signed = await new SignPdf().sign(
+ Buffer.from(unsigned),
+ new CadesSigner(identity, options.timestampUrl ?? null),
+ signingTime,
+ );
+
+ return new Uint8Array(signed);
+}
+
+export type GeneratedSealIdentity = SealIdentity & { certificatePem: string };
+
+/**
+ * A certificate made and signed by the install itself. It proves only that
+ * the holder of this key sealed the file, which is what tamper evidence needs.
+ */
+export function createSelfSignedSealIdentity({
+ commonName,
+ organization,
+ privateKeyPem,
+ publicKeyPem,
+ validYears = 20,
+}: {
+ commonName: string;
+ organization?: string | null;
+ privateKeyPem: string;
+ publicKeyPem: string;
+ validYears?: number;
+}): GeneratedSealIdentity {
+ const certificate = forge.pki.createCertificate();
+ const now = new Date();
+ const notAfter = new Date(now);
+
+ notAfter.setUTCFullYear(notAfter.getUTCFullYear() + validYears);
+
+ const serial = randomBytes(16);
+
+ serial[0] = serial[0]! & 0x7f;
+ certificate.serialNumber = serial.toString("hex");
+ certificate.publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
+ certificate.validity.notBefore = now;
+ certificate.validity.notAfter = notAfter;
+
+ const subject = [
+ { name: "commonName", value: commonName.slice(0, 64) },
+ ...(organization
+ ? [{ name: "organizationName", value: organization.slice(0, 64) }]
+ : []),
+ ];
+
+ certificate.setSubject(subject);
+ certificate.setIssuer(subject);
+ certificate.setExtensions([
+ { cA: false, critical: true, name: "basicConstraints" },
+ {
+ critical: true,
+ digitalSignature: true,
+ name: "keyUsage",
+ nonRepudiation: true,
+ },
+ { name: "subjectKeyIdentifier" },
+ ]);
+ certificate.sign(
+ forge.pki.privateKeyFromPem(privateKeyPem),
+ forge.md.sha256.create(),
+ );
+
+ const certificatePem = forge.pki.certificateToPem(certificate);
+
+ return {
+ certificateChainPem: [certificatePem],
+ certificatePem,
+ privateKeyPem,
+ };
+}
+
+/** Reads a PKCS#12 bundle (from a certificate authority) into an identity. */
+export function sealIdentityFromPkcs12(
+ p12: Uint8Array,
+ passphrase: string,
+): SealIdentity {
+ const parsed = forge.pkcs12.pkcs12FromAsn1(
+ asn1.fromDer(toBinary(p12)),
+ false,
+ passphrase,
+ );
+ const keyBag =
+ parsed.getBags({ bagType: forge.pki.oids.pkcs8ShroudedKeyBag })[
+ forge.pki.oids.pkcs8ShroudedKeyBag
+ ]?.[0] ??
+ parsed.getBags({ bagType: forge.pki.oids.keyBag })[
+ forge.pki.oids.keyBag
+ ]?.[0];
+ const certificates = (
+ parsed.getBags({ bagType: forge.pki.oids.certBag })[
+ forge.pki.oids.certBag
+ ] ?? []
+ )
+ .map((bag) => bag.cert)
+ .filter((cert): cert is forge.pki.Certificate => Boolean(cert));
+ const privateKey = keyBag?.key as forge.pki.rsa.PrivateKey | undefined;
+
+ if (!privateKey || certificates.length === 0) {
+ throw new PdfSealError(
+ "SEAL_P12_BASE64 must hold one private key and its certificate.",
+ );
+ }
+
+ const matching = certificates.find((certificate) => {
+ const publicKey = certificate.publicKey as forge.pki.rsa.PublicKey;
+
+ return (
+ publicKey.n.compareTo(privateKey.n) === 0 &&
+ publicKey.e.compareTo(privateKey.e) === 0
+ );
+ });
+
+ if (!matching) {
+ throw new PdfSealError(
+ "No certificate in SEAL_P12_BASE64 matches its private key.",
+ );
+ }
+
+ return {
+ certificateChainPem: [
+ matching,
+ ...certificates.filter((certificate) => certificate !== matching),
+ ].map((certificate) => forge.pki.certificateToPem(certificate)),
+ privateKeyPem: forge.pki.privateKeyToPem(privateKey),
+ };
+}
+
+export const SEAL_TEST_OIDS = OID;
diff --git a/src/lib/services/seal-identity.ts b/src/lib/services/seal-identity.ts
new file mode 100644
index 0000000..47b7912
--- /dev/null
+++ b/src/lib/services/seal-identity.ts
@@ -0,0 +1,272 @@
+import {
+ createCipheriv,
+ createDecipheriv,
+ generateKeyPairSync,
+ hkdfSync,
+ randomBytes,
+ randomUUID,
+} from "node:crypto";
+
+import { PDFDocument } from "pdf-lib";
+
+import { getDb, withTransaction, type DbPool } from "../db/connection.ts";
+import { getBranding } from "../settings.ts";
+import {
+ isProduction,
+ readEnv,
+ resolveAuthSecret,
+ type EnvSource,
+} from "../utils/env.ts";
+import {
+ createSelfSignedSealIdentity,
+ saveSealedPdf,
+ sealIdentityFromPkcs12,
+ type SealIdentity,
+ type SealOptions,
+} from "./pdf-seal.ts";
+
+// Where the install's seal key comes from:
+//
+// 1. SEAL_P12_BASE64 (+ SEAL_P12_PASSWORD): a certificate the organization
+// bought from a certificate authority, so readers show its name as
+// verified. Used as given, never stored.
+// 2. Otherwise a key the install makes for itself the first time it seals a
+// document. The private key is kept in the seal_keys table, encrypted with
+// a key derived from the auth secret. If that secret changes and the old
+// key can no longer be read, a new one is made; documents sealed before
+// still verify, because each carries its own certificate.
+
+const KEY_CONTEXT = "signudoc/seal-key/v1";
+const SEAL_KEY_LOCK_ID = 746108325;
+
+type CachedIdentity = { identity: SealIdentity; source: string };
+
+declare global {
+ var __signudocSealIdentity: CachedIdentity | undefined;
+}
+
+function encryptionKey(env: EnvSource): Buffer {
+ const secret = resolveAuthSecret(env);
+
+ if (!secret) {
+ if (isProduction(env)) {
+ throw new Error(
+ "Sealing documents needs BETTER_AUTH_SECRET, or a database password of at least 12 characters.",
+ );
+ }
+
+ // Local development without a password: nothing worth protecting.
+ return Buffer.from(
+ hkdfSync("sha256", "signudoc-development", "", KEY_CONTEXT, 32),
+ );
+ }
+
+ return Buffer.from(hkdfSync("sha256", secret, "", KEY_CONTEXT, 32));
+}
+
+export function encryptPrivateKey(pem: string, key: Buffer): string {
+ const iv = randomBytes(12);
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
+ const body = Buffer.concat([cipher.update(pem, "utf8"), cipher.final()]);
+
+ return [
+ "v1",
+ iv.toString("base64"),
+ cipher.getAuthTag().toString("base64"),
+ body.toString("base64"),
+ ].join(".");
+}
+
+export function decryptPrivateKey(value: string, key: Buffer): string | null {
+ const [version, iv, tag, body] = value.split(".");
+
+ if (version !== "v1" || !iv || !tag || !body) {
+ return null;
+ }
+
+ try {
+ const decipher = createDecipheriv(
+ "aes-256-gcm",
+ key,
+ Buffer.from(iv, "base64"),
+ );
+
+ decipher.setAuthTag(Buffer.from(tag, "base64"));
+
+ return Buffer.concat([
+ decipher.update(Buffer.from(body, "base64")),
+ decipher.final(),
+ ]).toString("utf8");
+ } catch {
+ return null;
+ }
+}
+
+function identityFromEnvironment(env: EnvSource): SealIdentity | null {
+ const bundle = readEnv(env, "SEAL_P12_BASE64");
+
+ if (!bundle) {
+ return null;
+ }
+
+ return sealIdentityFromPkcs12(
+ new Uint8Array(Buffer.from(bundle, "base64")),
+ readEnv(env, "SEAL_P12_PASSWORD") ?? "",
+ );
+}
+
+type SealKeyRow = {
+ certificatePem: string;
+ encryptedPrivateKey: string;
+ id: string;
+};
+
+async function identityFromDatabase(
+ env: EnvSource,
+ database: DbPool,
+): Promise<CachedIdentity> {
+ const key = encryptionKey(env);
+
+ return withTransaction(async (tx) => {
+ // One instance makes the key; any other waits here and then reads it.
+ await tx.query("SELECT pg_advisory_xact_lock($1)", [SEAL_KEY_LOCK_ID]);
+
+ const existing = await tx.query<SealKeyRow>(
+ `
+ SELECT
+ id,
+ certificate_pem AS "certificatePem",
+ encrypted_private_key AS "encryptedPrivateKey"
+ FROM seal_keys
+ WHERE retired_at IS NULL
+ LIMIT 1
+ `,
+ );
+ const row = existing.rows[0];
+
+ if (row) {
+ const privateKeyPem = decryptPrivateKey(row.encryptedPrivateKey, key);
+
+ if (privateKeyPem) {
+ return {
+ identity: {
+ certificateChainPem: [row.certificatePem],
+ privateKeyPem,
+ },
+ source: `database:${row.id}`,
+ };
+ }
+
+ console.warn(
+ "[seal] The stored seal key cannot be read with the current auth secret; making a new one.",
+ );
+ }
+
+ const branding = await getBranding(env);
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", {
+ modulusLength: 3072,
+ privateKeyEncoding: { format: "pem", type: "pkcs8" },
+ publicKeyEncoding: { format: "pem", type: "spki" },
+ });
+ const generated = createSelfSignedSealIdentity({
+ commonName: `${branding.organizationName ?? branding.productName} document seal`,
+ organization: branding.organizationName,
+ privateKeyPem: privateKey,
+ publicKeyPem: publicKey,
+ });
+ const now = Math.floor(Date.now() / 1000);
+ const id = randomUUID();
+
+ await tx.query(
+ `UPDATE seal_keys SET retired_at = $1 WHERE retired_at IS NULL`,
+ [now],
+ );
+ await tx.query(
+ `
+ INSERT INTO seal_keys (id, certificate_pem, encrypted_private_key, created_at)
+ VALUES ($1, $2, $3, $4)
+ `,
+ [id, generated.certificatePem, encryptPrivateKey(privateKey, key), now],
+ );
+
+ return { identity: generated, source: `database:${id}` };
+ }, database);
+}
+
+export async function getSealIdentity({
+ database = getDb(),
+ env = process.env,
+}: { database?: DbPool; env?: EnvSource } = {}): Promise<SealIdentity> {
+ const cached = globalThis.__signudocSealIdentity;
+
+ if (cached) {
+ return cached.identity;
+ }
+
+ const fromEnvironment = identityFromEnvironment(env);
+ const resolved = fromEnvironment
+ ? { identity: fromEnvironment, source: "environment" }
+ : await identityFromDatabase(env, database);
+
+ globalThis.__signudocSealIdentity = resolved;
+
+ return resolved.identity;
+}
+
+/** Forgets the loaded key, for tests. */
+export function resetSealIdentityCache() {
+ globalThis.__signudocSealIdentity = undefined;
+}
+
+export type SealPurpose = "signed-document" | "certificate";
+
+/**
+ * Saves a finished PDF sealed with the install's key, so any later change to
+ * it shows in a PDF reader.
+ */
+export async function saveInstallSealedPdf(
+ pdfDocument: PDFDocument,
+ purpose: SealPurpose,
+ {
+ database,
+ env = process.env,
+ identity,
+ }: { database?: DbPool; env?: EnvSource; identity?: SealIdentity } = {},
+): Promise<Uint8Array> {
+ const sealIdentity = identity ?? (await getSealIdentity({ database, env }));
+ const branding = await getBranding(env);
+ const timestampUrl = readEnv(env, "SEAL_TIMESTAMP_URL") ?? null;
+ const options: SealOptions = {
+ contactInfo: branding.supportAddress ?? "",
+ name: branding.organizationName ?? branding.productName,
+ reason:
+ purpose === "signed-document"
+ ? `Signed with ${branding.productName}; sealed so that later changes are detectable`
+ : `${branding.productName} audit certificate`,
+ timestampUrl,
+ };
+
+ if (!timestampUrl) {
+ return saveSealedPdf(pdfDocument, sealIdentity, options);
+ }
+
+ try {
+ return await saveSealedPdf(
+ await clonePdf(pdfDocument),
+ sealIdentity,
+ options,
+ );
+ } catch (error) {
+ // A time-stamping service that is down must not stop a signing. The
+ // document is still sealed, only without the independent time.
+ console.error("[seal] Timestamping failed; sealing without it.", error);
+ return saveSealedPdf(pdfDocument, sealIdentity, {
+ ...options,
+ timestampUrl: null,
+ });
+ }
+}
+
+async function clonePdf(pdfDocument: PDFDocument): Promise<PDFDocument> {
+ return PDFDocument.load(await pdfDocument.save({ useObjectStreams: false }));
+}
diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.ts
index d45d665..500ff71 100644
--- a/src/lib/settings.test.ts
+++ b/src/lib/settings.test.ts
@@ -13,6 +13,7 @@ const stored: AppSettings = {
emailReadyAt: null,
organizationName: "Acme Corp",
privacyUrl: "https://acme.com/privacy",
+ retentionDays: null,
senderAddress: "[email protected]",
setupCompletedAt: 1_800_000_000,
signupMode: "domains",
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 98af550..01b8950 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -21,6 +21,11 @@ export type AppSettings = {
emailReadyAt: number | null;
organizationName: string | null;
privacyUrl: string | null;
+ /**
+ * Days a finished envelope is kept before the nightly job deletes it, or
+ * null to keep finished envelopes until someone deletes them.
+ */
+ retentionDays: number | null;
senderAddress: string | null;
setupCompletedAt: number | null;
signupMode: SignupMode;
@@ -63,6 +68,7 @@ type AppSettingsRow = {
email_ready_at: number | null;
organization_name: string | null;
privacy_url: string | null;
+ retention_days: number | null;
sender_address: string | null;
setup_completed_at: number | null;
signup_mode: SignupMode;
@@ -75,6 +81,7 @@ const SETTINGS_COLUMNS = `
email_ready_at,
organization_name,
privacy_url,
+ retention_days,
sender_address,
setup_completed_at,
signup_mode,
@@ -90,6 +97,7 @@ const UNSET_SETTINGS: AppSettings = {
emailReadyAt: null,
organizationName: null,
privacyUrl: null,
+ retentionDays: null,
senderAddress: null,
setupCompletedAt: null,
signupMode: "open",
@@ -144,6 +152,7 @@ function mapSettingsRow(row: AppSettingsRow): AppSettings {
emailReadyAt: row.email_ready_at,
organizationName: row.organization_name,
privacyUrl: row.privacy_url,
+ retentionDays: row.retention_days,
senderAddress: row.sender_address,
setupCompletedAt: row.setup_completed_at,
signupMode: row.signup_mode,
@@ -264,10 +273,11 @@ export async function saveSettings(
signup_mode,
support_address,
terms_url,
+ retention_days,
created_at,
updated_at
)
- values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10)
+ values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $10, $10)
on conflict (id) do update set
allowed_email_domains = excluded.allowed_email_domains,
email_ready_at = excluded.email_ready_at,
@@ -278,6 +288,7 @@ export async function saveSettings(
signup_mode = excluded.signup_mode,
support_address = excluded.support_address,
terms_url = excluded.terms_url,
+ retention_days = excluded.retention_days,
updated_at = excluded.updated_at
returning ${SETTINGS_COLUMNS}
`,
@@ -292,6 +303,7 @@ export async function saveSettings(
next.supportAddress,
next.termsUrl,
now,
+ next.retentionDays,
],
);
diff --git a/src/lib/signature-evidence.dbtest.ts b/src/lib/signature-evidence.dbtest.ts
new file mode 100644
index 0000000..ee7f9b5
--- /dev/null
+++ b/src/lib/signature-evidence.dbtest.ts
@@ -0,0 +1,236 @@
+import assert from "node:assert/strict";
+import { 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 { runRetentionSweep } from "./retention.ts";
+import { recordAuditEvent, verifyAuditChain } from "./services/audit.ts";
+import type { EmailService } from "./services/email.ts";
+import { createStorageService } from "./services/storage.ts";
+import { eraseSignerData, exportSignerData } from "./signer-data.ts";
+
+// The audit hash chain, signer data requests, account hand-over and the
+// retention period, against a real Postgres. Run with `npm run test:db`.
+
+let database: pg.Pool;
+let storageDir: string;
+const createdUsers: string[] = [];
+let settingsRowExisted = true;
+
+before(async () => {
+ database = await openTestDatabase();
+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-evidence-"));
+ settingsRowExisted =
+ (await database.query(`select 1 from app_settings`)).rowCount === 1;
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.query(
+ settingsRowExisted
+ ? `update app_settings set retention_days = null`
+ : `delete from app_settings`,
+ );
+ await database.end();
+ await rm(storageDir, { force: true, recursive: true });
+});
+
+function storage() {
+ return createStorageService({
+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
+ });
+}
+
+async function createUser(role: "admin" | "user" = "user") {
+ const id = randomUUID();
+
+ createdUsers.push(id);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, $2, $3, $4)`,
+ [id, `User ${id.slice(0, 4)}`, `${id}@example.test`, role],
+ );
+
+ return id;
+}
+
+async function createEnvelope(
+ userId: string,
+ status: "completed" | "draft" | "sent",
+ signerEmail: string,
+ finishedAt: number | null = null,
+) {
+ const id = randomUUID();
+
+ 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, completed_at
+ ) values ($1, $2, 'Test', $3, $4, 'test.pdf', 10, 1, $5, $6)
+ `,
+ [id, userId, status, `test/${id}.pdf`, "a".repeat(64), finishedAt],
+ );
+ await database.query(
+ `
+ insert into signers (id, envelope_id, name, email, sign_order, status)
+ values ($1, $2, 'Signer', $3, 1, 'pending')
+ `,
+ [randomUUID(), id, signerEmail],
+ );
+
+ return id;
+}
+
+async function envelopeOwner(envelopeId: string) {
+ const result = await database.query<{ user_id: string }>(
+ `select user_id from envelopes where id = $1`,
+ [envelopeId],
+ );
+
+ return result.rows[0]?.user_id ?? null;
+}
+
+test("the audit chain verifies, and shows an edited row", async () => {
+ const owner = await createUser();
+ const envelopeId = await createEnvelope(owner, "sent", "[email protected]");
+
+ for (const event of ["created", "sent", "viewed"] as const) {
+ await recordAuditEvent(
+ { actorType: "system", envelopeId, event, metadata: { n: event } },
+ database,
+ );
+ }
+
+ assert.deepEqual(await verifyAuditChain(envelopeId, database), {
+ chainedEvents: 3,
+ ok: true,
+ });
+
+ await database.query(
+ `update audit_events set ip_address = '10.0.0.1' where envelope_id = $1 and event = 'sent'`,
+ [envelopeId],
+ );
+
+ const check = await verifyAuditChain(envelopeId, database);
+
+ assert.equal(check.ok, false);
+ assert.equal(check.ok ? null : check.brokenAtSequence, 2);
+});
+
+test("a signer's data can be exported, then erased from finished envelopes only", async () => {
+ const owner = await createUser();
+ const email = `${randomUUID()}@example.test`;
+ const finished = await createEnvelope(owner, "completed", email, 1);
+ const inFlight = await createEnvelope(owner, "sent", email);
+ const draft = await createEnvelope(owner, "draft", email);
+
+ const exported = await exportSignerData(email.toUpperCase(), database);
+
+ assert.equal(exported.envelopes.length, 3);
+
+ await assert.rejects(eraseSignerData(email, "[email protected]", database));
+
+ const result = await eraseSignerData(email, email, database);
+
+ assert.equal(result.deletedEnvelopes, 1);
+ assert.equal(result.removedFromDrafts, 1);
+ assert.deepEqual(
+ result.skippedInProgress.map((row) => row.id),
+ [inFlight],
+ );
+ assert.equal(await envelopeOwner(finished), null);
+ assert.equal(await envelopeOwner(draft), owner);
+ assert.equal((await exportSignerData(email, database)).envelopes.length, 1);
+});
+
+test("closing an account hands finished envelopes to an administrator", async () => {
+ const admin = await createUser("admin");
+ const leaver = await createUser();
+ const finished = await createEnvelope(
+ leaver,
+ "completed",
+ 1,
+ );
+ const draft = await createEnvelope(leaver, "draft", "[email protected]");
+
+ await database.query(
+ `
+ insert into account_closure_requests
+ (user_id, requested_at, export_expires_at, purge_after_at, updated_at)
+ values ($1, 1, 1, 1, 1)
+ `,
+ [leaver],
+ );
+
+ const summary = await runRetentionSweep({
+ database,
+ storageService: storage(),
+ });
+
+ assert.ok(!summary.accountPurgeFailures.includes(leaver));
+ assert.equal(await envelopeOwner(finished), admin);
+ assert.equal(await envelopeOwner(draft), null);
+});
+
+test("the retention period warns the sender, then deletes", async () => {
+ const owner = await createUser();
+ const now = 2_000_000_000;
+ const day = 24 * 60 * 60;
+ const old = await createEnvelope(
+ owner,
+ "completed",
+ now - 400 * day,
+ );
+ const recent = await createEnvelope(
+ owner,
+ "completed",
+ now - 10 * day,
+ );
+ const sent: string[] = [];
+ const emailService = {
+ send: async (message: { subject: string; to: string }) => {
+ sent.push(message.to);
+
+ return { accepted: [message.to], rejected: [] };
+ },
+ sendBatch: async () => ({ accepted: [], rejected: [] }),
+ } as unknown as EmailService;
+
+ await database.query(
+ `insert into app_settings (id, signup_mode, retention_days, created_at, updated_at)
+ values (true, 'closed', 365, 1, 1)
+ on conflict (id) do update set retention_days = 365`,
+ );
+
+ const first = await runRetentionSweep({
+ database,
+ emailService,
+ now,
+ storageService: storage(),
+ });
+
+ assert.ok(first.finishedEnvelopeWarningsSent >= 1);
+ assert.ok(sent.includes(`${owner}@example.test`));
+ assert.equal(await envelopeOwner(old), owner);
+
+ const later = await runRetentionSweep({
+ database,
+ emailService,
+ now: now + 8 * day,
+ storageService: storage(),
+ });
+
+ assert.ok(later.finishedEnvelopesDeleted >= 1);
+ assert.equal(await envelopeOwner(old), null);
+ assert.equal(await envelopeOwner(recent), owner);
+});
diff --git a/src/lib/signer-checks.test.ts b/src/lib/signer-checks.test.ts
new file mode 100644
index 0000000..97e33f9
--- /dev/null
+++ b/src/lib/signer-checks.test.ts
@@ -0,0 +1,86 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ buildVerificationCookieValue,
+ checkAccessCode,
+ checkEmailCode,
+ hashAccessCode,
+ issueEmailCode,
+ maskEmailAddress,
+ readCookie,
+ readVerifiedMethods,
+ requiredSignerChecks,
+} from "./signer-checks.ts";
+
+test("an access code matches regardless of case and spaces, and nothing else does", () => {
+ const stored = hashAccessCode("Blue Harbor 42");
+
+ assert.equal(checkAccessCode("blueharbor42", stored), true);
+ assert.equal(checkAccessCode(" BLUE HARBOR 42 ", stored), true);
+ assert.equal(checkAccessCode("blueharbor43", stored), false);
+ assert.equal(checkAccessCode("blueharbor42", "garbage"), false);
+});
+
+test("an emailed code is six digits and checks against its hash", () => {
+ const { code, hash } = issueEmailCode();
+
+ assert.match(code, /^\d{6}$/);
+ assert.equal(checkEmailCode(code, hash), true);
+ assert.equal(
+ checkEmailCode(code === "000000" ? "000001" : "000000", hash),
+ false,
+ );
+});
+
+test("the verification cookie is bound to its link and expires", () => {
+ const now = 1_800_000_000;
+ const { value } = buildVerificationCookieValue(
+ "hash-a",
+ ["email_code", "access_code"],
+ now,
+ );
+
+ assert.deepEqual(readVerifiedMethods("hash-a", value, now + 60), [
+ "access_code",
+ "email_code",
+ ]);
+ assert.deepEqual(readVerifiedMethods("hash-b", value, now + 60), []);
+ assert.deepEqual(readVerifiedMethods("hash-a", value, now + 9 * 60 * 60), []);
+});
+
+test("a cookie whose method list was edited is rejected", () => {
+ const now = 1_800_000_000;
+ const { value } = buildVerificationCookieValue(
+ "hash-a",
+ ["access_code"],
+ now,
+ );
+ const [expires, , signature] = value.split(".");
+
+ assert.deepEqual(
+ readVerifiedMethods(
+ "hash-a",
+ `${expires}.access_code+email_code.${signature}`,
+ now,
+ ),
+ [],
+ );
+});
+
+test("required checks follow the signer's settings", () => {
+ assert.deepEqual(
+ requiredSignerChecks({ accessCodeHash: null, requireEmailCode: false }),
+ [],
+ );
+ assert.deepEqual(
+ requiredSignerChecks({ accessCodeHash: "x", requireEmailCode: true }),
+ ["access_code", "email_code"],
+ );
+});
+
+test("cookie and address helpers", () => {
+ assert.equal(readCookie("a=1; sd_v_x=abc%2Edef; b=2", "sd_v_x"), "abc.def");
+ assert.equal(readCookie(null, "a"), null);
+ assert.equal(maskEmailAddress("[email protected]"), "j***@acme.com");
+});
diff --git a/src/lib/signer-checks.ts b/src/lib/signer-checks.ts
new file mode 100644
index 0000000..648ab96
--- /dev/null
+++ b/src/lib/signer-checks.ts
@@ -0,0 +1,232 @@
+import {
+ createHmac,
+ randomBytes,
+ randomInt,
+ scryptSync,
+ timingSafeEqual,
+} from "node:crypto";
+
+import { type DbExecutor, getDb, queryOne } from "./db/connection.ts";
+import { hashOpaqueToken } from "./services/opaque-tokens.ts";
+import { resolveAuthSecret } from "./utils/env.ts";
+
+// Extra checks a sender can ask for before a signer may open and sign:
+//
+// - access_code: a code the sender tells the signer some other way (by
+// phone, in person). Proves more than holding the email.
+// - email_code: a one-time code emailed when the signer opens the link.
+// Proves the person signing controls the mailbox at that moment, not just
+// that they hold a forwarded link.
+//
+// Passing a check sets a cookie for this link only, valid for a few hours.
+
+export const signerCheckMethods = ["access_code", "email_code"] as const;
+export type SignerCheckMethod = (typeof signerCheckMethods)[number];
+
+export const EMAIL_CODE_TTL_SECONDS = 10 * 60;
+export const EMAIL_CODE_MAX_ATTEMPTS = 5;
+export const EMAIL_CODE_RESEND_SECONDS = 60;
+const VERIFICATION_COOKIE_TTL_SECONDS = 8 * 60 * 60;
+const COOKIE_CONTEXT = "signudoc/signer-verification/v1";
+
+export type SignerCheckState = {
+ accessCodeHash: string | null;
+ consentedAt: number | null;
+ emailCodeAttempts: number;
+ emailCodeExpiresAt: number | null;
+ emailCodeHash: string | null;
+ emailCodeSentAt: number | null;
+ requireEmailCode: boolean;
+};
+
+export async function getSignerCheckState(
+ signerId: string,
+ database: DbExecutor = getDb(),
+): Promise<SignerCheckState> {
+ const row = await queryOne<SignerCheckState>(
+ database,
+ `
+ SELECT
+ access_code_hash AS "accessCodeHash",
+ consented_at AS "consentedAt",
+ email_code_attempts AS "emailCodeAttempts",
+ email_code_expires_at AS "emailCodeExpiresAt",
+ email_code_hash AS "emailCodeHash",
+ email_code_sent_at AS "emailCodeSentAt",
+ require_email_code AS "requireEmailCode"
+ FROM signers
+ WHERE id = $1
+ `,
+ [signerId],
+ );
+
+ return (
+ row ?? {
+ accessCodeHash: null,
+ consentedAt: null,
+ emailCodeAttempts: 0,
+ emailCodeExpiresAt: null,
+ emailCodeHash: null,
+ emailCodeSentAt: null,
+ requireEmailCode: false,
+ }
+ );
+}
+
+export function requiredSignerChecks(
+ state: Pick<SignerCheckState, "accessCodeHash" | "requireEmailCode">,
+): SignerCheckMethod[] {
+ return [
+ ...(state.accessCodeHash ? (["access_code"] as const) : []),
+ ...(state.requireEmailCode ? (["email_code"] as const) : []),
+ ];
+}
+
+/** Access codes are short, so they are stored with a slow, salted hash. */
+export function hashAccessCode(code: string): string {
+ const salt = randomBytes(16);
+ const hash = scryptSync(normalizeCode(code), salt, 32);
+
+ return `scrypt$${salt.toString("base64")}$${hash.toString("base64")}`;
+}
+
+function normalizeCode(code: string): string {
+ return code.trim().replace(/\s+/g, "").toUpperCase();
+}
+
+export function checkAccessCode(code: string, stored: string): boolean {
+ const [scheme, salt, hash] = stored.split("$");
+
+ if (scheme !== "scrypt" || !salt || !hash) {
+ return false;
+ }
+
+ const expected = Buffer.from(hash, "base64");
+ const actual = scryptSync(
+ normalizeCode(code),
+ Buffer.from(salt, "base64"),
+ expected.length,
+ );
+
+ return timingSafeEqual(actual, expected);
+}
+
+export function issueEmailCode(): { code: string; hash: string } {
+ const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
+
+ return { code, hash: hashEmailCode(code) };
+}
+
+export function hashEmailCode(code: string): string {
+ return createHmac("sha256", cookieSecret())
+ .update(`email-code:${normalizeCode(code)}`)
+ .digest("hex");
+}
+
+export function checkEmailCode(code: string, storedHash: string): boolean {
+ const actual = Buffer.from(hashEmailCode(code), "hex");
+ const expected = Buffer.from(storedHash, "hex");
+
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
+}
+
+function cookieSecret(): string {
+ return resolveAuthSecret() ?? "signudoc-development-only";
+}
+
+export function verificationCookieName(signingTokenHash: string): string {
+ return `sd_v_${signingTokenHash.slice(0, 16)}`;
+}
+
+function signCookie(
+ signingTokenHash: string,
+ expiresAt: number,
+ methods: readonly SignerCheckMethod[],
+): string {
+ return createHmac("sha256", cookieSecret())
+ .update(COOKIE_CONTEXT)
+ .update(`|${signingTokenHash}|${String(expiresAt)}|${methods.join("+")}`)
+ .digest("base64url");
+}
+
+export function buildVerificationCookieValue(
+ signingTokenHash: string,
+ methods: readonly SignerCheckMethod[],
+ now = Math.floor(Date.now() / 1000),
+): { maxAge: number; value: string } {
+ const expiresAt = now + VERIFICATION_COOKIE_TTL_SECONDS;
+ const sorted = [...new Set(methods)].sort();
+
+ return {
+ maxAge: VERIFICATION_COOKIE_TTL_SECONDS,
+ value: `${String(expiresAt)}.${sorted.join("+")}.${signCookie(signingTokenHash, expiresAt, sorted)}`,
+ };
+}
+
+export function readVerifiedMethods(
+ signingTokenHash: string,
+ cookieValue: string | null | undefined,
+ now = Math.floor(Date.now() / 1000),
+): SignerCheckMethod[] {
+ if (!cookieValue) {
+ return [];
+ }
+
+ const [expiresText, methodsText, signature] = cookieValue.split(".");
+ const expiresAt = Number(expiresText);
+
+ if (!signature || !Number.isFinite(expiresAt) || expiresAt < now) {
+ return [];
+ }
+
+ const methods = (methodsText ?? "")
+ .split("+")
+ .filter((method): method is SignerCheckMethod =>
+ (signerCheckMethods as readonly string[]).includes(method),
+ );
+ const expected = Buffer.from(
+ signCookie(signingTokenHash, expiresAt, methods),
+ );
+ const actual = Buffer.from(signature);
+
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
+ return [];
+ }
+
+ return methods;
+}
+
+/** Reads one cookie from a Cookie header. */
+export function readCookie(
+ cookieHeader: string | null | undefined,
+ name: string,
+): string | null {
+ for (const part of (cookieHeader ?? "").split(";")) {
+ const [key, ...rest] = part.trim().split("=");
+
+ if (key === name) {
+ return decodeURIComponent(rest.join("="));
+ }
+ }
+
+ return null;
+}
+
+/** The checks a browser has passed for this signing link, from its cookie. */
+export function verifiedMethodsFromCookies(
+ token: string,
+ readCookieValue: (name: string) => string | null | undefined,
+): SignerCheckMethod[] {
+ const tokenHash = hashOpaqueToken(token);
+
+ return readVerifiedMethods(
+ tokenHash,
+ readCookieValue(verificationCookieName(tokenHash)),
+ );
+}
+
+export function maskEmailAddress(email: string): string {
+ const [local = "", domain = ""] = email.split("@");
+
+ return `${local.slice(0, 1)}${"*".repeat(Math.max(1, local.length - 1))}@${domain}`;
+}
diff --git a/src/lib/signer-data.ts b/src/lib/signer-data.ts
new file mode 100644
index 0000000..47785ae
--- /dev/null
+++ b/src/lib/signer-data.ts
@@ -0,0 +1,201 @@
+import { type DbExecutor, getDb, queryMany } from "./db/connection.ts";
+import { deleteEnvelopesAndFiles } from "./retention.ts";
+import { emailSchema } from "./schemas/common.ts";
+
+// What an administrator needs to answer a signer who asks for their data
+// (GDPR Articles 15 and 20) or for it to be erased (Article 17).
+//
+// A signed document holds every party's signature, and its seal breaks if
+// any part is removed, so erasure works on whole envelopes. Envelopes still
+// out for signature are never touched: void them first.
+
+export class SignerDataError extends Error {
+ readonly statusCode: number;
+
+ constructor(message: string, statusCode = 400) {
+ super(message);
+ this.name = "SignerDataError";
+ this.statusCode = statusCode;
+ }
+}
+
+type SignerEnvelopeRow = {
+ declineReason: string | null;
+ declinedAt: number | null;
+ envelopeCreatedAt: number;
+ envelopeId: string;
+ envelopeStatus: string;
+ envelopeTitle: string;
+ signedAt: number | null;
+ signerEmail: string;
+ signerId: string;
+ signerName: string;
+ signerStatus: string;
+};
+
+function parseEmail(email: unknown): string {
+ const parsed = emailSchema.safeParse(email);
+
+ if (!parsed.success) {
+ throw new SignerDataError("Enter the signer's email address.");
+ }
+
+ return parsed.data.toLowerCase();
+}
+
+async function listSignerEnvelopes(
+ email: string,
+ database: DbExecutor,
+): Promise<SignerEnvelopeRow[]> {
+ return queryMany<SignerEnvelopeRow>(
+ database,
+ `
+ SELECT
+ s.id AS "signerId",
+ s.name AS "signerName",
+ s.email AS "signerEmail",
+ s.status AS "signerStatus",
+ s.signed_at AS "signedAt",
+ s.declined_at AS "declinedAt",
+ s.decline_reason AS "declineReason",
+ e.id AS "envelopeId",
+ e.title AS "envelopeTitle",
+ e.status AS "envelopeStatus",
+ e.created_at AS "envelopeCreatedAt"
+ FROM signers s
+ JOIN envelopes e ON e.id = s.envelope_id
+ WHERE lower(s.email) = $1
+ ORDER BY e.created_at ASC, e.id ASC
+ `,
+ [email],
+ );
+}
+
+export type SignerDataExport = {
+ auditEvents: Record<string, unknown>[];
+ email: string;
+ envelopes: SignerEnvelopeRow[];
+ exportedAt: string;
+ fields: Record<string, unknown>[];
+ note: string;
+};
+
+/** Everything stored about one signer email, as JSON. */
+export async function exportSignerData(
+ rawEmail: unknown,
+ database: DbExecutor = getDb(),
+): Promise<SignerDataExport> {
+ const email = parseEmail(rawEmail);
+ const envelopes = await listSignerEnvelopes(email, database);
+ const signerIds = envelopes.map((row) => row.signerId);
+ const envelopeIds = envelopes.map((row) => row.envelopeId);
+ const [fields, auditEvents] = await Promise.all([
+ queryMany<Record<string, unknown>>(
+ database,
+ `
+ SELECT
+ envelope_id AS "envelopeId",
+ type,
+ label,
+ input_method AS "inputMethod",
+ value,
+ checked,
+ image_key IS NOT NULL AS "hasImage",
+ submitted_at AS "submittedAt"
+ FROM fields
+ WHERE signer_id = ANY($1::text[])
+ ORDER BY envelope_id, page, y, x
+ `,
+ [signerIds],
+ ),
+ queryMany<Record<string, unknown>>(
+ database,
+ `
+ SELECT
+ envelope_id AS "envelopeId",
+ event,
+ actor_type AS "actorType",
+ actor_email AS "actorEmail",
+ ip_address AS "ipAddress",
+ user_agent AS "userAgent",
+ metadata,
+ created_at AS "createdAt"
+ FROM audit_events
+ WHERE envelope_id = ANY($1::text[])
+ AND (lower(actor_email) = $2 OR metadata->>'signerId' = ANY($3::text[]))
+ ORDER BY created_at, sequence NULLS LAST
+ `,
+ [envelopeIds, email, signerIds],
+ ),
+ ]);
+
+ return {
+ auditEvents,
+ email,
+ envelopes,
+ exportedAt: new Date().toISOString(),
+ fields,
+ note: "Signed PDFs and audit certificates are not included here. Download them from each envelope, or ask the sender.",
+ };
+}
+
+export type SignerErasureResult = {
+ deletedEnvelopes: number;
+ removedFromDrafts: number;
+ skippedInProgress: { id: string; title: string }[];
+};
+
+/**
+ * Erases one signer email: drops them from drafts and deletes every
+ * finished envelope they took part in, with its files and audit trail.
+ * The caller must have confirmed that no law requires those records kept.
+ */
+export async function eraseSignerData(
+ rawEmail: unknown,
+ confirmation: unknown,
+ database: DbExecutor = getDb(),
+): Promise<SignerErasureResult> {
+ const email = parseEmail(rawEmail);
+
+ if (
+ typeof confirmation !== "string" ||
+ confirmation.trim().toLowerCase() !== email
+ ) {
+ throw new SignerDataError(
+ "Type the signer's email address again to confirm.",
+ );
+ }
+
+ const envelopes = await listSignerEnvelopes(email, database);
+ const drafts = envelopes.filter((row) => row.envelopeStatus === "draft");
+ const finished = envelopes.filter((row) =>
+ ["completed", "declined", "voided"].includes(row.envelopeStatus),
+ );
+ const inProgress = envelopes.filter((row) => row.envelopeStatus === "sent");
+
+ if (drafts.length > 0) {
+ await database.query(
+ `
+ DELETE FROM fields WHERE signer_id = ANY($1::text[])
+ `,
+ [drafts.map((row) => row.signerId)],
+ );
+ await database.query(`DELETE FROM signers WHERE id = ANY($1::text[])`, [
+ drafts.map((row) => row.signerId),
+ ]);
+ }
+
+ const deletedEnvelopes = await deleteEnvelopesAndFiles(
+ [...new Set(finished.map((row) => row.envelopeId))],
+ database,
+ );
+
+ return {
+ deletedEnvelopes,
+ removedFromDrafts: drafts.length,
+ skippedInProgress: inProgress.map((row) => ({
+ id: row.envelopeId,
+ title: row.envelopeTitle,
+ })),
+ };
+}
diff --git a/src/lib/signing-route.ts b/src/lib/signing-route.ts
new file mode 100644
index 0000000..77ba2af
--- /dev/null
+++ b/src/lib/signing-route.ts
@@ -0,0 +1,36 @@
+import { NextResponse } from "next/server";
+
+import {
+ readCookie,
+ verifiedMethodsFromCookies,
+ type SignerCheckMethod,
+} from "./signer-checks.ts";
+import type { SigningVerificationRequiredError } from "./signing.ts";
+
+/** The extra signer checks this request's browser has passed for the link. */
+export function verifiedMethodsForRequest(
+ token: string,
+ request: Request,
+): SignerCheckMethod[] {
+ const cookieHeader = request.headers.get("cookie");
+
+ return verifiedMethodsFromCookies(token, (name) =>
+ readCookie(cookieHeader, name),
+ );
+}
+
+export function verificationRequiredResponse(
+ error: SigningVerificationRequiredError,
+) {
+ return NextResponse.json(
+ {
+ ...error.details,
+ error: error.message,
+ state: "verification-required",
+ },
+ {
+ headers: { "cache-control": "private, no-store" },
+ status: error.statusCode,
+ },
+ );
+}
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index e8117a3..29f49b2 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -15,7 +15,10 @@ import {
envelopePageSchema,
envelopeRecordSchema,
} from "./schemas/envelope.ts";
-import { createRecipientDownloadLink } from "./downloads.ts";
+import {
+ createRecipientDownloadLink,
+ sanitizeFileNameSegment,
+} from "./downloads.ts";
import {
fieldRecordSchema,
MAX_DRAWN_SIGNATURE_BYTES,
@@ -23,8 +26,11 @@ import {
type SigningFieldSubmission,
} from "./schemas/field.ts";
import {
+ signerCheckRequestSchema,
+ signerConsentRequestSchema,
signingPayloadSchema,
signingDeclineResponseSchema,
+ type SigningVerificationState,
type SigningDeclineResponse,
type SigningPayload,
signingSubmitResponseSchema,
@@ -36,8 +42,14 @@ import { getBranding } from "./settings.ts";
import {
listAuditEventsForEnvelope,
recordAuditEvent,
+ recordEmailSent,
} from "./services/audit.ts";
-import { createEmailService, type EmailService } from "./services/email.ts";
+import {
+ createEmailService,
+ fitsAsAttachments,
+ type EmailAttachment,
+ type EmailService,
+} from "./services/email.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
import { hashOpaqueToken } from "./services/opaque-tokens.ts";
import {
@@ -63,6 +75,24 @@ import { requireConfigValue } from "./services/service-config.ts";
import { RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS } from "./types/domain.ts";
import { getEnv } from "./utils/env.ts";
import { escapeHtml } from "./utils/html.ts";
+import {
+ buildElectronicRecordsDisclosure,
+ CONSENT_STATEMENT,
+ ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+} from "./electronic-records-disclosure.ts";
+import {
+ checkAccessCode,
+ checkEmailCode,
+ EMAIL_CODE_MAX_ATTEMPTS,
+ EMAIL_CODE_RESEND_SECONDS,
+ EMAIL_CODE_TTL_SECONDS,
+ getSignerCheckState,
+ issueEmailCode,
+ maskEmailAddress,
+ requiredSignerChecks,
+ type SignerCheckMethod,
+ type SignerCheckState,
+} from "./signer-checks.ts";
type SigningRequestMeta = {
ipAddress?: string | null;
@@ -163,6 +193,8 @@ type ResolvedSigningContext = {
type SubmitSigningOptions = {
database?: DbPool;
requestMeta?: SigningRequestMeta;
+ /** The extra checks this browser has passed for the link (from its cookie). */
+ verifiedMethods?: readonly SignerCheckMethod[];
};
const signingUnavailableStatusCodeMap: Record<
@@ -214,6 +246,10 @@ function getSigningSubmitUrl(token: string): string {
return `/api/signing/${encodeURIComponent(token)}/submit`;
}
+function getSigningConsentUrl(token: string): string {
+ return `/api/signing/${encodeURIComponent(token)}/consent`;
+}
+
function getSigningDeclineUrl(token: string): string {
return `/api/signing/${encodeURIComponent(token)}/decline`;
}
@@ -333,6 +369,7 @@ function buildDeclineNotificationEmail(input: {
}
function buildCompletionSignerEmail(input: {
+ attached: boolean;
branding: Branding;
evidenceDownloadUrl: string;
envelopeId: string;
@@ -347,17 +384,21 @@ function buildCompletionSignerEmail(input: {
`Hi ${input.signerName},`,
"",
`"${input.envelopeTitle}" from ${input.senderName} has been fully signed in ${input.branding.productName}.`,
- "The completed document and redacted certificate are ready.",
+ input.attached
+ ? "The completed document and its certificate are attached. Keep them: they are your copy of the agreement."
+ : "The completed document and its certificate are ready.",
"",
- `Download links (available for ${RECIPIENT_DOWNLOAD_LINK_TTL_DAYS} days):`,
+ `Download links (available for ${RECIPIENT_DOWNLOAD_LINK_TTL_DAYS} days; an expired link offers to send a new one):`,
`Signed PDF: ${input.signedDownloadUrl}`,
`Redacted certificate: ${input.evidenceDownloadUrl}`,
].join("\n");
const htmlBody = [
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
`<p>&ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; from ${escapeHtml(input.senderName)} has been fully signed in ${escapeHtml(input.branding.productName)}.</p>`,
- "<p>The completed document and redacted certificate are ready.</p>",
- `<p>Download links are available for ${RECIPIENT_DOWNLOAD_LINK_TTL_DAYS} days.</p>`,
+ input.attached
+ ? "<p>The completed document and its certificate are attached. Keep them: they are your copy of the agreement.</p>"
+ : "<p>The completed document and its certificate are ready.</p>",
+ `<p>Download links are available for ${RECIPIENT_DOWNLOAD_LINK_TTL_DAYS} days. An expired link offers to send a new one.</p>`,
`<p><a href="${escapeHtml(input.signedDownloadUrl)}">Download signed PDF</a><br /><a href="${escapeHtml(input.evidenceDownloadUrl)}">Download redacted certificate</a></p>`,
].join("");
const legalFooter = withUserEmailLegalFooter(
@@ -719,7 +760,9 @@ function isFieldSubmissionComplete(
}
function buildSignedAuditEvent(input: {
+ authMethods: readonly SignerCheckMethod[];
envelopeId: string;
+ signatureMethods: readonly string[];
requestMeta: SigningRequestMeta;
signer: ReturnType<typeof signerRecordSchema.parse>;
submittedAt: number;
@@ -738,6 +781,8 @@ function buildSignedAuditEvent(input: {
signerId: input.signer.id,
signerName: input.signer.name,
signerOrder: input.signer.signOrder,
+ authMethods: [...input.authMethods],
+ signatureMethods: [...input.signatureMethods],
timezoneOffsetMinutes: input.timezoneOffsetMinutes,
},
userAgent: input.requestMeta.userAgent ?? null,
@@ -843,6 +888,10 @@ function applyCurrentSignerDecline(
}
async function sendCompletionEmails(input: {
+ attachments: {
+ recipientCertificate: Uint8Array;
+ signedPdf: Uint8Array;
+ };
database?: DbExecutor;
emailService: EmailService;
envelopeId: string;
@@ -850,6 +899,22 @@ async function sendCompletionEmails(input: {
sender: SenderRow;
signers: Array<ReturnType<typeof signerRecordSchema.parse>>;
}) {
+ const fileNameStem =
+ sanitizeFileNameSegment(input.envelopeTitle) ||
+ `envelope-${input.envelopeId}`;
+ const attachments: EmailAttachment[] = [
+ {
+ content: input.attachments.signedPdf,
+ contentType: "application/pdf",
+ filename: `${fileNameStem} - signed.pdf`,
+ },
+ {
+ content: input.attachments.recipientCertificate,
+ contentType: "application/pdf",
+ filename: `${fileNameStem} - certificate.pdf`,
+ },
+ ];
+ const attach = fitsAsAttachments(attachments);
const senderName = normalizeSenderName(input.sender);
const issuedAt = Math.floor(Date.now() / 1000);
const branding = await getBranding();
@@ -888,32 +953,68 @@ async function sendCompletionEmails(input: {
),
]);
- return buildCompletionSignerEmail({
+ return {
+ message: {
+ ...buildCompletionSignerEmail({
+ attached: attach,
+ branding,
+ envelopeId: input.envelopeId,
+ envelopeTitle: input.envelopeTitle,
+ evidenceDownloadUrl: redactedEvidenceLink.url,
+ senderName,
+ signedDownloadUrl: signedLink.url,
+ signerEmail: signer.email,
+ signerName: signer.name,
+ }),
+ ...(attach ? { attachments } : {}),
+ },
+ signerId: signer.id,
+ };
+ }),
+ );
+ const messages = [
+ {
+ message: buildCompletionSenderEmail({
branding,
envelopeId: input.envelopeId,
envelopeTitle: input.envelopeTitle,
- evidenceDownloadUrl: redactedEvidenceLink.url,
+ senderEmail: input.sender.email,
senderName,
- signedDownloadUrl: signedLink.url,
- signerEmail: signer.email,
- signerName: signer.name,
- });
- }),
- );
- const messages = [
- buildCompletionSenderEmail({
- branding,
- envelopeId: input.envelopeId,
- envelopeTitle: input.envelopeTitle,
- senderEmail: input.sender.email,
- senderName,
- }),
+ }),
+ signerId: null,
+ },
...signerMessages,
];
- await input.emailService.sendBatch(messages, {
- idempotencyKey: `completion/${input.envelopeId}`,
- });
+ // One by one: Resend's batch endpoint does not take attachments. Each
+ // message is tried even if another fails, so one bad address does not cost
+ // everyone else their copy.
+ const failures: unknown[] = [];
+
+ for (const [index, { message, signerId }] of messages.entries()) {
+ try {
+ const delivery = await input.emailService.send(message, {
+ idempotencyKey: `completion/${input.envelopeId}/${String(index)}`,
+ });
+
+ await recordEmailSent(
+ {
+ envelopeId: input.envelopeId,
+ messageId: delivery.messageId,
+ recipient: message.to,
+ signerId,
+ template: "completion_notification",
+ },
+ input.database,
+ );
+ } catch (error) {
+ failures.push(error);
+ }
+ }
+
+ if (failures.length > 0) {
+ throw new AggregateError(failures, "Some completion emails were not sent.");
+ }
}
export class SigningMutationError extends Error {
@@ -926,6 +1027,273 @@ export class SigningMutationError extends Error {
}
}
+/** The signer must pass the sender's extra checks before going further. */
+export class SigningVerificationRequiredError extends Error {
+ readonly details: SigningVerificationState;
+ readonly statusCode = 401;
+
+ constructor(details: SigningVerificationState) {
+ super("Confirm your identity to open this document.");
+ this.name = "SigningVerificationRequiredError";
+ this.details = details;
+ }
+}
+
+async function assertSignerChecksPassed(
+ context: ResolvedSigningContext,
+ verifiedMethods: readonly SignerCheckMethod[],
+ database: DbExecutor,
+): Promise<{ passed: SignerCheckMethod[]; state: SignerCheckState }> {
+ const state = await getSignerCheckState(context.signer.id!, database);
+ const required = requiredSignerChecks(state);
+ const pending = required.filter(
+ (method) => !verifiedMethods.includes(method),
+ );
+
+ if (pending.length > 0) {
+ throw new SigningVerificationRequiredError({
+ emailCodeSentAt: state.emailCodeSentAt,
+ envelopeTitle: context.envelope.title,
+ maskedEmail: maskEmailAddress(context.signer.email),
+ pending,
+ required,
+ senderName: normalizeSenderName(context.sender),
+ });
+ }
+
+ return { passed: required, state };
+}
+
+function signerAuditMetadata(context: ResolvedSigningContext) {
+ return {
+ signerEmail: context.signer.email,
+ signerId: context.signer.id,
+ signerName: context.signer.name,
+ signerOrder: context.signer.signOrder,
+ };
+}
+
+/** Emails the signer a one-time code, when the sender asked for one. */
+export async function sendSignerEmailCode(
+ token: string,
+ {
+ database = getDb(),
+ emailService = createEmailService(),
+ }: { database?: DbPool; emailService?: EmailService } = {},
+): Promise<{ emailCodeSentAt: number; maskedEmail: string }> {
+ const context = await resolveSigningContext(token, { database });
+ const state = await getSignerCheckState(context.signer.id!, database);
+ const now = Math.floor(Date.now() / 1000);
+
+ if (!state.requireEmailCode) {
+ throw new SigningMutationError("No code is needed for this link.", 400);
+ }
+
+ if (
+ state.emailCodeSentAt !== null &&
+ now - state.emailCodeSentAt < EMAIL_CODE_RESEND_SECONDS &&
+ state.emailCodeHash
+ ) {
+ return {
+ emailCodeSentAt: state.emailCodeSentAt,
+ maskedEmail: maskEmailAddress(context.signer.email),
+ };
+ }
+
+ const issued = issueEmailCode();
+ const branding = await getBranding();
+
+ await database.query(
+ `
+ UPDATE signers
+ SET
+ email_code_hash = $1,
+ email_code_expires_at = $2,
+ email_code_attempts = 0,
+ email_code_sent_at = $3
+ WHERE id = $4
+ `,
+ [issued.hash, now + EMAIL_CODE_TTL_SECONDS, now, context.signer.id],
+ );
+
+ const minutes = Math.round(EMAIL_CODE_TTL_SECONDS / 60);
+ const textBody = [
+ `Hi ${context.signer.name},`,
+ "",
+ `Your code to open "${context.envelope.title}" in ${branding.productName} is:`,
+ "",
+ issued.code,
+ "",
+ `It works for ${String(minutes)} minutes. If you did not just open a signing link, ignore this email.`,
+ ].join("\n");
+ const htmlBody = [
+ `<p>Hi ${escapeHtml(context.signer.name)},</p>`,
+ `<p>Your code to open &ldquo;${escapeHtml(context.envelope.title)}&rdquo; in ${escapeHtml(branding.productName)} is:</p>`,
+ `<p style="font-size:24px;font-weight:700;letter-spacing:4px">${issued.code}</p>`,
+ `<p>It works for ${String(minutes)} minutes. If you did not just open a signing link, ignore this email.</p>`,
+ ].join("");
+ const body = withUserEmailLegalFooter({ htmlBody, textBody }, branding);
+ const delivery = await emailService.send({
+ htmlBody: body.htmlBody,
+ subject: `Your code for "${context.envelope.title}"`,
+ template: "signing_code",
+ textBody: body.textBody,
+ to: context.signer.email,
+ });
+
+ await recordEmailSent(
+ {
+ envelopeId: context.envelope.id,
+ messageId: delivery.messageId,
+ recipient: context.signer.email,
+ signerId: context.signer.id,
+ template: "signing_code",
+ },
+ database,
+ );
+
+ return {
+ emailCodeSentAt: now,
+ maskedEmail: maskEmailAddress(context.signer.email),
+ };
+}
+
+/**
+ * Checks an access code or emailed code. Returns every check this browser
+ * has now passed, for the caller to store in the link's cookie.
+ */
+export async function verifySignerCheck(
+ token: string,
+ input: unknown,
+ {
+ database = getDb(),
+ requestMeta = {},
+ verifiedMethods = [],
+ }: SubmitSigningOptions = {},
+): Promise<SignerCheckMethod[]> {
+ const parsed = signerCheckRequestSchema.parse(input);
+ const context = await resolveSigningContext(token, { database });
+ const state = await getSignerCheckState(context.signer.id!, database);
+ const now = Math.floor(Date.now() / 1000);
+ let passed = false;
+
+ if (!requiredSignerChecks(state).includes(parsed.method)) {
+ throw new SigningMutationError("This check is not needed.", 400);
+ }
+
+ if (parsed.method === "access_code") {
+ passed = checkAccessCode(parsed.code, state.accessCodeHash!);
+ } else {
+ if (
+ !state.emailCodeHash ||
+ state.emailCodeExpiresAt === null ||
+ state.emailCodeExpiresAt < now
+ ) {
+ throw new SigningMutationError(
+ "That code has expired. Send a new one.",
+ 410,
+ );
+ }
+
+ passed = checkEmailCode(parsed.code, state.emailCodeHash);
+
+ const attempts = state.emailCodeAttempts + 1;
+
+ await database.query(
+ passed || attempts >= EMAIL_CODE_MAX_ATTEMPTS
+ ? `UPDATE signers SET email_code_hash = NULL, email_code_expires_at = NULL, email_code_attempts = $1 WHERE id = $2`
+ : `UPDATE signers SET email_code_attempts = $1 WHERE id = $2`,
+ [attempts, context.signer.id],
+ );
+ }
+
+ await recordAuditEvent(
+ {
+ actorEmail: context.signer.email,
+ actorType: "signer",
+ envelopeId: context.envelope.id,
+ event: passed ? "verified" : "verification_failed",
+ ipAddress: requestMeta.ipAddress ?? null,
+ metadata: { ...signerAuditMetadata(context), method: parsed.method },
+ userAgent: requestMeta.userAgent ?? null,
+ },
+ database,
+ );
+
+ if (!passed) {
+ throw new SigningMutationError("That code is not right.", 400);
+ }
+
+ return [...new Set([...verifiedMethods, parsed.method])];
+}
+
+/** Records that the signer agreed to use electronic records and signatures. */
+export async function recordSignerConsent(
+ token: string,
+ input: unknown,
+ {
+ database = getDb(),
+ requestMeta = {},
+ verifiedMethods = [],
+ }: SubmitSigningOptions = {},
+): Promise<{ consentedAt: number }> {
+ const parsed = signerConsentRequestSchema.parse(input);
+ const context = await resolveSigningContext(token, { database });
+ const { state } = await assertSignerChecksPassed(
+ context,
+ verifiedMethods,
+ database,
+ );
+
+ if (parsed.disclosureVersion !== ELECTRONIC_RECORDS_DISCLOSURE_VERSION) {
+ throw new SigningMutationError(
+ "The disclosure has changed. Reload the page to read the current one.",
+ 409,
+ );
+ }
+
+ if (state.consentedAt !== null) {
+ return { consentedAt: state.consentedAt };
+ }
+
+ const consentedAt = Math.floor(Date.now() / 1000);
+
+ await withTransaction(async (tx) => {
+ const updated = await tx.query(
+ `
+ UPDATE signers
+ SET consented_at = $1
+ WHERE id = $2 AND consented_at IS NULL
+ `,
+ [consentedAt, context.signer.id],
+ );
+
+ if (updated.rowCount !== 1) {
+ return;
+ }
+
+ await recordAuditEvent(
+ {
+ actorEmail: context.signer.email,
+ actorType: "signer",
+ createdAt: consentedAt,
+ envelopeId: context.envelope.id,
+ event: "consented",
+ ipAddress: requestMeta.ipAddress ?? null,
+ metadata: {
+ ...signerAuditMetadata(context),
+ disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+ statement: CONSENT_STATEMENT,
+ },
+ userAgent: requestMeta.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+
+ return { consentedAt };
+}
+
async function resolveSigningContext(
token: string,
{
@@ -1008,13 +1376,21 @@ export async function getSigningPayloadForToken(
{
database = getDb(),
requestMeta = {},
+ verifiedMethods = [],
}: {
database?: DbPool;
requestMeta?: SigningRequestMeta;
+ verifiedMethods?: readonly SignerCheckMethod[];
} = {},
): Promise<SigningPayload> {
const context = await resolveSigningContext(token, { database });
+ const { state: checkState } = await assertSignerChecksPassed(
+ context,
+ verifiedMethods,
+ database,
+ );
const storageService = createStorageService();
+ const branding = await getBranding();
await recordViewedEventOnce(context, requestMeta, database);
@@ -1076,7 +1452,17 @@ export async function getSigningPayloadForToken(
);
return signingPayloadSchema.parse({
+ consentUrl: getSigningConsentUrl(token),
+ consentedAt: checkState.consentedAt,
currentSignerFields,
+ disclosure: {
+ sections: buildElectronicRecordsDisclosure({
+ contactAddress: branding.supportAddress ?? context.sender.email,
+ senderName: normalizeSenderName(context.sender),
+ }),
+ statement: CONSENT_STATEMENT,
+ version: ELECTRONIC_RECORDS_DISCLOSURE_VERSION,
+ },
declineUrl: getSigningDeclineUrl(token),
documentUrl: getSigningDocumentUrl(token),
envelopeId: context.envelope.id,
@@ -1099,10 +1485,27 @@ export async function getSigningPayloadForToken(
export async function submitSigningForToken(
token: string,
input: unknown,
- { database = getDb(), requestMeta = {} }: SubmitSigningOptions = {},
+ {
+ database = getDb(),
+ requestMeta = {},
+ verifiedMethods = [],
+ }: SubmitSigningOptions = {},
): Promise<SigningSubmitResponse> {
const parsedInput = signingSubmissionSchema.parse(input);
const context = await resolveSigningContext(token, { database });
+ const signerChecks = await assertSignerChecksPassed(
+ context,
+ verifiedMethods,
+ database,
+ );
+
+ if (signerChecks.state.consentedAt === null) {
+ throw new SigningMutationError(
+ "Agree to use electronic records and signatures before signing.",
+ 409,
+ );
+ }
+
const emailService = createEmailService();
const storageService = createStorageService();
const currentSignerId = context.signer.id;
@@ -1308,7 +1711,25 @@ export async function submitSigningForToken(
}
const signedAuditEvent = buildSignedAuditEvent({
+ authMethods: signerChecks.passed,
envelopeId: context.envelope.id,
+ signatureMethods: [
+ ...new Set(
+ [...fieldUpdates.values()]
+ .filter((update) =>
+ currentSignerFields.some(
+ (field) =>
+ field.id === update.fieldId &&
+ (field.type === "signature" || field.type === "initials"),
+ ),
+ )
+ .map((update) => update.inputMethod)
+ .filter(
+ (method): method is "typed" | "drawn" =>
+ method === "typed" || method === "drawn",
+ ),
+ ),
+ ],
requestMeta,
signer: context.signer,
submittedAt,
@@ -1422,6 +1843,7 @@ export async function submitSigningForToken(
{
actorEmail: signedAuditEvent.actorEmail,
actorType: signedAuditEvent.actorType,
+ id: signedAuditEvent.id,
createdAt: signedAuditEvent.createdAt,
envelopeId: signedAuditEvent.envelopeId,
event: signedAuditEvent.event,
@@ -1435,7 +1857,7 @@ export async function submitSigningForToken(
signingStatePersisted = true;
try {
- await emailService.send(
+ const delivery = await emailService.send(
buildSigningInvitationEmail({
branding: await getBranding(),
envelopeTitle: context.envelope.title,
@@ -1445,6 +1867,17 @@ export async function submitSigningForToken(
signingUrl: nextSignerLink.url,
}),
);
+
+ await recordEmailSent(
+ {
+ envelopeId: context.envelope.id,
+ messageId: delivery.messageId,
+ recipient: nextSigner.email,
+ signerId: nextSigner.id,
+ template: "signing_invitation",
+ },
+ database,
+ );
} catch (error) {
console.error(
`Failed to send next signer invitation for envelope ${context.envelope.id} to ${nextSigner.email}:`,
@@ -1583,7 +2016,10 @@ export async function submitSigningForToken(
signed_pdf_key = $1,
evidence_key = $2,
completed_at = $3,
- updated_at = $4
+ updated_at = $4,
+ signed_pdf_sha256 = $6,
+ evidence_sha256 = $7,
+ recipient_evidence_sha256 = $8
WHERE id = $5
AND status = 'sent'
`,
@@ -1593,6 +2029,9 @@ export async function submitSigningForToken(
finalArtifacts.generatedAt,
finalArtifacts.generatedAt,
context.envelope.id,
+ finalArtifacts.signedPdf.sha256,
+ finalArtifacts.certificate.sha256,
+ finalArtifacts.recipientCertificate.sha256,
],
);
@@ -1607,6 +2046,7 @@ export async function submitSigningForToken(
{
actorEmail: signedAuditEvent.actorEmail,
actorType: signedAuditEvent.actorType,
+ id: signedAuditEvent.id,
createdAt: signedAuditEvent.createdAt,
envelopeId: signedAuditEvent.envelopeId,
event: signedAuditEvent.event,
@@ -1641,6 +2081,10 @@ export async function submitSigningForToken(
try {
await sendCompletionEmails({
+ attachments: {
+ recipientCertificate: finalArtifacts.recipientCertificate.body,
+ signedPdf: finalArtifacts.signedPdf.body,
+ },
database,
emailService,
envelopeId: context.envelope.id,
@@ -1676,10 +2120,16 @@ export async function submitSigningForToken(
export async function declineSigningForToken(
token: string,
input: unknown,
- { database = getDb(), requestMeta = {} }: SubmitSigningOptions = {},
+ {
+ database = getDb(),
+ requestMeta = {},
+ verifiedMethods = [],
+ }: SubmitSigningOptions = {},
): Promise<SigningDeclineResponse> {
const parsedInput = declineEnvelopeSchema.parse(input);
const context = await resolveSigningContext(token, { database });
+
+ await assertSignerChecksPassed(context, verifiedMethods, database);
const emailService = createEmailService();
const storageService = createStorageService();
const currentSignerId = context.signer.id;
@@ -1740,7 +2190,8 @@ export async function declineSigningForToken(
declinedAuditEvent,
];
const storedCertificateKeys: string[] = [];
- let certificate: { key: string };
+ let certificate: { key: string; sha256: string };
+ let recipientCertificateSha256: string;
try {
certificate = await storeEnvelopeCertificatePdf(
@@ -1774,6 +2225,7 @@ export async function declineSigningForToken(
},
);
storedCertificateKeys.push(recipientCertificate.key);
+ recipientCertificateSha256 = recipientCertificate.sha256;
} catch (error) {
await Promise.all(
storedCertificateKeys.map((key) =>
@@ -1822,11 +2274,20 @@ export async function declineSigningForToken(
status = 'declined',
evidence_key = $1,
declined_at = $2,
- updated_at = $3
+ updated_at = $3,
+ evidence_sha256 = $5,
+ recipient_evidence_sha256 = $6
WHERE id = $4
AND status = 'sent'
`,
- [certificate.key, declinedAt, declinedAt, context.envelope.id],
+ [
+ certificate.key,
+ declinedAt,
+ declinedAt,
+ context.envelope.id,
+ certificate.sha256,
+ recipientCertificateSha256,
+ ],
);
if (declinedEnvelopeResult.rowCount !== 1) {
@@ -1840,6 +2301,7 @@ export async function declineSigningForToken(
{
actorEmail: declinedAuditEvent.actorEmail,
actorType: declinedAuditEvent.actorType,
+ id: declinedAuditEvent.id,
createdAt: declinedAuditEvent.createdAt,
envelopeId: declinedAuditEvent.envelopeId,
event: declinedAuditEvent.event,
@@ -1860,7 +2322,7 @@ export async function declineSigningForToken(
}
try {
- await emailService.send(
+ const delivery = await emailService.send(
buildDeclineNotificationEmail({
branding: await getBranding(),
declineReason,
@@ -1872,6 +2334,16 @@ export async function declineSigningForToken(
signerName: context.signer.name,
}),
);
+
+ await recordEmailSent(
+ {
+ envelopeId: context.envelope.id,
+ messageId: delivery.messageId,
+ recipient: context.sender.email,
+ template: "decline_notification",
+ },
+ database,
+ );
} catch (error) {
console.error(
`Failed to send decline notification for envelope ${context.envelope.id}:`,
@@ -1890,11 +2362,15 @@ export async function getSigningDocumentForToken(
token: string,
{
database = getDb(),
+ verifiedMethods = [],
}: {
database?: DbPool;
+ verifiedMethods?: readonly SignerCheckMethod[];
} = {},
) {
const context = await resolveSigningContext(token, { database });
+
+ await assertSignerChecksPassed(context, verifiedMethods, database);
const storageService = createStorageService();
return storageService.getObject(context.envelope.sourcePdfKey);
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index a09e254..50069df 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -33,9 +33,13 @@ export const auditEventTypes = [
"created",
"sent",
"viewed",
+ "consented",
+ "verified",
+ "verification_failed",
"signed",
"declined",
"reminded_manual",
+ "email_sent",
"completed",
"voided",
] as const;
@@ -49,12 +53,15 @@ export const emailTemplateKinds = [
"contact_form",
"email_verification",
"signing_invitation",
+ "signing_code",
"change_email_confirmation",
"manual_nudge",
"completion_notification",
+ "download_links",
"decline_notification",
"void_notification",
"password_reset",
+ "retention_notice",
"test_email",
] as const;
diff --git a/src/lib/utils/env.ts b/src/lib/utils/env.ts
index 8daed92..f312eb9 100644
--- a/src/lib/utils/env.ts
+++ b/src/lib/utils/env.ts
@@ -18,7 +18,10 @@ export class MissingEnvError extends Error {
const PLACEHOLDER_PREFIX = "replace-with-";
// Values copied from .env.example and never filled in count as not set.
-function readEnv(env: EnvSource, variableName: string): string | undefined {
+export function readEnv(
+ env: EnvSource,
+ variableName: string,
+): string | undefined {
const value = env[variableName];
if (typeof value !== "string") {
@@ -37,7 +40,7 @@ function readEnv(env: EnvSource, variableName: string): string | undefined {
return trimmedValue;
}
-function isProduction(env: EnvSource): boolean {
+export function isProduction(env: EnvSource): boolean {
return env.NODE_ENV === "production";
}
diff --git a/src/lib/verify.ts b/src/lib/verify.ts
new file mode 100644
index 0000000..3cec41f
--- /dev/null
+++ b/src/lib/verify.ts
@@ -0,0 +1,84 @@
+import { z } from "zod";
+
+import { getDb, queryOne, type DbExecutor } from "./db/connection.ts";
+
+// 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.
+
+export const verifyRequestSchema = z.object({
+ sha256: z
+ .string()
+ .trim()
+ .toLowerCase()
+ .regex(/^[a-f0-9]{64}$/, "Expected a SHA-256 value."),
+});
+
+export type VerifyResult =
+ | { match: false }
+ | {
+ envelopeId: string;
+ fileKind: "signed-document" | "certificate";
+ finishedAt: number | null;
+ match: true;
+ signerCount: number;
+ status: "completed" | "declined" | "voided";
+ title: string;
+ };
+
+type VerifyRow = {
+ completedAt: number | null;
+ declinedAt: number | null;
+ envelopeId: string;
+ evidenceSha256: string | null;
+ recipientEvidenceSha256: string | null;
+ signedPdfSha256: string | null;
+ signerCount: number;
+ status: "completed" | "declined" | "voided";
+ title: string;
+ voidedAt: number | null;
+};
+
+export async function verifyDocumentHash(
+ sha256: string,
+ database: DbExecutor = getDb(),
+): Promise<VerifyResult> {
+ const row = await queryOne<VerifyRow>(
+ database,
+ `
+ SELECT
+ e.id AS "envelopeId",
+ e.title,
+ e.status,
+ e.completed_at AS "completedAt",
+ e.declined_at AS "declinedAt",
+ e.voided_at AS "voidedAt",
+ e.signed_pdf_sha256 AS "signedPdfSha256",
+ e.evidence_sha256 AS "evidenceSha256",
+ e.recipient_evidence_sha256 AS "recipientEvidenceSha256",
+ (SELECT count(*)::int FROM signers s WHERE s.envelope_id = e.id) AS "signerCount"
+ FROM envelopes e
+ WHERE e.signed_pdf_sha256 = $1
+ OR e.evidence_sha256 = $1
+ OR e.recipient_evidence_sha256 = $1
+ LIMIT 1
+ `,
+ [sha256],
+ );
+
+ if (!row) {
+ return { match: false };
+ }
+
+ return {
+ envelopeId: row.envelopeId,
+ fileKind:
+ row.signedPdfSha256 === sha256 ? "signed-document" : "certificate",
+ finishedAt: row.completedAt ?? row.declinedAt ?? row.voidedAt,
+ match: true,
+ signerCount: row.signerCount,
+ status: row.status,
+ title: row.title,
+ };
+}
diff --git a/src/proxy.ts b/src/proxy.ts
index 4ddee69..7e9ba93 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -138,7 +138,8 @@ function applySecurityHeaders(response: NextResponse, pathname: string) {
if (
!pathname.startsWith("/sign/") &&
!pathname.startsWith("/api/signing/") &&
- !pathname.startsWith("/api/download/")
+ !pathname.startsWith("/api/download/") &&
+ !pathname.startsWith("/download/")
) {
return response;
}