Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Merge main, API signing steps and the webhook changes into embedded signing
Claudeae24e26076b7
diff --cc docs/api.mdindex 01d8334,8f774da..9f33c33--- a/docs/api.md+++ b/docs/api.md@@@ -235,10 -239,9 +242,11 @@@ Every endpoint that returns an envelopenvelope past its deadline has `expired: true` until it is voided or thedeadline moves.- A signer's `status` is `pending` (not their turn yet), `notified` (their- turn, invited), `signed` or `declined`. `viewedAt` is when they first- opened it.+ turn, invited), `signed` or `declined`. `step` is their step of the signing+ order: signers who share one sign at the same time. `viewedAt` is when they+ first opened it.+- `delivery` is `email` (signers are invited by email) or `embedded` (your+ app shows the signing page, see [Embedded signing](#embedded-signing)).- `files` gives the paths to download once there is something to download:the signed PDF once the envelope is completed, and the certificate ofcompletion once it is completed, declined or voided.@@@ -248,25 -251,24 +256,25 @@@ To know when something happens without## Endpoints-| Method and path | Access | What it does |-| ---------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `GET /api/v1/me` | read | Which key this is and whom it acts as. |-| `POST /api/v1/envelopes` | write | Creates an envelope, and sends it if asked. |-| `GET /api/v1/envelopes` | read | Lists envelopes, newest first: `?status=`, `?limit=` (up to 100, 25 by default), and `?cursor=` with the `nextCursor` of the page before. |-| `GET /api/v1/envelopes/{id}` | read | One envelope. |-| `POST /api/v1/envelopes/{id}/send` | write | Sends a draft. Body: the `send` options above. |-| `POST /api/v1/envelopes/{id}/void` | write | Voids a sent envelope. Body: `{"reason": "…"}`, required on Part 11 installs. |-| `POST /api/v1/envelopes/{id}/remind` | write | Emails a reminder to each signer whose turn it is, at most once a day as in the web app. |-| `DELETE /api/v1/envelopes/{id}` | write | Deletes a draft. |-| `GET /api/v1/envelopes/{id}/events` | read | The audit trail, oldest first. |-| `GET /api/v1/envelopes/{id}/files/signed` | read | The signed PDF. |-| `GET /api/v1/envelopes/{id}/files/certificate` | read | The certificate of completion. |-| `POST /api/v1/uploads` | write | An upload URL for a PDF over 4 MB. |-| `GET /api/v1/templates` | read | Saved templates, with their roles in signing order. |-| `POST /api/v1/templates/{id}/envelopes` | write | An envelope from a template: `title`, `signers` (`name`, `email`, and `signatureMeaning` on Part 11 installs, one per role in order), and optionally `metadata` and `send`. Takes an `Idempotency-Key`. |-| `GET /api/v1/webhook-deliveries` | read | Webhook deliveries, newest first, with the payload each carried: `?since=` (ISO time), `?type=`, `?status=`, `?limit=`, `?cursor=`. See [Webhooks](#webhooks). |-| `GET /api/v1/openapi.json` | none | The OpenAPI 3.1 description of all of this, for code generators and API tools. |+| Method and path | Access | What it does |+| ----------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `GET /api/v1/me` | read | Which key this is and whom it acts as. |+| `POST /api/v1/envelopes` | write | Creates an envelope, and sends it if asked. |+| `GET /api/v1/envelopes` | read | Lists envelopes, newest first: `?status=`, `?limit=` (up to 100, 25 by default), and `?cursor=` with the `nextCursor` of the page before. |+| `GET /api/v1/envelopes/{id}` | read | One envelope. |+| `POST /api/v1/envelopes/{id}/send` | write | Sends a draft. Body: the `send` options above. |+| `POST /api/v1/envelopes/{id}/void` | write | Voids a sent envelope. Body: `{"reason": "…"}`, required on Part 11 installs. |- | `POST /api/v1/envelopes/{id}/remind` | write | Emails the signer whose turn it is a reminder, at most once a day as in the web app. |++| `POST /api/v1/envelopes/{id}/remind` | write | Emails a reminder to each signer whose turn it is, at most once a day as in the web app. |+| `POST /api/v1/envelopes/{id}/signers/{signerId}/embed-link` | write | A signing link for an embedded envelope, to show in a frame. Body: `{"origin": "https://…"}`. See [Embedded signing](#embedded-signing). |+| `DELETE /api/v1/envelopes/{id}` | write | Deletes a draft. |+| `GET /api/v1/envelopes/{id}/events` | read | The audit trail, oldest first. |+| `GET /api/v1/envelopes/{id}/files/signed` | read | The signed PDF. |+| `GET /api/v1/envelopes/{id}/files/certificate` | read | The certificate of completion. |+| `POST /api/v1/uploads` | write | An upload URL for a PDF over 4 MB. |+| `GET /api/v1/templates` | read | Saved templates, with their roles in signing order. |+| `POST /api/v1/templates/{id}/envelopes` | write | An envelope from a template: `title`, `signers` (`name`, `email`, and `signatureMeaning` on Part 11 installs, one per role in order), and optionally `metadata` and `send`. Takes an `Idempotency-Key`. |+| `GET /api/v1/webhook-deliveries` | read | Webhook deliveries, newest first, with the payload each carried: `?since=` (ISO time), `?type=`, `?status=`, `?limit=`, `?cursor=`. See [Webhooks](#webhooks). |+| `GET /api/v1/openapi.json` | none | The OpenAPI 3.1 description of all of this, for code generators and API tools. |Envelopes made through the API are ordinary envelopes: they show in the key'sadministrator's documents, can be followed and voided there, and their audit@@@ -407,111 -409,3 +415,112 @@@ and is ignored on VercelSigning secrets are stored encrypted with a key derived from`BETTER_AUTH_SECRET`. If that secret changes, deliveries fail with a noteto make a new secret in Settings.++## Embedded signing++With embedded signing, a signer signs inside your own app instead of+following a link in an email. Your app signs the person in, asks SignuDoc+for a signing link, and shows it in a frame on its page. SignuDoc emails+no invitations or reminders for these envelopes. When an envelope is+finished, the signers, copy recipients and sender get the finished document+by email as usual.++### Allow your site++An administrator lists the sites that may show signing pages, under+Settings, Organization, Embedded signing: one exact origin each, such as+`https://app.example.com`, with no path, up to 10. Until at least one site+is listed, embedded sends are refused. Adding and removing sites is in the+site audit trail. Every other page of SignuDoc can never be framed.++Only list sites you trust. Your app, not an email address, decides who+signs an embedded envelope, so the certificate of completion says the+signer was identified by the app that sent it (it names the API key) and+signed in a page on its site.++### Send for embedded signing++Send as usual with `"delivery": "embedded"` in `send`:++```json+"send": { "delivery": "embedded", "permittedUseConfirmed": true }+```++Embedded envelopes are simple electronic signatures with no extra checks:+`accessCode`, `requireEmailCode`, `signatureLevel` other than `simple`, and+Part 11 mode are refused, because your app is the check. They get no+reminders (`/remind` answers 409) and their signers cannot be corrected+after sending; void and send a new one instead.++### Show the signing page++When it is a signer's turn (their `status` is `notified`), ask for a link:++```sh+curl https://sign.example.com/api/v1/envelopes/8c1d…/signers/51ab…/embed-link \+ -H "Authorization: Bearer sdk_…" \+ -H "Content-Type: application/json" \+ -d '{"origin": "https://app.example.com"}'+```++```json+{+ "object": "embed_link",+ "url": "https://sign.example.com/embed/sign/…?origin=https%3A%2F%2Fapp.example.com",+ "expiresAt": "2026-11-18T09:15:00.000Z"+}+```++Put `url` in a frame on the page at `origin`, exactly as it came, with its+`origin` parameter:++```html+<iframe+ src="https://sign.example.com/embed/sign/…?origin=https%3A%2F%2Fapp.example.com"+ title="Sign your agreement"+ style="width: 100%; height: 800px; border: 0"+></iframe>+```++- `origin` must be one of the allowed sites, and the page opens only inside+ a frame on that site: browsers refuse to show it anywhere else.+- A link must be opened within 15 minutes. Once opened, it lasts up to 4+ hours, or until the envelope's deadline if that is sooner. Ask for a new+ link each time you show the page; a new link replaces the signer's last+ one.+- Changing the envelope's deadline never makes a link last longer, though+ an earlier deadline still cuts it short.+- Removing a site from the list stops every link made for it at once,+ even one that is open. Ask for a new link for a site that is still+ allowed.+- A signer who is not yet at their turn gets 409. With several signers, the- next one's turn starts when the one before signs: watch for the++ next step's turns start once everyone in the step before has signed, and++ signers who share a step are all `notified` at once: watch for the+ `signer.signed` webhook, whose `data.envelope` shows who is `notified`+ now.+- Asking for links is limited to 300 per 10 minutes per account.++### Hear what happened++The frame tells your page when the signer is done, with `postMessage` sent+only to your origin:++```js+window.addEventListener("message", (event) => {+ if (event.origin !== "https://sign.example.com") return;++ switch (event.data.type) {+ case "signudoc:signed": // { envelopeId, signerId }+ case "signudoc:declined": // { envelopeId, signerId }+ case "signudoc:error": // { state }: "expired", "already-signed", "completed", "voided", …+ }+});+```++Treat these messages as a hint for your page, such as closing the frame.+For your records, rely on the [webhooks](#webhooks) or the envelope's+status in the API, which are signed or authenticated.++For a page on your own machine while developing, set+`EMBED_ALLOW_HTTP_ORIGINS=1` to allow `http://` origins; it is ignored on+Vercel.diff --cc src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.tsindex 5de67b8,0000000..56850bfmode 100644,000000..100644--- a/src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.ts+++ b/src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.ts@@@ -1,54 -1,0 +1,54 @@@+import { MAX_JSON_BODY_BYTES, readBodyWithin } from "@/lib/api/body";+import { apiError, apiJson, bodyTooLarge } from "@/lib/api/http";+import { applyAccountLimit, handleApi } from "@/lib/api/route";+import { issueEmbedLink } from "@/lib/embedding";++type RouteContext = { params: Promise<{ id: string; signerId: string }> };+- // A signing link for an embedded envelope, for the signer whose turn it- // is, to show in a frame on an allowed site. Each call replaces the- // signer's last link. See docs/api.md, "Embedded signing".++// A signing link for an embedded envelope, for a signer whose turn it is,++// to show in a frame on an allowed site. Each call replaces the signer's++// last link. See docs/api.md, "Embedded signing".++export async function POST(request: Request, context: RouteContext) {+ return handleApi(request, "write", "api_embed_link_failure", async (api) => {+ const limited = await applyAccountLimit(api, {+ key: "api-embed-link",+ limit: 300,+ windowMs: 10 * 60 * 1000,+ });++ if (limited) {+ return limited;+ }++ const { id, signerId } = await context.params;+ const raw = await readBodyWithin(request, MAX_JSON_BODY_BYTES);++ if (!raw) {+ return bodyTooLarge();+ }++ // No body gets the same answer as a body without an origin, which+ // says what to send.+ const text = new TextDecoder().decode(raw);+ let body: { origin?: unknown } | null = null;++ if (text.trim()) {+ try {+ body = JSON.parse(text) as { origin?: unknown } | null;+ } catch {+ return apiError(400, "invalid_request", "The body is not valid JSON.");+ }+ }++ const link = await issueEmbedLink({+ apiKeyId: api.actor.apiKeyId,+ envelopeId: id,+ origin: body?.origin,+ signerId,+ userId: api.actor.userId,+ });++ return apiJson({ ...link, object: "embed_link" }, { status: 201 });+ });+}diff --cc src/lib/api/openapi.tsindex f2a6db4,98c1857..778b88f--- a/src/lib/api/openapi.ts+++ b/src/lib/api/openapi.ts@@@ -570,70 -581,6 +589,70 @@@ export function buildOpenApiDocumentsummary: "Send a draft",},},+ "/envelopes/{id}/signers/{signerId}/embed-link": {+ post: {+ parameters: [+ idParameter,+ {+ in: "path",+ name: "signerId",+ required: true,+ schema: { type: "string" },+ },+ ],+ requestBody: {+ content: {+ "application/json": {+ schema: {+ properties: {+ origin: {+ description:+ "The exact origin of the page that frames the signer, such as https://app.example.com. Must be allowed in Settings.",+ type: "string",+ },+ },+ required: ["origin"],+ type: "object",+ },+ },+ },+ required: true,+ },+ responses: {+ "201": {+ content: {+ "application/json": {+ schema: {+ properties: {+ expiresAt: {+ description:+ "When the link stops working if it is not opened.",+ format: "date-time",+ type: "string",+ },+ object: { const: "embed_link", type: "string" },+ url: {+ description:+ "The page to show in the frame, with its origin parameter. Use it as it is.",+ format: "uri",+ type: "string",+ },+ },+ required: ["object", "url", "expiresAt"],+ type: "object",+ },+ },+ },+ description:+ "The link to frame (url) and when it stops working if not opened (expiresAt). Each call replaces the signer's last link.",+ },+ "413": errorResponse,+ ...errors,+ },+ summary:- "Get a signing link to show in a frame, for the signer whose turn it is",++ "Get a signing link to show in a frame, for a signer whose turn it is",+ },+ },"/envelopes/{id}/void": {post: {parameters: [idParameter],diff --cc src/lib/embedding.dbtest.tsindex 3689528,0000000..59132a6mode 100644,000000..100644--- a/src/lib/embedding.dbtest.ts+++ b/src/lib/embedding.dbtest.ts@@@ -1,702 -1,0 +1,821 @@@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, afterEach, before, test } from "node:test";++import { PDFDocument } from "pdf-lib";+import type pg from "pg";++import { createApiKey } from "./api-keys.ts";+import {+ apiCreateEnvelopeSchema,+ createEnvelopeForApi,+ type ApiActor,+} from "./api/envelopes.ts";+import { openTestDatabase } from "./db/test-database.ts";++import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";+import {+ addEmbedOrigin,+ EmbeddingError,+ issueEmbedLink,+ listEmbedOrigins,+ openEmbedLink,+ readEmbedEvidence,+ removeEmbedOrigin,+} from "./embedding.ts";+import {+ changeEnvelopeDeadline,+ correctSentEnvelopeSigner,+ EnvelopeMutationError,+} from "./envelopes.ts";+import { ReminderMutationError, sendManualEnvelopeNudge } from "./reminders.ts";+import { hashOpaqueToken } from "./services/opaque-tokens.ts";+import {+ declineSigningForToken,+ getSigningPayloadForToken,++ recordSignerConsent,+ SigningAccessError,++ submitSigningForToken,+} from "./signing.ts";+import { setWebhookDrainScheduler } from "./webhooks/outbox.ts";++// Embedded signing against a real Postgres and real files. Run with+// `npm run test:db`.++const SETTINGS = [+ "APP_URL",+ "DATABASE_URL",+ "EMAIL_CAPTURE_DIR",+ "EMAIL_DRIVER",+ "STORAGE_DRIVER",+ "STORAGE_LOCAL_DIR",+] as const;+const ORIGIN = "https://app.example.com";++// A PNG of one transparent pixel, standing in for a drawn signature.++const DRAWN_SIGNATURE =++ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";++let database: pg.Pool;+let workDir: string;+let pdf: Uint8Array;+const createdUsers: string[] = [];+const settingsBefore = new Map<string, string | undefined>();++before(async () => {+ database = await openTestDatabase();+ workDir = await mkdtemp(path.join(tmpdir(), "signudoc-embed-"));++ for (const name of SETTINGS) {+ settingsBefore.set(name, process.env[name]);+ }++ process.env.APP_URL = "http://localhost:3000";+ process.env.DATABASE_URL =+ process.env.E2E_DATABASE_URL ??+ "postgres://signudoc:[email protected]:5432/signudoc_e2e";+ process.env.EMAIL_CAPTURE_DIR = path.join(workDir, "outbox");+ process.env.EMAIL_DRIVER = "capture";+ process.env.STORAGE_DRIVER = "local";+ process.env.STORAGE_LOCAL_DIR = path.join(workDir, "storage");+ setWebhookDrainScheduler(() => undefined);++ const document = await PDFDocument.create();++ document.addPage([612, 792]);+ pdf = await document.save();+ // The end-to-end run shares this database and leaves its site behind.+ await database.query(`delete from embed_allowed_origins`);+});++afterEach(async () => {+ await database.query(`delete from embed_allowed_origins`);+});++after(async () => {+ setWebhookDrainScheduler(null);+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();++ for (const [name, value] of settingsBefore) {+ if (value === undefined) {+ delete process.env[name];+ } else {+ process.env[name] = value;+ }+ }++ await rm(workDir, { force: true, recursive: true });+});++async function createAdmin(): Promise<ApiActor> {+ const userId = randomUUID();+ const email = `${userId}@example.test`;++ createdUsers.push(userId);+ await database.query(+ `+ insert into public."user" (id, name, email, role, "emailVerified")+ values ($1, 'Ops Admin', $2, 'admin', true)+ `,+ [userId, email],+ );++ const { summary } = await createApiKey(+ { email, userId },+ { expiresInDays: null, name: "Portal", scope: "write" },+ database,+ );++ return {+ apiKeyId: summary.id,+ email,+ ipAddress: null,+ name: "Ops Admin",+ userAgent: null,+ userId,+ };+}++function request(options: { accessCode?: string; delivery?: string } = {}) {+ const tag = randomUUID().slice(0, 8);++ return apiCreateEnvelopeSchema.parse({+ fields: [+ {+ height: 0.05,+ page: 1,+ signer: "a",+ type: "signature",+ width: 0.3,+ x: 0.1,+ y: 0.7,+ },+ {+ height: 0.05,+ page: 1,+ signer: "b",+ type: "signature",+ width: 0.3,+ x: 0.5,+ y: 0.7,+ },+ ],+ send: {+ delivery: options.delivery ?? "embedded",+ permittedUseConfirmed: true,+ },+ signers: [+ {+ email: `first-${tag}@example.test`,+ name: "First Signer",+ ref: "a",+ ...(options.accessCode ? { accessCode: options.accessCode } : {}),+ },+ { email: `second-${tag}@example.test`, name: "Second Signer", ref: "b" },+ ],+ title: "Portal agreement",+ });+}++async function create(+ actor: ApiActor,+ options?: Parameters<typeof request>[0],+) {+ return createEnvelopeForApi(+ actor,+ request(options),+ { body: pdf, contentType: "application/pdf", filename: "a.pdf" },+ database,+ );+}++async function invitationsTo(email: string): Promise<number> {+ const dir = process.env.EMAIL_CAPTURE_DIR!;+ const files = await readdir(dir).catch(() => [] as string[]);+ let count = 0;++ for (const file of files) {+ const message = JSON.parse(+ await readFile(path.join(dir, file), "utf8"),+ ) as {+ template?: string;+ to?: string | string[];+ };++ if (+ message.template === "signing_invitation" &&+ [message.to].flat().includes(email)+ ) {+ count += 1;+ }+ }++ return count;+}++function tokenOf(url: string): string {+ return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");+}++test("only an administrator lists sites, and only exact https origins", async () => {+ const admin = await createAdmin();++ await assert.rejects(+ addEmbedOrigin(admin, "https://app.example.com/path", { database }),+ (error: unknown) =>+ error instanceof EmbeddingError && error.statusCode === 400,+ );+ assert.equal(+ await addEmbedOrigin(admin, "https://App.Example.com/", { database }),+ ORIGIN,+ );+ // Adding it again changes nothing.+ await addEmbedOrigin(admin, ORIGIN, { database });+ assert.deepEqual(+ (await listEmbedOrigins(database)).map((row) => row.origin),+ [ORIGIN],+ );++ await database.query(`update public."user" set role = 'user' where id = $1`, [+ admin.userId,+ ]);+ await assert.rejects(+ removeEmbedOrigin(admin, ORIGIN, database),+ (error: unknown) =>+ error instanceof EmbeddingError && error.statusCode === 403,+ );+});++test("an embedded send is refused while no site is allowed, or with signer checks", async () => {+ const admin = await createAdmin();++ await assert.rejects(+ create(admin),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ /Embedded signing is off/.test(error.message),+ );++ await addEmbedOrigin(admin, ORIGIN, { database });+ await assert.rejects(+ create(admin, { accessCode: "1234" }),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ /access codes/.test(error.message),+ );+});++test("an embedded envelope emails no invitation, and the app gets a link for the signer whose turn it is", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const [first, second] = envelope.signers;++ assert.equal(envelope.delivery, "embedded");+ assert.equal(envelope.status, "sent");+ assert.equal(await invitationsTo(first!.email), 0);++ // Not yet the second signer's turn; an unlisted site is refused.+ await assert.rejects(+ issueEmbedLink(+ {+ envelopeId: envelope.id,+ origin: ORIGIN,+ signerId: second!.id,+ userId: admin.userId,+ },+ { database },+ ),+ (error: unknown) =>+ error instanceof EmbeddingError && error.statusCode === 409,+ );+ await assert.rejects(+ issueEmbedLink(+ {+ envelopeId: envelope.id,+ origin: "https://other.example.com",+ signerId: first!.id,+ userId: admin.userId,+ },+ { database },+ ),+ (error: unknown) =>+ error instanceof EmbeddingError && error.statusCode === 403,+ );+ // Someone else's envelope is not found.+ const stranger = await createAdmin();++ await assert.rejects(+ issueEmbedLink(+ {+ envelopeId: envelope.id,+ origin: ORIGIN,+ signerId: first!.id,+ userId: stranger.userId,+ },+ { database },+ ),+ (error: unknown) =>+ error instanceof EmbeddingError && error.statusCode === 404,+ );++ const link = await issueEmbedLink(+ {+ envelopeId: envelope.id,+ origin: ORIGIN,+ signerId: first!.id,+ userId: admin.userId,+ },+ { database },+ );+ const url = new URL(link.url);++ assert.equal(url.searchParams.get("origin"), ORIGIN);+ assert.match(url.pathname, /^\/embed\/sign\//);+ assert.ok(Date.parse(link.expiresAt) - Date.now() <= 15 * 60 * 1000 + 1000);++ const token = tokenOf(link.url);++ assert.deepEqual(+ await openEmbedLink(token, "https://other.example.com", database),+ {+ ok: false,+ reason: "wrong_origin",+ },+ );+ assert.deepEqual(await openEmbedLink(token, ORIGIN, database), { ok: true });++ // Opening it gave it a signing session, not just 15 minutes.+ const expiry = await database.query<{ expiresAt: number }>(+ `select signing_token_expires_at as "expiresAt" from signers where id = $1`,+ [first!.id],+ );++ assert.ok(expiry.rows[0]!.expiresAt - Date.now() / 1000 > 60 * 60);++ const payload = await getSigningPayloadForToken(token, { database });++ assert.equal(payload.signer.id, first!.id);++ // A new link replaces the last one.+ const replacement = await issueEmbedLink(+ {+ envelopeId: envelope.id,+ origin: ORIGIN,+ signerId: first!.id,+ userId: admin.userId,+ },+ { database },+ );++ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ (error: unknown) =>+ error instanceof SigningAccessError && error.state === "expired",+ );+ assert.ok(+ await getSigningPayloadForToken(tokenOf(replacement.url), { database }),+ );+});+++test("signers of an embedded envelope who share a step each get a link, and the next step is not emailed", async () => {++ const admin = await createAdmin();++++ await addEmbedOrigin(admin, ORIGIN, { database });++++ const tag = randomUUID().slice(0, 8);++ const signatureFor = (signer: string, x: number) => ({++ height: 0.05,++ page: 1,++ signer,++ type: "signature",++ width: 0.2,++ x,++ y: 0.7,++ });++ const envelope = await createEnvelopeForApi(++ admin,++ apiCreateEnvelopeSchema.parse({++ fields: [++ signatureFor("a", 0.05),++ signatureFor("b", 0.35),++ signatureFor("c", 0.65),++ ],++ send: { delivery: "embedded", permittedUseConfirmed: true },++ signers: [++ {++ email: `first-${tag}@example.test`,++ name: "First",++ ref: "a",++ step: 1,++ },++ {++ email: `second-${tag}@example.test`,++ name: "Second",++ ref: "b",++ step: 1,++ },++ {++ email: `third-${tag}@example.test`,++ name: "Third",++ ref: "c",++ step: 2,++ },++ ],++ title: "Portal agreement",++ }),++ { body: pdf, contentType: "application/pdf", filename: "a.pdf" },++ database,++ );++ const [first, second, third] = envelope.signers;++++ assert.deepEqual(++ envelope.signers.map((signer) => signer.status),++ ["notified", "notified", "pending"],++ );++++ // Both signers of the first step can have a link at once, and the next++ // step's cannot yet.++ const tokens = [++ await linkFor(admin, envelope.id, first!.id),++ await linkFor(admin, envelope.id, second!.id),++ ];++++ await assert.rejects(++ linkFor(admin, envelope.id, third!.id),++ (error: unknown) =>++ error instanceof EmbeddingError && error.statusCode === 409,++ );++++ for (const [index, token] of tokens.entries()) {++ const signerId = [first!.id, second!.id][index]!;++ const field = await database.query<{ id: string }>(++ `select id from fields where envelope_id = $1 and signer_id = $2`,++ [envelope.id, signerId],++ );++++ assert.deepEqual(await openEmbedLink(token, ORIGIN, database), {++ ok: true,++ });++ await recordSignerConsent(++ token,++ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },++ { database },++ );++ await submitSigningForToken(++ token,++ {++ clientTimezoneOffsetMinutes: 0,++ fields: [++ {++ fieldId: field.rows[0]!.id,++ imageDataUrl: DRAWN_SIGNATURE,++ inputMethod: "drawn",++ type: "signature",++ },++ ],++ },++ { database },++ );++ }++++ // The second step has started, and its signer was not emailed: the app++ // asks for their link.++ const statuses = await database.query<{ status: string }>(++ `select status from signers where id = $1`,++ [third!.id],++ );++++ assert.equal(statuses.rows[0]?.status, "notified");++ assert.equal(await invitationsTo(third!.email), 0);++ assert.ok(await linkFor(admin, envelope.id, third!.id));++});+++test("an embedded link not opened in time stops working", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const link = await issueEmbedLink(+ {+ envelopeId: envelope.id,+ origin: ORIGIN,+ signerId: envelope.signers[0]!.id,+ userId: admin.userId,+ },+ { database },+ );+ const token = tokenOf(link.url);++ await database.query(+ `update signers set signing_token_expires_at = $2 where signing_token_hash = $1`,+ [hashOpaqueToken(token), Math.floor(Date.now() / 1000) - 1],+ );+ // Opening it late does not bring it back.+ await openEmbedLink(token, ORIGIN, database);+ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ (error: unknown) =>+ error instanceof SigningAccessError && error.state === "expired",+ );+});++test("an emailed envelope gets no embed links, and an embedded one no reminders or corrections", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const emailed = await create(admin, { delivery: "email" });++ assert.equal(emailed.delivery, "email");+ // The capture check above would see an invitation if one went out.+ assert.equal(await invitationsTo(emailed.signers[0]!.email), 1);+ await assert.rejects(+ issueEmbedLink(+ {+ envelopeId: emailed.id,+ origin: ORIGIN,+ signerId: emailed.signers[0]!.id,+ userId: admin.userId,+ },+ { database },+ ),+ (error: unknown) =>+ error instanceof EmbeddingError && error.statusCode === 409,+ );++ const embedded = await create(admin);+ const sender = { senderEmail: admin.email, senderName: admin.name };++ await assert.rejects(+ sendManualEnvelopeNudge(admin.userId, embedded.id, sender, { database }),+ (error: unknown) =>+ error instanceof ReminderMutationError && error.statusCode === 409,+ );+ await assert.rejects(+ correctSentEnvelopeSigner(+ admin.userId,+ embedded.id,+ embedded.signers[0]!.id,+ { email: "[email protected]", name: "New Name" },+ sender,+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError && error.statusCode === 409,+ );+});++async function linkFor(+ admin: ApiActor,+ envelopeId: string,+ signerId: string,+ apiKeyId: string = admin.apiKeyId,+) {+ const link = await issueEmbedLink(+ { apiKeyId, envelopeId, origin: ORIGIN, signerId, userId: admin.userId },+ { database },+ );++ return tokenOf(link.url);+}++async function signerLink(signerId: string) {+ const row = await database.query<{+ expiresAt: number;+ openedAt: number | null;+ }>(+ `+ select signing_token_expires_at as "expiresAt",+ embed_link_opened_at as "openedAt"+ from signers where id = $1+ `,+ [signerId],+ );++ return row.rows[0]!;+}++test("removing a site stops the links made for it, opened or not", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const token = await linkFor(admin, envelope.id, envelope.signers[0]!.id);+ // A second link that is never opened.+ const waiting = await create(admin);+ const unopened = await linkFor(admin, waiting.id, waiting.signers[0]!.id);++ assert.deepEqual(await openEmbedLink(token, ORIGIN, database), { ok: true });+ await removeEmbedOrigin(admin, ORIGIN, database);++ const isExpired = (error: unknown) =>+ error instanceof SigningAccessError && error.state === "expired";++ assert.deepEqual(await openEmbedLink(token, ORIGIN, database), {+ ok: false,+ reason: "wrong_origin",+ });+ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ isExpired,+ );+ await assert.rejects(+ getSigningPayloadForToken(unopened, { database }),+ isExpired,+ );++ // Adding the site back revives neither old link; a new one works.+ await addEmbedOrigin(admin, ORIGIN, { database });+ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ isExpired,+ );+ await assert.rejects(+ getSigningPayloadForToken(unopened, { database }),+ isExpired,+ );++ const fresh = await linkFor(admin, envelope.id, envelope.signers[0]!.id);++ assert.ok(await getSigningPayloadForToken(fresh, { database }));+});++test("a new deadline does not bring back or stretch an embedded link", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const token = await linkFor(admin, envelope.id, signerId);+ const before = await signerLink(signerId);++ await changeEnvelopeDeadline(+ admin.userId,+ envelope.id,+ { expiresInDays: 30, senderEmail: admin.email },+ { database },+ );+ assert.equal((await signerLink(signerId)).expiresAt, before.expiresAt);++ // An expired link stays expired.+ await database.query(+ `update signers set signing_token_expires_at = $2 where id = $1`,+ [signerId, Math.floor(Date.now() / 1000) - 1],+ );+ await changeEnvelopeDeadline(+ admin.userId,+ envelope.id,+ { expiresInDays: 30, senderEmail: admin.email },+ { database },+ );+ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ (error: unknown) =>+ error instanceof SigningAccessError && error.state === "expired",+ );+});++test("an old link opened while it is being replaced does not open the new one", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const oldToken = await linkFor(admin, envelope.id, signerId);+ let replaced = false;+ // Replaces the link between openEmbedLink's read and its update.+ const racing = {+ query: async (text: string, values?: unknown[]) => {+ const result = await database.query(text, values);++ if (!replaced) {+ replaced = true;+ await linkFor(admin, envelope.id, signerId);+ }++ return result;+ },+ connect: () => database.connect(),+ } as unknown as pg.Pool;++ await openEmbedLink(oldToken, ORIGIN, racing);+ assert.ok(replaced);++ const after = await signerLink(signerId);++ assert.equal(after.openedAt, null);+ assert.ok(after.expiresAt - Date.now() / 1000 <= 15 * 60 + 1);+});++test("a signer who declines in the app is recorded as declining there", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const token = await linkFor(admin, envelope.id, signerId);++ await openEmbedLink(token, ORIGIN, database);+ await declineSigningForToken(token, { reason: "Wrong terms" }, { database });++ const declined = await database.query<{ metadata: Record<string, unknown> }>(+ `+ select metadata from audit_events+ where envelope_id = $1 and event = 'declined'+ `,+ [envelope.id],+ );++ assert.deepEqual(declined.rows[0]?.metadata.embedded, {+ apiKeyName: "Portal",+ origin: ORIGIN,+ });+});++test("the evidence names the key that asked for the link, not the one that made the envelope", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const { summary: other } = await createApiKey(+ { email: admin.email, userId: admin.userId },+ { expiresInDays: null, name: "Kiosk", scope: "write" },+ database,+ );++ await linkFor(admin, envelope.id, signerId, other.id);+ assert.deepEqual(await readEmbedEvidence(envelope.id, signerId, database), {+ apiKeyName: "Kiosk",+ origin: ORIGIN,+ });+});++test("a link opened while its site is being removed stays expired", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const token = await linkFor(admin, envelope.id, signerId);+ let removed = false;+ // Removes the site between openEmbedLink's read and its update.+ const racing = {+ query: async (text: string, values?: unknown[]) => {+ const result = await database.query(text, values);++ if (!removed) {+ removed = true;+ await removeEmbedOrigin(admin, ORIGIN, database);+ }++ return result;+ },+ connect: () => database.connect(),+ } as unknown as pg.Pool;++ assert.deepEqual(await openEmbedLink(token, ORIGIN, racing), {+ ok: false,+ reason: "wrong_origin",+ });+ assert.ok(removed);++ const after = await signerLink(signerId);++ assert.equal(after.openedAt, null);+ assert.ok(after.expiresAt < Date.now() / 1000);+});++test("a site already on a full list can be added again without an error", async () => {+ const admin = await createAdmin();+ const sites = Array.from(+ { length: 10 },+ (_, index) => `https://app${String(index)}.example.com`,+ );++ for (const site of sites) {+ await addEmbedOrigin(admin, site, { database });+ }++ assert.equal(await addEmbedOrigin(admin, sites[3]!, { database }), sites[3]!);+ await assert.rejects(+ addEmbedOrigin(admin, "https://eleventh.example.com", { database }),+ (error: unknown) =>+ error instanceof EmbeddingError && error.statusCode === 409,+ );+ assert.equal((await listEmbedOrigins(database)).length, 10);+});diff --cc src/lib/embedding.tsindex f57f475,0000000..75d6ec4mode 100644,000000..100644--- a/src/lib/embedding.ts+++ b/src/lib/embedding.ts@@@ -1,517 -1,0 +1,517 @@@+import {+ getDb,+ queryMany,+ queryOne,+ withTransaction,+ type DbExecutor,+ type DbPool,+} from "./db/connection.ts";+import { hashOpaqueToken } from "./services/opaque-tokens.ts";+import { issueSigningLink } from "./services/signing-links.ts";+import { recordSystemAuditEvent } from "./services/system-audit.ts";+import type { EnvSource } from "./utils/env.ts";+import { parseEmbedOrigin } from "./embed-origin.ts";++export { httpEmbedOriginsAllowed, parseEmbedOrigin } from "./embed-origin.ts";++// Embedded signing: an app shows SignuDoc's signing page inside its own+// site, in a frame, instead of SignuDoc emailing the signer a link. See+// db/migrations/20261118120000_embedded_signing.sql and+// 20261118120500_embed_link_api_key.sql.+//+// - An administrator lists the sites allowed to frame signing pages.+// - An envelope sent through the API with delivery "embedded" emails no+// invitations or reminders.- // - For the signer whose turn it is, the app asks the API for a link made++// - For each signer whose turn it is, the app asks the API for a link made+// for one of those sites. Each request replaces the last link. A link+// not opened within 15 minutes stops working; once opened it lasts for+// the signing session.+// - The page at /embed/sign/{token}?origin=... may only be framed by that+// origin (proxy.ts), opens only for the origin the link was made for,+// and tells the parent page when the signer signs or declines.++export const MAX_EMBED_ORIGINS = 10;+/** How long a new link waits to be opened. */+export const EMBED_LINK_TTL_SECONDS = 15 * 60;+/** How long an opened link lasts, at most: one signing session. */+export const EMBED_SESSION_SECONDS = 4 * 60 * 60;++export class EmbeddingError extends Error {+ readonly statusCode: number;++ constructor(message: string, statusCode: number) {+ super(message);+ this.name = "EmbeddingError";+ this.statusCode = statusCode;+ }+}++type Actor = {+ email: string;+ ipAddress?: string | null;+ userAgent?: string | null;+ userId: string;+};++function nowInSeconds() {+ return Math.floor(Date.now() / 1000);+}++export async function listEmbedOrigins(+ database: DbExecutor = getDb(),+): Promise<Array<{ createdAt: number; origin: string }>> {+ return queryMany(+ database,+ `+ SELECT origin, created_at AS "createdAt"+ FROM embed_allowed_origins+ ORDER BY created_at, origin+ `,+ );+}++export async function isEmbedOriginAllowed(+ origin: string,+ database: DbExecutor = getDb(),+): Promise<boolean> {+ const row = await queryOne<{ origin: string }>(+ database,+ `SELECT origin FROM embed_allowed_origins WHERE origin = $1`,+ [origin],+ );++ return row !== null;+}++export async function hasEmbedOrigins(+ database: DbExecutor = getDb(),+): Promise<boolean> {+ const row = await queryOne<{ any: boolean }>(+ database,+ `SELECT EXISTS (SELECT 1 FROM embed_allowed_origins) AS any`,+ );++ return row?.any ?? false;+}++async function requireAdmin(actor: Actor, tx: DbExecutor) {+ const row = await queryOne<{ role: string }>(+ tx,+ `SELECT role FROM "user" WHERE id = $1 FOR UPDATE`,+ [actor.userId],+ );++ if (row?.role !== "admin") {+ throw new EmbeddingError("Only an administrator can do this.", 403);+ }+}++export async function addEmbedOrigin(+ actor: Actor,+ value: unknown,+ options: { database?: DbPool; env?: EnvSource } = {},+): Promise<string> {+ const origin = parseEmbedOrigin(value, options.env);++ if (!origin) {+ throw new EmbeddingError(+ "Enter one site as https:// and its address, such as https://app.example.com, with no path.",+ 400,+ );+ }++ await withTransaction(async (tx) => {+ await requireAdmin(actor, tx);+ await tx.query(+ `LOCK TABLE embed_allowed_origins IN SHARE ROW EXCLUSIVE MODE`,+ );++ // A site already on the list takes no new place, so adding it again+ // succeeds and changes nothing, even when the list is full.+ const count = await queryOne<{ count: number }>(+ tx,+ `SELECT count(*)::int AS count FROM embed_allowed_origins WHERE origin <> $1`,+ [origin],+ );++ if ((count?.count ?? 0) >= MAX_EMBED_ORIGINS) {+ throw new EmbeddingError(+ `Up to ${String(MAX_EMBED_ORIGINS)} sites can be allowed. Remove one first.`,+ 409,+ );+ }++ const inserted = await tx.query(+ `+ INSERT INTO embed_allowed_origins (origin, created_by, created_at)+ VALUES ($1, $2, $3)+ ON CONFLICT DO NOTHING+ `,+ [origin, actor.userId, nowInSeconds()],+ );++ if ((inserted.rowCount ?? 0) === 1) {+ await recordSystemAuditEvent(+ {+ actorEmail: actor.email,+ actorUserId: actor.userId,+ event: "embed_origin_added",+ ipAddress: actor.ipAddress ?? null,+ metadata: { origin },+ userAgent: actor.userAgent ?? null,+ },+ tx,+ );+ }+ }, options.database ?? getDb());++ return origin;+}++export async function removeEmbedOrigin(+ actor: Actor,+ origin: string,+ database: DbPool = getDb(),+): Promise<void> {+ await withTransaction(async (tx) => {+ await requireAdmin(actor, tx);++ const removed = await tx.query(+ `DELETE FROM embed_allowed_origins WHERE origin = $1`,+ [origin],+ );++ if ((removed.rowCount ?? 0) === 0) {+ throw new EmbeddingError("That site is not on the list.", 404);+ }++ // Links already made for the site stop working at once, opened or+ // not. The signer's row is kept: the app can ask for a link for a+ // site that is still allowed.+ const now = nowInSeconds();++ await tx.query(+ `+ UPDATE signers+ SET signing_token_expires_at = LEAST(signing_token_expires_at, $2 - 1),+ updated_at = $2+ WHERE embed_origin = $1+ AND status = 'notified'+ AND signing_token_hash IS NOT NULL+ `,+ [origin, now],+ );++ await recordSystemAuditEvent(+ {+ actorEmail: actor.email,+ actorUserId: actor.userId,+ event: "embed_origin_removed",+ ipAddress: actor.ipAddress ?? null,+ metadata: { origin },+ userAgent: actor.userAgent ?? null,+ },+ tx,+ );+ }, database);+}++/** The path of the embedded signing page for a token and origin. */+export function embedSigningPath(token: string, origin: string): string {+ return `/embed/sign/${encodeURIComponent(token)}?${new URLSearchParams({ origin }).toString()}`;+}++/**- * A new signing link for the signer whose turn it is on an embedded++ * A new signing link for a signer whose turn it is on an embedded+ * envelope of `userId`'s, made for `origin`. Replaces the signer's last+ * link.+ */+export async function issueEmbedLink(+ input: {+ /** The key asking for the link; the signature's evidence names it. */+ apiKeyId?: string | null;+ envelopeId: string;+ origin: unknown;+ signerId: string;+ userId: string;+ },+ options: { database?: DbPool; env?: EnvSource } = {},+): Promise<{ expiresAt: string; url: string }> {+ const database = options.database ?? getDb();+ const origin = parseEmbedOrigin(input.origin, options.env);++ if (!origin) {+ throw new EmbeddingError(+ "origin: give the exact origin of the page that frames the signer, such as https://app.example.com.",+ 400,+ );+ }++ if (!(await isEmbedOriginAllowed(origin, database))) {+ throw new EmbeddingError(+ "origin: this site is not allowed to frame signing pages. An administrator can add it under Settings, Organization, Embedded signing.",+ 403,+ );+ }++ const now = nowInSeconds();++ return withTransaction(async (tx) => {+ // Holds the site on the list until this link is saved. Removing the+ // site deletes this row and then expires its links, so it waits for+ // this link and expires it too, or goes first and this is refused.+ // Taken before any other lock here, so the two cannot deadlock.+ const stillAllowed = await queryOne<{ origin: string }>(+ tx,+ `SELECT origin FROM embed_allowed_origins WHERE origin = $1 FOR SHARE`,+ [origin],+ );++ if (!stillAllowed) {+ throw new EmbeddingError(+ "origin: this site is not allowed to frame signing pages. An administrator can add it under Settings, Organization, Embedded signing.",+ 403,+ );+ }++ const envelope = await queryOne<{+ delivery: string;+ expiresAt: number | null;+ status: string;+ }>(+ tx,+ `+ SELECT delivery, status, expires_at AS "expiresAt"+ FROM envelopes WHERE id = $1 AND user_id = $2+ FOR NO KEY UPDATE+ `,+ [input.envelopeId, input.userId],+ );++ if (!envelope) {+ throw new EmbeddingError("Envelope not found.", 404);+ }++ if (envelope.delivery !== "embedded") {+ throw new EmbeddingError(+ 'This envelope\'s signers get their links by email. Send it with delivery "embedded" to sign it in your app.',+ 409,+ );+ }++ if (+ envelope.status !== "sent" ||+ (envelope.expiresAt !== null && envelope.expiresAt <= now)+ ) {+ throw new EmbeddingError(+ "This envelope is not out for signature any more.",+ 409,+ );+ }++ const signer = await queryOne<{ status: string }>(+ tx,+ `+ SELECT status FROM signers+ WHERE id = $1 AND envelope_id = $2 AND role = 'signer'+ FOR UPDATE+ `,+ [input.signerId, input.envelopeId],+ );++ if (!signer) {+ throw new EmbeddingError("Signer not found.", 404);+ }++ if (signer.status !== "notified") {+ throw new EmbeddingError(+ signer.status === "pending"+ ? "It is not this signer's turn yet."+ : "This signer has already finished.",+ 409,+ );+ }++ const lifetime = Math.min(+ EMBED_LINK_TTL_SECONDS,+ (envelope.expiresAt ?? now + EMBED_LINK_TTL_SECONDS) - now,+ );+ const link = await issueSigningLink(+ { expiresInSeconds: lifetime, issuedAt: now },+ { env: options.env },+ );++ await tx.query(+ `+ UPDATE signers+ SET signing_token_hash = $1, signing_token_expires_at = $2,+ embed_origin = $3, embed_link_opened_at = NULL, updated_at = $4,+ embed_api_key_id = $6+ WHERE id = $5+ `,+ [+ link.tokenHash,+ link.exp,+ origin,+ now,+ input.signerId,+ input.apiKeyId ?? null,+ ],+ );++ return {+ expiresAt: new Date(link.exp * 1000).toISOString(),+ url: new URL(+ embedSigningPath(link.token, origin),+ new URL(link.url).origin,+ ).toString(),+ };+ }, database);+}++export type EmbedOpenResult =+ | { ok: true }+ | { ok: false; reason: "not_embedded" | "wrong_origin" | "unknown" };++/**+ * Checks that an embedded link is opened for the site it was made for,+ * and on first opening gives it the rest of a signing session. Leaves+ * other problems (expired, already signed) to the signing page itself.+ */+export async function openEmbedLink(+ token: string,+ origin: string | null,+ database: DbPool = getDb(),+ now: number = nowInSeconds(),+): Promise<EmbedOpenResult> {+ const row = await queryOne<{+ delivery: string;+ embedLinkOpenedAt: number | null;+ embedOrigin: string | null;+ envelopeExpiresAt: number | null;+ expiresAt: number | null;+ id: string;+ originAllowed: boolean;+ }>(+ database,+ `+ SELECT s.id, s.embed_origin AS "embedOrigin",+ s.embed_link_opened_at AS "embedLinkOpenedAt",+ s.signing_token_expires_at AS "expiresAt",+ e.delivery, e.expires_at AS "envelopeExpiresAt",+ EXISTS (+ SELECT 1 FROM embed_allowed_origins a WHERE a.origin = s.embed_origin+ ) AS "originAllowed"+ FROM signers s+ JOIN envelopes e ON e.id = s.envelope_id+ WHERE s.signing_token_hash = $1+ `,+ [hashOpaqueToken(token)],+ );++ if (!row) {+ return { ok: false, reason: "unknown" };+ }++ if (row.delivery !== "embedded") {+ return { ok: false, reason: "not_embedded" };+ }++ // The site must still be on the list: removing it stops its links.+ if (!origin || row.embedOrigin !== origin || !row.originAllowed) {+ return { ok: false, reason: "wrong_origin" };+ }++ if (+ row.embedLinkOpenedAt === null &&+ row.expiresAt !== null &&+ row.expiresAt >= now+ ) {+ const sessionEnd = Math.min(+ now + EMBED_SESSION_SECONDS,+ row.envelopeExpiresAt ?? now + EMBED_SESSION_SECONDS,+ );++ const stillAllowed = await withTransaction(async (tx) => {+ // Held while the link opens, as when it is issued. Removing the site+ // deletes this row, so it either waits and then expires the opened+ // link, or went first and the link does not open.+ const site = await tx.query(+ `SELECT origin FROM embed_allowed_origins WHERE origin = $1 FOR SHARE`,+ [origin],+ );++ if ((site.rowCount ?? 0) === 0) {+ return false;+ }++ // Matched on the token too: a link replaced since the read above+ // must not be marked opened, or given a session, by the old one.+ await tx.query(+ `+ UPDATE signers+ SET embed_link_opened_at = $2,+ signing_token_expires_at = GREATEST(signing_token_expires_at, $3)+ WHERE id = $1 AND embed_link_opened_at IS NULL+ AND signing_token_hash = $4 AND signing_token_expires_at >= $2+ `,+ [row.id, now, sessionEnd, hashOpaqueToken(token)],+ );++ return true;+ }, database);++ if (!stillAllowed) {+ return { ok: false, reason: "wrong_origin" };+ }+ }++ return { ok: true };+}++/** What a signature made through an embedded link records about it. */+export async function readEmbedEvidence(+ envelopeId: string,+ signerId: string,+ database: DbExecutor = getDb(),+): Promise<{ apiKeyName: string | null; origin: string | null } | null> {+ const row = await queryOne<{+ apiKeyName: string | null;+ delivery: string;+ origin: string | null;+ }>(+ database,+ `+ SELECT e.delivery, s.embed_origin AS origin, k.name AS "apiKeyName"+ FROM envelopes e+ JOIN signers s ON s.envelope_id = e.id AND s.id = $2+ -- The key that asked for this signer's link, not the one that made+ -- the envelope.+ LEFT JOIN api_keys k ON k.id = s.embed_api_key_id+ WHERE e.id = $1+ `,+ [envelopeId, signerId],+ );++ return row?.delivery === "embedded"+ ? { apiKeyName: row.apiKeyName, origin: row.origin }+ : null;+}++/** Whether an envelope's signers sign in another app. */+export async function isEmbeddedEnvelope(+ envelopeId: string,+ database: DbExecutor = getDb(),+ ownerId?: string,+): Promise<boolean> {+ const row = await queryOne<{ delivery: string }>(+ database,+ `+ SELECT delivery FROM envelopes+ WHERE id = $1 AND ($2::text IS NULL OR user_id = $2)+ `,+ [envelopeId, ownerId ?? null],+ );++ return row?.delivery === "embedded";+}diff --cc src/lib/envelopes.tsindex e0c0370,61e9417..1a0e2fd--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@@ -128,8 -128,19 +128,20 @@@ importimport { formatEnvelopeOwner } from "./envelope-access.ts";import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";import { hashAccessCode } from "./signer-checks.ts";+ import {+ describeSignerLimit,+ getMaxSignersPerEnvelope,+ } from "./signer-limit.ts";+ import {+ firstStepSigners,+ hasSharedSigningStep,+ joinNames,+ normalizeSigningSteps,+ signingStepOf,+ SigningStepError,+ } from "./signing-steps.ts";import { escapeHtml } from "./utils/html.ts";+import { hasEmbedOrigins, isEmbeddedEnvelope } from "./embedding.ts";import { releaseSentWebhook } from "./webhooks/outbox.ts";type CreateDraftEnvelopeOptions = {@@@ -2846,42 -2904,32 +2974,54 @@@ export async function sendDraftEnvelopethrow error;}+ if (delivery === "embedded") {- // No invitation: the app asks the API for a link for each signer in- // turn (see embedding.ts). The envelope is out for signature now, so- // its envelope.sent webhook can go.++ // No invitation: the app asks the API for a link for each signer++ // whose turn it is (see embedding.ts). The envelope is out for++ // signature now, so its envelope.sent webhook can go.+ await releaseSentWebhook(envelopeId, database).catch((error: unknown) => {+ console.error(+ `Releasing the envelope.sent webhook of ${envelopeId} failed:`,+ error,+ );+ });++ return sendEnvelopeResponseSchema.parse({+ envelopeId,+ expiresAt,- notifiedSignerName: firstSigner.name,++ notifiedSignerName: describeNotifiedSigners(++ firstSigners.map((signer) => signer.name),++ ),+ redirectPath: `/envelopes/${envelopeId}`,+ sentAt,+ });+ }+- let invitationMessageId: string | undefined;+ // The first invitation decides whether the envelope went out. If it+ // fails, nothing has been delivered, and the envelope goes back to being+ // a draft. Once one has been accepted the envelope is out: a later one+ // that fails is logged, and the sender's reminder (or the automatic one)+ // sends that signer a new link.+ const invitationMessageIds = new Map<string, string | undefined>();+ let branding: Branding;try {- invitationMessageId = (- await emailService.send(- buildSigningInvitationEmail({- branding: await getBranding(),- envelopeTitle: envelope.title,- expiresAt,- senderName: input.senderName,- signerEmail: firstSigner.email,- signerName: firstSigner.name,- signingUrl: issuedLink.url,- }),- )- ).messageId;+ branding = await getBranding();+ invitationMessageIds.set(+ firstSigner.id,+ (+ await emailService.send(+ buildSigningInvitationEmail({+ branding,+ envelopeTitle: envelope.title,+ expiresAt,+ senderName: input.senderName,+ signerEmail: firstSigner.email,+ signerName: firstSigner.name,+ signingUrl: issuedLinks.get(firstSigner.id)!.url,+ }),+ )+ ).messageId,+ );} catch (error) {await withTransaction(async (tx) => {const revertedEnvelope = await tx.query(diff --cc src/lib/reminders.tsindex cfce243,8f8d5dc..64c1cdb--- a/src/lib/reminders.ts+++ b/src/lib/reminders.ts@@@ -692,35 -771,45 +793,49 @@@ export async function sendAutomaticEnvedatabase = getDb(),emailService,nowUnixTimestamp = Math.floor(Date.now() / 1000),- }: SendReminderOptions = {},+ signerId,+ }: SendReminderOptions & {+ /** One waiting signer. Left out: each waiting signer who is due. */+ signerId?: string;+ } = {},): Promise<boolean> {+ if (await isEmbeddedEnvelope(envelopeId, database)) {+ return false;+ }+- let persisted: PersistedReminder;+ const targets = signerId+ ? [signerId]+ : await listWaitingSignerIds(envelopeId, database);+ let sent = false;- try {- persisted = await persistReminder(- envelopeId,- { kind: "automatic" },- nowUnixTimestamp,+ for (const target of targets) {+ let persisted: PersistedReminder;++ try {+ persisted = await persistReminder(+ envelopeId,+ { kind: "automatic" },+ nowUnixTimestamp,+ database,+ target,+ );+ } catch (error) {+ if (error instanceof ReminderMutationError) {+ continue;+ }++ throw error;+ }++ await deliverReminder(+ persisted,+ "automatic",database,+ emailService ?? createEmailService(),);- } catch (error) {- if (error instanceof ReminderMutationError) {- return false;- }- throw error;+ sent = true;}- await deliverReminder(- persisted,- "automatic",- database,- emailService ?? createEmailService(),- );-- return true;+ return sent;}diff --cc src/lib/signing.tsindex 34869a2,9318a60..00a0683--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@@ -74,11 -74,7 +74,8 @@@ importstoreRecipientEnvelopeCertificatePdf,} from "./services/pdf-finalize.ts";import { buildSigningInvitationEmail } from "./services/signing-invitation-email.ts";+import { readEmbedEvidence } from "./embedding.ts";- import {- issueSigningLink,- type IssuedSigningLink,- } from "./services/signing-links.ts";+ import { issueSigningLink } from "./services/signing-links.ts";import { signingProviderById } from "./services/signing-providers.ts";import {buildEnvelopeCertificateKey,@@@ -1068,7 -1070,7 +1074,8 @@@ function buildDeclinedAuditEvent(inputsignerId: input.signer.id,signerName: input.signer.name,signerOrder: input.signer.signOrder,+ signingStep: signingStepOf(input.signer),+ ...(input.embedded ? { embedded: input.embedded } : {}),},userAgent: input.requestMeta.userAgent ?? null,};@@@ -2823,16 -2872,8 +2886,12 @@@ async function submitSigningOncesigningStatePersisted = true;await deleteReplacedRevision(replacedRevisionKey, storageService);- if (!nextSignerDelivery) {- throw new SigningMutationError(- "Unable to activate the next signer for this envelope.",- 500,- );- }- // Nobody to invite while others in this step are still signing.- for (const nextSignerDelivery of nextSignerDeliveries) {++ // Nobody to invite while others in this step are still signing. In++ // an embedded envelope nobody is emailed: the app starts the next++ // step's turns, and the signer.signed webhook shows who is next.++ const invitations = embedded ? [] : nextSignerDeliveries;+- // In an embedded envelope the app starts the next signer's turn:- // the signer.signed webhook shows who is next.- if (!embedded) {++ for (const nextSignerDelivery of invitations) {try {const delivery = await emailService.send(buildSigningInvitationEmail({