Skip to content

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

TypeScript

Add embedded signing: show the signing page inside an allowed app

Claude72650e989d4f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 935a6db..14c19c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,10 +30,18 @@ release says when it does.
delivery log with "Send again", a test button and secret rotation;
`GET /api/v1/webhook-deliveries` lets an app catch up. A new daily cron
job, `/api/internal/webhooks`, sends retries that are due.
+- Embedded signing: an app can send an envelope with
+ `"delivery": "embedded"` and show the signing page in a frame on its own
+ site, from a link it asks for at
+ `POST /api/v1/envelopes/{id}/signers/{signerId}/embed-link`. No invitations
+ are emailed. Only sites an administrator lists under Settings,
+ Organization, Embedded signing can frame the page, and the frame tells
+ the app with `postMessage` when the signer signs or declines. The
+ certificate of completion says the signer was identified by the app.
This changes the database: the new `api_keys`, `api_idempotency`,
-`webhook_endpoints` and `webhook_deliveries` tables and three new columns
-are added by the migrations that run on deploy.
+`webhook_endpoints`, `webhook_deliveries` and `embed_allowed_origins`
+tables and six new columns are added by the migrations that run on deploy.
## [0.3.0] - 2026-11-16
diff --git a/db/migrations/20261118120000_embedded_signing.sql b/db/migrations/20261118120000_embedded_signing.sql
new file mode 100644
index 0000000..50097ca
--- /dev/null
+++ b/db/migrations/20261118120000_embedded_signing.sql
@@ -0,0 +1,33 @@
+-- Embedded signing: an app shows the signing page inside its own site, in
+-- a frame, instead of SignuDoc emailing the signer a link.
+--
+-- envelopes.delivery
+-- * 'email' (every envelope until now): signers get their links by email.
+-- * 'embedded': sent through the API. No signing invitations or reminders
+-- are emailed; the app asks the API for a short-lived link for the
+-- signer whose turn it is and frames it on a site listed below. The
+-- finished copy is still emailed to everyone.
+--
+-- signers.embed_origin: the site the current link was made for. The page
+-- refuses to open for any other, and the certificate names it.
+-- signers.embed_link_opened_at: when the current link was first opened.
+-- An unopened link lasts 15 minutes; once opened, it lasts for the
+-- signing session.
+--
+-- embed_allowed_origins: the sites (exact origins, such as
+-- https://app.example.com) an administrator allows to frame signing
+-- pages. Empty means embedding is off.
+
+alter table public.envelopes
+ add column if not exists delivery text not null default 'email'
+ check (delivery in ('email', 'embedded'));
+
+alter table public.signers
+ add column if not exists embed_origin text,
+ add column if not exists embed_link_opened_at bigint;
+
+create table if not exists public.embed_allowed_origins (
+ origin text primary key check (length(origin) between 8 and 255),
+ created_by text references public."user"(id) on delete set null,
+ created_at bigint not null
+);
diff --git a/docs/api.md b/docs/api.md
index c22265b..428a26e 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -143,7 +143,9 @@ Things to know:
not let be signed electronically (see `/electronic-signatures` on your
install). `expiresInDays` (1 to 365) and `reminderIntervalDays` (1 to 30)
are as in the web app, and `signatureLevel` is `advanced` or `qualified` on
- installs with a signing provider.
+ installs with a signing provider. `"delivery": "embedded"` sends no
+ emails and has your app show the signing page instead (see
+ [Embedded signing](#embedded-signing)); the default is `"email"`.
- **All or nothing.** If anything about the request is wrong, a field off
its page or a signer without a signature field, nothing is kept: no
half-made draft is left behind.
@@ -199,6 +201,7 @@ Every endpoint that returns an envelope returns the same object:
"expiresAt": "2026-12-01T09:00:01.000Z",
"pageCount": 2,
"signatureLevel": "simple",
+ "delivery": "email",
"metadata": { "invoice": "INV-1042" },
"signers": [
{
@@ -225,6 +228,8 @@ Every endpoint that returns an envelope returns the same object:
- A signer's `status` is `pending` (not their turn yet), `notified` (their
turn, invited), `signed` or `declined`. `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 of
completion once it is completed, declined or voided.
@@ -234,24 +239,25 @@ To know when something happens without asking again and again, use
## 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 the signer whose turn it is a reminder, 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`, 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}/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`, 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's
administrator's documents, can be followed and voided there, and their audit
@@ -379,3 +385,105 @@ and is ignored on Vercel.
Signing secrets are stored encrypted with a key derived from
`BETTER_AUTH_SECRET`. If that secret changes, deliveries fail with a note
to 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`:
+
+```html
+<iframe
+ src="https://sign.example.com/embed/sign/…"
+ 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.
+- 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
+ `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", "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 --git a/docs/self-hosting.md b/docs/self-hosting.md
index 157d42e..d3d6cc5 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -184,6 +184,10 @@ Another app can create and send envelopes through the [SignuDoc API](api.md). An
An administrator can add webhook endpoints under Settings, Organization, Webhooks, so another app hears when an envelope is sent, viewed, signed, completed, declined, voided or expires. Deliveries are signed, retried for about two and a half days, and listed in a delivery log. Adding, changing and removing endpoints is in the site audit trail. Retries that are due are sent by the next request that changes an envelope, the next API call, or a daily cron job on `/api/internal/webhooks`, which takes the same `CRON_SECRET` as the daily cleanup. See [Webhooks](api.md#webhooks).
+### Embedded signing
+
+An app can show the signing page inside its own site, for envelopes it sends through the API with embedded delivery: no invitations are emailed, and the app says who the signer is. An administrator lists the sites allowed to do this under Settings, Organization, Embedded signing; with none listed it is off, and no page can be framed. See [Embedded signing](api.md#embedded-signing).
+
### Send the audit trail to your SIEM
Every row added to the site audit trail or to a document's audit trail is also written to the function logs, once it is saved, as one line of JSON. So are refused requests and failures worth a look. A Vercel log drain (team Settings, Drains, or an observability integration from the Vercel Marketplace such as Datadog, Axiom or Better Stack) then delivers them to your SIEM as fields it can search and alert on. Log drains are a paid Vercel feature; see Vercel's pricing page for which plans have them.
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index 107a546..ae92955 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -1,9 +1,14 @@
import { expect, test, type Page } from "@playwright/test";
import pg from "pg";
-import { e2eDatabaseUrl, e2eSetupToken } from "../playwright.config";
+import {
+ e2eDatabaseUrl,
+ e2eOutboxDir,
+ e2eSetupToken,
+} from "../playwright.config";
import { extractLink, extractLinks, waitForEmail } from "./support/outbox";
import { totpCode } from "./support/totp";
+import { startEmbedParent } from "./support/embed-parent";
import { writeSamplePdf } from "./support/sample-pdf";
import {
hasValidSignature,
@@ -1540,6 +1545,264 @@ test("an administrator makes an API key and a webhook, an app sends and download
await receiver.close();
});
+test("an app shows the signing page in its own site, only on a site an administrator allowed, and hears that it was signed", async ({
+ baseURL,
+ browser,
+ page,
+ playwright,
+}) => {
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+ let adminEmail = "";
+
+ await database.connect();
+
+ try {
+ adminEmail =
+ (
+ await database.query<{ email: string }>(
+ `select email from public."user" where role = 'admin' order by "createdAt" limit 1`,
+ )
+ ).rows[0]?.email ?? "";
+ } finally {
+ await database.end();
+ }
+
+ expect(adminEmail).not.toBe("");
+
+ const api = await playwright.request.newContext({ baseURL });
+ const portal = await startEmbedParent();
+ const stranger = await startEmbedParent();
+ let key = "";
+
+ await test.step("an administrator makes a key and allows the app's site", async () => {
+ 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("/settings");
+ await page.getByPlaceholder("For example: Billing app").fill("Portal");
+ await page.getByRole("button", { name: "Create key" }).click();
+ key =
+ (await page.getByTestId("new-api-key").locator("code").textContent()) ??
+ "";
+ expect(key).toMatch(/^sdk_/);
+ await page.getByRole("button", { name: "Done" }).click();
+
+ await page
+ .getByPlaceholder("https://app.example.com", { exact: true })
+ .fill(portal.origin);
+ await page.getByRole("button", { name: "Allow site" }).click();
+ await expect(
+ page
+ .getByRole("list", { name: "Sites allowed to embed signing" })
+ .getByText(portal.origin),
+ ).toBeVisible();
+ });
+
+ const auth = () => ({ authorization: `Bearer ${key}` });
+ const signerEmail = `embedded-signer+${String(Date.now())}@example.com`;
+ let envelopeId = "";
+ let signerId = "";
+
+ await test.step("the app sends an envelope for embedded signing, and no email goes out", async () => {
+ const pdfPath = await writeSamplePdf(
+ test.info().outputPath("embedded-agreement.pdf"),
+ );
+ const { readFile } = await import("node:fs/promises");
+ const created = await api.post("/api/v1/envelopes", {
+ headers: auth(),
+ multipart: {
+ data: JSON.stringify({
+ fields: [
+ {
+ height: 0.05,
+ page: 1,
+ signer: "client",
+ type: "signature",
+ width: 0.3,
+ x: 0.1,
+ y: 0.7,
+ },
+ ],
+ send: { delivery: "embedded", permittedUseConfirmed: true },
+ signers: [
+ { email: signerEmail, name: "Robin Portal", ref: "client" },
+ ],
+ title: "Portal service agreement",
+ }),
+ file: {
+ buffer: await readFile(pdfPath),
+ mimeType: "application/pdf",
+ name: "agreement.pdf",
+ },
+ },
+ });
+
+ expect(created.status()).toBe(201);
+
+ const envelope = (await created.json()) as {
+ delivery: string;
+ id: string;
+ signers: Array<{ id: string; status: string }>;
+ status: string;
+ };
+
+ expect(envelope).toMatchObject({
+ delivery: "embedded",
+ signers: [{ status: "notified" }],
+ status: "sent",
+ });
+ envelopeId = envelope.id;
+ signerId = envelope.signers[0]!.id;
+ });
+
+ let link = "";
+
+ await test.step("a signing link is made only for an allowed site", async () => {
+ const path = `/api/v1/envelopes/${envelopeId}/signers/${signerId}/embed-link`;
+ const refused = await api.post(path, {
+ data: { origin: stranger.origin },
+ headers: auth(),
+ });
+
+ expect(refused.status()).toBe(403);
+
+ const made = await api.post(path, {
+ data: { origin: portal.origin },
+ headers: auth(),
+ });
+
+ expect(made.status()).toBe(201);
+
+ const body = (await made.json()) as { object: string; url: string };
+
+ expect(body.object).toBe("embed_link");
+ link = body.url;
+ expect(new URL(link).searchParams.get("origin")).toBe(portal.origin);
+ });
+
+ await test.step("another site cannot frame that link", async () => {
+ const strangerPage = await page.context().newPage();
+ const refusals: string[] = [];
+
+ strangerPage.on("console", (message) => {
+ if (/frame-ancestors/.test(message.text())) {
+ refusals.push(message.text());
+ }
+ });
+ await strangerPage.goto(stranger.pageFor(link));
+ await expect.poll(() => refusals.length).toBeGreaterThan(0);
+ await expect(
+ strangerPage
+ .frameLocator("#signing")
+ .getByRole("dialog", { name: "Before you sign" }),
+ ).toHaveCount(0);
+ await strangerPage.close();
+ });
+
+ await test.step("the signer signs inside the app's page, and the app is told", async () => {
+ const context = await browser.newContext();
+ const portalPage = await context.newPage();
+
+ await portalPage.goto(portal.pageFor(link));
+
+ const frame = portalPage.frameLocator("#signing");
+ const consent = frame.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 frame.getByRole("button", { exact: true, name: "Signature" }).click();
+ await frame
+ .getByRole("dialog", { name: "Add your signature" })
+ .getByRole("button", { name: "Apply signature" })
+ .click();
+ await frame.getByRole("button", { name: "Finish" }).click();
+ await frame
+ .getByRole("dialog", { name: "Finish signing?" })
+ .getByRole("button", { name: "Finish signing" })
+ .click();
+
+ await expect
+ .poll(() =>
+ portalPage.evaluate(() =>
+ (
+ window as unknown as {
+ signudocMessages: Array<{ data: { type?: string } }>;
+ }
+ ).signudocMessages.map((message) => message.data.type),
+ ),
+ )
+ .toContain("signudoc:signed");
+
+ const messages = await portalPage.evaluate(
+ () =>
+ (
+ window as unknown as {
+ signudocMessages: Array<{ data: unknown; origin: string }>;
+ }
+ ).signudocMessages,
+ );
+
+ expect(
+ messages.find(
+ (message) =>
+ (message.data as { type?: string }).type === "signudoc:signed",
+ ),
+ ).toMatchObject({
+ data: { envelopeId, signerId, type: "signudoc:signed" },
+ origin: new URL(baseURL!).origin,
+ });
+ // The frame moves on to the embedded done page, still inside the app.
+ await expect
+ .poll(() =>
+ portalPage
+ .frames()
+ .some((child) => /\/embed\/sign\/[^/]+\/done/.test(child.url())),
+ )
+ .toBe(true);
+ await context.close();
+ });
+
+ await test.step("the envelope is completed, and the signer was never emailed an invitation", async () => {
+ await expect
+ .poll(async () => {
+ const response = await api.get(`/api/v1/envelopes/${envelopeId}`, {
+ headers: auth(),
+ });
+
+ return ((await response.json()) as { status: string }).status;
+ })
+ .toBe("completed");
+
+ const { readdir, readFile } = await import("node:fs/promises");
+ const invitations: string[] = [];
+
+ for (const file of await readdir(e2eOutboxDir)) {
+ const message = JSON.parse(
+ await readFile(`${e2eOutboxDir}/${file}`, "utf8"),
+ ) as { template?: string; to?: string | string[] };
+
+ if (
+ message.template === "signing_invitation" &&
+ [message.to].flat().includes(signerEmail)
+ ) {
+ invitations.push(file);
+ }
+ }
+
+ expect(invitations).toEqual([]);
+ });
+
+ await api.dispose();
+ await portal.close();
+ await stranger.close();
+});
+
test("two-step sign-in: an administrator sets it up and requires it of everyone", async ({
browser,
page,
diff --git a/e2e/support/embed-parent.ts b/e2e/support/embed-parent.ts
new file mode 100644
index 0000000..f753fe5
--- /dev/null
+++ b/e2e/support/embed-parent.ts
@@ -0,0 +1,42 @@
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+
+// A stand-in for an app that shows SignuDoc's signing page in a frame. It
+// serves one page that frames whatever ?src= says and keeps every message
+// the frame posts to it in window.signudocMessages.
+
+const PAGE = `<!doctype html>
+<html>
+ <head><meta charset="utf-8"><title>Customer portal</title></head>
+ <body>
+ <h1>Customer portal</h1>
+ <iframe id="signing" title="Sign your agreement" style="width:1200px;height:800px;border:0"></iframe>
+ <script>
+ window.signudocMessages = [];
+ window.addEventListener("message", (event) => {
+ window.signudocMessages.push({ data: event.data, origin: event.origin });
+ });
+ document.getElementById("signing").src =
+ new URLSearchParams(location.search).get("src") || "about:blank";
+ </script>
+ </body>
+</html>`;
+
+export async function startEmbedParent() {
+ const server = createServer((_request, response) => {
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
+ response.end(PAGE);
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+
+ const { port } = server.address() as AddressInfo;
+ const origin = `http://127.0.0.1:${String(port)}`;
+
+ return {
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
+ origin,
+ pageFor: (src: string) =>
+ `${origin}/?${new URLSearchParams({ src }).toString()}`,
+ };
+}
diff --git a/playwright.config.ts b/playwright.config.ts
index 73d925c..fc63b7e 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -74,6 +74,8 @@ export default defineConfig({
// a real Vercel Blob store, direct browser upload included.
STORAGE_DRIVER: process.env.E2E_STORAGE_DRIVER ?? "local",
STORAGE_LOCAL_DIR: path.join(e2eDataDir, "storage"),
+ // The page that frames embedded signing in the test is plain http.
+ EMBED_ALLOW_HTTP_ORIGINS: "1",
// The webhook receiver in the test listens on 127.0.0.1.
WEBHOOK_ALLOW_PRIVATE_URLS: "1",
},
diff --git a/src/app/api/admin/embed-origins/route.ts b/src/app/api/admin/embed-origins/route.ts
new file mode 100644
index 0000000..faac566
--- /dev/null
+++ b/src/app/api/admin/embed-origins/route.ts
@@ -0,0 +1,72 @@
+import { NextResponse } from "next/server";
+
+import {
+ addEmbedOrigin,
+ EmbeddingError,
+ listEmbedOrigins,
+ removeEmbedOrigin,
+} from "@/lib/embedding";
+import {
+ handleWebhookAdmin,
+ noStore,
+ readJsonObject,
+} from "@/lib/webhooks/admin-route";
+
+// The sites allowed to show signing pages in a frame (embedded signing).
+// Administrators only, not on hosted installs.
+
+function embeddingErrorResponse(error: unknown): Response {
+ if (error instanceof EmbeddingError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ throw error;
+}
+
+export function GET(request: Request) {
+ return handleWebhookAdmin(request, "embed_origin_list_failure", async () =>
+ NextResponse.json(
+ { origins: await listEmbedOrigins() },
+ { headers: noStore },
+ ),
+ );
+}
+
+export function POST(request: Request) {
+ return handleWebhookAdmin(
+ request,
+ "embed_origin_add_failure",
+ async (actor) => {
+ const body = await readJsonObject(request);
+
+ try {
+ const origin = await addEmbedOrigin(actor, body.origin);
+
+ return NextResponse.json({ origin }, { headers: noStore, status: 201 });
+ } catch (error) {
+ return embeddingErrorResponse(error);
+ }
+ },
+ );
+}
+
+export function DELETE(request: Request) {
+ return handleWebhookAdmin(
+ request,
+ "embed_origin_remove_failure",
+ async (actor) => {
+ const origin = new URL(request.url).searchParams.get("origin") ?? "";
+
+ try {
+ await removeEmbedOrigin(actor, origin);
+
+ return NextResponse.json({ removed: true }, { headers: noStore });
+ } catch (error) {
+ return embeddingErrorResponse(error);
+ }
+ },
+ );
+}
diff --git 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
new file mode 100644
index 0000000..da9d769
--- /dev/null
+++ b/src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.ts
@@ -0,0 +1,37 @@
+import { apiJson } 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".
+
+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 body = (await request.json().catch(() => null)) as {
+ origin?: unknown;
+ } | null;
+
+ const link = await issueEmbedLink({
+ envelopeId: id,
+ origin: body?.origin,
+ signerId,
+ userId: api.actor.userId,
+ });
+
+ return apiJson({ ...link, object: "embed_link" }, { status: 201 });
+ });
+}
diff --git a/src/app/embed/sign/[token]/done/page.tsx b/src/app/embed/sign/[token]/done/page.tsx
new file mode 100644
index 0000000..ecaf93b
--- /dev/null
+++ b/src/app/embed/sign/[token]/done/page.tsx
@@ -0,0 +1,19 @@
+import { SigningDoneShell } from "@/components/signing/signing-done-shell";
+
+// Where an embedded signer lands after signing. The page that frames it was
+// told already (signudoc:signed); this is what the signer sees meanwhile.
+
+type EmbedSignDonePageProps = {
+ searchParams?: Promise<{ title?: string | string[] }>;
+};
+
+export default async function EmbedSignDonePage({
+ searchParams,
+}: EmbedSignDonePageProps) {
+ const resolved = searchParams ? await searchParams : undefined;
+ const envelopeTitle = Array.isArray(resolved?.title)
+ ? resolved.title[0]
+ : resolved?.title;
+
+ return <SigningDoneShell embedded envelopeTitle={envelopeTitle} />;
+}
diff --git a/src/app/embed/sign/[token]/layout.tsx b/src/app/embed/sign/[token]/layout.tsx
new file mode 100644
index 0000000..c67f4fd
--- /dev/null
+++ b/src/app/embed/sign/[token]/layout.tsx
@@ -0,0 +1,29 @@
+import type { Metadata } from "next";
+import type { ReactNode } from "react";
+import { connection } from "next/server";
+
+import { BrandingProvider } from "@/components/layout/branding-provider";
+import { getInstallMetadata } from "@/lib/install";
+import { getBranding } from "@/lib/settings";
+
+export async function generateMetadata(): Promise<Metadata> {
+ await connection();
+
+ return getInstallMetadata();
+}
+
+// Embedded signing pages carry the name of the organization that sent the
+// document, as the emailed ones do.
+export default async function EmbeddedSigningLayout({
+ children,
+}: Readonly<{
+ children: ReactNode;
+}>) {
+ await connection();
+
+ return (
+ <BrandingProvider branding={await getBranding()}>
+ {children}
+ </BrandingProvider>
+ );
+}
diff --git a/src/app/embed/sign/[token]/page.tsx b/src/app/embed/sign/[token]/page.tsx
new file mode 100644
index 0000000..7625948
--- /dev/null
+++ b/src/app/embed/sign/[token]/page.tsx
@@ -0,0 +1,93 @@
+import { headers } from "next/headers";
+
+import { SigningShell } from "@/components/signing/signing-shell";
+import { getDb } from "@/lib/db/connection";
+import { isEmbedOriginAllowed, openEmbedLink } from "@/lib/embedding";
+import { parseEmbedOrigin } from "@/lib/embed-origin";
+import { getClientIpAddress } from "@/lib/security/request";
+import {
+ SigningAccessError,
+ SigningVerificationRequiredError,
+ getSigningPayloadForToken,
+} from "@/lib/signing";
+
+// The signing page, shown in a frame inside another app (see
+// src/lib/embedding.ts). proxy.ts lets only the ?origin= site frame it;
+// this page opens only when that is the site the link was made for.
+// Embedded signers have no extra checks, so no cookie is needed: browsers
+// do not send this site's cookies inside another site's frame.
+
+type EmbedSignPageProps = {
+ params: Promise<{ token: string }>;
+ searchParams: Promise<{ origin?: string | string[] }>;
+};
+
+export default async function EmbedSignPage({
+ params,
+ searchParams,
+}: EmbedSignPageProps) {
+ const { token } = await params;
+ const { origin: originParam } = await searchParams;
+ const origin = parseEmbedOrigin(
+ Array.isArray(originParam) ? originParam[0] : originParam,
+ );
+ const database = getDb();
+ const opened = await openEmbedLink(token, origin, database).catch(
+ () => ({ ok: false, reason: "unknown" }) as const,
+ );
+
+ if (!opened.ok) {
+ // Only an allowed site is told why; anything else learns nothing.
+ const tellOrigin =
+ origin &&
+ opened.reason === "unknown" &&
+ (await isEmbedOriginAllowed(origin, database).catch(() => false))
+ ? origin
+ : null;
+
+ return (
+ <SigningShell
+ embedOrigin={tellOrigin}
+ initialState={opened.reason === "unknown" ? "expired" : "error"}
+ key={token}
+ token={token}
+ />
+ );
+ }
+
+ let initialState:
+ "already-signed" | "declined" | "error" | "expired" | "voided" | undefined;
+ let record: Awaited<ReturnType<typeof getSigningPayloadForToken>> | null =
+ null;
+
+ try {
+ const requestHeaders = await headers();
+
+ record = await getSigningPayloadForToken(token, {
+ database,
+ requestMeta: {
+ ipAddress: getClientIpAddress(requestHeaders),
+ userAgent: requestHeaders.get("user-agent")?.trim() ?? null,
+ },
+ });
+ } catch (error) {
+ if (error instanceof SigningAccessError) {
+ initialState = error.state;
+ } else if (error instanceof SigningVerificationRequiredError) {
+ // Embedded envelopes are sent without extra checks.
+ initialState = "error";
+ } else {
+ initialState = "error";
+ }
+ }
+
+ return (
+ <SigningShell
+ embedOrigin={origin}
+ initialState={initialState}
+ key={token}
+ record={record ?? undefined}
+ token={token}
+ />
+ );
+}
diff --git a/src/components/settings/embedding-panel.tsx b/src/components/settings/embedding-panel.tsx
new file mode 100644
index 0000000..1154889
--- /dev/null
+++ b/src/components/settings/embedding-panel.tsx
@@ -0,0 +1,178 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+// The sites allowed to show SignuDoc's signing page inside their own pages
+// (embedded signing, through the API). Administrators only.
+
+const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";
+const EMBED_DOCS_URL =
+ "https://github.com/NYLLON-SOFTWARE/SignuDoc/blob/main/docs/api.md#embedded-signing";
+
+type Payload = {
+ error?: string;
+ origin?: string;
+ origins?: Array<{ createdAt: number; origin: string }>;
+} | null;
+
+export function EmbeddingPanel() {
+ const [origins, setOrigins] = useState<string[] | null>(null);
+ const [value, setValue] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const [pending, setPending] = useState<string | null>(null);
+ const [revision, setRevision] = useState(0);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ void (async () => {
+ try {
+ const response = await fetch("/api/admin/embed-origins", {
+ cache: "no-store",
+ });
+ const payload = (await response.json().catch(() => null)) as Payload;
+
+ if (!cancelled) {
+ if (response.ok && payload?.origins) {
+ setOrigins(payload.origins.map((entry) => entry.origin));
+ } else {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ }
+ }
+ } catch {
+ if (!cancelled) {
+ setError(GENERIC_ERROR_MESSAGE);
+ }
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [revision]);
+
+ async function change(method: "DELETE" | "POST", origin: string) {
+ setPending(origin);
+ setError(null);
+
+ try {
+ const response = await fetch(
+ method === "DELETE"
+ ? `/api/admin/embed-origins?${new URLSearchParams({ origin }).toString()}`
+ : "/api/admin/embed-origins",
+ method === "DELETE"
+ ? { method }
+ : {
+ body: JSON.stringify({ origin }),
+ headers: { "content-type": "application/json" },
+ method,
+ },
+ );
+ const payload = (await response.json().catch(() => null)) as Payload;
+
+ if (!response.ok) {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ if (method === "POST") {
+ setValue("");
+ }
+
+ setRevision((current) => current + 1);
+ } catch {
+ setError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setPending(null);
+ }
+ }
+
+ return (
+ <div className="space-y-5 border-t border-(--border) pt-8">
+ <div className="space-y-2">
+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">
+ Embedded signing
+ </h3>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ Let an app show the signing page inside its own site, for envelopes it
+ sends through the API with{" "}
+ <a
+ className="font-semibold text-(--accent) underline-offset-4 hover:underline"
+ href={EMBED_DOCS_URL}
+ rel="noreferrer"
+ target="_blank"
+ >
+ embedded delivery
+ </a>
+ . No invitations are emailed for those: the app signs the person in
+ and says who they are, so list only sites you trust. Every other page
+ of SignuDoc stays impossible to frame.
+ </p>
+ </div>
+
+ <div className="flex max-w-xl flex-wrap items-end gap-3">
+ <label className="grid min-w-0 flex-1 gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Site
+ </span>
+ <input
+ autoComplete="off"
+ className="field-input"
+ disabled={pending !== null}
+ inputMode="url"
+ maxLength={255}
+ name="embed-origin"
+ onChange={(event) => setValue(event.target.value)}
+ placeholder="https://app.example.com"
+ value={value}
+ />
+ </label>
+ <button
+ className="btn-quiet min-h-12 px-5 text-sm"
+ disabled={pending !== null || value.trim().length === 0}
+ onClick={() => void change("POST", value)}
+ type="button"
+ >
+ {pending === value && value ? "Adding..." : "Allow site"}
+ </button>
+ </div>
+
+ {error ? (
+ <p className="notice notice-danger max-w-2xl" role="alert">
+ {error}
+ </p>
+ ) : null}
+
+ {origins === null ? null : origins.length === 0 ? (
+ <p className="text-sm text-(--secondary)">
+ No sites yet, so embedded signing is off.
+ </p>
+ ) : (
+ <ul
+ aria-label="Sites allowed to embed signing"
+ className="grid max-w-2xl gap-2"
+ >
+ {origins.map((origin) => (
+ <li
+ className="well flex flex-wrap items-center justify-between gap-2 px-4 py-3"
+ key={origin}
+ >
+ <span className="font-mono text-sm break-all text-(--fg)">
+ {origin}
+ </span>
+ <button
+ aria-label={`Remove ${origin}`}
+ className="btn-quiet btn-quiet-danger"
+ disabled={pending !== null}
+ onClick={() => void change("DELETE", origin)}
+ type="button"
+ >
+ {pending === origin ? "Removing..." : "Remove"}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
index f7a5c21..e4f5940 100644
--- a/src/components/settings/organization-settings.tsx
+++ b/src/components/settings/organization-settings.tsx
@@ -6,6 +6,7 @@ import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
import { ApiKeysPanel } from "@/components/settings/api-keys-panel";
import { BrandingPanel } from "@/components/settings/branding-panel";
+import { EmbeddingPanel } from "@/components/settings/embedding-panel";
import { Part11Panel } from "@/components/settings/part11-panel";
import { PeoplePanel } from "@/components/settings/people-panel";
import { SecurityPanel } from "@/components/settings/security-panel";
@@ -419,6 +420,8 @@ export function OrganizationSettings({
{!values.hosted ? <WebhooksPanel /> : null}
+ {!values.hosted ? <EmbeddingPanel /> : null}
+
<SignerDataPanel />
</div>
</section>
diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsx
index b8f0e80..ee54f92 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -26,6 +26,8 @@ const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {
api_key_created: "API key created",
api_key_revoked: "API key revoked",
email_domain_changed: "Email domain changed",
+ embed_origin_added: "Site allowed to embed signing",
+ embed_origin_removed: "Site no longer allowed to embed signing",
identity_verification_revoked: "Identity confirmation taken back",
identity_verified: "Identity confirmed",
logo_changed: "Logo changed",
@@ -110,6 +112,9 @@ function describeEvent(event: SystemAuditEvent): string {
]
.filter(Boolean)
.join(", ");
+ case "embed_origin_added":
+ case "embed_origin_removed":
+ return typeof metadata.origin === "string" ? metadata.origin : "";
case "webhook_endpoint_created":
case "webhook_endpoint_changed":
case "webhook_endpoint_deleted":
diff --git a/src/components/signing/embed-parent-message.tsx b/src/components/signing/embed-parent-message.tsx
new file mode 100644
index 0000000..75766a2
--- /dev/null
+++ b/src/components/signing/embed-parent-message.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import { useEffect } from "react";
+
+// Tells the page that frames an embedded signing page what happened, once.
+// Only ever to the origin the link was made for, which the server checked
+// against the install's allowed sites, so nothing goes to a stranger.
+
+export type EmbedMessage = {
+ envelopeId?: string;
+ signerId?: string;
+ state?: string;
+ type: "signudoc:declined" | "signudoc:error" | "signudoc:signed";
+};
+
+export function postToEmbedParent(origin: string, message: EmbedMessage) {
+ if (window.parent !== window) {
+ window.parent.postMessage(message, origin);
+ }
+}
+
+export function EmbedParentMessage({
+ message,
+ origin,
+}: {
+ message: EmbedMessage;
+ origin: string;
+}) {
+ const { envelopeId, signerId, state, type } = message;
+
+ useEffect(() => {
+ postToEmbedParent(origin, { envelopeId, signerId, state, type });
+ }, [envelopeId, origin, signerId, state, type]);
+
+ return null;
+}
diff --git a/src/components/signing/signing-done-shell.tsx b/src/components/signing/signing-done-shell.tsx
index 7672eb3..9b9b13e 100644
--- a/src/components/signing/signing-done-shell.tsx
+++ b/src/components/signing/signing-done-shell.tsx
@@ -4,10 +4,15 @@ import { PublicLegalFooter } from "@/components/layout/public-legal-links";
const fallbackEnvelopeTitle = "this document";
type SigningDoneShellProps = {
+ /** Shown inside another app's page, which carries on from here. */
+ embedded?: boolean;
envelopeTitle?: string | null;
};
-export function SigningDoneShell({ envelopeTitle }: SigningDoneShellProps) {
+export function SigningDoneShell({
+ embedded = false,
+ envelopeTitle,
+}: SigningDoneShellProps) {
const resolvedEnvelopeTitle =
envelopeTitle && envelopeTitle.trim().length > 0
? envelopeTitle.trim()
@@ -60,9 +65,11 @@ export function SigningDoneShell({ envelopeTitle }: SigningDoneShellProps) {
You&apos;ll receive an email with the signed document once all
parties have signed.
</p>
- <p className="mt-8 inline-flex rounded-full bg-(--surface) px-4 py-2 text-sm font-semibold text-(--secondary)">
- You can close this tab.
- </p>
+ {embedded ? null : (
+ <p className="mt-8 inline-flex rounded-full bg-(--surface) px-4 py-2 text-sm font-semibold text-(--secondary)">
+ You can close this tab.
+ </p>
+ )}
</section>
</main>
diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsx
index fd488a4..9c82792 100644
--- a/src/components/signing/signing-live-shell.tsx
+++ b/src/components/signing/signing-live-shell.tsx
@@ -52,6 +52,7 @@ import {
isNumberEntry,
NUMBER_ENTRY_MESSAGE,
} from "@/lib/field-choices";
+import { postToEmbedParent } from "./embed-parent-message";
const typedSignatureFont =
'"Snell Roundhand", "Brush Script MT", "Segoe Script", cursive';
@@ -449,9 +450,12 @@ function describeProviderProblem(
}
export function SigningLiveShell({
+ embedOrigin = null,
record,
signatureProblem = null,
}: {
+ /** The site framing an embedded signing page, told when it is done. */
+ embedOrigin?: string | null;
record: SigningPayload;
signatureProblem?: ProviderSignatureProblem | null;
}) {
@@ -674,6 +678,14 @@ export function SigningLiveShell({
const fallbackRedirectPath = `${window.location.pathname.replace(/\/$/, "")}/done?title=${encodeURIComponent(record.envelopeTitle)}`;
+ if (embedOrigin) {
+ postToEmbedParent(embedOrigin, {
+ envelopeId: record.envelopeId,
+ signerId: record.signer.id,
+ type: "signudoc:signed",
+ });
+ }
+
window.location.assign(payload?.redirectPath ?? fallbackRedirectPath);
} catch {
setSubmitError(defaultSubmitErrorMessage);
@@ -745,6 +757,14 @@ export function SigningLiveShell({
return;
}
+ if (embedOrigin) {
+ postToEmbedParent(embedOrigin, {
+ envelopeId: record.envelopeId,
+ signerId: record.signer.id,
+ type: "signudoc:declined",
+ });
+ }
+
window.location.reload();
} catch {
setDeclineError(defaultDeclineErrorMessage);
diff --git a/src/components/signing/signing-shell.tsx b/src/components/signing/signing-shell.tsx
index db0d842..0a2a8b6 100644
--- a/src/components/signing/signing-shell.tsx
+++ b/src/components/signing/signing-shell.tsx
@@ -8,6 +8,7 @@ import type {
SigningPayload,
SigningVerificationState,
} from "@/lib/schemas/signing";
+import { EmbedParentMessage } from "./embed-parent-message";
import { SignerVerificationScreen } from "./signer-verification-screen";
import {
SigningLiveShell,
@@ -18,6 +19,11 @@ type SigningUnavailableState =
"already-signed" | "declined" | "error" | "expired" | "voided";
type SigningShellProps = {
+ /**
+ * Set on an embedded signing page: the site framing it, which is told
+ * when the signer signs or declines, or why the page cannot be used.
+ */
+ embedOrigin?: string | null;
initialState?: SigningUnavailableState;
record?: SigningPayload;
/** Set when the signer came back from a signing provider without signing. */
@@ -56,6 +62,7 @@ const tokenStateCopy: Record<
};
export function SigningShell({
+ embedOrigin = null,
initialState,
record,
signatureProblem,
@@ -64,7 +71,11 @@ export function SigningShell({
}: SigningShellProps) {
if (record) {
return (
- <SigningLiveShell record={record} signatureProblem={signatureProblem} />
+ <SigningLiveShell
+ embedOrigin={embedOrigin}
+ record={record}
+ signatureProblem={signatureProblem}
+ />
);
}
@@ -72,13 +83,26 @@ export function SigningShell({
return <SignerVerificationScreen state={verification} token={token} />;
}
- const tokenState = tokenStateCopy[initialState ?? "error"];
+ const state = initialState ?? "error";
+ const tokenState = tokenStateCopy[state];
return (
- <StandaloneStateScreen
- description={tokenState.description}
- title={tokenState.title}
- />
+ <>
+ {embedOrigin ? (
+ <EmbedParentMessage
+ message={{ state, type: "signudoc:error" }}
+ origin={embedOrigin}
+ />
+ ) : null}
+ <StandaloneStateScreen
+ description={
+ embedOrigin && state === "expired"
+ ? "Ask the app you are using for a new signing link."
+ : tokenState.description
+ }
+ title={tokenState.title}
+ />
+ </>
);
}
diff --git a/src/lib/api/envelope-view.ts b/src/lib/api/envelope-view.ts
index 99d5074..2be35de 100644
--- a/src/lib/api/envelope-view.ts
+++ b/src/lib/api/envelope-view.ts
@@ -34,6 +34,8 @@ export type ApiEnvelope = {
copyRecipients: Array<{ email: string; id: string; name: string }>;
createdAt: string;
declinedAt: string | null;
+ /** "email", or "embedded" when signers sign inside the calling app. */
+ delivery: "email" | "embedded";
expired: boolean;
expiresAt: string | null;
files: { certificate: string | null; signed: string | null };
@@ -57,6 +59,7 @@ export function isoTime(seconds: number | null | undefined): string | null {
type EnvelopeRow = {
apiMetadata: Record<string, unknown> | null;
+ delivery: "email" | "embedded";
completedAt: number | null;
createdAt: number;
declinedAt: number | null;
@@ -101,6 +104,7 @@ const ENVELOPE_COLUMNS = `
e.expires_at AS "expiresAt",
e.signature_level AS "signatureLevel",
e.api_metadata AS "apiMetadata",
+ e.delivery,
e.created_at AS "createdAt"
`;
@@ -175,6 +179,7 @@ export function toApiEnvelope(
})),
createdAt: isoTime(row.createdAt) ?? new Date(0).toISOString(),
declinedAt: isoTime(row.declinedAt),
+ delivery: row.delivery,
expired:
row.status === "sent" && row.expiresAt !== null && row.expiresAt <= now,
expiresAt: isoTime(row.expiresAt),
diff --git a/src/lib/api/envelopes.ts b/src/lib/api/envelopes.ts
index 0333be3..f243eef 100644
--- a/src/lib/api/envelopes.ts
+++ b/src/lib/api/envelopes.ts
@@ -68,6 +68,7 @@ const metadataSchema = z
);
export const apiSendOptionsSchema = z.object({
+ delivery: z.enum(["email", "embedded"]).optional(),
expiresInDays: deadlineDaysSchema.optional(),
permittedUseConfirmed: z.literal(true, {
message:
@@ -174,6 +175,7 @@ export async function sendEnvelopeForApi(
envelopeId,
{
apiKeyId: actor.apiKeyId,
+ delivery: options.delivery,
expiresInDays: options.expiresInDays,
ipAddress: actor.ipAddress,
reminderIntervalDays: options.reminderIntervalDays,
diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts
index bf88a45..52e9027 100644
--- a/src/lib/api/openapi.ts
+++ b/src/lib/api/openapi.ts
@@ -128,6 +128,7 @@ export function buildOpenApiDocument(serverUrl: string) {
},
createdAt: { format: "date-time", type: "string" },
declinedAt: isoTime,
+ delivery: { enum: ["email", "embedded"], type: "string" },
expired: { type: "boolean" },
expiresAt: isoTime,
files: {
@@ -226,6 +227,13 @@ export function buildOpenApiDocument(serverUrl: string) {
},
SendOptions: {
properties: {
+ delivery: {
+ default: "email",
+ description:
+ "embedded: signers sign inside your app (see POST /envelopes/{id}/signers/{signerId}/embed-link), and no invitations or reminders are emailed.",
+ enum: ["email", "embedded"],
+ type: "string",
+ },
expiresInDays: { maximum: 365, minimum: 1, type: "integer" },
permittedUseConfirmed: {
const: true,
@@ -424,6 +432,46 @@ export function buildOpenApiDocument(serverUrl: string) {
summary: "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": {
+ description:
+ "The link to frame (url) and when it stops working if not opened (expiresAt). Each call replaces the signer's last link.",
+ },
+ ...errors,
+ },
+ summary:
+ "Get a signing link to show in a frame, for the signer whose turn it is",
+ },
+ },
"/envelopes/{id}/void": {
post: {
parameters: [idParameter],
diff --git a/src/lib/api/route.ts b/src/lib/api/route.ts
index d42b0d2..825e2a8 100644
--- a/src/lib/api/route.ts
+++ b/src/lib/api/route.ts
@@ -7,6 +7,7 @@ import {
type RateLimitState,
} from "../auth/api-key.ts";
import { DownloadAccessError } from "../downloads.ts";
+import { EmbeddingError } from "../embedding.ts";
import {
EnvelopeDocumentAccessError,
EnvelopeMutationError,
@@ -55,6 +56,14 @@ export function apiErrorFor(error: unknown): Response | null {
: apiError(400, "invalid_request", error.message);
}
+ if (error instanceof EmbeddingError) {
+ return apiError(
+ error.statusCode,
+ codeForStatus(error.statusCode),
+ error.message,
+ );
+ }
+
if (error instanceof PendingUploadError) {
return apiError(400, "invalid_request", error.message);
}
diff --git a/src/lib/embed-origin.test.ts b/src/lib/embed-origin.test.ts
new file mode 100644
index 0000000..0875390
--- /dev/null
+++ b/src/lib/embed-origin.test.ts
@@ -0,0 +1,86 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { frameAncestorsFor, parseEmbedOrigin } from "./embed-origin.ts";
+
+test("an embed origin is one exact https site", () => {
+ const env = {};
+
+ assert.equal(
+ parseEmbedOrigin("https://app.example.com", env),
+ "https://app.example.com",
+ );
+ assert.equal(
+ parseEmbedOrigin("https://App.Example.com/", env),
+ "https://app.example.com",
+ );
+ assert.equal(
+ parseEmbedOrigin("https://app.example.com:8443", env),
+ "https://app.example.com:8443",
+ );
+
+ for (const bad of [
+ "http://app.example.com",
+ "https://app.example.com/path",
+ "https://app.example.com?x=1",
+ "https://*.example.com",
+ "https://[email protected]",
+ "app.example.com",
+ "javascript:alert(1)",
+ "",
+ null,
+ 42,
+ ]) {
+ assert.equal(parseEmbedOrigin(bad, env), null, String(bad));
+ }
+});
+
+test("plain http origins only when asked for, and never on Vercel", () => {
+ assert.equal(
+ parseEmbedOrigin("http://127.0.0.1:4000", {
+ EMBED_ALLOW_HTTP_ORIGINS: "1",
+ }),
+ "http://127.0.0.1:4000",
+ );
+ assert.equal(
+ parseEmbedOrigin("http://127.0.0.1:4000", {
+ EMBED_ALLOW_HTTP_ORIGINS: "1",
+ VERCEL: "1",
+ }),
+ null,
+ );
+});
+
+test("only an embedded signing page may be framed, and only by the site it names", () => {
+ const env = {};
+ const named = new URLSearchParams({ origin: "https://app.example.com" });
+
+ assert.equal(
+ frameAncestorsFor("/embed/sign/abc", named, env),
+ "https://app.example.com",
+ );
+ assert.equal(frameAncestorsFor("/sign/abc", named, env), "'none'");
+ assert.equal(frameAncestorsFor("/settings", named, env), "'none'");
+ assert.equal(
+ frameAncestorsFor(
+ "/embed/sign/abc",
+ new URLSearchParams({
+ origin: "https://a.example.com https://b.example.com",
+ }),
+ env,
+ ),
+ "'none'",
+ );
+ assert.equal(
+ frameAncestorsFor(
+ "/embed/sign/abc",
+ new URLSearchParams({ origin: "https://app.example.com; script-src *" }),
+ env,
+ ),
+ "'none'",
+ );
+ assert.equal(
+ frameAncestorsFor("/embed/sign/abc", new URLSearchParams(), env),
+ "'none'",
+ );
+});
diff --git a/src/lib/embed-origin.ts b/src/lib/embed-origin.ts
new file mode 100644
index 0000000..4b58621
--- /dev/null
+++ b/src/lib/embed-origin.ts
@@ -0,0 +1,71 @@
+import type { EnvSource } from "./utils/env.ts";
+
+// Reading the site that may frame an embedded signing page. Kept apart
+// from embedding.ts, which talks to the database, because proxy.ts needs
+// it on every request to /embed/sign.
+
+/**
+ * Plain-http origins, for a test page on this machine. Never on Vercel,
+ * whatever the variable says.
+ */
+export function httpEmbedOriginsAllowed(env: EnvSource = process.env) {
+ return env.EMBED_ALLOW_HTTP_ORIGINS === "1" && !env.VERCEL;
+}
+
+/**
+ * An exact origin, such as https://app.example.com, or null. Paths,
+ * queries, wildcards and user names are refused, so what is allowed is
+ * exactly one site.
+ */
+export function parseEmbedOrigin(
+ value: unknown,
+ env: EnvSource = process.env,
+): string | null {
+ if (typeof value !== "string") {
+ return null;
+ }
+
+ const trimmed = value.trim().replace(/\/$/, "");
+
+ if (trimmed.length === 0 || trimmed.length > 255 || trimmed.includes("*")) {
+ return null;
+ }
+
+ let url: URL;
+
+ try {
+ url = new URL(trimmed);
+ } catch {
+ return null;
+ }
+
+ const allowedProtocol =
+ url.protocol === "https:" ||
+ (url.protocol === "http:" && httpEmbedOriginsAllowed(env));
+
+ if (!allowedProtocol || url.username || url.password) {
+ return null;
+ }
+
+ // Nothing but the origin itself.
+ return url.origin.toLowerCase() === trimmed.toLowerCase() ? url.origin : null;
+}
+
+/**
+ * The Content-Security-Policy frame-ancestors sources for a path: the
+ * origin named in ?origin= on an embedded signing page, else none. The page
+ * itself then refuses to open unless that origin is the one its link was
+ * made for, and the link was made only for an origin an administrator
+ * allowed. So a page shows in a frame only on an allowed site.
+ */
+export function frameAncestorsFor(
+ pathname: string,
+ searchParams: URLSearchParams,
+ env: EnvSource = process.env,
+): string {
+ if (!pathname.startsWith("/embed/sign/")) {
+ return "'none'";
+ }
+
+ return parseEmbedOrigin(searchParams.get("origin"), env) ?? "'none'";
+}
diff --git a/src/lib/embedding.dbtest.ts b/src/lib/embedding.dbtest.ts
new file mode 100644
index 0000000..9c5174a
--- /dev/null
+++ b/src/lib/embedding.dbtest.ts
@@ -0,0 +1,447 @@
+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 {
+ addEmbedOrigin,
+ EmbeddingError,
+ issueEmbedLink,
+ listEmbedOrigins,
+ openEmbedLink,
+ removeEmbedOrigin,
+} from "./embedding.ts";
+import {
+ correctSentEnvelopeSigner,
+ EnvelopeMutationError,
+} from "./envelopes.ts";
+import { ReminderMutationError, sendManualEnvelopeNudge } from "./reminders.ts";
+import { hashOpaqueToken } from "./services/opaque-tokens.ts";
+import { getSigningPayloadForToken, SigningAccessError } 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";
+
+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();
+});
+
+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("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,
+ );
+});
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
new file mode 100644
index 0000000..8ecf681
--- /dev/null
+++ b/src/lib/embedding.ts
@@ -0,0 +1,439 @@
+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.
+//
+// - 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 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`,
+ );
+
+ const count = await queryOne<{ count: number }>(
+ tx,
+ `SELECT count(*)::int AS count FROM embed_allowed_origins`,
+ );
+
+ 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);
+ }
+
+ 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
+ * envelope of `userId`'s, made for `origin`. Replaces the signer's last
+ * link.
+ */
+export async function issueEmbedLink(
+ input: {
+ 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) => {
+ 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 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
+ WHERE id = $5
+ `,
+ [link.tokenHash, link.exp, origin, now, input.signerId],
+ );
+
+ 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: DbExecutor = 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;
+ }>(
+ 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"
+ 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" };
+ }
+
+ if (!origin || row.embedOrigin !== origin) {
+ 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,
+ );
+
+ await database.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
+ `,
+ [row.id, now, sessionEnd],
+ );
+ }
+
+ 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
+ LEFT JOIN api_keys k ON k.id = e.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 --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index c283d9e..a025e7a 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -124,6 +124,7 @@ import {
import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";
import { hashAccessCode } from "./signer-checks.ts";
import { escapeHtml } from "./utils/html.ts";
+import { hasEmbedOrigins, isEmbeddedEnvelope } from "./embedding.ts";
import { requestWebhookDrain } from "./webhooks/outbox.ts";
type CreateDraftEnvelopeOptions = {
@@ -143,6 +144,11 @@ type CreateDraftEnvelopeInput = {
type SendDraftEnvelopeInput = {
/** The API key that sent it, recorded in the audit trail. */
apiKeyId?: string | null;
+ /**
+ * "embedded": signers sign inside another app (see embedding.ts), so no
+ * invitations or reminders are emailed. API only. "email" by default.
+ */
+ delivery?: "email" | "embedded";
/** How many days signers get. The default applies when left out. */
expiresInDays?: number;
/** Days between automatic reminders. Null or left out means none. */
@@ -2396,6 +2402,44 @@ export async function sendDraftEnvelope(
}
}
+ const delivery = input.delivery ?? "email";
+
+ if (delivery === "embedded") {
+ if (part11) {
+ throw new EnvelopeMutationError(
+ "Part 11 envelopes are signed with the signers' own accounts on this install, so they cannot be embedded in another app.",
+ 400,
+ );
+ }
+
+ if (signatureLevel !== "simple") {
+ throw new EnvelopeMutationError(
+ "Advanced and qualified signatures send the signer to the signing provider, so they cannot be embedded in another app.",
+ 400,
+ );
+ }
+
+ if (!(await hasEmbedOrigins(database))) {
+ throw new EnvelopeMutationError(
+ "Embedded signing is off: no site is allowed to show signing pages. An administrator can add one under Settings, Organization, Embedded signing.",
+ 400,
+ );
+ }
+
+ const checks = await listSignerCheckSettings(envelopeId, database);
+
+ if (
+ [...checks.values()].some(
+ (check) => check.hasAccessCode || check.requireEmailCode,
+ )
+ ) {
+ throw new EnvelopeMutationError(
+ "Embedded signers are identified by your app, so leave out access codes and emailed codes.",
+ 400,
+ );
+ }
+ }
+
const part11SignerAccounts = new Map<string, string>();
if (part11) {
@@ -2535,6 +2579,13 @@ export async function sendDraftEnvelope(
);
}
+ if (delivery === "embedded") {
+ await tx.query(
+ `UPDATE envelopes SET delivery = 'embedded' WHERE id = $1`,
+ [envelopeId],
+ );
+ }
+
if (part11) {
await tx.query(`UPDATE envelopes SET part11 = true WHERE id = $1`, [
envelopeId,
@@ -2602,6 +2653,7 @@ export async function sendDraftEnvelope(
ipAddress: input.ipAddress ?? null,
metadata: {
...(input.apiKeyId ? { apiKeyId: input.apiKeyId } : {}),
+ ...(delivery === "embedded" ? { delivery } : {}),
// The send route refuses a send without this confirmation.
expiresAt,
reminderIntervalDays: input.reminderIntervalDays ?? null,
@@ -2627,6 +2679,20 @@ export async function sendDraftEnvelope(
throw 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.
+ requestWebhookDrain();
+
+ return sendEnvelopeResponseSchema.parse({
+ envelopeId,
+ expiresAt,
+ notifiedSignerName: firstSigner.name,
+ redirectPath: `/envelopes/${envelopeId}`,
+ sentAt,
+ });
+ }
+
let invitationMessageId: string | undefined;
try {
@@ -2865,6 +2931,14 @@ export async function correctSentEnvelopeSigner(
}: CorrectSentEnvelopeSignerOptions = {},
): Promise<CorrectSentSignerResult> {
const parsedInput = correctSentSignerSchema.parse(input);
+
+ if (await isEmbeddedEnvelope(envelopeId, database, userId)) {
+ throw new EnvelopeMutationError(
+ "This envelope is signed in another app, which says who signs. Void it and send a new one to change a signer.",
+ 409,
+ );
+ }
+
// Read settings before taking the envelope lock: an uncached read inside the
// transaction borrows a second pool connection, and overlapping corrections
// holding the others while they wait on the lock would starve it.
diff --git a/src/lib/reminders.ts b/src/lib/reminders.ts
index 75bf18c..9f34b1a 100644
--- a/src/lib/reminders.ts
+++ b/src/lib/reminders.ts
@@ -24,6 +24,7 @@ import {
} from "./services/audit.ts";
import { createEmailService, type EmailService } from "./services/email.ts";
import { buildDeadlineLine } from "./services/signing-invitation-email.ts";
+import { isEmbeddedEnvelope } from "./embedding.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
import {
formatReminderAvailableAt,
@@ -618,6 +619,15 @@ export async function sendManualEnvelopeNudge(
nowUnixTimestamp = Math.floor(Date.now() / 1000),
}: SendReminderOptions = {},
) {
+ // Its signers sign in another app, which reminds them itself. A reminder
+ // would also retire the link that app holds.
+ if (await isEmbeddedEnvelope(envelopeId, database, userId)) {
+ throw new ReminderMutationError(
+ "This envelope is signed in another app, so SignuDoc does not email its signers.",
+ 409,
+ );
+ }
+
const persisted = await persistReminder(
envelopeId,
{ ...input, kind: "manual", userId },
@@ -658,6 +668,10 @@ export async function sendAutomaticEnvelopeReminder(
nowUnixTimestamp = Math.floor(Date.now() / 1000),
}: SendReminderOptions = {},
): Promise<boolean> {
+ if (await isEmbeddedEnvelope(envelopeId, database)) {
+ return false;
+ }
+
let persisted: PersistedReminder;
try {
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index 3617d40..c29a3c4 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -917,6 +917,21 @@ function currentSignerIdentityStart(
}
/** What the record shows about how one signer was identified and agreed. */
+/**
+ * For a signature made inside another app: identity then rests on that app
+ * having signed the person in, and the certificate says so.
+ */
+function describeEmbeddedDelivery(embedded: Record<string, unknown>): string {
+ const origin =
+ typeof embedded.origin === "string" ? embedded.origin : "another site";
+ const key =
+ typeof embedded.apiKeyName === "string"
+ ? ` through the API key "${embedded.apiKeyName}"`
+ : "";
+
+ return `a signing link given to the app at ${origin}${key} (embedded signing; that app identified the signer)`;
+}
+
function describeSignerEvidence(
signer: SignerRecord,
auditEvents: readonly AuditEventRecord[],
@@ -944,8 +959,14 @@ function describeSignerEvidence(
}
}
+ const embedded =
+ signed?.metadata?.embedded && typeof signed.metadata.embedded === "object"
+ ? (signed.metadata.embedded as Record<string, unknown>)
+ : null;
const checks = [
- "possession of the emailed signing link",
+ embedded
+ ? describeEmbeddedDelivery(embedded)
+ : "possession of the emailed signing link",
...readStringArray(signed?.metadata?.authMethods).map(
(method) => AUTHENTICATION_LABELS[method] ?? method,
),
diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.ts
index ae5b5e4..3ecbcf5 100644
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@ -47,6 +47,8 @@ export const systemAuditEventTypes = [
"webhook_endpoint_created",
"webhook_endpoint_changed",
"webhook_endpoint_deleted",
+ "embed_origin_added",
+ "embed_origin_removed",
] as const;
export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 5a28d43..12f9356 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -70,6 +70,7 @@ import {
storeRecipientEnvelopeCertificatePdf,
} from "./services/pdf-finalize.ts";
import { buildSigningInvitationEmail } from "./services/signing-invitation-email.ts";
+import { readEmbedEvidence } from "./embedding.ts";
import {
issueSigningLink,
type IssuedSigningLink,
@@ -990,6 +991,7 @@ type Part11SignatureRecord = {
function buildSignedAuditEvent(input: {
authMethods: readonly SignerCheckMethod[];
+ embedded?: { apiKeyName: string | null; origin: string | null } | null;
envelopeId: string;
part11?: Part11SignatureRecord | null;
providerSignature?: ProviderSignatureEvidence | null;
@@ -1015,6 +1017,7 @@ function buildSignedAuditEvent(input: {
authMethods: [...input.authMethods],
signatureMethods: [...input.signatureMethods],
timezoneOffsetMinutes: input.timezoneOffsetMinutes,
+ ...(input.embedded ? { embedded: input.embedded } : {}),
...(input.part11 ? { part11: input.part11 } : {}),
...(input.providerSignature
? { providerSignature: input.providerSignature }
@@ -2316,6 +2319,14 @@ export async function submitSigningForToken(
): Promise<SigningSubmitResponse> {
const parsedInput = signingSubmissionSchema.parse(input);
const context = await resolveSigningContext(token, { database });
+ // Signed inside another app: no email to the next signer, and the
+ // evidence says where.
+ const embedded = context.signer.id
+ ? await readEmbedEvidence(context.envelope.id, context.signer.id, database)
+ : null;
+ const doneRedirectPath = embedded?.origin
+ ? `/embed/sign/${encodeURIComponent(token)}/done?${new URLSearchParams({ origin: embedded.origin, title: context.envelope.title }).toString()}`
+ : getSigningDoneRedirectPath(token, context.envelope.title);
// 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.
@@ -2414,6 +2425,7 @@ export async function submitSigningForToken(
const signedAuditEvent = buildSignedAuditEvent({
authMethods: signerChecks.passed,
+ embedded,
envelopeId: context.envelope.id,
part11: part11Signature,
providerSignature: providerSignature?.evidence ?? null,
@@ -2626,39 +2638,43 @@ export async function submitSigningForToken(
);
}
- try {
- const delivery = await emailService.send(
- buildSigningInvitationEmail({
- branding: await getBranding(),
- envelopeTitle: context.envelope.title,
- expiresAt: nextSignerDeadline,
- senderName: normalizeSenderName(context.sender),
- signerEmail: nextSignerDelivery.email,
- signerName: nextSignerDelivery.name,
- signingUrl: nextSignerLink.url,
- }),
- );
+ // In an embedded envelope the app starts the next signer's turn:
+ // the signer.signed webhook shows who is next.
+ if (!embedded) {
+ try {
+ const delivery = await emailService.send(
+ buildSigningInvitationEmail({
+ branding: await getBranding(),
+ envelopeTitle: context.envelope.title,
+ expiresAt: nextSignerDeadline,
+ senderName: normalizeSenderName(context.sender),
+ signerEmail: nextSignerDelivery.email,
+ signerName: nextSignerDelivery.name,
+ signingUrl: nextSignerLink.url,
+ }),
+ );
- await recordEmailSent(
- {
- envelopeId: context.envelope.id,
- messageId: delivery.messageId,
- recipient: nextSignerDelivery.email,
- signerId: nextSignerDelivery.id,
- template: "signing_invitation",
- },
- database,
- );
- } catch (error) {
- console.error(
- `Failed to send next signer invitation for envelope ${context.envelope.id} to ${nextSignerDelivery.email}:`,
- error,
- );
+ await recordEmailSent(
+ {
+ envelopeId: context.envelope.id,
+ messageId: delivery.messageId,
+ recipient: nextSignerDelivery.email,
+ signerId: nextSignerDelivery.id,
+ template: "signing_invitation",
+ },
+ database,
+ );
+ } catch (error) {
+ console.error(
+ `Failed to send next signer invitation for envelope ${context.envelope.id} to ${nextSignerDelivery.email}:`,
+ error,
+ );
+ }
}
return signingSubmitResponseSchema.parse({
envelopeId: context.envelope.id,
- redirectPath: getSigningDoneRedirectPath(token, context.envelope.title),
+ redirectPath: doneRedirectPath,
submittedAt,
});
}
@@ -2923,7 +2939,7 @@ export async function submitSigningForToken(
return signingSubmitResponseSchema.parse({
envelopeId: context.envelope.id,
- redirectPath: getSigningDoneRedirectPath(token, context.envelope.title),
+ redirectPath: doneRedirectPath,
submittedAt,
});
} catch (error) {
diff --git a/src/proxy.ts b/src/proxy.ts
index b08f169..aab91af 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -1,6 +1,7 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
+import { frameAncestorsFor } from "@/lib/embed-origin";
import { supportsDirectUploads } from "@/lib/services/storage/driver";
const DEFAULT_PERMISSIONS_POLICY = [
@@ -48,13 +49,13 @@ function resolveBlobUploadSource() {
return `${apiUrl.replace(/\/+$/, "")}/`;
}
-function buildContentSecurityPolicy() {
+function buildContentSecurityPolicy(frameAncestors: string) {
const preview = isVercelPreview();
const botProtection = process.env.NEXT_PUBLIC_BOTID === "1";
const directives: Array<[name: string, sources: Array<string | false>]> = [
["default-src", ["'self'"]],
["base-uri", ["'self'"]],
- ["frame-ancestors", ["'none'"]],
+ ["frame-ancestors", [frameAncestors]],
["form-action", ["'self'"]],
["object-src", ["'none'"]],
[
@@ -119,12 +120,26 @@ function buildContentSecurityPolicy() {
.join("; ");
}
-function applySecurityHeaders(response: NextResponse, pathname: string) {
- response.headers.set("Content-Security-Policy", buildContentSecurityPolicy());
+function applySecurityHeaders(
+ response: NextResponse,
+ pathname: string,
+ searchParams: URLSearchParams,
+) {
+ // Only an embedded signing page may be framed, and only by the site its
+ // link names (see src/lib/embed-origin.ts). Everything else, never.
+ const frameAncestors = frameAncestorsFor(pathname, searchParams);
+
+ response.headers.set(
+ "Content-Security-Policy",
+ buildContentSecurityPolicy(frameAncestors),
+ );
response.headers.set("Permissions-Policy", DEFAULT_PERMISSIONS_POLICY);
response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
response.headers.set("X-Content-Type-Options", "nosniff");
- response.headers.set("X-Frame-Options", "DENY");
+
+ if (frameAncestors === "'none'") {
+ response.headers.set("X-Frame-Options", "DENY");
+ }
if (isProductionEnvironment()) {
response.headers.set(
@@ -135,6 +150,7 @@ function applySecurityHeaders(response: NextResponse, pathname: string) {
if (
!pathname.startsWith("/sign/") &&
+ !pathname.startsWith("/embed/sign/") &&
!pathname.startsWith("/api/signing/") &&
!pathname.startsWith("/api/download/") &&
!pathname.startsWith("/download/")
@@ -161,7 +177,11 @@ function applySecurityHeaders(response: NextResponse, pathname: string) {
export function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
- return applySecurityHeaders(NextResponse.next(), pathname);
+ return applySecurityHeaders(
+ NextResponse.next(),
+ pathname,
+ request.nextUrl.searchParams,
+ );
}
export const config = {