Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let signers sign in their own names through eID Easy or a CSC provider
Claude0f4a84209af2
diff --git a/.env.example b/.env.exampleindex 26a860d..ab22874 100644--- a/.env.example+++ b/.env.example@@ -91,3 +91,24 @@ EMAIL_DRIVER=capture# archive timestamp go into the PDF. If the server cannot be reached, the# PDF is sealed without a timestamp.# SEAL_TIMESTAMP_URL=++# Signatures in the signers' own names (eIDAS advanced or qualified), through+# a signing provider outside Vercel. Unset, signers make simple electronic+# signatures. See "Signatures in the signers' own names" in+# docs/self-hosting.md.+#+# eID Easy (eideasy.com). EIDEASY_API_URL=https://test.eideasy.com for its+# test environment.+# EIDEASY_CLIENT_ID=+# EIDEASY_SECRET=+# EIDEASY_API_URL=+#+# A trust service provider's CSC API v2 remote signing service.+# CSC_API_URL=+# CSC_CLIENT_ID=+# CSC_CLIENT_SECRET=+# CSC_PROVIDER_NAME=+# CSC_OAUTH_URL=+#+# With both set: eideasy (the default) or csc.+# SIGNING_PROVIDER=diff --git a/README.md b/README.mdindex 5afe8a4..d57385e 100644--- a/README.md+++ b/README.md@@ -136,20 +136,20 @@ DocuSign does more, and charges for it per user. SignuDoc does the everyday sign### Where DocuSign does more-| | SignuDoc | DocuSign eSignature |-| ------------------------------------------------------- | ------------------------------ | ----------------------------------------------------- |-| **More than one document per envelope, and Word files** | — PDF only, one per envelope | ✅ |-| **Signing at the same time** | — in order only | ✅ |-| **Bulk send, web forms, payments** | — | ✅ on Business Pro |-| **API and webhooks** | — not yet | ✅ API plans from $50 a month |-| **Integrations** | — | ✅ 1,000+, including Salesforce, Microsoft and Google |-| **Languages** | — signing pages in English | ✅ signing in 44 languages |-| **Single sign-on** | — email and password | ✅ SAML SSO on Enhanced |-| **Advanced and qualified signatures (eIDAS)** | — simple electronic signatures | ✅ |-| **HIPAA, 21 CFR Part 11, certifications** | Part 11 mode; you validate | ✅ on Enhanced or as add-ons |-| **Support** | GitHub issues | ✅ 24/7 on Enhanced |--If your agreements run through Salesforce, need SMS checks or qualified signatures, or go out by the thousand in bulk, DocuSign earns its price. If you want to send everyday agreements, keep the evidence, and own the whole thing, SignuDoc is built for you.+| | SignuDoc | DocuSign eSignature |+| ------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------- |+| **More than one document per envelope, and Word files** | — PDF only, one per envelope | ✅ |+| **Signing at the same time** | — in order only | ✅ |+| **Bulk send, web forms, payments** | — | ✅ on Business Pro |+| **API and webhooks** | — not yet | ✅ API plans from $50 a month |+| **Integrations** | — | ✅ 1,000+, including Salesforce, Microsoft and Google |+| **Languages** | — signing pages in English | ✅ signing in 44 languages |+| **Single sign-on** | — email and password | ✅ SAML SSO on Enhanced |+| **Advanced and qualified signatures (eIDAS)** | With a provider you add: eID Easy or a CSC remote signing service | ✅ |+| **HIPAA, 21 CFR Part 11, certifications** | Part 11 mode; you validate | ✅ on Enhanced or as add-ons |+| **Support** | GitHub issues | ✅ 24/7 on Enhanced |++If your agreements run through Salesforce, need SMS checks or ID document checks, or go out by the thousand in bulk, DocuSign earns its price. If you want to send everyday agreements, keep the evidence, and own the whole thing, SignuDoc is built for you.## What it costs@@ -227,10 +227,12 @@ SignuDoc is not a law firm and does not give legal advice, and nothing here is aEvery install has a page at `/electronic-signatures` that says what it is for, and senders confirm it before each send. It is meant for ordinary business agreements, such as contracts, NDAs, statements of work, offer letters, purchase orders and approvals. It is **not** built for:-- documents that need an advanced or qualified electronic signature (AdES or QES) under eIDAS;+- documents that need an advanced or qualified electronic signature (AdES or QES) under eIDAS, unless you add a signing provider (see below);- protected health information under HIPAA;- documents that many laws keep out of electronic signature, such as wills, family-law matters, court orders, notices of foreclosure, eviction, utility shut-off or insurance cancellation, and in most EU countries real estate transfers and documents that need a notary.+For **advanced or qualified electronic signatures** under eIDAS, connect a signing provider: [eID Easy](https://eideasy.com), or a trust service provider's remote signing service that speaks the CSC API v2. A sender can then choose that signature type for an envelope, and each signer proves who they are at the provider and signs with a certificate in their own name. Every signature goes into the PDF in a revision of its own, so all of them stay valid, and the finished PDF gets long-term validation. The provider is a paid service outside Vercel, so it is optional, and the flow has been tested against stand-ins for both interfaces but not yet against the live services. [Signatures in the signers' own names](docs/self-hosting.md#signatures-in-the-signers-own-names-eidas-ades-and-qes) has the setup.+For FDA 21 CFR Part 11 records, an administrator can turn on **Part 11 mode** under Settings. Signers then sign with their own accounts, whose identity an administrator has confirmed, give their password again at each signature, and see the meaning of their signature (approval, review, responsibility or authorship) printed beside it with their name and the time. Audit trails export as CSV, and finished records are never deleted on a timer. That covers the software's part only: validating your install, writing and following your own procedures, training your people and certifying your electronic signatures to the FDA stay with your organization. The [Part 11 validation pack](docs/part11/README.md) gives you starting documents for that: requirements, a traceability matrix, a risk assessment, qualification scripts, SOP templates and the FDA letter.Your install carries your organization's name, and your organization is responsible for how it is used: linking your own terms and privacy policy, keeping the support address pointed at a mailbox someone reads, choosing how long documents are kept, and answering signers' data requests. [Your responsibilities](docs/self-hosting.md#your-responsibilities) has the details.diff --git a/db/migrations/20261116090000_signer_signatures.sql b/db/migrations/20261116090000_signer_signatures.sqlnew file mode 100644index 0000000..8d9a1f5--- /dev/null+++ b/db/migrations/20261116090000_signer_signatures.sql@@ -0,0 +1,62 @@+-- Signatures in the signer's own name: advanced (AdES) and qualified (QES)+-- electronic signatures under eIDAS, made by a signing provider (eID Easy, or+-- a trust service provider with the Cloud Signature Consortium API).+--+-- * envelopes.signature_level: simple (SignuDoc's own signature, sealed by+-- the install), advanced or qualified. Chosen when the envelope is sent,+-- with the provider it was sent with.+-- * envelopes.revision_key / revision_sha256: the PDF as the last signer+-- signed it. Each signer adds a revision with their own signature on top,+-- so the signatures before stay valid.+-- * provider_signing_sessions: one signer's trip to the provider. What the+-- signer submitted, the signing link and the provider's working state are+-- kept encrypted (secret_data), and only until the signer is back.++alter table public.envelopes+ add column if not exists signature_level text not null default 'simple',+ add column if not exists signature_provider text,+ add column if not exists revision_key text,+ add column if not exists revision_sha256 text;++do $$+begin+ if not exists (+ select 1 from pg_constraint where conname = 'envelopes_signature_level_check'+ ) then+ alter table public.envelopes+ add constraint envelopes_signature_level_check+ check (+ signature_level in ('simple', 'advanced', 'qualified')+ and (signature_level = 'simple') = (signature_provider is null)+ );+ end if;+end+$$;++create table if not exists public.provider_signing_sessions (+ id text primary key,+ envelope_id text not null references public.envelopes (id) on delete cascade,+ signer_id text not null references public.signers (id) on delete cascade,+ provider text not null,+ level text not null check (level in ('advanced', 'qualified')),+ -- pending: at the provider; signing: back with a signature, being saved.+ state text not null default 'pending'+ check (state in ('pending', 'signing', 'completed', 'failed')),+ -- The revision this one is added to: null for the first signer.+ base_sha256 text,+ -- This signer's revision, prepared, then signed.+ revision_key text not null,+ -- SHA-256 (hex) of the bytes the signature covers.+ content_digest text not null,+ secret_data text not null,+ submitted_at bigint not null,+ created_at bigint not null,+ expires_at bigint not null,+ completed_at bigint+);++create index if not exists idx_provider_signing_sessions_signer+ on public.provider_signing_sessions (signer_id, state);++create index if not exists idx_provider_signing_sessions_envelope+ on public.provider_signing_sessions (envelope_id);diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 0503572..ee6c94a 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -72,18 +72,20 @@ 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). |-| `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, and long-term validation. See [Long-term validation](#long-term-validation). |+| 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, and long-term validation. See [Long-term validation](#long-term-validation). |+| `EIDEASY_CLIENT_ID`, `EIDEASY_SECRET` | Let senders ask for advanced or qualified signatures in the signers' own names, through eID Easy. See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). |+| `CSC_API_URL`, `CSC_CLIENT_ID`, `CSC_CLIENT_SECRET` | The same through a trust service provider's remote signing service (CSC API v2). See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). |## Set the site up@@ -137,7 +139,30 @@ Under eIDAS, a seal is the organization's counterpart of a signature. A seal tha- Get it as a PKCS#12 file with an RSA key (SignuDoc does not read EC keys from a file yet), and set it as `SEAL_P12_BASE64` (the file in base64) and `SEAL_P12_PASSWORD`. Keep the file somewhere safe outside Vercel too: the key in it is what makes the seal yours.- Set `SEAL_TIMESTAMP_URL`, so the seal gets long-term validation as above. A timestamp server run by a qualified trust service provider gives a qualified electronic time stamp, which a court presumes accurate (Article 41).-What this gives you: each finished PDF and certificate carries your organization's advanced seal, showing it came from you unchanged. What it does not: the signers' own signatures stay simple electronic signatures, and the seal is not a qualified seal, which needs a qualified certificate held on a qualified device, usually a trust service provider's remote signing service rather than a file. This is not legal advice: whether a seal is enough for a document is for your own counsel.+What this gives you: each finished PDF and certificate carries your organization's advanced seal, showing it came from you unchanged. What it does not: the signers' own signatures stay simple electronic signatures (for signatures in their own names, see the next section), and the seal is not a qualified seal, which needs a qualified certificate held on a qualified device, usually a trust service provider's remote signing service rather than a file. This is not legal advice: whether a seal is enough for a document is for your own counsel.++### Signatures in the signers' own names (eIDAS AdES and QES)++Out of the box, signers make simple electronic signatures and the install seals the result. With a signing provider set up, a sender can instead choose **Advanced electronic signatures** or **Qualified electronic signatures** for an envelope, on the review page before sending. Each signer then fills in their fields as usual, and when they press Finish they go to the provider, prove who they are there (for example with a national eID card, Smart-ID or Mobile-ID, or the provider's own check), and sign with a certificate in their own name. They come back to the install, which checks the signature before keeping it.++What ends up in the PDF:++- Each signer's signature is a PAdES signature in a revision of its own, holding their filled-in fields. The revisions only add to the file, so every earlier signer's signature stays valid, and a PDF reader lists one signature per signer with the name from their certificate.+- When the last signer has signed, the install adds the certificates and revocation answers (B-LT), and with `SEAL_TIMESTAMP_URL` an archive timestamp too (B-LTA), as for the seal above. If the provider did not timestamp a signature, the install's timestamp server does.+- The signed PDF does not get the install's seal, because the signers' signatures already cover all of it. The certificate of completion is still sealed, and lists each signer's certificate, its issuer, and the provider.+- For a qualified signature, the install refuses a certificate that does not say it is qualified and held on a qualified signature device (the EU QC statements). It does not look the issuer up on the EU trusted lists; PDF readers and the EU's own validator do that when the document is checked.++Not available in Part 11 mode, where signers sign with their accounts instead.++**Setting up a provider.** Both are paid services outside Vercel and its Marketplace, so they are optional, and nothing changes until you set one up. Deploy again after setting the variables.++- **eID Easy** reaches most EU national eIDs, Smart-ID, Mobile-ID and several qualified providers through one account. Create an account and a client at [eideasy.com](https://eideasy.com), and set `EIDEASY_CLIENT_ID` and `EIDEASY_SECRET`. For eID Easy's test environment, also set `EIDEASY_API_URL=https://test.eideasy.com`. If eID Easy asks for the addresses it may send signers back to, give it `https://<your domain>/api/signing/provider/return`.+- **A trust service provider with a CSC API v2 remote signing service**, for signers who already have a signing certificate there. Set `CSC_API_URL` (the service's base address, ending in `/csc/v2`), `CSC_CLIENT_ID`, `CSC_CLIENT_SECRET`, and `CSC_PROVIDER_NAME` (the name signers see). Set `CSC_OAUTH_URL` when the provider's OAuth server is not at `<CSC_API_URL>/oauth2`. Register `https://<your domain>/api/signing/provider/return` as the OAuth redirect address.+- With both set, eID Easy is used for new envelopes unless `SIGNING_PROVIDER=csc`. Envelopes already sent finish with the provider they were sent with, as long as it is still set up.++**What has and has not been checked.** The signing flow is tested end to end against stand-ins that follow eID Easy's and the CSC API v2's published interfaces, and PDF readers check the signatures it produces. It has not yet been run against the live services, so try it on the provider's test environment before you rely on it, and tell us on GitHub what you find.++Whether a document needs an advanced or a qualified signature, and whether a given signature meets the law where you and the signers are, is a legal question. This is not legal advice.## Running in the EUdiff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 1541b9e..6679829 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -1023,3 +1023,152 @@ test("in Part 11 mode a verified account signs, with its password and a stated m).toBe(200);});});++test("a signer signs with a qualified signature in their own name, through the signing provider", async ({+ browser,+ page,+}, testInfo) => {+ const runId = String(Date.now());+ const signerEmail = `qualified+${runId}@example.com`;+ const signerName = "Quinn Qualified";+ const signatureType = "Qualified electronic signatures through eID Easy";+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });+ let adminEmail = "";++ await database.connect();++ try {+ const admin = await database.query<{ email: string }>(+ `select email from public."user" where role = 'admin' limit 1`,+ );++ adminEmail = admin.rows[0]?.email ?? "";+ } finally {+ await database.end();+ }++ expect(adminEmail).not.toBe("");++ let envelopeId = "";++ await test.step("the sender asks for qualified signatures", async () => {+ const pdfPath = await writeSamplePdf(testInfo.outputPath("supply.pdf"));++ await page.goto("/login");+ await page.getByLabel("Email").fill(adminEmail);+ await page.getByLabel("Password").fill(PASSWORD);+ await page.getByRole("button", { name: "Log in" }).click();+ await expect(page).toHaveURL(/\/dashboard$/);++ await page.goto("/envelopes/new");+ await page.getByLabel("Envelope title").fill("Supply agreement");+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);+ await page.getByRole("button", { name: "Next ->" }).click();+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);+ envelopeId = /\/envelopes\/([^/]+)\/signers$/.exec(page.url())?.[1] ?? "";++ await page.getByLabel("Signer 1 name").fill(signerName);+ await page.getByLabel("Signer 1 email").fill(signerEmail);+ await page.getByRole("button", { name: "Next →" }).click();+ await expect(page).toHaveURL(/\/prepare$/);++ await page.getByRole("button", { exact: true, name: "Signature" }).click();++ const placementTarget = page.getByLabel("Place Signature on page 1");+ const box = await placementTarget.boundingBox();++ await placementTarget.click({+ position: { x: box!.width * 0.3, y: box!.height * 0.6 },+ });+ await expect(page.getByRole("status")).toHaveText("Saved");+ await page.getByRole("button", { name: "Next →" }).click();+ await expect(page).toHaveURL(/\/review$/);++ await page.getByLabel("Signature type").selectOption("qualified");+ await expect(page.getByText(/this is not legal advice/)).toBeVisible();+ await page.getByRole("button", { name: "Send envelope" }).click();++ const confirmation = page.getByRole("dialog", {+ name: "Send this envelope?",+ });++ await expect(+ confirmation.getByText(`Signature type: ${signatureType}.`),+ ).toBeVisible();+ await confirmation.getByRole("checkbox").check();+ await confirmation.getByRole("button", { name: "Send now" }).click();+ await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}$`));+ await expect(page.getByText(signatureType)).toBeVisible();+ });++ await test.step("the signer fills in the document, then signs at the provider", async () => {+ const invitation = await waitForEmail({+ template: "signing_invitation",+ to: signerEmail,+ });+ const signerContext = await browser.newContext({+ viewport: { height: 900, width: 1440 },+ });+ const signerPage = await signerContext.newPage();+ const providerRequests: string[] = [];++ signerPage.on("request", (request) => {+ if (request.url().includes("/eideasy/")) {+ providerRequests.push(new URL(request.url()).pathname);+ }+ });++ await signerPage.goto(extractLink(invitation.text, "/sign/"));++ const consent = signerPage.getByRole("dialog", { name: "Before you sign" });++ await consent+ .getByRole("checkbox", {+ name: "I agree to use electronic records and signatures",+ })+ .check();+ await consent.getByRole("button", { name: "Agree and continue" }).click();+ await signerPage+ .getByRole("button", { exact: true, name: "Signature" })+ .click();+ await signerPage+ .getByRole("dialog", { name: "Add your signature" })+ .getByRole("button", { name: "Apply signature" })+ .click();+ await signerPage.getByRole("button", { name: "Finish" }).click();++ const finish = signerPage.getByRole("dialog", { name: "Finish signing?" });++ await expect(+ finish.getByText(/asks for a qualified electronic signature/),+ ).toBeVisible();+ await finish.getByRole("button", { name: "Continue to eID Easy" }).click();+ await expect(signerPage).toHaveURL(/\/sign\/[^/]+\/done/);+ // The browser went to the provider and came back.+ expect(providerRequests).toContain("/eideasy/sign_contract_external");+ await signerContext.close();+ });++ await test.step("the signed PDF carries the signer's own signature", async () => {+ await waitForEmail({ template: "completion_notification", to: adminEmail });++ const signed = await page.request.get(+ `/api/envelopes/${envelopeId}/download?type=signed`,+ );++ await expectPdfResponse(signed);++ const text = (await signed.body()).toString("latin1");++ expect(text).toContain("/SubFilter /ETSI.CAdES.detached");+ // No install seal on top: the signer's signature covers the document.+ expect(text.match(/\/ByteRange/g)?.length).toBe(1);++ await page.goto(`/envelopes/${envelopeId}`);+ await expect(+ page.getByText(+ `Signed by ${signerName} with a qualified electronic signature through eID Easy`,+ ),+ ).toBeVisible();+ });+});diff --git a/e2e/support/provider-stand-in.ts b/e2e/support/provider-stand-in.tsnew file mode 100644index 0000000..07a4c62--- /dev/null+++ b/e2e/support/provider-stand-in.ts@@ -0,0 +1,31 @@+// Stand-ins for a signing provider, for the end-to-end test: eID Easy's+// signing API, signing with a qualified certificate from the test CA. The+// app under test is pointed at it with EIDEASY_API_URL. Runs until stopped.++import { startTestPki } from "../../src/lib/services/pki-test-support.ts";+import { startProviderStandIns } from "../../src/lib/services/signing-provider-test-support.ts";++const port = Number(process.env.E2E_PROVIDER_PORT ?? 3101);+const pki = await startTestPki();+const signer = pki.issueSigner({+ commonName: "Quinn Qualified",+ qualified: true,+});+const standIns = await startProviderStandIns(+ {+ chain: [signer.certificate, pki.caCertificate],+ privateKeyPem: signer.privateKeyPem,+ },+ { port },+);++console.log(`[provider stand-in] eID Easy at ${standIns.eidEasyUrl}`);++async function stop() {+ await standIns.close();+ await pki.close();+ process.exit(0);+}++process.on("SIGINT", () => void stop());+process.on("SIGTERM", () => void stop());diff --git a/playwright.config.ts b/playwright.config.tsindex 8374632..c1245f8 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -23,6 +23,9 @@ export const e2eDataDir = path.resolve(".data", "e2e");export const e2eOutboxDir = path.join(e2eDataDir, "outbox");// First-run setup asks for this, as it does on a deployment that sets one.export const e2eSetupToken = "e2e-setup-token";+// A stand-in for eID Easy, so the test can sign with a qualified+// certificate in the signer's own name without the real service.+const providerPort = Number(process.env.E2E_PROVIDER_PORT ?? port + 1);export default defineConfig({expect: { timeout: 20_000 },@@ -46,37 +49,50 @@ export default defineConfig({baseURL,trace: "retain-on-failure",},- webServer: {- command:- process.env.E2E_DEV === "1"- ? `npx next dev --port ${String(port)}`- : `npx next build && npx next start --port ${String(port)}`,- env: {- APP_URL: baseURL,- BETTER_AUTH_SECRET: "e2e-only-secret-not-used-anywhere-else-0123456789",- BETTER_AUTH_URL: baseURL,- DATABASE_URL: e2eDatabaseUrl,- EMAIL_CAPTURE_DIR: e2eOutboxDir,- EMAIL_DRIVER: "capture",- NEXT_TELEMETRY_DISABLED: "1",- // The breach check calls an outside service; the test must not.- PASSWORD_BREACH_CHECK: "off",- SETUP_TOKEN: e2eSetupToken,- // "local" unless E2E_STORAGE_DRIVER says otherwise. With "blob" and a- // BLOB_READ_WRITE_TOKEN in the environment, the same test runs against- // a real Vercel Blob store, direct browser upload included.- STORAGE_DRIVER: process.env.E2E_STORAGE_DRIVER ?? "local",- STORAGE_LOCAL_DIR: path.join(e2eDataDir, "storage"),+ webServer: [+ {+ command:+ process.env.E2E_DEV === "1"+ ? `npx next dev --port ${String(port)}`+ : `npx next build && npx next start --port ${String(port)}`,+ env: {+ APP_URL: baseURL,+ BETTER_AUTH_SECRET: "e2e-only-secret-not-used-anywhere-else-0123456789",+ BETTER_AUTH_URL: baseURL,+ DATABASE_URL: e2eDatabaseUrl,+ EMAIL_CAPTURE_DIR: e2eOutboxDir,+ EIDEASY_API_URL: `http://127.0.0.1:${String(providerPort)}/eideasy`,+ EIDEASY_CLIENT_ID: "test-client",+ EIDEASY_SECRET: "test-secret",+ EMAIL_DRIVER: "capture",+ NEXT_TELEMETRY_DISABLED: "1",+ // The breach check calls an outside service; the test must not.+ PASSWORD_BREACH_CHECK: "off",+ SETUP_TOKEN: e2eSetupToken,+ // "local" unless E2E_STORAGE_DRIVER says otherwise. With "blob" and a+ // BLOB_READ_WRITE_TOKEN in the environment, the same test runs against+ // a real Vercel Blob store, direct browser upload included.+ STORAGE_DRIVER: process.env.E2E_STORAGE_DRIVER ?? "local",+ STORAGE_LOCAL_DIR: path.join(e2eDataDir, "storage"),+ },+ reuseExistingServer: false,+ timeout: 300_000,+ // Playwright starts the server before the test database is prepared:+ // on a first run, as in CI, it has no tables at all, and on later runs+ // it holds the last run's data. So the readiness check must be+ // something that never touches the database. A page would remember for+ // a minute that the site is already set up, and an API route can fail+ // outright for want of tables.+ url: `${baseURL}/icon.svg`,},- reuseExistingServer: false,- timeout: 300_000,- // Playwright starts the server before the test database is prepared:- // on a first run, as in CI, it has no tables at all, and on later runs- // it holds the last run's data. So the readiness check must be- // something that never touches the database. A page would remember for- // a minute that the site is already set up, and an API route can fail- // outright for want of tables.- url: `${baseURL}/icon.svg`,- },+ {+ command:+ "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON e2e/support/provider-stand-in.ts",+ env: { E2E_PROVIDER_PORT: String(providerPort) },+ reuseExistingServer: false,+ timeout: 60_000,+ url: `http://127.0.0.1:${String(providerPort)}/health`,+ },+ ],workers: 1,});diff --git a/src/app/api/envelopes/[id]/send/route.ts b/src/app/api/envelopes/[id]/send/route.tsindex 7aee114..4864f87 100644--- a/src/app/api/envelopes/[id]/send/route.ts+++ b/src/app/api/envelopes/[id]/send/route.ts@@ -24,6 +24,7 @@ type EnvelopeSendRouteContext = {type SendEnvelopeRequest = {expiresInDays?: unknown;reminderIntervalDays?: unknown;+ signatureLevel?: unknown;permittedUseConfirmed?: boolean;};@@ -71,13 +72,14 @@ export async function POST(const options = sendEnvelopeOptionsSchema.safeParse({expiresInDays: body.expiresInDays ?? undefined,reminderIntervalDays: body.reminderIntervalDays ?? undefined,+ signatureLevel: body.signatureLevel ?? undefined,});if (!options.success) {return NextResponse.json({error:- "Choose a deadline between 1 and 365 days from now, and reminders between 1 and 30 days apart.",+ "Choose a deadline between 1 and 365 days from now, reminders between 1 and 30 days apart, and a signature type this install offers.",},{ status: 400 },);@@ -90,6 +92,7 @@ export async function POST({expiresInDays: options.data.expiresInDays,reminderIntervalDays: options.data.reminderIntervalDays,+ signatureLevel: options.data.signatureLevel,ipAddress,senderEmail: session.user.email,senderName:diff --git a/src/app/api/signing/[token]/provider/start/route.ts b/src/app/api/signing/[token]/provider/start/route.tsnew file mode 100644index 0000000..df1f958--- /dev/null+++ b/src/app/api/signing/[token]/provider/start/route.ts@@ -0,0 +1,110 @@+import { NextResponse } from "next/server";+import { ZodError } from "zod";++import { getDb } from "@/lib/db/connection";+import { startProviderSigning } from "@/lib/provider-signing";+import {+ verificationRequiredResponse,+ verifiedMethodsForRequest,+} from "@/lib/signing-route";+import {+ SigningAccessError,+ SigningMutationError,+ SigningVerificationRequiredError,+} from "@/lib/signing";+import { logRouteError } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import { getClientIpAddress } from "@/lib/security/request";++// Preparing the signer's revision of the PDF and handing its hash to the+// signing provider can take a while on a long document.+export const maxDuration = 60;++type ProviderStartRouteContext = {+ params: Promise<{+ token: string;+ }>;+};++const NO_STORE = { "cache-control": "private, no-store" };++/**+ * Starts a signature through the envelope's signing provider. Takes the+ * same body as submit, and answers where to send the signer.+ */+export async function POST(+ request: Request,+ context: ProviderStartRouteContext,+) {+ const { token } = await context.params;+ const rateLimitResponse = await applyRateLimit({+ category: "signing_submit",+ key: buildRateLimitKey([+ "signing-provider-start",+ token,+ getClientIpAddress(request.headers) ?? "unknown",+ ]),+ limit: 10,+ request,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const body = (await request.json().catch(() => null)) as unknown;++ try {+ const { redirectUrl } = await startProviderSigning(token, body, {+ database: getDb(),+ language: request.headers.get("accept-language")?.slice(0, 2) ?? null,+ verifiedMethods: verifiedMethodsForRequest(token, request),+ });++ return NextResponse.json(+ { redirectUrl },+ { headers: NO_STORE, status: 200 },+ );+ } catch (error) {+ if (error instanceof ZodError) {+ return NextResponse.json(+ { error: error.issues[0]?.message ?? "Invalid signing submission." },+ { headers: NO_STORE, status: 400 },+ );+ }++ if (error instanceof SigningVerificationRequiredError) {+ return verificationRequiredResponse(error);+ }++ if (error instanceof SigningAccessError) {+ return NextResponse.json(+ { error: error.message, state: error.state },+ { headers: NO_STORE, status: error.statusCode },+ );+ }++ if (error instanceof SigningMutationError) {+ return NextResponse.json(+ { error: error.message },+ { headers: NO_STORE, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "signing_submit_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while starting a provider signature.",+ path: request.url,+ });++ return NextResponse.json(+ { error: "Unable to start signing." },+ { headers: NO_STORE, status: 500 },+ );+ }+}diff --git a/src/app/api/signing/provider/return/route.ts b/src/app/api/signing/provider/return/route.tsnew file mode 100644index 0000000..610c2ce--- /dev/null+++ b/src/app/api/signing/provider/return/route.ts@@ -0,0 +1,110 @@+import { NextResponse } from "next/server";++import { getDb } from "@/lib/db/connection";+import {+ ProviderSigningError,+ resumeProviderSigning,+} from "@/lib/provider-signing";+import { readCookie, verifiedMethodsFromCookies } from "@/lib/signer-checks";+import { logRouteError } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import {+ getClientIpAddress,+ getRequestUserAgent,+} from "@/lib/security/request";++// The last signer's return also finishes the envelope: long-term validation+// asks certificate authorities, within 15 seconds, and the PDFs are stored.+export const maxDuration = 60;++function seeOther(location: string, request: Request) {+ return NextResponse.redirect(new URL(location, request.url), {+ headers: { "cache-control": "private, no-store" },+ status: 303,+ });+}++function endedPage() {+ return new NextResponse(+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Signing session ended</title></head><body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; line-height: 1.5"><h1 style="font-size: 1.25rem">This signing session has ended</h1><p>Nothing was signed. Open the signing link from your email again to sign.</p></body></html>`,+ {+ headers: {+ "cache-control": "private, no-store",+ "content-type": "text/html; charset=utf-8",+ },+ status: 410,+ },+ );+}++/**+ * Where a signing provider sends the signer back. The state names the+ * signing session, which holds everything else.+ */+export async function GET(request: Request) {+ const url = new URL(request.url);+ const state = url.searchParams.get("state");++ if (!state || state.length > 128) {+ return endedPage();+ }++ const rateLimitResponse = await applyRateLimit({+ category: "signing_submit",+ key: buildRateLimitKey([+ "signing-provider-return",+ getClientIpAddress(request.headers) ?? "unknown",+ ]),+ limit: 30,+ request,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const cookieHeader = request.headers.get("cookie");++ try {+ const next = await resumeProviderSigning(state, url.searchParams, {+ database: getDb(),+ requestMeta: {+ ipAddress: getClientIpAddress(request.headers),+ userAgent: getRequestUserAgent(request.headers),+ },+ verifiedMethodsFor: (token) =>+ verifiedMethodsFromCookies(token, (name) =>+ readCookie(cookieHeader, name),+ ),+ });++ return seeOther(+ "redirectUrl" in next ? next.redirectUrl : next.redirectPath,+ request,+ );+ } catch (error) {+ if (error instanceof ProviderSigningError) {+ if (!error.token) {+ return endedPage();+ }++ return seeOther(+ `/sign/${encodeURIComponent(error.token)}?signatureProblem=${error.problem}`,+ request,+ );+ }++ logRouteError(error, {+ category: "signing_submit_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure when a signer came back from a provider.",+ path: url.pathname,+ });++ return endedPage();+ }+}diff --git a/src/app/sign/[token]/page.tsx b/src/app/sign/[token]/page.tsxindex 91e51e0..ad6a0ba 100644--- a/src/app/sign/[token]/page.tsx+++ b/src/app/sign/[token]/page.tsx@@ -15,10 +15,19 @@ type SignPageProps = {params: Promise<{token: string;}>;+ searchParams: Promise<{ signatureProblem?: string | string[] }>;};-export default async function SignPage({ params }: SignPageProps) {+const SIGNATURE_PROBLEMS = ["cancelled", "expired", "failed"] as const;++export default async function SignPage({+ params,+ searchParams,+}: SignPageProps) {const { token } = await params;+ const { signatureProblem: problemParam } = await searchParams;+ const signatureProblem =+ SIGNATURE_PROBLEMS.find((problem) => problem === problemParam) ?? null;let initialState:"already-signed" | "declined" | "error" | "expired" | "voided" | undefined;let record: Awaited<ReturnType<typeof getSigningPayloadForToken>> | null =@@ -55,6 +64,7 @@ export default async function SignPage({ params }: SignPageProps) {initialState={initialState}key={token}record={record ?? undefined}+ signatureProblem={signatureProblem}token={token}verification={verification ?? undefined}/>diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex 53fc47c..fd0be9a 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -411,6 +411,11 @@ export function EnvelopeDetailShell({<p className="text-sm text-(--secondary)">Created {activeRecord.createdAtLabel}</p>+ {record.signatureTypeLabel ? (+ <span className="pill pill-neutral">+ {record.signatureTypeLabel}+ </span>+ ) : null}</div></div></div>diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsxindex 8982011..90bc0cf 100644--- a/src/components/envelopes/review-shell.tsx+++ b/src/components/envelopes/review-shell.tsx@@ -67,6 +67,19 @@ type ReviewSigner = {type SendPhase = "error" | "idle" | "sending";+type SignatureLevel = "advanced" | "qualified" | "simple";++function describeSignatureLevel(level: SignatureLevel, providerName: string) {+ switch (level) {+ case "advanced":+ return `Advanced electronic signatures through ${providerName}`;+ case "qualified":+ return `Qualified electronic signatures through ${providerName}`;+ default:+ return "SignuDoc signatures";+ }+}+function buildSuccessMessage(firstSignerName: string) {return `Envelope sent. ${firstSignerName} has been notified.`;}@@ -82,6 +95,8 @@ export function ReviewShell({const [reminderDays, setReminderDays] = useState<number | null>(DEFAULT_ENVELOPE_REMINDER_DAYS,);+ const [signatureLevel, setSignatureLevel] =+ useState<SignatureLevel>("simple");const [isConfirmationOpen, setIsConfirmationOpen] = useState(false);const [notice, setNotice] = useState<string | null>(null);const [sendPhase, setSendPhase] = useState<SendPhase>("idle");@@ -131,6 +146,7 @@ export function ReviewShell({expiresInDays: deadlineDays,permittedUseConfirmed: true,reminderIntervalDays: reminderDays,+ ...(record?.signingProvider ? { signatureLevel } : {}),}),headers: {"content-type": "application/json",@@ -412,6 +428,40 @@ export function ReviewShell({later from the envelope.</p></div>++ {record.signingProvider ? (+ <div className="well mt-4 p-4">+ <label className="grid gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Signature type+ </span>+ <select+ className="field-input"+ disabled={sendPhase === "sending" || Boolean(notice)}+ onChange={(event) =>+ setSignatureLevel(event.target.value as SignatureLevel)+ }+ value={signatureLevel}+ >+ {(["simple", "advanced", "qualified"] as const).map(+ (level) => (+ <option key={level} value={level}>+ {describeSignatureLevel(+ level,+ record.signingProvider!.name,+ )}+ </option>+ ),+ )}+ </select>+ </label>+ <p className="mt-3 text-sm leading-6 text-(--secondary)">+ {signatureLevel === "simple"+ ? "Signers sign here, and the finished PDF is sealed by this install."+ : `Each signer proves who they are at ${record.signingProvider.name} and signs with a certificate in their own name. ${signatureLevel === "qualified" ? "A qualified signature needs a qualified certificate, which not every signer has. " : ""}Which type a document needs is a legal question; this is not legal advice.`}+ </p>+ </div>+ ) : null}</article></div>@@ -442,6 +492,14 @@ export function ReviewShell({isSending={sendPhase === "sending"}onCancel={closeConfirmation}onConfirm={handleConfirmSend}+ signatureType={+ record.signingProvider && signatureLevel !== "simple"+ ? describeSignatureLevel(+ signatureLevel,+ record.signingProvider.name,+ )+ : null+ }signerCount={activeRecord.signers.length}title={activeRecord.title}/>@@ -457,6 +515,8 @@ type SendConfirmationDialogProps = {isSending: boolean;onCancel: () => void;onConfirm: () => void;+ /** Set when signers sign through the install's signing provider. */+ signatureType: string | null;signerCount: number;title: string;};@@ -468,6 +528,7 @@ function SendConfirmationDialog({isSending,onCancel,onConfirm,+ signatureType,signerCount,title,}: SendConfirmationDialogProps) {@@ -496,6 +557,12 @@ function SendConfirmationDialog({: `The first signer (${firstSignerName}) will be notified immediately.`}{" "}The request expires in {deadlineDays} days.</p>+ {signatureType ? (+ <p>+ Signature type: {signatureType}. It cannot be changed once+ the envelope is sent.+ </p>+ ) : null}</div></DialogDescription></DialogHeader>diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsxindex e36ca2b..5759ad4 100644--- a/src/components/signing/signing-live-shell.tsx+++ b/src/components/signing/signing-live-shell.tsx@@ -428,7 +428,30 @@ function buildSigningSubmissionPayload(};}-export function SigningLiveShell({ record }: { record: SigningPayload }) {+/** Why a signer came back from their signing provider without signing. */+export type ProviderSignatureProblem = "cancelled" | "expired" | "failed";++function describeProviderProblem(+ problem: ProviderSignatureProblem,+ providerName: string,+): string {+ switch (problem) {+ case "cancelled":+ return `You did not finish signing at ${providerName}. Nothing was signed, so you can try again.`;+ case "expired":+ return "Your earlier signing session ended before it finished. Nothing was signed, so you can try again.";+ default:+ return `${providerName} could not complete your signature. Nothing was signed. Try again, or ask the sender for help.`;+ }+}++export function SigningLiveShell({+ record,+ signatureProblem = null,+}: {+ record: SigningPayload;+ signatureProblem?: ProviderSignatureProblem | null;+}) {const [activePage, setActivePage] = useState(record.currentSignerFields[0]?.page ??record.visibleFields[0]?.page ??@@ -455,6 +478,9 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {const [reauthPassword, setReauthPassword] = useState("");const [isMeaningConfirmed, setIsMeaningConfirmed] = useState(false);const part11 = record.part11 ?? null;+ // Signed with a certificate in the signer's own name: Finish goes to the+ // signing provider, which signs, then sends the signer back.+ const providerSignature = record.providerSignature ?? null;const isReauthReady =part11 === null ||(isMeaningConfirmed &&@@ -592,27 +618,31 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {setSubmitError(null);try {- const response = await fetch(record.submitUrl, {- body: JSON.stringify({- ...buildSigningSubmissionPayload(record, enteredValues),- ...(part11- ? {- reauthentication: {- email: reauthEmail,- meaningConfirmed: true,- password: reauthPassword,- },- }- : {}),- }),- headers: {- "content-type": "application/json",+ const response = await fetch(+ providerSignature?.startUrl ?? record.submitUrl,+ {+ body: JSON.stringify({+ ...buildSigningSubmissionPayload(record, enteredValues),+ ...(part11+ ? {+ reauthentication: {+ email: reauthEmail,+ meaningConfirmed: true,+ password: reauthPassword,+ },+ }+ : {}),+ }),+ headers: {+ "content-type": "application/json",+ },+ method: "POST",},- method: "POST",- });+ );const payload = (await response.json().catch(() => null)) as {error?: string;redirectPath?: string;+ redirectUrl?: string;state?: string;} | null;@@ -628,6 +658,17 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {return;}+ if (providerSignature) {+ if (!payload?.redirectUrl) {+ setSubmitError(defaultSubmitErrorMessage);+ setIsSubmitting(false);+ return;+ }++ window.location.assign(payload.redirectUrl);+ return;+ }+const fallbackRedirectPath = `${window.location.pathname.replace(/\/$/, "")}/done?title=${encodeURIComponent(record.envelopeTitle)}`;window.location.assign(payload?.redirectPath ?? fallbackRedirectPath);@@ -780,6 +821,14 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {</header><main className="mx-auto flex w-full max-w-[1320px] flex-1 flex-col gap-5 px-4 pb-8 pt-1 sm:px-6">+ {signatureProblem && providerSignature ? (+ <div className="notice notice-danger" role="alert">+ {describeProviderProblem(+ signatureProblem,+ providerSignature.providerName,+ )}+ </div>+ ) : null}<section className="grid gap-5 xl:grid-cols-[minmax(0,1fr)_340px]"><div className="flex min-w-0 flex-col gap-4"><div className="panel rounded-[1.25rem] px-4 py-3">@@ -1111,10 +1160,28 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {setSubmitError(null);}}>- <p className="text-sm leading-6 text-(--secondary)">- By clicking Finish, you confirm that your electronic signature is- intended to be binding for this document.- </p>+ {providerSignature ? (+ <div className="grid gap-3 text-sm leading-6 text-(--secondary)">+ <p>+ This document asks for{" "}+ {providerSignature.level === "qualified"+ ? "a qualified electronic signature"+ : "an advanced electronic signature"}+ , made with a certificate in your own name.+ </p>+ <p>+ Next, {providerSignature.providerName} asks you to confirm who+ you are and to approve the signature. When it is done, you come+ back here. By continuing, you confirm that your signature is+ intended to be binding for this document.+ </p>+ </div>+ ) : (+ <p className="text-sm leading-6 text-(--secondary)">+ By clicking Finish, you confirm that your electronic signature is+ intended to be binding for this document.+ </p>+ )}{part11 ? (<div className="grid gap-4"><div className="well rounded-xl px-3.5 py-3">@@ -1186,7 +1253,13 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {loading={isSubmitting}onClick={handleFinishSigning}>- {isSubmitting ? "Finishing..." : "Finish signing"}+ {providerSignature+ ? isSubmitting+ ? "Preparing..."+ : `Continue to ${providerSignature.providerName}`+ : isSubmitting+ ? "Finishing..."+ : "Finish signing"}</ShellButton></div></DialogFrame>diff --git a/src/components/signing/signing-shell.tsx b/src/components/signing/signing-shell.tsxindex e736c7b..db0d842 100644--- a/src/components/signing/signing-shell.tsx+++ b/src/components/signing/signing-shell.tsx@@ -9,7 +9,10 @@ import type {SigningVerificationState,} from "@/lib/schemas/signing";import { SignerVerificationScreen } from "./signer-verification-screen";-import { SigningLiveShell } from "./signing-live-shell";+import {+ SigningLiveShell,+ type ProviderSignatureProblem,+} from "./signing-live-shell";type SigningUnavailableState ="already-signed" | "declined" | "error" | "expired" | "voided";@@ -17,6 +20,8 @@ type SigningUnavailableState =type SigningShellProps = {initialState?: SigningUnavailableState;record?: SigningPayload;+ /** Set when the signer came back from a signing provider without signing. */+ signatureProblem?: ProviderSignatureProblem | null;token: string;verification?: SigningVerificationState;};@@ -53,11 +58,14 @@ const tokenStateCopy: Record<export function SigningShell({initialState,record,+ signatureProblem,token,verification,}: SigningShellProps) {if (record) {- return <SigningLiveShell record={record} />;+ return (+ <SigningLiveShell record={record} signatureProblem={signatureProblem} />+ );}if (verification) {diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 3e4a81e..6295201 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -83,6 +83,11 @@ import {buildEnvelopeOriginalPdfKey,buildEnvelopeThumbnailKey,} from "./services/storage-keys.ts";+import {+ configuredSigningProvider,+ signingProviderById,+ type SigningProviderId,+} from "./services/signing-providers.ts";import {createStorageService,StorageObjectNotFoundError,@@ -123,6 +128,11 @@ type SendDraftEnvelopeInput = {expiresInDays?: number;/** Days between automatic reminders. Null or left out means none. */reminderIntervalDays?: number | null;+ /**+ * Advanced or qualified: each signer signs with a certificate in their+ * own name through the install's signing provider. Simple by default.+ */+ signatureLevel?: "advanced" | "qualified" | "simple";ipAddress?: string | null;senderEmail: string;senderName: string;@@ -157,6 +167,8 @@ type EnvelopeRow = {pageCount: number;part11: boolean;sentAt: number | null;+ signatureLevel: "advanced" | "qualified" | "simple";+ signatureProvider: string | null;signedPdfKey: string | null;sourcePdfFilename: string;sourcePdfHash: string;@@ -287,6 +299,11 @@ export type ReviewSignerSummary = {export type ReviewEnvelopeData = {canSend: boolean;+ /**+ * The install's signing provider, when the sender may choose signatures+ * in the signers' own names. Null without one, or in Part 11 mode.+ */+ signingProvider: { name: string } | null;copyRecipients: readonly CopyRecipientRecord[];disabledReason: string | null;envelopeId: string;@@ -372,6 +389,11 @@ export type EnvelopeDetailData = {manualReminder: EnvelopeDetailManualReminderState | null;/** Sent in Part 11 mode: a void needs a reason. */part11: boolean;+ /**+ * How signers sign, when not with SignuDoc's own simple signature: for+ * example "Qualified electronic signatures through eID Easy".+ */+ signatureTypeLabel: string | null;signers: readonly EnvelopeDetailSignerView[];status: EnvelopeRecord["status"];timeline: readonly EnvelopeDetailTimelineItem[];@@ -751,6 +773,8 @@ async function getEnvelopeByIdForUser(expires_at AS "expiresAt",reminder_interval_days AS "reminderIntervalDays",part11,+ signature_level AS "signatureLevel",+ signature_provider AS "signatureProvider",created_at AS "createdAt",updated_at AS "updatedAt"FROM envelopes@@ -1171,6 +1195,62 @@ function buildVoidNotificationEmail(input: {};}+const SIGNATURE_LEVEL_NAMES = {+ advanced: "advanced electronic signature",+ qualified: "qualified electronic signature",+} as const;++function providerName(id: string | null | undefined): string | null {+ if (!id) {+ return null;+ }++ return (+ signingProviderById(id as SigningProviderId)?.name ??+ (id === "eideasy" ? "eID Easy" : id)+ );+}++function describeSignatureType(envelope: EnvelopeRecord): string | null {+ const level = envelope.signatureLevel;++ if (!level || level === "simple") {+ return null;+ }++ const name = SIGNATURE_LEVEL_NAMES[level];+ const through = providerName(envelope.signatureProvider);++ return `${name[0]!.toUpperCase()}${name.slice(1)}s${through ? ` through ${through}` : ""}`;+}++/** "with a qualified electronic signature through eID Easy", or null. */+function describeProviderSignature(metadata: unknown): string | null {+ if (typeof metadata !== "object" || metadata === null) {+ return null;+ }++ const signature = (metadata as { providerSignature?: unknown })+ .providerSignature;++ if (typeof signature !== "object" || signature === null) {+ return null;+ }++ const { level, provider } = signature as {+ level?: unknown;+ provider?: unknown;+ };++ if (level !== "advanced" && level !== "qualified") {+ return null;+ }++ return `with ${level === "advanced" ? "an" : "a"} ${SIGNATURE_LEVEL_NAMES[level]}${+ typeof provider === "string" ? ` through ${provider}` : ""+ }`;+}+function buildTimelineDescription(event: AuditEventRecord): string {const signerName =typeof event.metadata?.signerName === "string"@@ -1200,7 +1280,9 @@ function buildTimelineDescription(event: AuditEventRecord): string {"meaning" in event.metadata.part11 &&typeof event.metadata.part11.meaning === "string"? `Signed by ${targetLabel} (${signatureMeaningLabel(parseSignatureMeaning(event.metadata.part11.meaning)) ?? event.metadata.part11.meaning}, password given again)`- : `Signed by ${targetLabel}`;+ : describeProviderSignature(event.metadata)+ ? `Signed by ${targetLabel} ${describeProviderSignature(event.metadata)!}`+ : `Signed by ${targetLabel}`;case "declined":return declineReason? `Declined by ${targetLabel} — ${declineReason}`@@ -1364,6 +1446,8 @@ export async function listEnvelopesForUser(expires_at AS "expiresAt",reminder_interval_days AS "reminderIntervalDays",part11,+ signature_level AS "signatureLevel",+ signature_provider AS "signatureProvider",created_at AS "createdAt",updated_at AS "updatedAt"FROM envelopes@@ -1511,6 +1595,7 @@ export async function getEnvelopeDetailDataForUser(: null,manualReminder,part11: Boolean(envelope.part11),+ signatureTypeLabel: describeSignatureType(envelope),signers: signerViews,status: envelope.status,timeline,@@ -1773,9 +1858,14 @@ export async function getReviewEnvelopeDataForUser();const isEmpty = signers.length === 0 || fields.length === 0;const choiceProblem = describeChoiceProblem(signers, fields);+ const provider = configuredSigningProvider();+ const part11Mode = provider+ ? ((await readStoredSettings(database))?.part11Mode ?? false)+ : false;return {canSend: !isEmpty && !missingSignatureSigner && !choiceProblem,+ signingProvider: provider && !part11Mode ? { name: provider.name } : null,copyRecipients,disabledReason: missingSignatureSigner? `Every signer must have at least one Signature field before sending. ${missingSignatureSigner.name} is missing one.`@@ -1906,6 +1996,30 @@ export async function sendDraftEnvelope(// In Part 11 mode each signer signs with their own verified account, and// the envelope keeps that rule even if the mode is turned off later.const part11 = (await readStoredSettings(database))?.part11Mode ?? false;++ // Signatures in the signers' own names need the install's signing+ // provider. Part 11 envelopes are signed with the signers' accounts, and+ // the two are not combined.+ const signatureLevel = input.signatureLevel ?? "simple";+ const signingProvider =+ signatureLevel === "simple" ? null : configuredSigningProvider();++ if (signatureLevel !== "simple") {+ if (!signingProvider) {+ throw new EnvelopeMutationError(+ "This install has no signing provider for advanced or qualified signatures.",+ 400,+ );+ }++ if (part11) {+ throw new EnvelopeMutationError(+ "Part 11 mode signs with the signers' accounts. Send with simple signatures.",+ 400,+ );+ }+ }+const part11SignerAccounts = new Map<string, string>();if (part11) {@@ -2034,6 +2148,17 @@ export async function sendDraftEnvelope([sentAt, envelopeId],);+ if (signingProvider) {+ await tx.query(+ `+ UPDATE envelopes+ SET signature_level = $1, signature_provider = $2+ WHERE id = $3+ `,+ [signatureLevel, signingProvider.id, envelopeId],+ );+ }+if (part11) {await tx.query(`UPDATE envelopes SET part11 = true WHERE id = $1`, [envelopeId,@@ -2106,6 +2231,12 @@ export async function sendDraftEnvelope(permittedUseConfirmed: true,permittedUseVersion: PERMITTED_USE_VERSION,...(part11 ? { part11: true } : {}),+ ...(signingProvider+ ? {+ signatureLevel,+ signingProvider: signingProvider.name,+ }+ : {}),signerEmail: firstSigner.email,signerId: firstSigner.id,signerName: firstSigner.name,@@ -2146,6 +2277,8 @@ export async function sendDraftEnvelope(expires_at = NULL,reminder_interval_days = NULL,part11 = false,+ signature_level = 'simple',+ signature_provider = NULL,updated_at = $1WHERE id = $2AND user_id = $3diff --git a/src/lib/permitted-uses.ts b/src/lib/permitted-uses.tsindex 9901e03..06f5cf2 100644--- a/src/lib/permitted-uses.ts+++ b/src/lib/permitted-uses.ts@@ -27,7 +27,7 @@ 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.",+ "Anything your law requires to carry a qualified electronic signature (QES), unless this install has a signing provider and the envelope is sent with qualified signatures, each signer holding a qualified certificate.",];export const WHAT_IT_IS: UseSection = {@@ -42,7 +42,7 @@ export const WHAT_IT_IS: UseSection = {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 not a qualified seal: it is the install's own, or, with a seal certificate the organization buys, an advanced electronic seal for the organization, not for the signers.",+ "Not an advanced (AdES) or qualified (QES) electronic signature under eIDAS as it comes. An install can add a signing provider, and then a sender can ask each signer to sign with an advanced or qualified signature in their own name through it; without one, the seal on finished PDFs is the install's own or, with a seal certificate the organization buys, an advanced electronic seal for the organization, not for the signers.","Not a validated FDA 21 CFR Part 11 system as it comes. An administrator can turn on Part 11 mode (signers sign with their own confirmed accounts and password, and each signature shows its meaning), but your organization still has to validate the install, write and follow its own procedures, and certify its electronic signatures to the FDA.","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.",diff --git a/src/lib/provider-signing.dbtest.ts b/src/lib/provider-signing.dbtest.tsnew file mode 100644index 0000000..968f684--- /dev/null+++ b/src/lib/provider-signing.dbtest.ts@@ -0,0 +1,628 @@+import assert from "node:assert/strict";+import { createHash, randomUUID } from "node:crypto";+import { execFile } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, before, test } from "node:test";+import { promisify } from "node:util";++import { PDFDocument, StandardFonts } from "pdf-lib";+import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";+import {+ EnvelopeMutationError,+ getEnvelopeDetailDataForUser,+ getReviewEnvelopeDataForUser,+ replaceDraftEnvelopeFields,+ replaceDraftEnvelopeSigners,+ sendDraftEnvelope,+} from "./envelopes.ts";+import {+ ProviderSigningError,+ resumeProviderSigning,+ startProviderSigning,+} from "./provider-signing.ts";+import { verifyAuditChain } from "./services/audit.ts";+import { findSignatures } from "./services/pdf-incremental.ts";+import { resetValidationCache } from "./services/pdf-ltv.ts";+import { startTestPki, type TestPki } from "./services/pki-test-support.ts";+import { checkSignerSignature } from "./services/signer-cms.ts";+import {+ followSigner,+ STAND_IN_CLIENT,+ startProviderStandIns,+ type ProviderStandIns,+} from "./services/signing-provider-test-support.ts";+import { issueSigningLink } from "./services/signing-links.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import {+ recordSignerConsent,+ SigningMutationError,+ submitSigningForToken,+} from "./signing.ts";++// Signatures in the signers' own names, through a signing provider, against+// a real Postgres: the sender's choice, each signer's trip to the provider+// and back, and the signed PDF with one signature per signer. The provider+// is the eID Easy stand-in, signing with certificates from the test CA.+// Run with `npm run test:db`.++const run = promisify(execFile);++let database: pg.Pool;+let storageDir: string;+let storageService: StorageService;+let pki: TestPki;+let standIns: ProviderStandIns;+const createdUsers: string[] = [];+const envBefore = new Map<string, string | undefined>();++function setEnv(values: Record<string, string | undefined>) {+ for (const [name, value] of Object.entries(values)) {+ if (!envBefore.has(name)) {+ envBefore.set(name, process.env[name]);+ }++ if (value === undefined) {+ delete process.env[name];+ } else {+ process.env[name] = value;+ }+ }+}++before(async () => {+ database = await openTestDatabase();+ // The invitation email reads the install's name through the shared pool.+ globalThis.__signudocPgPool = database;+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-provider-"));+ resetValidationCache();+ pki = await startTestPki();++ const signer = pki.issueSigner({+ commonName: "Qualified Signer",+ qualified: true,+ });++ standIns = await startProviderStandIns({+ chain: [signer.certificate, pki.caCertificate],+ privateKeyPem: signer.privateKeyPem,+ });+ setEnv({+ APP_URL: "https://sign.example.test",+ EIDEASY_API_URL: standIns.eidEasyUrl,+ EIDEASY_CLIENT_ID: STAND_IN_CLIENT.id,+ EIDEASY_SECRET: STAND_IN_CLIENT.secret,+ EMAIL_CAPTURE_DIR: path.join(storageDir, "outbox"),+ EMAIL_DRIVER: "capture",+ SEAL_TIMESTAMP_URL: undefined,+ SIGNING_PROVIDER: undefined,+ STORAGE_DRIVER: "local",+ STORAGE_LOCAL_DIR: storageDir,+ });+ storageService = createStorageService();+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();++ for (const [name, value] of envBefore) {+ if (value === undefined) {+ delete process.env[name];+ } else {+ process.env[name] = value;+ }+ }++ await standIns.close();+ await pki.close();+ resetValidationCache();+ await rm(storageDir, { force: true, recursive: true });+});++/** A draft with two signers, each with a signature field. */+async function createDraft() {+ const userId = randomUUID();+ const envelopeId = randomUUID();+ const sourcePdf = await PDFDocument.create();+ const font = await sourcePdf.embedFont(StandardFonts.Helvetica);++ sourcePdf+ .addPage([612, 792])+ .drawText("Supply agreement", { font, x: 72, y: 720 });++ const sourceBytes = await sourcePdf.save();+ const sourceKey = `test/${envelopeId}/source.pdf`;++ createdUsers.push(userId);+ await storageService.putObject({+ body: sourceBytes,+ contentType: "application/pdf",+ key: sourceKey,+ });+ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,+ [userId, `${userId}@example.test`],+ );+ 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+ ) values ($1, $2, 'Supply agreement', 'draft', $3, 'supply.pdf', $4, 1, $5)+ `,+ [+ envelopeId,+ userId,+ sourceKey,+ sourceBytes.length,+ createHash("sha256").update(sourceBytes).digest("hex"),+ ],+ );+ await database.query(+ `+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)+ values ($1, $2, 1, 612, 792)+ `,+ [randomUUID(), envelopeId],+ );++ const saved = await replaceDraftEnvelopeSigners(+ userId,+ envelopeId,+ {+ signers: [+ { email: "[email protected]", name: "Riley Recipient" },+ { email: "[email protected]", name: "Casey Second" },+ ],+ },+ database,+ );+ const [riley, casey] = saved.signers.map((signer) => signer.id);+ const fields = await replaceDraftEnvelopeFields(+ userId,+ envelopeId,+ {+ fields: [+ {+ height: 0.06,+ page: 1,+ required: true,+ signerId: riley,+ type: "signature",+ width: 0.3,+ x: 0.1,+ y: 0.6,+ },+ {+ height: 0.04,+ page: 1,+ required: true,+ signerId: riley,+ type: "text",+ width: 0.3,+ x: 0.1,+ y: 0.7,+ },+ {+ height: 0.06,+ page: 1,+ required: true,+ signerId: casey,+ type: "signature",+ width: 0.3,+ x: 0.5,+ y: 0.6,+ },+ ],+ },+ database,+ );+ const fieldsFor = (signerId: string) =>+ fields.fields+ .filter((field) => field.signerId === signerId)+ .map((field) => ({ id: field.id!, type: field.type }));++ return {+ casey: { fields: fieldsFor(casey!), id: casey!, name: "Casey Second" },+ envelopeId,+ riley: { fields: fieldsFor(riley!), id: riley!, name: "Riley Recipient" },+ userId,+ };+}++function send(+ draft: { envelopeId: string; userId: string },+ signatureLevel: "advanced" | "qualified" | "simple",+) {+ return sendDraftEnvelope(+ draft.userId,+ draft.envelopeId,+ {+ senderEmail: "[email protected]",+ senderName: "Sam Sender",+ signatureLevel,+ },+ { database },+ );+}++/**+ * A signing link for whoever's turn it is, and their consent. (The real+ * link went out by email.)+ */+async function linkFor(signerId: string) {+ const link = await issueSigningLink({ expiresInSeconds: 3600 });++ await database.query(+ `+ update signers+ set signing_token_hash = $1, signing_token_expires_at = $2+ where id = $3+ `,+ [link.tokenHash, link.exp, signerId],+ );+ await recordSignerConsent(+ link.token,+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },+ { database },+ );++ return link.token;+}++function submissionFor(signer: {+ fields: { id: string; type: string }[];+ name: string;+}) {+ return {+ clientTimezoneOffsetMinutes: 0,+ fields: signer.fields.map((field) =>+ field.type === "signature"+ ? {+ fieldId: field.id,+ inputMethod: "typed",+ type: "signature",+ value: signer.name,+ }+ : { fieldId: field.id, type: field.type, value: "Senior buyer" },+ ),+ };+}++/** The signer goes to the provider, signs, and comes back. */+async function signAtProvider(+ token: string,+ signer: { fields: { id: string; type: string }[]; name: string },+) {+ const started = await startProviderSigning(token, submissionFor(signer), {+ database,+ storageService,+ });+ const query = await followSigner(started.redirectUrl);++ return {+ query,+ finish: () =>+ resumeProviderSigning(query.get("state") ?? "", query, {+ database,+ storageService,+ verifiedMethodsFor: () => [],+ }),+ };+}++async function sessionStates(envelopeId: string) {+ const result = await database.query<{ state: string }>(+ `select state from provider_signing_sessions where envelope_id = $1`,+ [envelopeId],+ );++ // Sessions started in the same second have no order between them.+ return result.rows.map((row) => row.state).sort();+}++async function stored(key: string) {+ return (await storageService.headObject(key)).exists;+}++test("the sender can choose a provider's signature only when the install has one", async () => {+ const draft = await createDraft();++ assert.deepEqual(+ (+ await getReviewEnvelopeDataForUser(+ draft.userId,+ draft.envelopeId,+ database,+ )+ )?.signingProvider,+ { name: "eID Easy" },+ );++ setEnv({ EIDEASY_CLIENT_ID: undefined });++ try {+ assert.equal(+ (+ await getReviewEnvelopeDataForUser(+ draft.userId,+ draft.envelopeId,+ database,+ )+ )?.signingProvider,+ null,+ );+ await assert.rejects(+ send(draft, "qualified"),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ error.statusCode === 400 &&+ /no signing provider/.test(error.message),+ );+ } finally {+ setEnv({ EIDEASY_CLIENT_ID: STAND_IN_CLIENT.id });+ }++ const status = await database.query<{ status: string }>(+ `select status from envelopes where id = $1`,+ [draft.envelopeId],+ );++ assert.equal(status.rows[0]?.status, "draft");+});++test("two signers sign with qualified signatures, each in a revision of their own", async (t) => {+ const draft = await createDraft();++ await send(draft, "qualified");++ const sent = await database.query<{+ signature_level: string;+ signature_provider: string;+ }>(+ `select signature_level, signature_provider from envelopes where id = $1`,+ [draft.envelopeId],+ );++ assert.deepEqual(sent.rows[0], {+ signature_level: "qualified",+ signature_provider: "eideasy",+ });++ // Signing here directly is refused: this envelope is signed at the+ // provider.+ const rileyToken = await linkFor(draft.riley.id);++ await assert.rejects(+ submitSigningForToken(rileyToken, submissionFor(draft.riley), {+ database,+ storageService,+ }),+ SigningMutationError,+ );++ // Riley signs.+ const riley = await signAtProvider(rileyToken, draft.riley);+ const rileyDone = await riley.finish();++ assert.ok("redirectPath" in rileyDone);++ const afterRiley = await database.query<{+ revision_key: string;+ revision_sha256: string;+ status: string;+ }>(+ `select revision_key, revision_sha256, status from envelopes where id = $1`,+ [draft.envelopeId],+ );+ const firstRevisionKey = afterRiley.rows[0]!.revision_key;+ const firstRevision = (await storageService.getObject(firstRevisionKey)).body;++ assert.equal(afterRiley.rows[0]!.status, "sent");+ assert.equal(+ createHash("sha256").update(firstRevision).digest("hex"),+ afterRiley.rows[0]!.revision_sha256,+ );+ assert.equal(findSignatures(firstRevision).length, 1);++ // A second return for the same session does not sign again.+ await assert.rejects(+ resumeProviderSigning(riley.query.get("state") ?? "", riley.query, {+ database,+ storageService,+ verifiedMethodsFor: () => [],+ }),+ (error: unknown) =>+ error instanceof ProviderSigningError && error.problem === "expired",+ );++ // Casey signs on top of Riley's revision, and that finishes the envelope.+ const casey = await signAtProvider(+ await linkFor(draft.casey.id),+ draft.casey,+ );++ await casey.finish();++ const finished = await database.query<{+ revision_key: string;+ signed_pdf_key: string;+ status: string;+ }>(+ `select revision_key, signed_pdf_key, status from envelopes where id = $1`,+ [draft.envelopeId],+ );++ assert.equal(finished.rows[0]!.status, "completed");+ assert.deepEqual(await sessionStates(draft.envelopeId), [+ "completed",+ "completed",+ ]);+ // Riley's revision is inside Casey's, so it is not kept on its own.+ assert.equal(await stored(firstRevisionKey), false);++ const signedPdf = (+ await storageService.getObject(finished.rows[0]!.signed_pdf_key)+ ).body;++ // Riley's revision is the start of the signed PDF, byte for byte.+ assert.deepEqual(+ Buffer.from(signedPdf.subarray(0, firstRevision.length)),+ Buffer.from(firstRevision),+ );++ const signatures = findSignatures(signedPdf).filter(+ (signature) => signature.subFilter === "ETSI.CAdES.detached",+ );++ assert.equal(signatures.length, 2);++ for (const signature of signatures) {+ const [, firstLength, restStart, restLength] = signature.byteRange;+ const digest = createHash("sha256")+ .update(signedPdf.subarray(0, firstLength))+ .update(signedPdf.subarray(restStart, restStart + restLength))+ .digest();+ const checked = checkSignerSignature(signature.contents, digest, {+ level: "qualified",+ });++ assert.equal(checked.qualified, true);+ }++ // The record says how each signer signed.+ const signedEvents = await database.query<{+ metadata: { providerSignature?: Record<string, unknown> };+ }>(+ `select metadata from audit_events where envelope_id = $1 and event = 'signed' order by sequence`,+ [draft.envelopeId],+ );++ assert.equal(signedEvents.rows.length, 2);++ for (const row of signedEvents.rows) {+ assert.equal(row.metadata.providerSignature?.level, "qualified");+ assert.equal(row.metadata.providerSignature?.provider, "eID Easy");+ assert.equal(row.metadata.providerSignature?.method, "smart-id-signature");+ assert.match(+ String(row.metadata.providerSignature?.certificateSubject),+ /Qualified Signer/,+ );+ }++ assert.equal((await verifyAuditChain(draft.envelopeId, database)).ok, true);++ const detail = await getEnvelopeDetailDataForUser(+ draft.userId,+ draft.envelopeId,+ database,+ );++ assert.equal(+ detail?.signatureTypeLabel,+ "Qualified electronic signatures through eID Easy",+ );+ assert.ok(+ detail?.timeline.some(+ (item) =>+ item.description ===+ "Signed by Riley Recipient with a qualified electronic signature through eID Easy",+ ),+ JSON.stringify(detail?.timeline.map((item) => item.description)),+ );++ // Poppler finds both signatures valid, where it is installed.+ try {+ await run("pdfsig", ["-v"]);+ } catch {+ t.diagnostic("pdfsig is not installed; skipped the poppler check");+ return;+ }++ const file = path.join(storageDir, "signed.pdf");++ await writeFile(file, signedPdf);++ const { stdout } = await run("pdfsig", ["-nocert", file]).catch(+ (error: { stdout?: string }) => ({ stdout: error.stdout ?? "" }),+ );++ assert.equal(+ stdout.match(/Signature Validation: Signature is Valid\./g)?.length,+ 2,+ stdout,+ );+});++test("a signer who does not finish at the provider can try again", async () => {+ const draft = await createDraft();++ await send(draft, "advanced");++ const token = await linkFor(draft.riley.id);++ standIns.state.signerCancels = true;++ try {+ const cancelled = await signAtProvider(token, draft.riley);++ await assert.rejects(+ cancelled.finish(),+ (error: unknown) =>+ error instanceof ProviderSigningError &&+ error.token === token &&+ error.problem !== "expired",+ );+ } finally {+ standIns.state.signerCancels = false;+ }++ const failed = await database.query<{ revision_key: string }>(+ `select revision_key from provider_signing_sessions where envelope_id = $1`,+ [draft.envelopeId],+ );++ assert.deepEqual(await sessionStates(draft.envelopeId), ["failed"]);+ assert.equal(await stored(failed.rows[0]!.revision_key), false);++ const signer = await database.query<{ status: string }>(+ `select status from signers where id = $1`,+ [draft.riley.id],+ );++ assert.equal(signer.rows[0]?.status, "notified");++ // A second try works, and a trip started before it can no longer finish.+ const abandoned = await signAtProvider(token, draft.riley);+ const retry = await signAtProvider(token, draft.riley);++ await assert.rejects(+ abandoned.finish(),+ (error: unknown) =>+ error instanceof ProviderSigningError && error.problem === "expired",+ );+ await retry.finish();++ assert.deepEqual(await sessionStates(draft.envelopeId), [+ "completed",+ "failed",+ "failed",+ ]);++ const envelope = await database.query<{ revision_key: string | null }>(+ `select revision_key from envelopes where id = $1`,+ [draft.envelopeId],+ );++ assert.ok(envelope.rows[0]?.revision_key);+});diff --git a/src/lib/provider-signing.ts b/src/lib/provider-signing.tsnew file mode 100644index 0000000..031d27d--- /dev/null+++ b/src/lib/provider-signing.ts@@ -0,0 +1,565 @@+import { createHash, randomBytes } from "node:crypto";++import { getDb, queryOne, type DbPool } from "./db/connection.ts";+import { findSignatures, fillSignature } from "./services/pdf-incremental.ts";+import {+ prepareRevisionZero,+ prepareSignerRevision,+} from "./services/pdf-revision.ts";+import { requestDocumentTimestamp, sha256Hex } from "./services/pdf-seal.ts";+import {+ decryptPrivateKey,+ encryptPrivateKey,+ secretKeyFor,+} from "./services/seal-identity.ts";+import {+ addSignatureTimestamp,+ checkSignerSignature,+ SignerSignatureError,+ type SignatureLevel,+} from "./services/signer-cms.ts";+import {+ signingProviderById,+ SigningProviderError,+ type ProviderData,+} from "./services/signing-providers.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import { buildSignerRevisionKey } from "./services/storage-keys.ts";+import type { SignerCheckMethod } from "./signer-checks.ts";+import {+ prepareSignerSubmission,+ submitSigningForToken,+ SigningMutationError,+ type SigningRequestMeta,+} from "./signing.ts";+import { readEnv, resolveAppUrl, type EnvSource } from "./utils/env.ts";++// Signing with a certificate in the signer's own name (eIDAS AdES or QES).+//+// 1. start: the signer fills in their fields as usual and presses Continue.+// Their submission is checked as a submit would be, their revision of the+// PDF is prepared on top of the last one (see pdf-revision.ts), and the+// provider is given its hash. The signer goes to the provider.+// 2. resume: the provider sends the signer back here. Its signature is+// checked against the revision's hash (signer-cms.ts), put into the+// revision, and the submission is saved with that revision, exactly as a+// submit saves it. The last signer's revision becomes the signed PDF.+//+// The session keeps what the signer submitted, their signing link and the+// provider's working state, encrypted, for at most SESSION_SECONDS.++const SESSION_SECONDS = 30 * 60;+const SECRET_CONTEXT = "signudoc/provider-session/v1";++export const PROVIDER_RETURN_PATH = "/api/signing/provider/return";++type SessionSecret = {+ providerData: ProviderData;+ submission: unknown;+ token: string;+};++type SessionRow = {+ baseSha256: string | null;+ contentDigest: string;+ envelopeId: string;+ expiresAt: number;+ id: string;+ level: SignatureLevel;+ provider: string;+ revisionKey: string;+ secretData: string;+ state: "completed" | "failed" | "pending" | "signing";+ submittedAt: number;+};++/** Why a signer is sent back to the signing page, as the page shows it. */+export type ProviderSigningProblem = "cancelled" | "expired" | "failed";++export class ProviderSigningError extends Error {+ readonly problem: ProviderSigningProblem;+ readonly token: string | null;++ constructor(+ message: string,+ problem: ProviderSigningProblem,+ token: string | null,+ options?: { cause?: unknown },+ ) {+ super(message, options);+ this.name = "ProviderSigningError";+ this.problem = problem;+ this.token = token;+ }+}++function sealSecret(secret: SessionSecret, env: EnvSource): string {+ return encryptPrivateKey(+ JSON.stringify(secret),+ secretKeyFor(SECRET_CONTEXT, env),+ );+}++function openSecret(value: string, env: EnvSource): SessionSecret | null {+ const json = decryptPrivateKey(value, secretKeyFor(SECRET_CONTEXT, env));++ return json ? (JSON.parse(json) as SessionSecret) : null;+}++function returnUrlFor(env: EnvSource): string {+ const appUrl = resolveAppUrl(env);++ if (!appUrl) {+ throw new SigningMutationError(+ "Signing with a provider needs the install's public address (APP_URL).",+ 503,+ );+ }++ return new URL(PROVIDER_RETURN_PATH, appUrl).toString();+}++function signatureFieldName(name: string, index: number): string {+ // Dots separate the parts of a field's name in a PDF form.+ return `Signature ${String(index + 1)} - ${name.replace(/\./g, " ").slice(0, 80)}`;+}++/**+ * Prepares the signer's revision and sends them to the provider. Returns+ * where to send the signer's browser.+ */+export async function startProviderSigning(+ token: string,+ input: unknown,+ {+ database = getDb(),+ env = process.env,+ language = null,+ storageService = createStorageService(),+ verifiedMethods = [],+ }: {+ database?: DbPool;+ env?: EnvSource;+ language?: string | null;+ storageService?: StorageService;+ verifiedMethods?: readonly SignerCheckMethod[];+ } = {},+): Promise<{ redirectUrl: string }> {+ const prepared = await prepareSignerSubmission(token, input, {+ database,+ verifiedMethods,+ });+ const { context, submittedAt } = prepared;+ const level = context.envelope.signatureLevel as SignatureLevel;+ const provider = signingProviderById(+ context.envelope.signatureProvider ?? "",+ env,+ );++ if (!provider) {+ throw new SigningMutationError(+ "The signing provider this document was sent with is not set up any more. Ask the sender to send it again.",+ 503,+ );+ }++ const returnUrl = returnUrlFor(env);+ let base: Uint8Array;++ if (context.envelope.revisionKey) {+ base = (await storageService.getObject(context.envelope.revisionKey)).body;++ if (sha256Hex(base) !== context.envelope.revisionSha256) {+ throw new SigningMutationError(+ "The signed document stored for this envelope has changed. Ask the sender for help.",+ 500,+ );+ }+ } else {+ const source = (+ await storageService.getObject(context.envelope.sourcePdfKey)+ ).body;++ if (sha256Hex(source) !== context.envelope.sourcePdfHash) {+ throw new SigningMutationError(+ "The stored document no longer matches the one that was sent for signing.",+ 500,+ );+ }++ base = await prepareRevisionZero(source);+ }++ const signer = context.signer;+ const revision = await prepareSignerRevision(base, {+ fields: prepared.signerFields,+ images: prepared.images,+ signature: {+ fieldName: signatureFieldName(signer.name, prepared.signerIndex),+ name: signer.name,+ reason:+ level === "qualified"+ ? "Qualified electronic signature"+ : "Advanced electronic signature",+ signingTime: new Date(submittedAt * 1000),+ },+ });+ const sessionId = randomBytes(24).toString("base64url");+ const revisionKey = buildSignerRevisionKey({+ envelopeId: context.envelope.id,+ sessionId,+ sourcePdfKey: context.envelope.sourcePdfKey,+ userId: context.envelope.userId,+ });++ await storageService.putObject({+ body: revision.bytes,+ contentType: "application/pdf",+ key: revisionKey,+ });++ let step;++ try {+ step = await provider.start({+ contentDigest: revision.digest,+ documentName: context.envelope.title,+ language,+ level,+ returnUrl,+ signer: { email: signer.email, name: signer.name },+ state: sessionId,+ });+ } catch (error) {+ await storageService.deleteObject(revisionKey).catch(() => undefined);+ console.error(`[signing] ${provider.name} refused to start:`, error);+ throw new SigningMutationError(+ `${provider.name} could not start the signature. Try again in a moment.`,+ 502,+ );+ }++ const now = Math.floor(Date.now() / 1000);+ const earlier = await database.query<{ revisionKey: string }>(+ `+ UPDATE provider_signing_sessions+ SET state = 'failed'+ WHERE signer_id = $1 AND state = 'pending'+ RETURNING revision_key AS "revisionKey"+ `,+ [signer.id],+ );++ await database.query(+ `+ INSERT INTO provider_signing_sessions (+ id, envelope_id, signer_id, provider, level, state, base_sha256,+ revision_key, content_digest, secret_data, submitted_at, created_at,+ expires_at+ )+ VALUES ($1, $2, $3, $4, $5, 'pending', $6, $7, $8, $9, $10, $11, $12)+ `,+ [+ sessionId,+ context.envelope.id,+ signer.id,+ provider.id,+ level,+ context.envelope.revisionSha256 ?? null,+ revisionKey,+ revision.digest.toString("hex"),+ sealSecret({ providerData: step.data, submission: input, token }, env),+ submittedAt,+ now,+ now + SESSION_SECONDS,+ ],+ );++ // Only one trip to the provider at a time: an earlier one, in another tab,+ // can no longer finish.+ for (const row of earlier.rows) {+ await storageService.deleteObject(row.revisionKey).catch(() => undefined);+ }++ return { redirectUrl: step.redirectUrl };+}++async function failSession(+ session: SessionRow,+ database: DbPool,+ storageService: StorageService,+) {+ const failed = await database.query(+ `+ UPDATE provider_signing_sessions+ SET state = 'failed'+ WHERE id = $1 AND state IN ('pending', 'signing')+ `,+ [session.id],+ );++ if (failed.rowCount === 1) {+ await storageService+ .deleteObject(session.revisionKey)+ .catch(() => undefined);+ }+}++function signedContentDigest(bytes: Uint8Array): Buffer {+ const signature = findSignatures(bytes).at(-1)!;+ const [, firstLength, restStart, restLength] = signature.byteRange;++ return createHash("sha256")+ .update(bytes.subarray(0, firstLength))+ .update(bytes.subarray(restStart, restStart + restLength))+ .digest();+}++/**+ * The signer is back from the provider. Either they are sent on to its next+ * step, or the signature is checked and the submission saved. Returns where+ * to send the signer's browser.+ */+export async function resumeProviderSigning(+ sessionId: string,+ query: URLSearchParams,+ {+ database = getDb(),+ env = process.env,+ requestMeta = {},+ storageService = createStorageService(),+ verifiedMethodsFor,+ }: {+ database?: DbPool;+ env?: EnvSource;+ requestMeta?: SigningRequestMeta;+ storageService?: StorageService;+ /** The signer checks this browser has passed for the signing link. */+ verifiedMethodsFor: (token: string) => readonly SignerCheckMethod[];+ },+): Promise<{ redirectPath: string } | { redirectUrl: string }> {+ const session = await queryOne<SessionRow>(+ database,+ `+ SELECT+ id,+ envelope_id AS "envelopeId",+ provider,+ level,+ state,+ base_sha256 AS "baseSha256",+ revision_key AS "revisionKey",+ content_digest AS "contentDigest",+ secret_data AS "secretData",+ submitted_at AS "submittedAt",+ expires_at AS "expiresAt"+ FROM provider_signing_sessions+ WHERE id = $1+ `,+ [sessionId],+ );+ const secret = session ? openSecret(session.secretData, env) : null;++ if (!session || !secret) {+ throw new ProviderSigningError(+ "This signing session is not known here.",+ "expired",+ null,+ );+ }++ if (+ session.state !== "pending" ||+ session.expiresAt < Math.floor(Date.now() / 1000)+ ) {+ await failSession(session, database, storageService);+ throw new ProviderSigningError(+ "This signing session has ended.",+ "expired",+ secret.token,+ );+ }++ const provider = signingProviderById(session.provider, env);++ if (!provider) {+ await failSession(session, database, storageService);+ throw new ProviderSigningError(+ "The signing provider is not set up any more.",+ "failed",+ secret.token,+ );+ }++ const contentDigest = Buffer.from(session.contentDigest, "hex");+ let step;++ try {+ step = await provider.resume({+ contentDigest,+ data: secret.providerData,+ query,+ returnUrl: returnUrlFor(env),+ state: session.id,+ });+ } catch (error) {+ await failSession(session, database, storageService);+ console.error(`[signing] ${provider.name} did not sign:`, error);+ throw new ProviderSigningError(+ error instanceof SigningProviderError ? error.message : "Signing failed.",+ query.get("error") || /cancel/i.test(String(error))+ ? "cancelled"+ : "failed",+ secret.token,+ { cause: error },+ );+ }++ if (step.kind === "redirect") {+ await database.query(+ `+ UPDATE provider_signing_sessions+ SET secret_data = $1+ WHERE id = $2 AND state = 'pending'+ `,+ [sealSecret({ ...secret, providerData: step.data }, env), session.id],+ );++ return { redirectUrl: step.redirectUrl };+ }++ // One return finishes the session. A second one (a reload, or the+ // provider calling back twice) stops here instead of writing the revision+ // again.+ const claimed = await database.query(+ `+ UPDATE provider_signing_sessions+ SET state = 'signing'+ WHERE id = $1 AND state = 'pending'+ `,+ [session.id],+ );++ if (claimed.rowCount !== 1) {+ throw new ProviderSigningError(+ "This signing session is already being completed.",+ "expired",+ secret.token,+ );+ }++ try {+ const checked = checkSignerSignature(step.cms, contentDigest, {+ level: session.level,+ });+ const timestampUrl = readEnv(env, "SEAL_TIMESTAMP_URL");+ let cms = step.cms;+ let timestamped = checked.timestamped;++ // A signature timestamp (PAdES B-T) proves when the signer signed. The+ // provider usually adds one; when it did not, the install's own+ // time-stamping service can.+ if (!timestamped && timestampUrl) {+ try {+ cms = await addSignatureTimestamp(cms, (imprint) =>+ requestDocumentTimestamp(imprint, timestampUrl),+ );+ timestamped = true;+ } catch (error) {+ console.warn("[signing] The signature timestamp failed:", error);+ }+ }++ const prepared = (await storageService.getObject(session.revisionKey)).body;++ if (!signedContentDigest(prepared).equals(contentDigest)) {+ throw new SignerSignatureError(+ "The prepared document changed while the signer was away.",+ );+ }++ const signed = fillSignature(prepared, cms);+ const signedSha256 = sha256Hex(signed);++ await storageService.putObject({+ body: signed,+ contentType: "application/pdf",+ key: session.revisionKey,+ });++ const result = await submitSigningForToken(+ secret.token,+ secret.submission,+ {+ database,+ providerSignature: {+ baseSha256: session.baseSha256,+ evidence: {+ certificateIssuer: checked.issuer,+ certificateSerialNumber: checked.serialNumber,+ certificateSubject: checked.subject,+ certificateValidTo: Math.floor(checked.validTo.getTime() / 1000),+ level: session.level,+ method: step.method ?? null,+ provider: provider.name,+ qualified: checked.qualified,+ timestamped,+ },+ revision: {+ bytes: signed,+ key: session.revisionKey,+ sha256: signedSha256,+ },+ sessionId: session.id,+ submittedAt: session.submittedAt,+ },+ requestMeta,+ storageService,+ verifiedMethods: verifiedMethodsFor(secret.token),+ },+ );++ // The revision this one was built on is inside it now.+ const previous = await queryOne<{ revisionKey: string }>(+ database,+ `+ SELECT revision_key AS "revisionKey"+ FROM provider_signing_sessions+ WHERE envelope_id = $1+ AND state = 'completed'+ AND id <> $2+ AND revision_key <> $3+ ORDER BY completed_at DESC+ LIMIT 1+ `,+ [session.envelopeId, session.id, session.revisionKey],+ );++ if (previous) {+ await storageService+ .deleteObject(previous.revisionKey)+ .catch(() => undefined);+ }++ return { redirectPath: result.redirectPath };+ } catch (error) {+ await failSession(session, database, storageService);++ if (error instanceof SignerSignatureError) {+ console.error("[signing] The provider's signature was refused:", error);+ throw new ProviderSigningError(error.message, "failed", secret.token, {+ cause: error,+ });+ }++ throw new ProviderSigningError(+ error instanceof Error ? error.message : "Signing failed.",+ "failed",+ secret.token,+ { cause: error },+ );+ }+}diff --git a/src/lib/retention.ts b/src/lib/retention.tsindex 847fe2f..7d7abc1 100644--- a/src/lib/retention.ts+++ b/src/lib/retention.ts@@ -175,6 +175,9 @@ async function listFieldImagesForEnvelopeIds(const placeholders = envelopeIds.map((_, index) => `$${String(index + 1)}`).join(", ");+ // Drawn signatures, and the PDF revisions of signers who signed through a+ // signing provider (see provider-signing.ts): files named in rows rather+ // than kept at a fixed key.const rows = await queryMany<FieldImageRow>(database,`@@ -184,6 +187,15 @@ async function listFieldImagesForEnvelopeIds(FROM fieldsWHERE envelope_id IN (${placeholders})AND image_key IS NOT NULL+ UNION+ SELECT id, revision_key+ FROM envelopes+ WHERE id IN (${placeholders})+ AND revision_key IS NOT NULL+ UNION+ SELECT envelope_id, revision_key+ FROM provider_signing_sessions+ WHERE envelope_id IN (${placeholders})`,envelopeIds,);diff --git a/src/lib/schemas/envelope.ts b/src/lib/schemas/envelope.tsindex 864cf03..ec766ef 100644--- a/src/lib/schemas/envelope.ts+++ b/src/lib/schemas/envelope.ts@@ -50,6 +50,8 @@ export const reminderIntervalDaysSchema = zexport const sendEnvelopeOptionsSchema = z.object({expiresInDays: deadlineDaysSchema.optional(),reminderIntervalDays: reminderIntervalDaysSchema.optional(),+ /** Simple unless the install has a signing provider. */+ signatureLevel: z.enum(["simple", "advanced", "qualified"]).optional(),});export const changeRemindersSchema = z.object({@@ -125,6 +127,11 @@ export const auditEventRecordSchema = z.object({createdAt: unixTimestampSchema,});+/** How the signers sign. See provider-signing.ts. */+export const signatureLevelSchema = z.enum(["simple", "advanced", "qualified"]);++export type EnvelopeSignatureLevel = z.infer<typeof signatureLevelSchema>;+export const envelopeRecordSchema = z.object({id: idSchema,userId: idSchema,@@ -150,6 +157,15 @@ export const envelopeRecordSchema = z.object({reminderIntervalDays: reminderIntervalDaysSchema.optional(),/** Sent in Part 11 mode. See part11.ts. */part11: z.boolean().optional(),+ /**+ * Simple, or signed by each signer with a certificate in their own name+ * through a signing provider. See provider-signing.ts.+ */+ signatureLevel: signatureLevelSchema.optional(),+ signatureProvider: z.string().trim().min(1).nullable().optional(),+ /** The PDF as the last signer signed it, for provider signatures. */+ revisionKey: z.string().trim().min(1).nullable().optional(),+ revisionSha256: sourcePdfHashSchema.nullable().optional(),createdAt: unixTimestampSchema,updatedAt: unixTimestampSchema,});diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.tsindex ea8a17b..b9450ce 100644--- a/src/lib/schemas/signing.ts+++ b/src/lib/schemas/signing.ts@@ -85,6 +85,18 @@ export const signingPayloadSchema = z.object({}).nullable().optional(),+ /**+ * Set when each signer signs with a certificate in their own name through+ * a signing provider: Finish takes the signer there instead of submitting.+ */+ providerSignature: z+ .object({+ level: z.enum(["advanced", "qualified"]),+ providerName: z.string().trim().min(1),+ startUrl: z.string().trim().min(1),+ })+ .nullable()+ .optional(),senderName: z.string().trim().min(1).max(320),signer: z.object({email: emailSchema,diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 8d7dd6b..8f3e2f2 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -14,7 +14,11 @@ import { canonicalJson } from "../utils/canonical-json.ts";import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";import { embedTextFaces, type TextFace } from "./pdf-fonts.ts";import { sha256Hex } from "./pdf-seal.ts";-import { saveInstallSealedPdf, type SealPurpose } from "./seal-identity.ts";+import {+ finishSignerSignedPdf,+ saveInstallSealedPdf,+ type SealPurpose,+} from "./seal-identity.ts";import {buildEnvelopeCertificateKey,buildEnvelopeSignedPdfKey,@@ -240,7 +244,7 @@ function getFieldPadding(widthPt: number, heightPt: number): number {return Math.max(2, Math.min(widthPt, heightPt) * 0.12);}-function shouldStampField(field: FieldRecord): boolean {+export function shouldStampField(field: FieldRecord): boolean {if (field.type === "checkbox" || field.type === "radio") {return typeof field.checked === "boolean";}@@ -363,7 +367,7 @@ function buildCertificateAuditEvents(input: {);}-async function stampFieldValue(+export async function stampFieldValue(field: FieldRecord,page: PDFPage,fonts: {@@ -791,6 +795,70 @@ function readStringArray(value: unknown): string[] {: [];}+/**+ * A signature the signer made with their own certificate through the+ * install's signing provider: its level, the provider, and the certificate.+ */+function describeProviderSignatureEvidence(+ signed: AuditEventRecord | undefined,+ redacted: boolean,+): string[] {+ const value = signed?.metadata?.providerSignature;++ if (!value || typeof value !== "object") {+ return [];+ }++ const signature = value as Record<string, unknown>;+ const level =+ signature.level === "qualified"+ ? "a qualified electronic signature"+ : signature.level === "advanced"+ ? "an advanced electronic signature"+ : null;++ if (!level) {+ return [];+ }++ const provider =+ typeof signature.provider === "string"+ ? ` through ${signature.provider}`+ : "";+ const method =+ typeof signature.method === "string" ? ` (${signature.method})` : "";+ const details = [+ `Signed with ${level}${provider}${method}; the signature is in the signed PDF`,+ ];++ if (!redacted && typeof signature.certificateSubject === "string") {+ const issuer =+ typeof signature.certificateIssuer === "string"+ ? `, issued by ${signature.certificateIssuer}`+ : "";+ const serial =+ typeof signature.certificateSerialNumber === "string"+ ? `, serial ${signature.certificateSerialNumber}`+ : "";+ const validTo =+ typeof signature.certificateValidTo === "number"+ ? `, valid to ${formatAuditTimestamp(signature.certificateValidTo)}`+ : "";++ details.push(+ `Signing certificate: ${signature.certificateSubject}${issuer}${serial}${validTo}`,+ );+ }++ if (signature.timestamped === true) {+ details.push(+ "The signature carries a timestamp from a time-stamping service",+ );+ }++ return details;+}+/** What the record shows about how one signer was identified and agreed. */function describeSignerEvidence(signer: SignerRecord,@@ -851,6 +919,8 @@ function describeSignerEvidence(details.push(`Signature adopted by: ${methods.join(", ")}`);}+ details.push(...describeProviderSignatureEvidence(signed, redacted));+if (!redacted && signed?.ipAddress) {details.push(`Signed from IP ${signed.ipAddress}`);}@@ -1272,8 +1342,14 @@ export async function finalizeEnvelope(},{seal,+ signedRevision,storageService = createStorageService(),}: SealOption & {+ /**+ * The last signer's revision, when the signers signed with their own+ * certificates: it is the signed document, and gets validation data.+ */+ signedRevision?: Uint8Array;storageService?: StorageService;} = {},): Promise<FinalizedEnvelopeArtifacts> {@@ -1282,21 +1358,23 @@ export async function finalizeEnvelope(envelopeId: input.envelope.id,userId: input.envelope.userId,};- const signedPdfBytes = await renderFinalizedEnvelopePdf(- {- auditEvents: input.auditEvents,- completedAt: generatedAt,- copyRecipients: input.copyRecipients,- envelope: input.envelope,- fields: input.fields,- signers: input.signers,- sourcePdfKey: input.sourcePdf.key,- },- {- seal,- storageService,- },- );+ const signedPdfBytes = signedRevision+ ? await finishSignerSignedPdf(signedRevision)+ : await renderFinalizedEnvelopePdf(+ {+ auditEvents: input.auditEvents,+ completedAt: generatedAt,+ copyRecipients: input.copyRecipients,+ envelope: input.envelope,+ fields: input.fields,+ signers: input.signers,+ sourcePdfKey: input.sourcePdf.key,+ },+ {+ seal,+ storageService,+ },+ );const signedPdfSha256 = sha256Hex(signedPdfBytes);const completedEnvelope = {...input.envelope,diff --git a/src/lib/services/pdf-incremental.ts b/src/lib/services/pdf-incremental.tsindex eec8edf..d726a9b 100644--- a/src/lib/services/pdf-incremental.ts+++ b/src/lib/services/pdf-incremental.ts@@ -39,7 +39,7 @@ export type UpdatedObject = {ref: ObjectRef;};-type Trailer = {+export type Trailer = {id: string | null;info: string | null;root: ObjectRef;@@ -85,7 +85,7 @@ function dictionaryAt(text: string, start: number): string {throw new PdfUpdateError("The PDF trailer is not closed.");}-function readTrailer(bytes: Uint8Array): Trailer {+export function readTrailer(bytes: Uint8Array): Trailer {// Only the end of the file is needed, and a trailer is short.const tailStart = Math.max(0, bytes.length - 4096);const tail = Buffer.from(bytes.subarray(tailStart)).toString("latin1");@@ -219,16 +219,23 @@ export function signaturePlaceholder(contentsBytes: number): string {return `${BYTE_RANGE_PLACEHOLDER}\n/Contents <${"0".repeat(contentsBytes * 2)}>`;}+export type PreparedSignedUpdate = {+ /** The file with the update appended, its byte range set, its slot empty. */+ bytes: Uint8Array;+ /** What the signature covers: the file without the signature slot. */+ signedContent: Buffer;+};+/*** Appends an update whose objects include one signature dictionary written- * with `signaturePlaceholder`, then fills in its byte range and the value- * `sign` makes over the bytes that range covers.+ * with `signaturePlaceholder`, and sets its byte range. The signature goes+ * in later, with `fillSignature`, so it can be made elsewhere (a trust+ * service provider) between the two.*/-export async function appendSignedUpdate(+export function prepareSignedUpdate(bytes: Uint8Array,objects: readonly UpdatedObject[],- sign: (signedContent: Buffer) => Promise<Buffer>,-): Promise<Uint8Array> {+): PreparedSignedUpdate {const updated = Buffer.from(appendIncrementalUpdate(bytes, objects));const text = updated.toString("latin1");const rangeAt = text.indexOf(BYTE_RANGE_PLACEHOLDER, bytes.length);@@ -253,13 +260,47 @@ export async function appendSignedUpdate("latin1",);- const signature = await sign(- Buffer.concat([updated.subarray(0, open), updated.subarray(close + 1)]),+ return {+ bytes: new Uint8Array(updated),+ signedContent: Buffer.concat([+ updated.subarray(0, open),+ updated.subarray(close + 1),+ ]),+ };+}++/** Puts a signature into the empty slot of the file's last signature. */+export function fillSignature(+ prepared: Uint8Array,+ signature: Buffer,+): Uint8Array {+ const updated = Buffer.from(prepared);+ const text = updated.toString("latin1");+ const rangeAt = text.lastIndexOf("/ByteRange [");+ const match = /^\/ByteRange \[0 (\d+) (\d+) (\d+)\s*\]/.exec(+ text.slice(rangeAt, rangeAt + BYTE_RANGE_PLACEHOLDER.length + 1),);++ if (rangeAt === -1 || !match) {+ throw new PdfUpdateError("The PDF has no signature slot to fill.");+ }++ const open = Number(match[1]);+ const close = Number(match[2]) - 1;+ const [, , resume, rest] = match.map(Number) as number[];++ if (+ text[open] !== "<" ||+ text[close] !== ">" ||+ resume! + rest! !== updated.length ||+ /[^0]/.test(text.slice(open + 1, close))+ ) {+ throw new PdfUpdateError("The signature slot is not empty, or has moved.");+ }+const hex = signature.toString("hex");- const room = close - open - 1;- if (hex.length > room) {+ if (hex.length > close - open - 1) {throw new PdfUpdateError(`The signature (${String(signature.length)} bytes) does not fit its placeholder.`,);@@ -270,6 +311,21 @@ export async function appendSignedUpdate(return new Uint8Array(updated);}+/**+ * Appends an update whose objects include one signature dictionary written+ * with `signaturePlaceholder`, then fills in its byte range and the value+ * `sign` makes over the bytes that range covers.+ */+export async function appendSignedUpdate(+ bytes: Uint8Array,+ objects: readonly UpdatedObject[],+ sign: (signedContent: Buffer) => Promise<Buffer>,+): Promise<Uint8Array> {+ const prepared = prepareSignedUpdate(bytes, objects);++ return fillSignature(prepared.bytes, await sign(prepared.signedContent));+}+// --- Reading what is already there ---------------------------------------export type PdfSignature = {diff --git a/src/lib/services/pdf-ltv.ts b/src/lib/services/pdf-ltv.tsindex d6626bc..b43fcea 100644--- a/src/lib/services/pdf-ltv.ts+++ b/src/lib/services/pdf-ltv.ts@@ -61,6 +61,8 @@ const OIDS = {ocsp: "1.3.6.1.5.5.7.48.1",ocspBasic: "1.3.6.1.5.5.7.48.1.1",ocspNoCheck: "1.3.6.1.5.5.7.48.1.5",+ qcStatements: "1.3.6.1.5.5.7.1.3",+ qcType: "0.4.0.1862.1.6",sha1: "1.3.14.3.2.26",sha1WithRsa: "1.2.840.113549.1.1.5",sha256: "2.16.840.1.101.3.4.2.1",@@ -115,8 +117,14 @@ export type Certificate = {issuerName: Buffer;ocspNoCheck: boolean;ocspUrls: string[];+ /** The ids of its qualified certificate statements (ETSI EN 319 412-5). */+ qcStatements: string[];+ /** What its QcType statement says it is for: signatures, seals or web. */+ qcTypes: string[];/** The serial number's INTEGER content, as OCSP and CRLs compare it. */serial: Buffer;+ /** The subject key identifier extension's value, when it has one. */+ subjectKeyIdentifier: Buffer | null;/** The subject public key, without the BIT STRING's unused-bits byte. */subjectKey: Buffer;/** The subject Name, as encoded. */@@ -171,8 +179,11 @@ export function parseCertificate(input: Uint8Array): Certificate {issuerName: elementBytes(bytes, issuerName),ocspNoCheck: false,ocspUrls: [],+ qcStatements: [],+ qcTypes: [],serial: contentBytes(bytes, serial),subjectKey: contentBytes(bytes, key).subarray(1),+ subjectKeyIdentifier: null,subjectName: elementBytes(bytes, subject),x509: new X509Certificate(elementBytes(bytes, certificate)),};@@ -193,6 +204,21 @@ export function parseCertificate(input: Uint8Array): Certificate {if (id === OIDS.ocspNoCheck) {parsed.ocspNoCheck = true;+ } else if (id === "2.5.29.14") {+ parsed.subjectKeyIdentifier = contentBytes(bytes, inner);+ } else if (id === OIDS.qcStatements) {+ for (const statement of children(bytes, inner)) {+ const [statementId, info] = children(bytes, statement);+ const statementOid = readOid(bytes, statementId!);++ parsed.qcStatements.push(statementOid);++ if (statementOid === OIDS.qcType && info?.tag === TAG.sequence) {+ for (const type of children(bytes, info)) {+ parsed.qcTypes.push(readOid(bytes, type));+ }+ }+ }} else if (id === OIDS.crlDistributionPoints) {uriNames(bytes, inner, parsed.crlUrls);} else if (id === OIDS.infoAccess) {diff --git a/src/lib/services/pdf-revision.test.ts b/src/lib/services/pdf-revision.test.tsnew file mode 100644index 0000000..9530734--- /dev/null+++ b/src/lib/services/pdf-revision.test.ts@@ -0,0 +1,363 @@+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { promisify } from "node:util";++import { PDFDocument, PDFName, StandardFonts } from "pdf-lib";++import type { FieldRecord } from "../schemas/field.ts";+import { fillSignature, findSignatures } from "./pdf-incremental.ts";+import {+ addLongTermValidation,+ createValidationFetch,+ describePadesLevel,+ resetValidationCache,+} from "./pdf-ltv.ts";+import {+ prepareRevisionZero,+ prepareSignerRevision,+ SIGNER_SIGNATURE_BYTES,+} from "./pdf-revision.ts";+import { buildCadesSignature, requestDocumentTimestamp } from "./pdf-seal.ts";+import { startTestPki, type TestPki } from "./pki-test-support.ts";+import {+ addSignatureTimestamp,+ checkSignerSignature,+ SignerSignatureError,+} from "./signer-cms.ts";++const run = promisify(execFile);+const localFetch = createValidationFetch({ allowPrivateAddresses: true });+const now = Math.floor(Date.now() / 1000);++async function makeSource(): Promise<Uint8Array> {+ const pdf = await PDFDocument.create();+ const font = await pdf.embedFont(StandardFonts.Helvetica);++ for (const label of ["Page one", "Page two"]) {+ pdf.addPage([612, 792]).drawText(label, { font, x: 72, y: 720 });+ }++ return pdf.save();+}++function field(overrides: Partial<FieldRecord>): FieldRecord {+ return {+ createdAt: now - 500,+ height: 0.05,+ page: 1,+ required: true,+ signerId: "signer-1",+ submittedAt: now,+ type: "text",+ updatedAt: now,+ width: 0.3,+ x: 0.1,+ y: 0.1,+ ...overrides,+ } as FieldRecord;+}++const aliceFields = [+ field({+ id: "a-sign",+ inputMethod: "typed",+ type: "signature",+ value: "Alice Example",+ y: 0.7,+ }),+ field({ id: "a-text", type: "text", value: "Senior buyer", y: 0.8 }),+ field({+ checked: true,+ id: "a-check",+ type: "checkbox",+ width: 0.03,+ y: 0.85,+ }),+];+const bobFields = [+ field({+ id: "b-sign",+ inputMethod: "typed",+ page: 2,+ signerId: "signer-2",+ type: "signature",+ value: "Bob Example",+ y: 0.7,+ }),+ field({+ id: "b-date",+ page: 2,+ signerId: "signer-2",+ type: "date",+ value: "14 November 2026",+ y: 0.8,+ }),+];++/** Signs a prepared revision the way a provider would, and fills it in. */+async function signRevision(+ prepared: { bytes: Uint8Array; digest: Buffer },+ signer: { certificateChainPem: string[]; privateKeyPem: string },+ {+ level = "qualified",+ timestampUrl = null,+ }: { level?: "advanced" | "qualified"; timestampUrl?: string | null } = {},+) {+ const [signature] = findSignatures(prepared.bytes).slice(-1);+ const covered = Buffer.concat([+ Buffer.from(prepared.bytes.subarray(0, signature!.byteRange[1])),+ Buffer.from(+ prepared.bytes.subarray(+ signature!.byteRange[2],+ signature!.byteRange[2] + signature!.byteRange[3],+ ),+ ),+ ]);++ assert.deepEqual(+ createHash("sha256").update(covered).digest(),+ prepared.digest,+ );++ let cms: Buffer = Buffer.from(await buildCadesSignature(covered, signer));++ if (timestampUrl) {+ cms = await addSignatureTimestamp(cms, (imprint) =>+ requestDocumentTimestamp(imprint, timestampUrl),+ );+ }++ const checked = checkSignerSignature(cms, prepared.digest, { level });++ return { bytes: fillSignature(prepared.bytes, cms), checked };+}++async function withPki(body: (pki: TestPki) => Promise<void>) {+ resetValidationCache();++ const pki = await startTestPki();++ try {+ await body(pki);+ } finally {+ await pki.close();+ resetValidationCache();+ }+}++async function pdfsig(bytes: Uint8Array): Promise<string | null> {+ try {+ await run("pdfsig", ["-v"]);+ } catch {+ return null;+ }++ const directory = await mkdtemp(path.join(os.tmpdir(), "revision-"));++ try {+ const file = path.join(directory, "signed.pdf");++ await writeFile(file, bytes);++ // pdfsig exits with an error for a signature it cannot check (an+ // archive timestamp), and where NSS has no database.+ const { stdout } = await run("pdfsig", ["-nocert", file]).catch(+ (error: { stdout?: string }) => ({ stdout: error.stdout ?? "" }),+ );++ return stdout;+ } finally {+ await rm(directory, { force: true, recursive: true });+ }+}++test("each signer's revision keeps the signatures before it valid", async (t) => {+ await withPki(async (pki) => {+ const alice = pki.issueSigner({+ commonName: "Alice Example",+ qualified: true,+ });+ const bob = pki.issueSigner({ commonName: "Bob Example", qualified: true });+ const revisionZero = await prepareRevisionZero(await makeSource());+ const first = await signRevision(+ await prepareSignerRevision(revisionZero, {+ fields: aliceFields,+ images: new Map(),+ signature: {+ fieldName: "Alice Example (signer 1)",+ name: "Alice Example",+ reason: "Signed with SignuDoc",+ signingTime: new Date(),+ },+ }),+ alice,+ { timestampUrl: pki.timestampUrl },+ );++ assert.equal(first.checked.qualified, true);+ assert.equal(first.checked.timestamped, true);+ assert.match(first.checked.subject, /Alice Example/);++ // The first revision is the file it was made from, with more after it.+ assert.deepEqual(+ Buffer.from(first.bytes.subarray(0, revisionZero.length)),+ Buffer.from(revisionZero),+ );++ const second = await signRevision(+ await prepareSignerRevision(first.bytes, {+ fields: bobFields,+ images: new Map(),+ signature: {+ fieldName: "Bob Example (signer 2)",+ name: "Bob Example",+ signingTime: new Date(),+ },+ }),+ bob,+ );++ assert.deepEqual(+ Buffer.from(second.bytes.subarray(0, first.bytes.length)),+ Buffer.from(first.bytes),+ );++ const signatures = findSignatures(second.bytes);++ assert.equal(signatures.length, 2);+ assert.equal(signatures[0]!.subFilter, "ETSI.CAdES.detached");+ // The second signature covers the whole file.+ assert.equal(+ signatures[1]!.byteRange[2] + signatures[1]!.byteRange[3],+ second.bytes.length,+ );++ // The values are on the pages as locked annotations, and the signature+ // widgets show each signer's signature.+ const loaded = await PDFDocument.load(second.bytes);+ const annotations = loaded+ .getPages()+ .map((page) => page.node.Annots()?.size() ?? 0);++ assert.deepEqual(annotations, [3, 2]);+ assert.equal(loaded.getPageCount(), 2);++ const fields = loaded.getForm().getFields();++ assert.deepEqual(+ fields.map((item) => item.getName()),+ ["Alice Example (signer 1)", "Bob Example (signer 2)"],+ );++ for (const item of fields) {+ assert.ok(+ item.acroField.getWidgets()[0]!.dict.get(PDFName.of("AP")),+ "the signature widget has an appearance",+ );+ }++ // Then the install's long-term validation on top: B-LTA.+ const finished = await addLongTermValidation(second.bytes, {+ fetch: localFetch,+ timestamp: (digest) => requestDocumentTimestamp(digest, pki.timestampUrl),+ });++ assert.deepEqual(finished.problems, []);+ assert.equal(await describePadesLevel(finished.bytes), "B-LTA");++ const report = await pdfsig(finished.bytes);++ if (report === null) {+ t.diagnostic("pdfsig is not installed; skipped the poppler check");+ return;+ }++ assert.equal(+ report.match(/Signature Validation: Signature is Valid\./g)?.length,+ 2,+ report,+ );+ assert.match(report, /Signer Certificate Common Name: Alice Example/);+ assert.match(report, /Signer Certificate Common Name: Bob Example/);+ });+});++test("a signature for other content, or by another key, is refused", async () => {+ await withPki(async (pki) => {+ const alice = pki.issueSigner({+ commonName: "Alice Example",+ qualified: true,+ });+ const revisionZero = await prepareRevisionZero(await makeSource());+ const prepared = await prepareSignerRevision(revisionZero, {+ fields: aliceFields,+ images: new Map(),+ signature: { fieldName: "Alice", signingTime: new Date() },+ });+ const otherContent = Buffer.from(+ await buildCadesSignature(Buffer.from("something else"), alice),+ );++ assert.throws(+ () =>+ checkSignerSignature(otherContent, prepared.digest, {+ level: "advanced",+ }),+ /different content/,+ );++ // Alice's certificate with Bob's key.+ const bob = pki.issueSigner({ commonName: "Bob Example" });+ const [signature] = findSignatures(prepared.bytes);+ const covered = Buffer.concat([+ Buffer.from(prepared.bytes.subarray(0, signature!.byteRange[1])),+ Buffer.from(prepared.bytes.subarray(signature!.byteRange[2])),+ ]);+ const forged = Buffer.from(+ await buildCadesSignature(covered, {+ certificateChainPem: alice.certificateChainPem,+ privateKeyPem: bob.privateKeyPem,+ }),+ );++ assert.throws(+ () =>+ checkSignerSignature(forged, prepared.digest, { level: "advanced" }),+ /does not verify/,+ );+ });+});++test("a qualified signature needs a qualified certificate", async () => {+ await withPki(async (pki) => {+ const plain = pki.issueSigner({ commonName: "Carol Example" });+ const prepared = await prepareSignerRevision(+ await prepareRevisionZero(await makeSource()),+ {+ fields: aliceFields,+ images: new Map(),+ signature: { fieldName: "Carol", signingTime: new Date() },+ },+ );++ await assert.rejects(+ signRevision(prepared, plain, { level: "qualified" }),+ (error: unknown) =>+ error instanceof SignerSignatureError &&+ /not a qualified certificate/.test(error.message),+ );++ const advanced = await signRevision(prepared, plain, { level: "advanced" });++ assert.equal(advanced.checked.qualified, false);+ });+});++test("the signature slot fits a chain and a timestamp", () => {+ assert.ok(SIGNER_SIGNATURE_BYTES >= 16_384);+});diff --git a/src/lib/services/pdf-revision.ts b/src/lib/services/pdf-revision.tsnew file mode 100644index 0000000..dbaab12--- /dev/null+++ b/src/lib/services/pdf-revision.ts@@ -0,0 +1,425 @@+import { createHash } from "node:crypto";++import {+ PDFArray,+ PDFDict,+ PDFDocument,+ PDFHexString,+ PDFName,+ PDFNumber,+ PDFRef,+ PDFStream,+ type PDFImage,+ type PDFObject,+ type PDFPage,+} from "pdf-lib";++import type { FieldRecord } from "../schemas/field.ts";+import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";+import { shouldStampField, stampFieldValue } from "./pdf-finalize.ts";+import { embedTextFaces } from "./pdf-fonts.ts";+import {+ appendIncrementalUpdate,+ prepareSignedUpdate,+ readTrailer,+ signaturePlaceholder,+ type UpdatedObject,+} from "./pdf-incremental.ts";+import type { StorageService } from "./storage.ts";++// Revisions for documents each signer signs with their own certificate.+//+// The document is prepared once (revision 0). Then each signer's turn adds+// one revision on top: their field values as locked annotations, and their+// signature field with a signature over the whole file so far. Nothing an+// earlier signer signed changes, so every signature stays valid, and a PDF+// reader can show the document as each signer saw it. The organization's+// seal and long-term validation go on last, the same way.+//+// Revisions are written with pdf-lib for drawing, then only the objects it+// added or changed are appended, by hand, as an incremental update.++/** Room for a signer's CMS: certificate chain, timestamp and some spare. */+export const SIGNER_SIGNATURE_BYTES = 32_768;++/** Print, read only, locked, contents locked. */+const LOCKED_ANNOTATION_FLAGS = 4 | 64 | 128 | 512;++/** Print, locked: a signature widget. */+const SIGNATURE_WIDGET_FLAGS = 4 | 128;++function serialize(object: PDFObject): Buffer {+ const buffer = new Uint8Array(object.sizeInBytes());++ object.copyBytesInto(buffer, 0);++ return Buffer.from(buffer);+}++type Snapshot = Map<string, { object: PDFObject; text: string | null }>;++/** How every object looks before an edit, to find what the edit changed. */+function snapshot(document: PDFDocument): Snapshot {+ const result: Snapshot = new Map();++ for (const [ref, object] of document.context.enumerateIndirectObjects()) {+ result.set(ref.tag, {+ object,+ // Streams are compared by identity: pdf-lib never edits one in place.+ text:+ object instanceof PDFStream+ ? object.dict.toString()+ : object.toString(),+ });+ }++ return result;+}++/** The object numbers reachable from the catalog. */+function reachable(document: PDFDocument, root: PDFRef): Set<string> {+ const seen = new Set<string>();+ const stack: PDFObject[] = [root];++ while (stack.length > 0) {+ const value = stack.pop()!;++ if (value instanceof PDFRef) {+ if (seen.has(value.tag)) {+ continue;+ }++ seen.add(value.tag);++ const target = document.context.lookup(value);++ if (target) {+ stack.push(target);+ }+ } else if (value instanceof PDFDict) {+ for (const [, entry] of value.entries()) {+ stack.push(entry);+ }+ } else if (value instanceof PDFArray) {+ for (let index = 0; index < value.size(); index += 1) {+ stack.push(value.get(index));+ }+ } else if (value instanceof PDFStream) {+ stack.push(value.dict);+ }+ }++ return seen;+}++/** The objects an edit added or changed that the document still uses. */+function changedObjects(+ document: PDFDocument,+ before: Snapshot,+ root: PDFRef,+): UpdatedObject[] {+ const used = reachable(document, root);+ const objects: UpdatedObject[] = [];++ for (const [ref, object] of document.context.enumerateIndirectObjects()) {+ if (!used.has(ref.tag)) {+ continue;+ }++ const previous = before.get(ref.tag);+ const changed =+ !previous ||+ previous.object !== object ||+ previous.text !==+ (object instanceof PDFStream+ ? object.dict.toString()+ : object.toString());++ if (changed) {+ objects.push({+ body: serialize(object),+ ref: { generation: ref.generationNumber, number: ref.objectNumber },+ });+ }+ }++ return objects;+}++function pdfDate(date: Date): string {+ return `D:${date.toISOString().replace(/[-:T]/g, "").slice(0, 14)}Z`;+}++function textString(value: string): string {+ return PDFHexString.fromText(value).toString();+}++export type RevisionSignature = {+ contactInfo?: string;+ /** Bytes kept for the CMS. */+ contentsBytes?: number;+ /** The signature field's name, unique in the document. */+ fieldName: string;+ location?: string;+ name?: string;+ reason?: string;+ signingTime: Date;+};++export type RevisionEditContext = {+ document: PDFDocument;+ /** Sets where the signature's widget shows, and what it shows. */+ placeSignature: (widget: {+ appearance?: PDFRef;+ page: PDFPage;+ rect: [number, number, number, number];+ }) => void;+};++/**+ * Appends one revision: what `edit` draws, and, with `signature`, a+ * signature field whose value is still to be signed. Returns the prepared+ * file and the bytes the signature must cover; `fillSignature` puts the+ * CMS in. Without `signature` the file comes back complete.+ */+export async function appendRevision(+ bytes: Uint8Array,+ {+ edit,+ signature,+ }: {+ edit?: (context: RevisionEditContext) => Promise<void>;+ signature?: RevisionSignature;+ },+): Promise<{ bytes: Uint8Array; signedContent: Buffer | null }> {+ const document = await PDFDocument.load(bytes, { updateMetadata: false });+ const trailer = readTrailer(bytes);+ const root = PDFRef.of(trailer.root.number, trailer.root.generation);+ const before = snapshot(document);+ // Its number is taken now; the dictionary itself is written by hand.+ const signatureRef = signature ? document.context.nextRef() : null;+ let widget: {+ appearance?: PDFRef;+ page: PDFPage;+ rect: [number, number, number, number];+ } | null = null;++ await edit?.({+ document,+ placeSignature: (placed) => {+ widget = placed;+ },+ });++ if (signature && signatureRef) {+ const placed: {+ appearance?: PDFRef;+ page: PDFPage;+ rect: [number, number, number, number];+ } = widget ?? { page: document.getPage(0), rect: [0, 0, 0, 0] };+ const field = document.context.obj({+ F: SIGNATURE_WIDGET_FLAGS,+ FT: "Sig",+ P: placed.page.ref,+ Rect: placed.rect,+ Subtype: "Widget",+ T: PDFHexString.fromText(signature.fieldName),+ Type: "Annot",+ V: signatureRef,+ });++ if (placed.appearance) {+ field.set(+ PDFName.of("AP"),+ document.context.obj({ N: placed.appearance }),+ );+ }++ const fieldRef = document.context.register(field);+ const acroForm = document.catalog.getOrCreateAcroForm();+ const flags = acroForm.dict.lookupMaybe(PDFName.of("SigFlags"), PDFNumber);++ placed.page.node.addAnnot(fieldRef);+ acroForm.addField(fieldRef);+ acroForm.dict.set(+ PDFName.of("SigFlags"),+ PDFNumber.of((flags?.asNumber() ?? 0) | 3),+ );+ }++ await document.flush();++ const objects = changedObjects(document, before, root);++ if (!signature || !signatureRef) {+ return {+ bytes: appendIncrementalUpdate(bytes, objects),+ signedContent: null,+ };+ }++ const entries = [+ "/Type /Sig",+ "/Filter /Adobe.PPKLite",+ "/SubFilter /ETSI.CAdES.detached",+ `/M (${pdfDate(signature.signingTime)})`,+ ...(signature.name ? [`/Name ${textString(signature.name)}`] : []),+ ...(signature.reason ? [`/Reason ${textString(signature.reason)}`] : []),+ ...(signature.location+ ? [`/Location ${textString(signature.location)}`]+ : []),+ ...(signature.contactInfo+ ? [`/ContactInfo ${textString(signature.contactInfo)}`]+ : []),+ signaturePlaceholder(signature.contentsBytes ?? SIGNER_SIGNATURE_BYTES),+ ];++ objects.push({+ body: Buffer.from(`<<\n${entries.join("\n")}\n>>`, "latin1"),+ ref: {+ generation: signatureRef.generationNumber,+ number: signatureRef.objectNumber,+ },+ });++ const prepared = prepareSignedUpdate(bytes, objects);++ return { bytes: prepared.bytes, signedContent: prepared.signedContent };+}++/** SHA-256 of what a signature covers, as a CMS's messageDigest holds it. */+export function signedContentDigest(signedContent: Buffer): Buffer {+ return createHash("sha256").update(signedContent).digest();+}++/**+ * Revision 0: the source document, with any form it had flattened, saved+ * so that later revisions can be added to it (a classic cross-reference+ * table). Nothing is signed yet.+ */+export async function prepareRevisionZero(+ source: Uint8Array,+): Promise<Uint8Array> {+ const document = await PDFDocument.load(source, { updateMetadata: false });++ try {+ document.getForm().flatten();+ } catch {+ // Most source PDFs have no form.+ }++ return document.save({ useObjectStreams: false });+}++/**+ * One signer's revision: each of their field values drawn into its own+ * appearance, shown by a locked annotation over the field, and their first+ * signature field as the visible widget of their signature.+ *+ * `images` holds drawn signatures by key, since they are not stored yet.+ */+export async function prepareSignerRevision(+ base: Uint8Array,+ {+ fields,+ images,+ signature,+ }: {+ fields: readonly FieldRecord[];+ images: ReadonlyMap<string, Uint8Array>;+ signature: RevisionSignature;+ },+): Promise<{ bytes: Uint8Array; digest: Buffer }> {+ const imageStore = {+ getObject: async (key: string) => {+ const body = images.get(key);++ if (!body) {+ throw new Error(`The image ${key} is missing.`);+ }++ return { body };+ },+ } as unknown as StorageService;+ const prepared = await appendRevision(base, {+ edit: async ({ document, placeSignature }) => {+ const faces = await embedTextFaces(+ document,+ [fields.map((field) => field.value)],+ {+ signature: fields.some(+ (field) =>+ (field.type === "signature" || field.type === "initials") &&+ field.inputMethod !== "drawn",+ ),+ },+ );+ const imageCache = new Map<string, PDFImage>();+ let signaturePlaced = false;++ for (const field of fields.filter(shouldStampField)) {+ const page = document.getPage(field.page - 1);+ const size = { heightPt: page.getHeight(), widthPt: page.getWidth() };+ const rect = normalizedRectToPdfRect(field, size);+ // Drawn on a page of its own, then taken as a form XObject cut to+ // the field, so the original page's content is never touched.+ const scratch = document.addPage([size.widthPt, size.heightPt]);+ const box = {+ bottom: rect.yPt,+ left: rect.xPt,+ right: rect.xPt + rect.widthPt,+ top: rect.yPt + rect.heightPt,+ };++ await stampFieldValue(+ field,+ scratch,+ { auditRegular: faces.regular, signature: faces.signature },+ imageCache,+ document,+ imageStore,+ );++ const embedded = await document.embedPage(scratch, box);++ document.removePage(document.getPageCount() - 1);++ const annotationRect: [number, number, number, number] = [+ box.left,+ box.bottom,+ box.right,+ box.top,+ ];++ if (field.type === "signature" && !signaturePlaced) {+ signaturePlaced = true;+ placeSignature({+ appearance: embedded.ref,+ page,+ rect: annotationRect,+ });+ continue;+ }++ const annotation = document.context.register(+ document.context.obj({+ AP: { N: embedded.ref },+ F: LOCKED_ANNOTATION_FLAGS,+ NM: PDFHexString.fromText(`signudoc-field-${field.id ?? "field"}`),+ Rect: annotationRect,+ Subtype: "Stamp",+ Type: "Annot",+ }),+ );++ page.node.addAnnot(annotation);+ }+ },+ signature,+ });++ return {+ bytes: prepared.bytes,+ digest: signedContentDigest(prepared.signedContent!),+ };+}diff --git a/src/lib/services/pki-test-support.ts b/src/lib/services/pki-test-support.tsindex a613168..b0d95b5 100644--- a/src/lib/services/pki-test-support.ts+++ b/src/lib/services/pki-test-support.ts@@ -161,6 +161,14 @@ export type TestPki = {close: () => Promise<void>;/** The CA certificate, DER. */caCertificate: Buffer;+ /**+ * A person's signing certificate from the CA, as a signing provider would+ * hold it; `qualified` adds the qualified certificate statements.+ */+ issueSigner: (options: {+ commonName: string;+ qualified?: boolean;+ }) => SealIdentity & { certificate: Buffer };/** A seal identity issued by the CA, its chain holding only itself. */seal: SealIdentity;sealCertificate: Buffer;@@ -480,9 +488,48 @@ export async function startTestPki(): Promise<TestPki> {}};+ let signerSerial = 0x4000;+ const issueSigner: TestPki["issueSigner"] = ({ commonName, qualified }) => {+ const keys = makeKeys();+ // QCStatements: QcCompliance, QcSSCD, QcType esign (ETSI EN 319 412-5).+ const qcStatements = {+ id: "1.3.6.1.5.5.7.1.3",+ value: binary(+ der.sequence(+ der.sequence(der.oid("0.4.0.1862.1.1")),+ der.sequence(der.oid("0.4.0.1862.1.4")),+ der.sequence(+ der.oid("0.4.0.1862.1.6"),+ der.sequence(der.oid("0.4.0.1862.1.6.1")),+ ),+ ),+ ),+ };++ signerSerial += 1;++ const certificate = issueCertificate({+ commonName,+ extensions: [infoAccess, crlPoints, ...(qualified ? [qcStatements] : [])],+ issuer: { certificate: ca, keys: caKeys },+ keys,+ serial: signerSerial.toString(16),+ });++ return {+ certificate: certificateDer(certificate),+ certificateChainPem: [+ forge.pki.certificateToPem(certificate),+ forge.pki.certificateToPem(ca),+ ],+ privateKeyPem: keys.privateKeyPem,+ };+ };+return {caCertificate: caDer,close: () => new Promise<void>((resolve) => server.close(() => resolve())),+ issueSigner,seal: {certificateChainPem: [forge.pki.certificateToPem(sealCertificate)],privateKeyPem: sealKeys.privateKeyPem,diff --git a/src/lib/services/seal-identity.ts b/src/lib/services/seal-identity.tsindex 91a188f..c455672 100644--- a/src/lib/services/seal-identity.ts+++ b/src/lib/services/seal-identity.ts@@ -53,7 +53,7 @@ declare global {var __signudocSealIdentity: CachedIdentity | undefined;}-function encryptionKey(env: EnvSource): Buffer {+function encryptionKey(env: EnvSource, context: string = KEY_CONTEXT): Buffer {const secret = resolveAuthSecret(env);if (!secret) {@@ -65,11 +65,22 @@ function encryptionKey(env: EnvSource): Buffer {// Local development without a password: nothing worth protecting.return Buffer.from(- hkdfSync("sha256", "signudoc-development", "", KEY_CONTEXT, 32),+ hkdfSync("sha256", "signudoc-development", "", context, 32),);}- return Buffer.from(hkdfSync("sha256", secret, "", KEY_CONTEXT, 32));+ return Buffer.from(hkdfSync("sha256", secret, "", context, 32));+}++/**+ * A key for keeping something else secret in the database, derived from the+ * auth secret the same way as the seal key's, for its own purpose.+ */+export function secretKeyFor(+ context: string,+ env: EnvSource = process.env,+): Buffer {+ return encryptionKey(env, context);}export function encryptPrivateKey(pem: string, key: Buffer): string {@@ -329,6 +340,7 @@ async function withLongTermValidation(sealed: Uint8Array,timestampUrl: string | null,fetch: ValidationFetch | undefined,+ whose: "seal" | "signers" = "seal",): Promise<Uint8Array> {try {const result = await addLongTermValidation(sealed, {@@ -340,7 +352,9 @@ async function withLongTermValidation(if (result.revoked.length > 0) {console.error(- `[seal] A certificate authority says these certificates are revoked: ${result.revoked.join("; ")}. Readers will not accept the seal. Replace SEAL_P12_BASE64.`,+ whose === "seal"+ ? `[seal] A certificate authority says these certificates are revoked: ${result.revoked.join("; ")}. Readers will not accept the seal. Replace SEAL_P12_BASE64.`+ : `[seal] A certificate authority says these signers' certificates are revoked: ${result.revoked.join("; ")}. Readers will not accept those signatures.`,);}@@ -360,6 +374,28 @@ async function withLongTermValidation(}}+/**+ * The finished PDF of an envelope whose signers signed with certificates in+ * their own names: the last signer's revision, with the validation data of+ * every signature in it (PAdES B-LT), and with SEAL_TIMESTAMP_URL an archive+ * timestamp over all of it (B-LTA). The signers' signatures already protect+ * the document, so the install adds no seal of its own here.+ */+export async function finishSignerSignedPdf(+ revision: Uint8Array,+ {+ env = process.env,+ fetch,+ }: { env?: EnvSource; fetch?: ValidationFetch } = {},+): Promise<Uint8Array> {+ return withLongTermValidation(+ revision,+ readEnv(env, "SEAL_TIMESTAMP_URL") ?? null,+ fetch,+ "signers",+ );+}+async function clonePdf(pdfDocument: PDFDocument): Promise<PDFDocument> {return PDFDocument.load(await pdfDocument.save({ useObjectStreams: false }));}diff --git a/src/lib/services/signer-cms.ts b/src/lib/services/signer-cms.tsnew file mode 100644index 0000000..0f782a9--- /dev/null+++ b/src/lib/services/signer-cms.ts@@ -0,0 +1,652 @@+import {+ constants,+ createHash,+ verify as verifySignature,+ type KeyObject,+} from "node:crypto";++import {+ algorithm,+ children,+ contentBytes,+ contextTag,+ der,+ elementBytes,+ encode,+ encodeSmallInteger,+ readOid,+ readTlv,+ TAG,+ type Tlv,+} from "./der.ts";+import { parseCertificate, type Certificate } from "./pdf-ltv.ts";++// The CMS of one signer's own signature (CAdES, as PAdES uses it).+//+// A signing provider either returns the whole CMS (eID Easy), or signs a+// hash and leaves the CMS to us (the Cloud Signature Consortium API). Either+// way, before a signature goes into a document it is checked here: that it+// signs this revision's bytes, that the signature verifies with the+// certificate it names, and, for a qualified signature, that the certificate+// says it is qualified and its key is on a qualified signature creation+// device. Whether the certificate's issuer is a qualified trust service+// provider on the EU trusted list is for the reader to check: Acrobat and+// the EU's validation service do, from the list.++export const CMS_OIDS = {+ contentType: "1.2.840.113549.1.9.3",+ data: "1.2.840.113549.1.7.1",+ ecdsaSha256: "1.2.840.10045.4.3.2",+ ecdsaSha384: "1.2.840.10045.4.3.3",+ ecdsaSha512: "1.2.840.10045.4.3.4",+ ecPublicKey: "1.2.840.10045.2.1",+ messageDigest: "1.2.840.113549.1.9.4",+ qcCompliance: "0.4.0.1862.1.1",+ qcSscd: "0.4.0.1862.1.4",+ qcTypeSignature: "0.4.0.1862.1.6.1",+ rsaEncryption: "1.2.840.113549.1.1.1",+ rsaPss: "1.2.840.113549.1.1.10",+ sha256: "2.16.840.1.101.3.4.2.1",+ sha256WithRsa: "1.2.840.113549.1.1.11",+ sha384: "2.16.840.1.101.3.4.2.2",+ sha384WithRsa: "1.2.840.113549.1.1.12",+ sha512: "2.16.840.1.101.3.4.2.3",+ sha512WithRsa: "1.2.840.113549.1.1.13",+ signedData: "1.2.840.113549.1.7.2",+ signingCertificate: "1.2.840.113549.1.9.16.2.12",+ signingCertificateV2: "1.2.840.113549.1.9.16.2.47",+ signingTime: "1.2.840.113549.1.9.5",+ sha1: "1.3.14.3.2.26",+ timeStampToken: "1.2.840.113549.1.9.16.2.14",+} as const;++const HASHES: Record<string, string> = {+ [CMS_OIDS.sha1]: "sha1",+ [CMS_OIDS.sha256]: "sha256",+ [CMS_OIDS.sha384]: "sha384",+ [CMS_OIDS.sha512]: "sha512",+};++export class SignerSignatureError extends Error {+ constructor(message: string, options?: { cause?: unknown }) {+ super(message, options);+ this.name = "SignerSignatureError";+ }+}++// --- Building ------------------------------------------------------------++function attribute(type: string, value: Uint8Array): Buffer {+ return der.sequence(der.oid(type), der.set(value));+}++/** DER SET OF: the elements sorted by their encoding (X.690 11.6). */+function sortedSet(items: Buffer[]): Buffer {+ return der.set(...[...items].sort(Buffer.compare));+}++/**+ * The signed attributes of a PAdES signature, as the SET whose hash is+ * signed: the content type, the hash of the signed bytes and which+ * certificate signs (ESSCertIDv2 with SHA-256). No signing time: PAdES+ * keeps that in the signature dictionary.+ */+export function buildSignedAttributes({+ certificate,+ contentDigest,+}: {+ certificate: Uint8Array;+ contentDigest: Uint8Array;+}): Buffer {+ const certificateHash = createHash("sha256").update(certificate).digest();++ return sortedSet([+ attribute(CMS_OIDS.contentType, der.oid(CMS_OIDS.data)),+ attribute(CMS_OIDS.messageDigest, der.octets(contentDigest)),+ attribute(+ CMS_OIDS.signingCertificateV2,+ der.sequence(der.sequence(der.sequence(der.octets(certificateHash)))),+ ),+ ]);+}++/** Whether the certificate's key is an elliptic curve key (else RSA). */+export function hasEcKey(certificate: Certificate): boolean {+ const bytes = certificate.der;+ const tbs = children(bytes, readTlv(bytes))[0]!;+ const fields = children(bytes, tbs);+ const offset = fields[0]?.tag === contextTag(0) ? 1 : 0;+ const spki = fields[offset + 5]!;+ const keyAlgorithm = children(bytes, children(bytes, spki)[0]!)[0]!;++ return readOid(bytes, keyAlgorithm) === CMS_OIDS.ecPublicKey;+}++/** The algorithm a signature value was made with, for the SignerInfo. */+export function signatureAlgorithmFor(certificate: Certificate): Buffer {+ return hasEcKey(certificate)+ ? der.sequence(der.oid(CMS_OIDS.ecdsaSha256))+ : algorithm(CMS_OIDS.sha256WithRsa);+}++/**+ * An ECDSA signature as DER, from the raw r and s some services return.+ * A signature already in DER is returned as it is.+ */+export function ecdsaSignatureAsDer(signature: Buffer): Buffer {+ if (signature[0] === TAG.sequence) {+ try {+ const outer = readTlv(signature);++ if (outer.end === signature.length) {+ return signature;+ }+ } catch {+ // Not DER after all.+ }+ }++ const half = signature.length / 2;+ const integer = (value: Buffer) => {+ let start = 0;++ while (start < value.length - 1 && value[start] === 0) {+ start += 1;+ }++ const trimmed = value.subarray(start);++ return encode(+ TAG.integer,+ trimmed[0]! & 0x80 ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed,+ );+ };++ return der.sequence(+ integer(signature.subarray(0, half)),+ integer(signature.subarray(half)),+ );+}++/** A CMS SignedData (detached) from parts signed elsewhere. */+export function assembleSignedData({+ certificates,+ signature,+ signatureAlgorithm,+ signedAttributes,+ unsignedAttributes = [],+}: {+ /** The signer's certificate first, then its chain. */+ certificates: readonly Buffer[];+ signature: Buffer;+ signatureAlgorithm: Buffer;+ /** As `buildSignedAttributes` made them: a DER SET. */+ signedAttributes: Buffer;+ unsignedAttributes?: readonly Buffer[];+}): Buffer {+ const signer = parseCertificate(certificates[0]!);+ const signedAttributesTlv = readTlv(signedAttributes);+ const signerInfo = der.sequence(+ encodeSmallInteger(1),+ der.sequence(signer.issuerName, encode(TAG.integer, signer.serial)),+ algorithm(CMS_OIDS.sha256),+ // [0] IMPLICIT: the same content, under the context tag.+ encode(contextTag(0), contentBytes(signedAttributes, signedAttributesTlv)),+ signatureAlgorithm,+ der.octets(signature),+ ...(unsignedAttributes.length > 0+ ? [encode(contextTag(1), ...unsignedAttributes)]+ : []),+ );+ const signedData = der.sequence(+ encodeSmallInteger(1),+ der.set(algorithm(CMS_OIDS.sha256)),+ der.sequence(der.oid(CMS_OIDS.data)),+ encode(contextTag(0), ...certificates),+ der.set(signerInfo),+ );++ return der.sequence(+ der.oid(CMS_OIDS.signedData),+ encode(contextTag(0), signedData),+ );+}++// --- Reading -------------------------------------------------------------++type ParsedSignerInfo = {+ bytes: Buffer;+ certificates: Buffer[];+ digestAlgorithm: string;+ signature: Buffer;+ signatureAlgorithm: { oid: string; parameters: Tlv | null };+ /** The signed attributes, re-tagged as the SET that was signed. */+ signedAttributes: Buffer;+ signedAttributeValues: Map<string, Tlv[]>;+ signerIdentifier: Tlv;+ unsignedAttributeIds: string[];+};++function readAttributes(bytes: Buffer, tlv: Tlv): Map<string, Tlv[]> {+ const values = new Map<string, Tlv[]>();++ for (const item of children(bytes, tlv)) {+ const [id, set] = children(bytes, item);+ const oid = readOid(bytes, id!);++ if (values.has(oid)) {+ throw new SignerSignatureError(`The attribute ${oid} appears twice.`);+ }++ values.set(oid, children(bytes, set!));+ }++ return values;+}++function readSignedData(cms: Buffer): {+ parts: Tlv[];+ signedData: Tlv;+} {+ const contentInfo = readTlv(cms);++ if (contentInfo.end !== cms.length) {+ throw new SignerSignatureError("The signature has data after its end.");+ }++ const [type, wrapped] = children(cms, contentInfo);++ if (readOid(cms, type!) !== CMS_OIDS.signedData) {+ throw new SignerSignatureError("The signature is not a CMS SignedData.");+ }++ const signedData = children(cms, wrapped!)[0]!;++ return { parts: children(cms, signedData), signedData };+}++function readSignerInfo(cms: Buffer): ParsedSignerInfo {+ const { parts } = readSignedData(cms);+ const encapsulated = parts[2];++ // Detached: the content type only, no content.+ if (+ !encapsulated ||+ children(cms, encapsulated).length !== 1 ||+ readOid(cms, children(cms, encapsulated)[0]!) !== CMS_OIDS.data+ ) {+ throw new SignerSignatureError(+ "The signature is not a detached signature of data.",+ );+ }++ const certificates = parts+ .filter((part) => part.tag === contextTag(0))+ .flatMap((part) => children(cms, part))+ .filter((item) => item.tag === TAG.sequence)+ .map((item) => elementBytes(cms, item));+ const signerInfos = children(cms, parts[parts.length - 1]!);++ if (signerInfos.length !== 1) {+ throw new SignerSignatureError("The signature must have one signer.");+ }++ const fields = children(cms, signerInfos[0]!);+ const [, signerIdentifier, digestAlgorithm] = fields;+ const signedAttributes = fields.find((field) => field.tag === contextTag(0));++ if (!signedAttributes) {+ throw new SignerSignatureError("The signature has no signed attributes.");+ }++ const afterSigned = fields.slice(fields.indexOf(signedAttributes) + 1);+ const [signatureAlgorithm, signatureValue, unsigned] = afterSigned;+ const algorithmParts = children(cms, signatureAlgorithm!);+ const signed = elementBytes(cms, signedAttributes);++ // The signature covers the attributes encoded as a SET (RFC 5652 5.4).+ signed[0] = TAG.set;++ return {+ bytes: cms,+ certificates,+ digestAlgorithm: readOid(cms, children(cms, digestAlgorithm!)[0]!),+ signature: contentBytes(cms, signatureValue!),+ signatureAlgorithm: {+ oid: readOid(cms, algorithmParts[0]!),+ parameters:+ algorithmParts[1] && algorithmParts[1].tag !== TAG.null+ ? algorithmParts[1]+ : null,+ },+ signedAttributes: signed,+ signedAttributeValues: readAttributes(cms, signedAttributes),+ signerIdentifier: signerIdentifier!,+ unsignedAttributeIds:+ unsigned && unsigned.tag === contextTag(1)+ ? [...readAttributes(cms, unsigned).keys()]+ : [],+ };+}++function findSigner(+ info: ParsedSignerInfo,+ certificates: readonly Certificate[],+): Certificate {+ const { bytes, signerIdentifier } = info;+ const match = certificates.find((certificate) => {+ if (signerIdentifier.tag === TAG.sequence) {+ const [issuer, serial] = children(bytes, signerIdentifier);++ return (+ elementBytes(bytes, issuer!).equals(certificate.issuerName) &&+ contentBytes(bytes, serial!).equals(certificate.serial)+ );+ }++ // [0] SubjectKeyIdentifier+ return (+ signerIdentifier.tag === contextTag(0, false) &&+ certificate.subjectKeyIdentifier !== null &&+ contentBytes(bytes, signerIdentifier).equals(+ certificate.subjectKeyIdentifier,+ )+ );+ });++ if (!match) {+ throw new SignerSignatureError(+ "The signature does not include the certificate that made it.",+ );+ }++ return match;+}++function verifyValue(info: ParsedSignerInfo, key: KeyObject): boolean {+ const { bytes, signatureAlgorithm, signature, signedAttributes } = info;+ const digestHash = HASHES[info.digestAlgorithm];++ switch (signatureAlgorithm.oid) {+ case CMS_OIDS.rsaEncryption:+ return verifySignature(digestHash!, signedAttributes, key, signature);+ case CMS_OIDS.sha256WithRsa:+ return verifySignature("sha256", signedAttributes, key, signature);+ case CMS_OIDS.sha384WithRsa:+ return verifySignature("sha384", signedAttributes, key, signature);+ case CMS_OIDS.sha512WithRsa:+ return verifySignature("sha512", signedAttributes, key, signature);+ case CMS_OIDS.ecdsaSha256:+ case CMS_OIDS.ecdsaSha384:+ case CMS_OIDS.ecdsaSha512: {+ const hash =+ signatureAlgorithm.oid === CMS_OIDS.ecdsaSha256+ ? "sha256"+ : signatureAlgorithm.oid === CMS_OIDS.ecdsaSha384+ ? "sha384"+ : "sha512";++ return verifySignature(+ hash,+ signedAttributes,+ { dsaEncoding: "der", key },+ signature,+ );+ }+ case CMS_OIDS.rsaPss: {+ // RSASSA-PSS-params: [0] hash, [1] mask generation, [2] salt length.+ let hash = "sha1";+ let saltLength = 20;++ for (const field of signatureAlgorithm.parameters+ ? children(bytes, signatureAlgorithm.parameters)+ : []) {+ if (field.tag === contextTag(0)) {+ hash =+ HASHES[+ readOid(bytes, children(bytes, children(bytes, field)[0]!)[0]!)+ ] ?? "";+ } else if (field.tag === contextTag(2)) {+ const value = contentBytes(bytes, children(bytes, field)[0]!);++ saltLength = value.readUIntBE(0, Math.min(6, value.length));+ }+ }++ return verifySignature(+ hash,+ signedAttributes,+ { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength },+ signature,+ );+ }+ default:+ throw new SignerSignatureError(+ `The signature algorithm ${signatureAlgorithm.oid} is not supported.`,+ );+ }+}++function assertSigningCertificate(+ info: ParsedSignerInfo,+ certificate: Certificate,+) {+ const { bytes, signedAttributeValues } = info;+ const v2 = signedAttributeValues.get(CMS_OIDS.signingCertificateV2)?.[0];+ const v1 = signedAttributeValues.get(CMS_OIDS.signingCertificate)?.[0];+ const value = v2 ?? v1;++ if (!value) {+ throw new SignerSignatureError(+ "The signature does not name its certificate (signing-certificate attribute).",+ );+ }++ // SigningCertificate(V2) { certs SEQUENCE OF ESSCertID(v2), ... }+ const first = children(bytes, children(bytes, value)[0]!)[0]!;+ const parts = children(bytes, first);+ let hash = v2 ? "sha256" : "sha1";+ let hashField = parts[0]!;++ if (v2 && parts[0]!.tag === TAG.sequence) {+ hash = HASHES[readOid(bytes, children(bytes, parts[0]!)[0]!)] ?? "";+ hashField = parts[1]!;+ }++ if (+ !hash ||+ !contentBytes(bytes, hashField).equals(+ createHash(hash).update(certificate.der).digest(),+ )+ ) {+ throw new SignerSignatureError(+ "The signature names a different certificate from the one that made it.",+ );+ }+}++export type SignatureLevel = "advanced" | "qualified";++export type CheckedSignerSignature = {+ certificate: Certificate;+ /** The certificates the CMS carries, the signer's first. */+ chain: Buffer[];+ issuer: string;+ /** The certificate says it is qualified, for signatures, on a QSCD. */+ qualified: boolean;+ serialNumber: string;+ subject: string;+ /** The CMS carries a signature timestamp (PAdES B-T). */+ timestamped: boolean;+ validTo: Date;+};++function displayName(distinguishedName: string): string {+ return distinguishedName.replace(/\n/g, ", ");+}++/** Whether a certificate claims to be qualified for electronic signatures. */+export function isQualifiedSignatureCertificate(+ certificate: Certificate,+): boolean {+ return (+ certificate.qcStatements.includes(CMS_OIDS.qcCompliance) &&+ certificate.qcStatements.includes(CMS_OIDS.qcSscd) &&+ (certificate.qcTypes.length === 0 ||+ certificate.qcTypes.includes(CMS_OIDS.qcTypeSignature))+ );+}++/**+ * Checks a signer's CMS before it goes into the document: it signs exactly+ * `contentDigest` (SHA-256 of the revision's signed bytes), it verifies with+ * the certificate it names, that certificate is valid now, and, for a+ * qualified signature, the certificate says it is one.+ */+export function checkSignerSignature(+ cms: Uint8Array,+ contentDigest: Uint8Array,+ { level, now = new Date() }: { level: SignatureLevel; now?: Date },+): CheckedSignerSignature {+ let info: ParsedSignerInfo;++ try {+ info = readSignerInfo(Buffer.from(cms));+ } catch (error) {+ if (error instanceof SignerSignatureError) {+ throw error;+ }++ throw new SignerSignatureError("The signature could not be read.", {+ cause: error,+ });+ }++ if (info.digestAlgorithm !== CMS_OIDS.sha256) {+ throw new SignerSignatureError("The signature does not use SHA-256.");+ }++ const contentType = info.signedAttributeValues.get(CMS_OIDS.contentType);+ const messageDigest = info.signedAttributeValues.get(CMS_OIDS.messageDigest);++ if (+ contentType?.length !== 1 ||+ readOid(info.bytes, contentType[0]!) !== CMS_OIDS.data+ ) {+ throw new SignerSignatureError("The signature's content type is wrong.");+ }++ if (+ messageDigest?.length !== 1 ||+ !contentBytes(info.bytes, messageDigest[0]!).equals(+ Buffer.from(contentDigest),+ )+ ) {+ throw new SignerSignatureError(+ "The signature is for different content than this document.",+ );+ }++ const certificates = info.certificates.map((certificate) =>+ parseCertificate(certificate),+ );+ const signer = findSigner(info, certificates);+ let verified: boolean;++ try {+ verified = verifyValue(info, signer.x509.publicKey);+ } catch (error) {+ if (error instanceof SignerSignatureError) {+ throw error;+ }++ verified = false;+ }++ if (!verified) {+ throw new SignerSignatureError("The signature does not verify.");+ }++ assertSigningCertificate(info, signer);++ const validFrom = new Date(signer.x509.validFrom);+ const validTo = new Date(signer.x509.validTo);++ if (now < validFrom || now > validTo) {+ throw new SignerSignatureError("The signing certificate is not valid now.");+ }++ const qualified = isQualifiedSignatureCertificate(signer);++ if (level === "qualified" && !qualified) {+ throw new SignerSignatureError(+ "The certificate is not a qualified certificate for electronic signatures on a qualified device.",+ );+ }++ return {+ certificate: signer,+ chain: [+ signer.der,+ ...certificates+ .filter((certificate) => certificate !== signer)+ .map((certificate) => certificate.der),+ ],+ issuer: displayName(signer.x509.issuer),+ qualified,+ serialNumber: signer.serial.toString("hex"),+ subject: displayName(signer.x509.subject),+ timestamped: info.unsignedAttributeIds.includes(CMS_OIDS.timeStampToken),+ validTo,+ };+}++// --- Changing --------------------------------------------------------------++/**+ * Adds a signature timestamp (PAdES B-T) to a CMS that has none: the+ * timestamp token for the SHA-256 of the signature value, as an unsigned+ * attribute. The signature itself is unchanged.+ */+export async function addSignatureTimestamp(+ cms: Uint8Array,+ timestamp: (imprint: Buffer) => Promise<Buffer>,+): Promise<Buffer> {+ const bytes = Buffer.from(cms);+ const info = readSignerInfo(bytes);++ if (info.unsignedAttributeIds.includes(CMS_OIDS.timeStampToken)) {+ return bytes;+ }++ const token = await timestamp(+ createHash("sha256").update(info.signature).digest(),+ );+ const { parts } = readSignedData(bytes);+ const signerInfos = parts[parts.length - 1]!;+ const signerInfo = children(bytes, signerInfos)[0]!;+ const fields = children(bytes, signerInfo);+ const unsigned = fields.find((field) => field.tag === contextTag(1));+ const kept = fields+ .filter((field) => field !== unsigned)+ .map((field) => elementBytes(bytes, field));+ const attributes = [+ ...(unsigned+ ? children(bytes, unsigned).map((item) => elementBytes(bytes, item))+ : []),+ attribute(CMS_OIDS.timeStampToken, token),+ ];+ const newSignerInfo = der.sequence(+ ...kept,+ encode(contextTag(1), ...attributes),+ );+ const signedData = der.sequence(+ ...parts.slice(0, -1).map((part) => elementBytes(bytes, part)),+ der.set(newSignerInfo),+ );++ return der.sequence(+ der.oid(CMS_OIDS.signedData),+ encode(contextTag(0), signedData),+ );+}diff --git a/src/lib/services/signing-provider-test-support.ts b/src/lib/services/signing-provider-test-support.tsnew file mode 100644index 0000000..24839e0--- /dev/null+++ b/src/lib/services/signing-provider-test-support.ts@@ -0,0 +1,378 @@+import {+ createHash,+ createSign,+ privateEncrypt,+ randomBytes,+} from "node:crypto";+import {+ createServer,+ type IncomingMessage,+ type ServerResponse,+} from "node:http";++import { algorithm } from "./der.ts";+import {+ assembleSignedData,+ buildSignedAttributes,+ CMS_OIDS,+} from "./signer-cms.ts";++// Stand-ins for eID Easy and a Cloud Signature Consortium API v2 provider,+// for tests. Each signs with the key of a certificate from the test CA, the+// way the real services sign with the signer's key, and keeps to the parts+// of the protocols the clients use: client credentials, the redirect back+// with the state, PKCE, and a signature only for the hash the signer+// authorized.++export const STAND_IN_CLIENT = { id: "test-client", secret: "test-secret" };++export type StandInSigner = {+ /** The signer's certificate first, then the CA's. */+ chain: Buffer[];+ privateKeyPem: string;+};++export type ProviderStandIns = {+ close: () => Promise<void>;+ cscUrl: string;+ eidEasyUrl: string;+ state: {+ /** The query of the last CSC authorize request. */+ lastAuthorize: URLSearchParams | null;+ /** Signing requests refused for a hash nobody authorized. */+ refusedHashes: number;+ /** When true, the signer cancels at the provider. */+ signerCancels: boolean;+ };+};++const SHA256_DIGEST_INFO = Buffer.from(+ "3031300d060960864801650304020105000420",+ "hex",+);++async function readBody(request: IncomingMessage): Promise<string> {+ const chunks: Buffer[] = [];++ for await (const chunk of request) {+ chunks.push(chunk as Buffer);+ }++ return Buffer.concat(chunks).toString("utf8");+}++function json(response: ServerResponse, status: number, body: unknown) {+ response+ .writeHead(status, { "content-type": "application/json" })+ .end(JSON.stringify(body));+}++function redirect(response: ServerResponse, location: string) {+ response.writeHead(302, { location }).end();+}++/** A CAdES signature of `digest`, as eID Easy returns one. */+function cmsForDigest(signer: StandInSigner, digest: Buffer): Buffer {+ const signedAttributes = buildSignedAttributes({+ certificate: signer.chain[0]!,+ contentDigest: digest,+ });++ return assembleSignedData({+ certificates: signer.chain,+ signature: createSign("sha256")+ .update(signedAttributes)+ .sign(signer.privateKeyPem),+ signatureAlgorithm: algorithm(CMS_OIDS.sha256WithRsa),+ signedAttributes,+ });+}++export async function startProviderStandIns(+ signer: StandInSigner,+ { port = 0 }: { port?: number } = {},+): Promise<ProviderStandIns> {+ const state: ProviderStandIns["state"] = {+ lastAuthorize: null,+ refusedHashes: 0,+ signerCancels: false,+ };+ const documents = new Map<+ string,+ { digest: Buffer; redirect: string; signed: boolean }+ >();+ const codes = new Map<+ string,+ {+ challenge: string;+ hashes: string | null;+ redirectUri: string;+ scope: string;+ }+ >();+ const tokens = new Map<string, { hashes: string | null; scope: string }>();+ const server = createServer((request, response) => {+ void handle(request, response).catch(() => {+ response.writeHead(500).end();+ });+ });++ async function handle(request: IncomingMessage, response: ServerResponse) {+ const url = new URL(request.url ?? "/", "http://stand-in");+ const body = request.method === "POST" ? await readBody(request) : "";++ if (url.pathname === "/health") {+ json(response, 200, { status: "OK" });+ return;+ }++ // --- eID Easy ---+ if (url.pathname === "/eideasy/api/signatures/prepare-files-for-signing") {+ const input = JSON.parse(body) as {+ client_id: string;+ container_type: string;+ files: { fileContent: string }[];+ secret: string;+ signature_redirect: string;+ };++ if (+ input.client_id !== STAND_IN_CLIENT.id ||+ input.secret !== STAND_IN_CLIENT.secret+ ) {+ json(response, 401, { message: "Unknown client", status: "error" });+ return;+ }++ if (input.container_type !== "cades" || input.files.length !== 1) {+ json(response, 422, { message: "Unsupported", status: "error" });+ return;+ }++ const docId = randomBytes(8).toString("hex");++ documents.set(docId, {+ digest: Buffer.from(input.files[0]!.fileContent, "base64"),+ redirect: input.signature_redirect,+ signed: false,+ });+ json(response, 200, { doc_id: docId, status: "OK" });+ return;+ }++ if (url.pathname === "/eideasy/sign_contract_external") {+ const document = documents.get(url.searchParams.get("doc_id") ?? "");++ if (+ !document ||+ url.searchParams.get("client_id") !== STAND_IN_CLIENT.id+ ) {+ response.writeHead(404).end();+ return;+ }++ // The signer identifies themselves and approves.+ document.signed = !state.signerCancels;+ redirect(response, document.redirect);+ return;+ }++ if (url.pathname === "/eideasy/api/signatures/download-signed-file") {+ const input = JSON.parse(body) as {+ client_id: string;+ doc_id: string;+ secret: string;+ };+ const document = documents.get(input.doc_id);++ if (+ input.client_id !== STAND_IN_CLIENT.id ||+ input.secret !== STAND_IN_CLIENT.secret+ ) {+ json(response, 401, { message: "Unknown client", status: "error" });+ return;+ }++ if (!document?.signed) {+ json(response, 200, { message: "Not signed", status: "error" });+ return;+ }++ json(response, 200, {+ signed_file_contents: cmsForDigest(signer, document.digest).toString(+ "base64",+ ),+ signing_method: "smart-id-signature",+ status: "OK",+ });+ return;+ }++ // --- CSC API v2 ---+ if (url.pathname === "/csc/oauth2/authorize") {+ const query = url.searchParams;++ state.lastAuthorize = query;++ if (+ query.get("client_id") !== STAND_IN_CLIENT.id ||+ query.get("code_challenge_method") !== "S256" ||+ query.get("response_type") !== "code"+ ) {+ response.writeHead(400).end();+ return;+ }++ const back = new URL(query.get("redirect_uri")!);++ back.searchParams.set("state", query.get("state") ?? "");++ if (state.signerCancels) {+ back.searchParams.set("error", "access_denied");+ back.searchParams.set("error_description", "The user cancelled");+ redirect(response, back.toString());+ return;+ }++ const code = randomBytes(8).toString("hex");++ codes.set(code, {+ challenge: query.get("code_challenge")!,+ hashes: query.get("hashes"),+ redirectUri: query.get("redirect_uri")!,+ scope: query.get("scope")!,+ });+ back.searchParams.set("code", code);+ redirect(response, back.toString());+ return;+ }++ if (url.pathname === "/csc/oauth2/token") {+ const form = new URLSearchParams(body);+ const grant = codes.get(form.get("code") ?? "");++ codes.delete(form.get("code") ?? "");++ if (+ !grant ||+ form.get("client_id") !== STAND_IN_CLIENT.id ||+ form.get("client_secret") !== STAND_IN_CLIENT.secret ||+ form.get("redirect_uri") !== grant.redirectUri ||+ createHash("sha256")+ .update(form.get("code_verifier") ?? "")+ .digest("base64url") !== grant.challenge+ ) {+ json(response, 400, { error: "invalid_grant" });+ return;+ }++ const token = randomBytes(16).toString("hex");++ tokens.set(token, { hashes: grant.hashes, scope: grant.scope });+ json(response, 200, { access_token: token, token_type: "Bearer" });+ return;+ }++ const token = tokens.get(+ (request.headers.authorization ?? "").replace(/^Bearer /, ""),+ );++ if (url.pathname === "/csc/credentials/list") {+ if (token?.scope !== "service") {+ json(response, 401, { error: "invalid_token" });+ return;+ }++ json(response, 200, { credentialIDs: ["credential-1"] });+ return;+ }++ if (url.pathname === "/csc/credentials/info") {+ if (token?.scope !== "service") {+ json(response, 401, { error: "invalid_token" });+ return;+ }++ json(response, 200, {+ cert: {+ certificates: signer.chain.map((item) => item.toString("base64")),+ status: "valid",+ },+ key: { algo: [CMS_OIDS.rsaEncryption], status: "enabled" },+ });+ return;+ }++ if (url.pathname === "/csc/signatures/signHash") {+ const input = JSON.parse(body) as {+ credentialID: string;+ hashAlgorithmOID: string;+ hashes: string[];+ signAlgo: string;+ };+ const hash = Buffer.from(input.hashes[0] ?? "", "base64");++ // Only the hash the signer authorized, with this token, once.+ if (+ token?.scope !== "credential" ||+ token.hashes !== hash.toString("base64url") ||+ input.hashes.length !== 1 ||+ input.hashAlgorithmOID !== CMS_OIDS.sha256+ ) {+ state.refusedHashes += 1;+ json(response, 403, { error: "invalid_request" });+ return;+ }++ tokens.delete((request.headers.authorization ?? "").slice(7));+ json(response, 200, {+ signatures: [+ privateEncrypt(+ signer.privateKeyPem,+ Buffer.concat([SHA256_DIGEST_INFO, hash]),+ ).toString("base64"),+ ],+ });+ return;+ }++ response.writeHead(404).end();+ }++ await new Promise<void>((resolve) =>+ server.listen(port, "127.0.0.1", resolve),+ );++ const address = server.address();+ const base = `http://127.0.0.1:${String(typeof address === "object" && address ? address.port : 0)}`;++ return {+ close: () =>+ new Promise<void>((resolve) => {+ server.closeAllConnections();+ server.close(() => resolve());+ }),+ cscUrl: `${base}/csc`,+ eidEasyUrl: `${base}/eideasy`,+ state,+ };+}++/**+ * Follows a provider's redirect the way the signer's browser would, and+ * returns the query the signer comes back to the install with.+ */+export async function followSigner(+ redirectUrl: string,+): Promise<URLSearchParams> {+ const response = await fetch(redirectUrl, { redirect: "manual" });+ const location = response.headers.get("location");++ if (!location) {+ throw new Error(+ `The provider answered ${String(response.status)} without a redirect.`,+ );+ }++ return new URL(location).searchParams;+}diff --git a/src/lib/services/signing-providers.test.ts b/src/lib/services/signing-providers.test.tsnew file mode 100644index 0000000..227075a--- /dev/null+++ b/src/lib/services/signing-providers.test.ts@@ -0,0 +1,205 @@+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import test from "node:test";++import { startTestPki } from "./pki-test-support.ts";+import {+ followSigner,+ STAND_IN_CLIENT,+ startProviderStandIns,+ type ProviderStandIns,+} from "./signing-provider-test-support.ts";+import {+ configuredSigningProvider,+ createCscProvider,+ createEidEasyProvider,+ SigningProviderError,+ signingProviderById,+ type SigningProvider,+} from "./signing-providers.ts";+import { checkSignerSignature } from "./signer-cms.ts";++const RETURN_URL = "https://sign.example.org/api/signing/provider/return";+const digest = createHash("sha256").update("revision bytes").digest();++async function withStandIns(+ body: (standIns: ProviderStandIns) => Promise<void>,+) {+ const pki = await startTestPki();+ const signer = pki.issueSigner({+ commonName: "Alice Example",+ qualified: true,+ });+ const standIns = await startProviderStandIns({+ chain: [signer.certificate, pki.caCertificate],+ privateKeyPem: signer.privateKeyPem,+ });++ try {+ await body(standIns);+ } finally {+ await standIns.close();+ await pki.close();+ }+}++/** Runs a provider's whole flow, following each redirect as a browser. */+async function signWith(provider: SigningProvider) {+ const started = await provider.start({+ contentDigest: digest,+ documentName: "Supply agreement / 2026",+ level: "qualified",+ returnUrl: RETURN_URL,+ signer: { email: "[email protected]", name: "Alice Example" },+ state: "session-1",+ });+ let data = started.data;+ let redirectUrl = started.redirectUrl;++ for (let step = 0; step < 4; step += 1) {+ const query = await followSigner(redirectUrl);++ assert.equal(query.get("state"), "session-1");++ const next = await provider.resume({+ contentDigest: digest,+ data,+ query,+ returnUrl: RETURN_URL,+ state: "session-1",+ });++ if (next.kind === "signed") {+ return { cms: next.cms, method: next.method, steps: step + 1 };+ }++ data = next.data;+ redirectUrl = next.redirectUrl;+ }++ throw new Error("Too many steps.");+}++test("eID Easy signs the revision's hash in one redirect", async () => {+ await withStandIns(async (standIns) => {+ const provider = createEidEasyProvider({+ apiUrl: standIns.eidEasyUrl,+ clientId: STAND_IN_CLIENT.id,+ secret: STAND_IN_CLIENT.secret,+ });+ const signed = await signWith(provider);+ const checked = checkSignerSignature(signed.cms, digest, {+ level: "qualified",+ });++ assert.equal(signed.steps, 1);+ assert.equal(signed.method, "smart-id-signature");+ assert.equal(checked.qualified, true);+ assert.match(checked.subject, /Alice Example/);+ });+});++test("a signer who cancels at eID Easy gets no signature", async () => {+ await withStandIns(async (standIns) => {+ standIns.state.signerCancels = true;++ await assert.rejects(+ signWith(+ createEidEasyProvider({+ apiUrl: standIns.eidEasyUrl,+ clientId: STAND_IN_CLIENT.id,+ secret: STAND_IN_CLIENT.secret,+ }),+ ),+ (error: unknown) =>+ error instanceof SigningProviderError &&+ /no signature for this document/.test(error.message),+ );+ });+});++test("wrong eID Easy credentials are reported", async () => {+ await withStandIns(async (standIns) => {+ await assert.rejects(+ createEidEasyProvider({+ apiUrl: standIns.eidEasyUrl,+ clientId: STAND_IN_CLIENT.id,+ secret: "wrong",+ }).start({+ contentDigest: digest,+ documentName: "x",+ level: "advanced",+ returnUrl: RETURN_URL,+ signer: { email: "[email protected]", name: "A" },+ state: "s",+ }),+ /eID Easy failed: Unknown client/,+ );+ });+});++test("a CSC provider signs after the signer chooses a certificate and authorizes the hash", async () => {+ await withStandIns(async (standIns) => {+ const provider = createCscProvider({+ apiUrl: standIns.cscUrl,+ clientId: STAND_IN_CLIENT.id,+ clientSecret: STAND_IN_CLIENT.secret,+ name: "Test QTSP",+ });+ const signed = await signWith(provider);+ const checked = checkSignerSignature(signed.cms, digest, {+ level: "qualified",+ });++ assert.equal(signed.steps, 2);+ assert.equal(checked.qualified, true);+ // The second sign-in authorized one signature of one hash.+ assert.equal(standIns.state.lastAuthorize?.get("scope"), "credential");+ assert.equal(standIns.state.lastAuthorize?.get("numSignatures"), "1");+ assert.equal(standIns.state.refusedHashes, 0);+ });+});++test("a signer who cancels at the CSC provider is told where it stopped", async () => {+ await withStandIns(async (standIns) => {+ standIns.state.signerCancels = true;++ await assert.rejects(+ signWith(+ createCscProvider({+ apiUrl: standIns.cscUrl,+ clientId: STAND_IN_CLIENT.id,+ clientSecret: STAND_IN_CLIENT.secret,+ name: "Test QTSP",+ }),+ ),+ /Signing at Test QTSP did not finish \(The user cancelled\)/,+ );+ });+});++test("the provider comes from the environment", () => {+ assert.equal(configuredSigningProvider({}), null);+ assert.equal(+ configuredSigningProvider({+ EIDEASY_CLIENT_ID: "id",+ EIDEASY_SECRET: "secret",+ })?.id,+ "eideasy",+ );++ const both = {+ CSC_API_URL: "https://qtsp.example/csc/v2",+ CSC_CLIENT_ID: "id",+ CSC_CLIENT_SECRET: "secret",+ CSC_PROVIDER_NAME: "Example QTSP",+ EIDEASY_CLIENT_ID: "id",+ EIDEASY_SECRET: "secret",+ SIGNING_PROVIDER: "csc",+ };++ assert.equal(configuredSigningProvider(both)?.name, "Example QTSP");+ // An envelope sent with the other provider can still finish.+ assert.equal(signingProviderById("eideasy", both)?.id, "eideasy");+ assert.equal(signingProviderById("csc", {}), null);+});diff --git a/src/lib/services/signing-providers.ts b/src/lib/services/signing-providers.tsnew file mode 100644index 0000000..61388f7--- /dev/null+++ b/src/lib/services/signing-providers.ts@@ -0,0 +1,565 @@+import { createHash, randomBytes } from "node:crypto";++import { readEnv, type EnvSource } from "../utils/env.ts";+import { parseCertificate } from "./pdf-ltv.ts";+import {+ assembleSignedData,+ buildSignedAttributes,+ CMS_OIDS,+ ecdsaSignatureAsDer,+ hasEcKey,+ signatureAlgorithmFor,+ type SignatureLevel,+} from "./signer-cms.ts";++// Signing providers: the trust service that signs for a signer with a+// certificate in the signer's own name, for advanced (AdES) and qualified+// (QES) electronic signatures.+//+// SignuDoc prepares the signer's revision of the PDF and its hash; the+// provider identifies the signer, has them approve, and signs the hash.+// Two kinds are supported, configured by environment variables:+//+// - eID Easy (EIDEASY_CLIENT_ID, EIDEASY_SECRET): one redirect. eID Easy+// offers the signer the methods of their country (Smart-ID, Mobile-ID,+// national ID cards, and others), and returns a CAdES signature.+// - Any trust service provider with the Cloud Signature Consortium API v2+// (CSC_API_URL, CSC_CLIENT_ID, CSC_CLIENT_SECRET): the signer signs in at+// the provider twice, once to choose their certificate and once to+// authorize the signature of this hash. SignuDoc builds the CMS.+//+// Both are outside Vercel, and the organization pays the provider. Nothing+// here is used unless one is configured.++export type SigningProviderId = "csc" | "eideasy";++export class SigningProviderError extends Error {+ constructor(message: string, options?: { cause?: unknown }) {+ super(message, options);+ this.name = "SigningProviderError";+ }+}++/** What a provider keeps between steps. Stored encrypted with the session. */+export type ProviderData = Record<string, unknown>;++export type ProviderStep =+ | { data: ProviderData; kind: "redirect"; redirectUrl: string }+ | { cms: Buffer; kind: "signed"; method?: string | null };++export type ProviderStartInput = {+ /** SHA-256 of the revision bytes the signature covers. */+ contentDigest: Buffer;+ documentName: string;+ language?: string | null;+ level: SignatureLevel;+ /** Where the provider sends the signer back to, without a query. */+ returnUrl: string;+ signer: { email: string; name: string };+ /** Identifies this signing session when the signer comes back. */+ state: string;+};++export type ProviderResumeInput = {+ contentDigest: Buffer;+ data: ProviderData;+ /** The query the signer came back with. */+ query: URLSearchParams;+ returnUrl: string;+ state: string;+};++export interface SigningProvider {+ readonly id: SigningProviderId;+ /** The provider's name, as the signer sees it. */+ readonly name: string;+ resume(input: ProviderResumeInput): Promise<ProviderStep>;+ start(+ input: ProviderStartInput,+ ): Promise<ProviderStep & { kind: "redirect" }>;+}++const REQUEST_TIMEOUT_MS = 15_000;++async function callJson<T>(+ url: string,+ {+ body,+ form,+ headers = {},+ what,+ }: {+ body?: unknown;+ form?: Record<string, string>;+ headers?: Record<string, string>;+ what: string;+ },+): Promise<T> {+ let response: Response;++ try {+ response = await fetch(url, {+ body: form+ ? new URLSearchParams(form).toString()+ : JSON.stringify(body ?? {}),+ headers: {+ accept: "application/json",+ "content-type": form+ ? "application/x-www-form-urlencoded"+ : "application/json",+ ...headers,+ },+ method: "POST",+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ } catch (error) {+ throw new SigningProviderError(`${what} could not be reached.`, {+ cause: error,+ });+ }++ const text = await response.text();+ let parsed: unknown = null;++ try {+ parsed = text ? JSON.parse(text) : null;+ } catch {+ // Reported below.+ }++ if (!response.ok || parsed === null || typeof parsed !== "object") {+ const message =+ parsed && typeof parsed === "object" && "message" in parsed+ ? String((parsed as { message: unknown }).message)+ : parsed && typeof parsed === "object" && "error_description" in parsed+ ? String((parsed as { error_description: unknown }).error_description)+ : `answered ${String(response.status)}`;++ throw new SigningProviderError(`${what} failed: ${message.slice(0, 200)}`);+ }++ return parsed as T;+}++function trimSlash(url: string): string {+ return url.replace(/\/+$/, "");+}++function stoppedAt(name: string, query: URLSearchParams): never {+ const description =+ query.get("error_description") ?? query.get("error") ?? "cancelled";++ throw new SigningProviderError(+ `Signing at ${name} did not finish (${description.slice(0, 200)}).`,+ );+}++// --- eID Easy --------------------------------------------------------------++export function createEidEasyProvider({+ apiUrl = "https://id.eideasy.com",+ clientId,+ secret,+}: {+ apiUrl?: string;+ clientId: string;+ secret: string;+}): SigningProvider {+ const base = trimSlash(apiUrl);++ return {+ id: "eideasy",+ name: "eID Easy",+ async resume({ data, query }) {+ if (query.get("error")) {+ stoppedAt("eID Easy", query);+ }++ const docId = typeof data.docId === "string" ? data.docId : null;++ if (!docId) {+ throw new SigningProviderError("The eID Easy document is missing.");+ }++ const result = await callJson<{+ signed_file_contents?: string;+ signing_method?: string;+ status?: string;+ }>(`${base}/api/signatures/download-signed-file`, {+ body: {+ client_id: clientId,+ doc_id: docId,+ secret,+ verify_baseline: true,+ },+ what: "eID Easy",+ });++ // Anything but OK means there is no signature to use: eID Easy's own+ // guidance is not to treat the signature as verified then.+ if (result.status !== "OK" || !result.signed_file_contents) {+ throw new SigningProviderError(+ "eID Easy has no signature for this document. The signer may have cancelled.",+ );+ }++ return {+ cms: Buffer.from(result.signed_file_contents, "base64"),+ kind: "signed",+ method: result.signing_method ?? null,+ };+ },+ async start({ contentDigest, documentName, language, returnUrl, state }) {+ const redirect = new URL(returnUrl);++ redirect.searchParams.set("state", state);++ // The "cades" container signs the hash given as the file's content+ // and returns a detached CAdES signature (a CMS), for the PDF to hold.+ const prepared = await callJson<{ doc_id?: string; status?: string }>(+ `${base}/api/signatures/prepare-files-for-signing`,+ {+ body: {+ baseline: "T",+ client_id: clientId,+ container_type: "cades",+ files: [+ {+ fileContent: contentDigest.toString("base64"),+ fileName: `${documentName.replace(/[^\p{L}\p{N} ._-]/gu, "").slice(0, 80) || "document"}.pdf`,+ mimeType: "application/pdf",+ },+ ],+ noemails: true,+ secret,+ signature_redirect: redirect.toString(),+ },+ what: "eID Easy",+ },+ );++ if (!prepared.doc_id) {+ throw new SigningProviderError("eID Easy did not accept the document.");+ }++ const page = new URL(`${base}/sign_contract_external`);++ page.searchParams.set("client_id", clientId);+ page.searchParams.set("doc_id", prepared.doc_id);++ if (language) {+ page.searchParams.set("lang", language.slice(0, 2));+ }++ return {+ data: { docId: prepared.doc_id },+ kind: "redirect",+ redirectUrl: page.toString(),+ };+ },+ };+}++// --- Cloud Signature Consortium API v2 -------------------------------------++function base64Url(value: Buffer): string {+ return value.toString("base64url");+}++function pkce(): { challenge: string; verifier: string } {+ const verifier = base64Url(randomBytes(32));++ return {+ challenge: base64Url(createHash("sha256").update(verifier).digest()),+ verifier,+ };+}++type CscCredentialInfo = {+ cert?: { certificates?: string[]; status?: string };+ key?: { status?: string };+};++export function createCscProvider({+ apiUrl,+ clientId,+ clientSecret,+ name = "your trust service provider",+ oauthUrl,+}: {+ apiUrl: string;+ clientId: string;+ clientSecret: string;+ name?: string;+ oauthUrl?: string;+}): SigningProvider {+ const api = trimSlash(apiUrl);+ const oauth = trimSlash(oauthUrl ?? `${api}/oauth2`);+ const authorizeUrl = (+ params: Record<string, string>,+ state: string,+ returnUrl: string,+ challenge: string,+ ) => {+ const url = new URL(`${oauth}/authorize`);++ for (const [key, value] of Object.entries({+ client_id: clientId,+ code_challenge: challenge,+ code_challenge_method: "S256",+ redirect_uri: returnUrl,+ response_type: "code",+ state,+ ...params,+ })) {+ url.searchParams.set(key, value);+ }++ return url.toString();+ };+ const exchange = async (+ code: string,+ verifier: string,+ returnUrl: string,+ ): Promise<string> => {+ const token = await callJson<{ access_token?: string }>(`${oauth}/token`, {+ form: {+ client_id: clientId,+ client_secret: clientSecret,+ code,+ code_verifier: verifier,+ grant_type: "authorization_code",+ redirect_uri: returnUrl,+ },+ what: name,+ });++ if (!token.access_token) {+ throw new SigningProviderError(`${name} gave no access token.`);+ }++ return token.access_token;+ };++ return {+ id: "csc",+ name,+ async resume({ contentDigest, data, query, returnUrl, state }) {+ if (query.get("error")) {+ stoppedAt(name, query);+ }++ const code = query.get("code");+ const verifier = typeof data.verifier === "string" ? data.verifier : "";++ if (!code || !verifier) {+ throw new SigningProviderError(+ `${name} sent the signer back without a code.`,+ );+ }++ if (data.step === "service") {+ // The signer signed in: find their certificate, and ask them to+ // authorize the signature of exactly this hash.+ const bearer = {+ authorization: `Bearer ${await exchange(code, verifier, returnUrl)}`,+ };+ const list = await callJson<{ credentialIDs?: string[] }>(+ `${api}/credentials/list`,+ { body: {}, headers: bearer, what: name },+ );+ let chosen: { certificates: Buffer[]; id: string } | null = null;++ for (const credentialID of (list.credentialIDs ?? []).slice(0, 10)) {+ const info = await callJson<CscCredentialInfo>(+ `${api}/credentials/info`,+ {+ body: { certInfo: true, certificates: "chain", credentialID },+ headers: bearer,+ what: name,+ },+ );+ const certificates = (info.cert?.certificates ?? []).map((value) =>+ Buffer.from(value, "base64"),+ );++ if (+ certificates.length > 0 &&+ (info.cert?.status ?? "valid") === "valid" &&+ (info.key?.status ?? "enabled") === "enabled"+ ) {+ chosen = { certificates, id: credentialID };+ break;+ }+ }++ if (!chosen) {+ throw new SigningProviderError(+ `${name} has no usable signing certificate for this signer.`,+ );+ }++ // Read now, so a certificate that cannot be read stops here.+ parseCertificate(chosen.certificates[0]!);++ const signedAttributes = buildSignedAttributes({+ certificate: chosen.certificates[0]!,+ contentDigest,+ });+ const hash = createHash("sha256").update(signedAttributes).digest();+ const next = pkce();++ return {+ data: {+ certificates: chosen.certificates.map((value) =>+ value.toString("base64"),+ ),+ credentialID: chosen.id,+ signedAttributes: signedAttributes.toString("base64"),+ step: "credential",+ verifier: next.verifier,+ },+ kind: "redirect",+ redirectUrl: authorizeUrl(+ {+ credentialID: chosen.id,+ hashAlgorithmOID: CMS_OIDS.sha256,+ hashes: base64Url(hash),+ numSignatures: "1",+ scope: "credential",+ },+ state,+ returnUrl,+ next.challenge,+ ),+ };+ }++ if (data.step !== "credential") {+ throw new SigningProviderError(+ `The ${name} session is not one this install made.`,+ );+ }++ const signedAttributes = Buffer.from(+ String(data.signedAttributes),+ "base64",+ );+ const certificates = (data.certificates as string[]).map((value) =>+ Buffer.from(value, "base64"),+ );+ // The algorithm follows the certificate's key: ECDSA or RSA.+ const signer = parseCertificate(certificates[0]!);+ const ec = hasEcKey(signer);+ const signatureAlgorithm = signatureAlgorithmFor(signer);+ const hash = createHash("sha256").update(signedAttributes).digest();+ const credentialToken = await exchange(code, verifier, returnUrl);+ const signed = await callJson<{ signatures?: string[] }>(+ `${api}/signatures/signHash`,+ {+ body: {+ credentialID: data.credentialID,+ hashAlgorithmOID: CMS_OIDS.sha256,+ hashes: [hash.toString("base64")],+ operationMode: "S",+ signAlgo: ec ? CMS_OIDS.ecdsaSha256 : CMS_OIDS.rsaEncryption,+ },+ headers: { authorization: `Bearer ${credentialToken}` },+ what: name,+ },+ );+ const value = signed.signatures?.[0];++ if (!value) {+ throw new SigningProviderError(`${name} returned no signature.`);+ }++ const raw = Buffer.from(value, "base64");++ return {+ cms: assembleSignedData({+ certificates,+ signature: ec ? ecdsaSignatureAsDer(raw) : raw,+ signatureAlgorithm,+ signedAttributes,+ }),+ kind: "signed",+ method: "csc",+ };+ },+ async start({ returnUrl, state }) {+ const first = pkce();++ return {+ data: { step: "service", verifier: first.verifier },+ kind: "redirect",+ redirectUrl: authorizeUrl(+ { scope: "service" },+ state,+ returnUrl,+ first.challenge,+ ),+ };+ },+ };+}++// --- Configuration ---------------------------------------------------------++function configuredProviders(env: EnvSource): SigningProvider[] {+ const providers: SigningProvider[] = [];+ const eidEasyClient = readEnv(env, "EIDEASY_CLIENT_ID");+ const eidEasySecret = readEnv(env, "EIDEASY_SECRET");+ const cscApi = readEnv(env, "CSC_API_URL");+ const cscClient = readEnv(env, "CSC_CLIENT_ID");+ const cscSecret = readEnv(env, "CSC_CLIENT_SECRET");++ if (eidEasyClient && eidEasySecret) {+ providers.push(+ createEidEasyProvider({+ apiUrl: readEnv(env, "EIDEASY_API_URL"),+ clientId: eidEasyClient,+ secret: eidEasySecret,+ }),+ );+ }++ if (cscApi && cscClient && cscSecret) {+ providers.push(+ createCscProvider({+ apiUrl: cscApi,+ clientId: cscClient,+ clientSecret: cscSecret,+ name: readEnv(env, "CSC_PROVIDER_NAME"),+ oauthUrl: readEnv(env, "CSC_OAUTH_URL"),+ }),+ );+ }++ return providers;+}++/**+ * The provider new envelopes use, or null when none is configured. With+ * both configured, SIGNING_PROVIDER picks one; eID Easy otherwise.+ */+export function configuredSigningProvider(+ env: EnvSource = process.env,+): SigningProvider | null {+ const providers = configuredProviders(env);+ const choice = readEnv(env, "SIGNING_PROVIDER")?.toLowerCase();++ return (+ providers.find((provider) => provider.id === choice) ?? providers[0] ?? null+ );+}++/** The provider an envelope was sent with, if it is still configured. */+export function signingProviderById(+ id: string,+ env: EnvSource = process.env,+): SigningProvider | null {+ return (+ configuredProviders(env).find((provider) => provider.id === id) ?? null+ );+}diff --git a/src/lib/services/storage-keys.ts b/src/lib/services/storage-keys.tsindex 04bc610..5b750c4 100644--- a/src/lib/services/storage-keys.ts+++ b/src/lib/services/storage-keys.ts@@ -84,6 +84,24 @@ export function buildEnvelopeThumbnailKey(return path.posix.join(folder, "thumbnail.jpg");}+/**+ * One signer's revision of the PDF, when signers sign with their own+ * certificates through a signing provider: prepared, then signed. It sits+ * beside the original, for the same reason as the thumbnail.+ */+export function buildSignerRevisionKey(+ input: EnvelopeStorageIdentity & {+ sessionId: string;+ sourcePdfKey: string;+ },+): string {+ return path.posix.join(+ path.posix.dirname(buildEnvelopeThumbnailKey(input)),+ "revisions",+ `${input.sessionId}.pdf`,+ );+}+/*** A template's own copy of its document. It is a copy, not the file of the* envelope it was made from, so neither can take the other's file with itdiff --git a/src/lib/signing.ts b/src/lib/signing.tsindex 2650c12..f34ae4d 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -24,6 +24,7 @@ import {MAX_DRAWN_SIGNATURE_BYTES,signingSubmissionSchema,type SigningFieldSubmission,+ type SigningSubmission,} from "./schemas/field.ts";import {signerCheckRequestSchema,@@ -72,6 +73,7 @@ import {issueSigningLink,type IssuedSigningLink,} from "./services/signing-links.ts";+import { signingProviderById } from "./services/signing-providers.ts";import {buildEnvelopeCertificateKey,buildEnvelopeSignedPdfKey,@@ -112,7 +114,7 @@ import {type SignerCheckState,} from "./signer-checks.ts";-type SigningRequestMeta = {+export type SigningRequestMeta = {ipAddress?: string | null;userAgent?: string | null;};@@ -135,7 +137,11 @@ type SigningEnvelopeRow = {id: string;pageCount: number;part11: boolean;+ revisionKey: string | null;+ revisionSha256: string | null;sentAt: number | null;+ signatureLevel: "advanced" | "qualified" | "simple";+ signatureProvider: string | null;signedPdfKey: string | null;sourcePdfFilename: string;sourcePdfHash: string;@@ -215,9 +221,41 @@ type ResolvedSigningContext = {signers: Array<ReturnType<typeof signerRecordSchema.parse>>;};+/** What a signer's own certificate showed, kept in the audit trail. */+export type ProviderSignatureEvidence = {+ certificateIssuer: string;+ certificateSerialNumber: string;+ certificateSubject: string;+ /** Unix seconds. */+ certificateValidTo: number;+ level: "advanced" | "qualified";+ /** How the signer identified themselves at the provider, when it says. */+ method: string | null;+ provider: string;+ /** The certificate says it is qualified, on a qualified device. */+ qualified: boolean;+ timestamped: boolean;+};++/**+ * A signature a signing provider made for the signer, in a revision of the+ * PDF of its own. See provider-signing.ts.+ */+export type ProviderSignatureCompletion = {+ /** The revision this one was added to, as it was when the signer began. */+ baseSha256: string | null;+ evidence: ProviderSignatureEvidence;+ revision: { bytes: Uint8Array; key: string; sha256: string };+ sessionId: string;+ /** When the signer submitted, which the revision's dates are from. */+ submittedAt: number;+};+type SubmitSigningOptions = {database?: DbPool;emailService?: EmailService;+ /** Set when a signing provider signed: see provider-signing.ts. */+ providerSignature?: ProviderSignatureCompletion;requestMeta?: SigningRequestMeta;storageService?: StorageService;/** The extra checks this browser has passed for the link (from its cookie). */@@ -513,6 +551,10 @@ async function getEnvelopeRow(source_pdf_hash AS "sourcePdfHash",page_count AS "pageCount",part11,+ signature_level AS "signatureLevel",+ signature_provider AS "signatureProvider",+ revision_key AS "revisionKey",+ revision_sha256 AS "revisionSha256",sent_at AS "sentAt",completed_at AS "completedAt",declined_at AS "declinedAt",@@ -906,6 +948,7 @@ function buildSignedAuditEvent(input: {authMethods: readonly SignerCheckMethod[];envelopeId: string;part11?: Part11SignatureRecord | null;+ providerSignature?: ProviderSignatureEvidence | null;signatureMethods: readonly string[];requestMeta: SigningRequestMeta;signer: ReturnType<typeof signerRecordSchema.parse>;@@ -929,6 +972,9 @@ function buildSignedAuditEvent(input: {signatureMethods: [...input.signatureMethods],timezoneOffsetMinutes: input.timezoneOffsetMinutes,...(input.part11 ? { part11: input.part11 } : {}),+ ...(input.providerSignature+ ? { providerSignature: input.providerSignature }+ : {}),},userAgent: input.requestMeta.userAgent ?? null,};@@ -1759,6 +1805,17 @@ export async function getSigningPayloadForToken(.statement,}: null,+ providerSignature:+ context.envelope.signatureLevel === "advanced" ||+ context.envelope.signatureLevel === "qualified"+ ? {+ level: context.envelope.signatureLevel,+ providerName:+ signingProviderById(context.envelope.signatureProvider ?? "")+ ?.name ?? "the signing provider",+ startUrl: `/api/signing/${encodeURIComponent(token)}/provider/start`,+ }+ : null,senderName: normalizeSenderName(context.sender),signer: {email: context.signer.email,@@ -1851,41 +1908,65 @@ async function reauthenticatePart11Signer(};}-export async function submitSigningForToken(- token: string,- input: unknown,- {- database = getDb(),- emailService: givenEmailService,- requestMeta = {},- storageService: givenStorageService,- verifiedMethods = [],- verifyPassword,- }: SubmitSigningOptions = {},-): Promise<SigningSubmitResponse> {- const parsedInput = signingSubmissionSchema.parse(input);- const context = await resolveSigningContext(token, { database });- const signerChecks = await assertSignerChecksPassed(- context,- verifiedMethods,- database,+/**+ * Makes a provider-signed revision the envelope's current one, within the+ * transaction that records the signature. Refused when another revision was+ * committed since this signer began, so no signature is ever built on a+ * revision that is no longer the latest.+ */+async function commitProviderRevision(+ tx: DbExecutor,+ envelopeId: string,+ completion: ProviderSignatureCompletion,+ now: number,+) {+ const revision = await tx.query(+ `+ UPDATE envelopes+ SET revision_key = $1, revision_sha256 = $2+ WHERE id = $3+ AND revision_sha256 IS NOT DISTINCT FROM $4+ `,+ [+ completion.revision.key,+ completion.revision.sha256,+ envelopeId,+ completion.baseSha256,+ ],);- if (signerChecks.state.consentedAt === null) {+ if (revision.rowCount !== 1) {throw new SigningMutationError(- "Agree to use electronic records and signatures before signing.",+ "The document changed while you were signing. Open your signing link again.",409,);}- const emailService = givenEmailService ?? createEmailService();- const part11Signature = await reauthenticatePart11Signer(- context,- signerChecks.state,- parsedInput.reauthentication,- { database, emailService, requestMeta, verifyPassword },+ const session = await tx.query(+ `+ UPDATE provider_signing_sessions+ SET state = 'completed', completed_at = $1+ WHERE id = $2 AND envelope_id = $3 AND state = 'signing'+ `,+ [now, completion.sessionId, envelopeId],);- const storageService = givenStorageService ?? createStorageService();++ if (session.rowCount !== 1) {+ throw new SigningMutationError("This signing session has ended.", 409);+ }+}++type SigningContext = Awaited<ReturnType<typeof resolveSigningContext>>;++/**+ * What the signer's submission changes: each of their fields' new value,+ * checked against what the field accepts, and the drawn signatures to store.+ */+function buildSignerSubmission(+ context: SigningContext,+ parsedInput: SigningSubmission,+ submittedAt: number,+) {const currentSignerId = context.signer.id;if (!currentSignerId) {@@ -1931,7 +2012,6 @@ export async function submitSigningForToken(relevantSubmissions.set(submission.fieldId, submission);}- const submittedAt = Math.floor(Date.now() / 1000);const localDateValue = formatLocalSigningDate(submittedAt,parsedInput.clientTimezoneOffsetMinutes,@@ -2066,6 +2146,76 @@ export async function submitSigningForToken(assertRadioGroupsAnswered(currentSignerFields, fieldUpdates);+ return {+ currentSignerFields,+ currentSignerId,+ drawnSignatureUploads,+ fieldUpdates,+ };+}++export async function submitSigningForToken(+ token: string,+ input: unknown,+ {+ database = getDb(),+ emailService: givenEmailService,+ providerSignature,+ requestMeta = {},+ storageService: givenStorageService,+ verifiedMethods = [],+ verifyPassword,+ }: SubmitSigningOptions = {},+): Promise<SigningSubmitResponse> {+ const parsedInput = signingSubmissionSchema.parse(input);+ const context = await resolveSigningContext(token, { database });++ // A document sent for advanced or qualified signatures is signed by each+ // signer's provider, never by a plain submit, and the other way round.+ if ((context.envelope.signatureLevel ?? "simple") === "simple") {+ if (providerSignature) {+ throw new SigningMutationError(+ "This document is not signed through a signing provider.",+ 409,+ );+ }+ } else if (!providerSignature) {+ throw new SigningMutationError(+ "This document is signed with a certificate in your own name. Continue from the signing page.",+ 409,+ );+ }++ 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 = givenEmailService ?? createEmailService();+ const part11Signature = await reauthenticatePart11Signer(+ context,+ signerChecks.state,+ parsedInput.reauthentication,+ { database, emailService, requestMeta, verifyPassword },+ );+ const storageService = givenStorageService ?? createStorageService();+ const submittedAt =+ providerSignature?.submittedAt ?? Math.floor(Date.now() / 1000);+ const {+ currentSignerFields,+ currentSignerId,+ drawnSignatureUploads,+ fieldUpdates,+ } = buildSignerSubmission(context, parsedInput, submittedAt);+let signingStatePersisted = false;try {@@ -2110,6 +2260,7 @@ export async function submitSigningForToken(authMethods: signerChecks.passed,envelopeId: context.envelope.id,part11: part11Signature,+ providerSignature: providerSignature?.evidence ?? null,signatureMethods: [...new Set([...fieldUpdates.values()]@@ -2163,6 +2314,15 @@ export async function submitSigningForToken(nextSignerDeadline = lockedEnvelope.expiresAt;+ if (providerSignature) {+ await commitProviderRevision(+ tx,+ context.envelope.id,+ providerSignature,+ submittedAt,+ );+ }+for (const update of fieldUpdates.values()) {const result = await tx.query(`@@ -2349,6 +2509,7 @@ export async function submitSigningForToken(},},{+ signedRevision: providerSignature?.revision.bytes,storageService,},);@@ -2372,6 +2533,15 @@ export async function submitSigningForToken(await withTransaction(async (tx) => {await lockSentEnvelope(context.envelope.id, tx);+ if (providerSignature) {+ await commitProviderRevision(+ tx,+ context.envelope.id,+ providerSignature,+ submittedAt,+ );+ }+for (const update of fieldUpdates.values()) {const result = await tx.query(`@@ -2541,6 +2711,78 @@ export async function submitSigningForToken(}}+export type PreparedSignerSubmission = {+ context: SigningContext;+ /** Drawn signatures by the key they will be stored under. */+ images: Map<string, Uint8Array>;+ /** The signer's fields with the submitted values, for their revision. */+ signerFields: ReturnType<typeof fieldRecordSchema.parse>[];+ /** Where the signer is in the signing order, from 0. */+ signerIndex: number;+ submittedAt: number;+};++/**+ * Checks a submission the way submitting does, without saving anything: for+ * a signer who signs through a signing provider, whose signature is made+ * before their submission is saved. See provider-signing.ts.+ */+export async function prepareSignerSubmission(+ token: string,+ input: unknown,+ {+ database = getDb(),+ submittedAt = Math.floor(Date.now() / 1000),+ verifiedMethods = [],+ }: {+ database?: DbPool;+ submittedAt?: number;+ verifiedMethods?: readonly SignerCheckMethod[];+ } = {},+): Promise<PreparedSignerSubmission> {+ const parsedInput = signingSubmissionSchema.parse(input);+ const context = await resolveSigningContext(token, { database });++ if ((context.envelope.signatureLevel ?? "simple") === "simple") {+ throw new SigningMutationError(+ "This document is not signed through a signing provider.",+ 409,+ );+ }++ 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 { currentSignerId, drawnSignatureUploads, fieldUpdates } =+ buildSignerSubmission(context, parsedInput, submittedAt);++ return {+ context,+ images: new Map(+ drawnSignatureUploads.map((upload) => [upload.imageKey, upload.body]),+ ),+ signerFields: applyFieldUpdatesToRecords(+ context.fields,+ fieldUpdates,+ submittedAt,+ ).filter((field) => field.signerId === currentSignerId),+ signerIndex: context.signers.findIndex(+ (signer) => signer.id === currentSignerId,+ ),+ submittedAt,+ };+}+export async function declineSigningForToken(token: string,input: unknown,