Skip to content

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

TypeScript

Add the /api/v1 envelope endpoints

Claude293dfb5566d9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b29149c..bfdca00 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,9 +16,15 @@ release says when it does.
be read-only, can expire, and stop working when revoked or when their
administrator stops being one. `GET /api/v1/me` checks a key works. See
[docs/api.md](docs/api.md).
-
-This changes the database: the new `api_keys` table is added by the
-migration that runs on deploy.
+- API endpoints under `/api/v1`: create an envelope from a PDF with its
+ signers, copy recipients and fields, and send it, in one call (all or
+ nothing, safe to retry with an `Idempotency-Key`); send, void, remind and
+ delete; list and read envelopes and their audit trail; download the signed
+ PDF and the certificate; start an envelope from a template; upload PDFs
+ over 4 MB straight to Blob. `GET /api/v1/openapi.json` describes it all.
+
+This changes the database: the new `api_keys` and `api_idempotency` tables
+and three new columns are added by the migrations that run on deploy.
## [0.3.0] - 2026-11-16
diff --git a/db/migrations/20261118100000_api_envelopes.sql b/db/migrations/20261118100000_api_envelopes.sql
new file mode 100644
index 0000000..f1dd3c5
--- /dev/null
+++ b/db/migrations/20261118100000_api_envelopes.sql
@@ -0,0 +1,34 @@
+-- What the public API (/api/v1) keeps beyond what the web app does.
+--
+-- * envelopes.api_key_id: the key that created the envelope, kept after the
+-- key is revoked so the record can always say how it was made. Null for
+-- envelopes made in the web app.
+-- * envelopes.api_metadata: up to 2 KB of JSON the calling app sets when it
+-- creates the envelope, returned in every response, so the app can match
+-- the envelope to its own records.
+-- * signers.api_ref: the name the calling app gave the signer in the create
+-- request, returned with the signer.
+-- * api_idempotency: the first response to a request sent with an
+-- Idempotency-Key header, for 24 hours, so a retried request gets the
+-- same answer instead of creating or sending a second envelope. A row
+-- with no response yet is a request still being worked on.
+
+alter table public.envelopes
+ add column if not exists api_key_id text,
+ add column if not exists api_metadata jsonb;
+
+alter table public.signers
+ add column if not exists api_ref text;
+
+create table if not exists public.api_idempotency (
+ api_key_id text not null,
+ idempotency_key text not null check (length(idempotency_key) between 1 and 255),
+ request_hash text not null check (length(request_hash) = 64),
+ status_code integer,
+ response jsonb,
+ created_at bigint not null,
+ primary key (api_key_id, idempotency_key)
+);
+
+create index if not exists api_idempotency_created_at_idx
+ on public.api_idempotency (created_at);
diff --git a/docs/api.md b/docs/api.md
index a993416..e60496d 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1,7 +1,8 @@
# The SignuDoc API
-Another app can use SignuDoc through its API: check a key works now, and
-create, send and track envelopes as the next releases add those endpoints.
+Another app can use SignuDoc through its API: create an envelope from a
+PDF, send it, follow it, and download the signed PDF and the certificate of
+completion.
Everything here runs inside your own install; nothing goes through a
service of ours.
@@ -87,12 +88,170 @@ stands:
- `RateLimit-Remaining`: requests left in it.
- `RateLimit-Reset`: seconds until the window starts again.
-The limits the web app has on creating and sending envelopes apply to keys
-too. An address that sends 30 bad keys in 10 minutes is turned away until
+On top of that, each key may create 60 envelopes in 10 minutes and send 100
+in an hour. Your email provider's own limits usually bite first: Resend's
+free plan sends 100 emails a day. An address that sends 30 bad keys in 10 minutes is turned away until
the 10 minutes are up.
+## A first envelope in one call
+
+Upload the PDF, name the signers, place the fields, and send, all at once.
+`data` is the envelope as JSON:
+
+```sh
+curl https://sign.example.com/api/v1/envelopes \
+ -H "Authorization: Bearer sdk_…" \
+ -H "Idempotency-Key: order-1042" \
+ -F 'data={
+ "title": "Service agreement",
+ "signers": [
+ { "ref": "client", "name": "Casey Client", "email": "[email protected]" }
+ ],
+ "fields": [
+ { "signer": "client", "type": "signature", "page": 1,
+ "x": 0.1, "y": 0.8, "width": 0.3, "height": 0.05 },
+ { "signer": "client", "type": "date", "page": 1,
+ "x": 0.5, "y": 0.8, "width": 0.2, "height": 0.03 }
+ ],
+ "metadata": { "invoice": "INV-1042" },
+ "send": { "expiresInDays": 14, "permittedUseConfirmed": true }
+ }'
+```
+
+The answer is the envelope (see [The envelope](#the-envelope)), with status
+`sent`, and the first signer has their invitation email. Leave out `send` to
+make a draft and send it later with `POST /api/v1/envelopes/{id}/send`.
+
+Things to know:
+
+- **Signers** sign in the order given. Each has a `ref`, your own name for
+ them (letters, digits, `.`, `_`, `:` and `-`), which fields use to say whose
+ they are and which comes back with the signer. Up to 10 signers, and up to
+ 10 `copyRecipients` (`name`, `email`) who get the finished document.
+ `accessCode` and `requireEmailCode: true` add the same extra checks the web
+ app offers.
+- **Fields** are placed on a page by fractions of its width and height from
+ its top left corner: `"x": 0.1, "y": 0.8` is 10% in from the left and 80%
+ down. Types: `signature`, `initials`, `date`, `text`, `checkbox`, `number`,
+ `dropdown` (with `options`), `radio` (buttons with one `groupId` are one
+ question). `required` is true unless set to false. Every signer needs at
+ least one `signature` field.
+- **Sending** needs `"permittedUseConfirmed": true`: your app confirms, as the
+ web app's send button asks a person to, that the envelope is an ordinary
+ business agreement and not one of the kinds of document that the law does
+ 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.
+- **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.
+- **`metadata`** is up to 2 KB of JSON of your own, returned with the
+ envelope, for matching it to your records.
+- **`Idempotency-Key`** makes a retry safe. A request with a key SignuDoc has
+ seen in the last 24 hours gets the first answer again (with the header
+ `Idempotent-Replayed: true`) instead of making a second envelope. The same
+ key with a different request is refused with 422. Use one key per thing
+ you mean to send, such as the invoice number.
+
+### PDFs over 4 MB
+
+On Vercel a request to the app can carry at most 4.5 MB, so a bigger PDF (up
+to 20 MB) goes straight to storage first:
+
+```sh
+curl -X POST https://sign.example.com/api/v1/uploads -H "Authorization: Bearer sdk_…"
+# {"uploadId": "…", "url": "https://…", "method": "PUT",
+# "headers": {"content-type": "application/pdf"}, "expiresAt": "…"}
+
+curl -X PUT "<url>" -H "content-type: application/pdf" --data-binary @big.pdf
+```
+
+Then create the envelope with JSON instead of a form, naming the upload:
+
+```sh
+curl https://sign.example.com/api/v1/envelopes \
+ -H "Authorization: Bearer sdk_…" -H "content-type: application/json" \
+ -d '{ "uploadId": "…", "filename": "big.pdf", "title": "…", "signers": […], "fields": […] }'
+```
+
+The upload URL works for 10 minutes, and an upload that is never used is
+deleted after a day. Installs that keep files on their own disk (not on
+Vercel) do not need this and answer 404: send any size in the form.
+
+## The envelope
+
+Every endpoint that returns an envelope returns the same object:
+
+```json
+{
+ "object": "envelope",
+ "id": "8c1d…",
+ "title": "Service agreement",
+ "status": "sent",
+ "expired": false,
+ "createdAt": "2026-11-17T09:00:00.000Z",
+ "sentAt": "2026-11-17T09:00:01.000Z",
+ "completedAt": null,
+ "declinedAt": null,
+ "voidedAt": null,
+ "expiresAt": "2026-12-01T09:00:01.000Z",
+ "pageCount": 2,
+ "signatureLevel": "simple",
+ "metadata": { "invoice": "INV-1042" },
+ "signers": [
+ {
+ "id": "51ab…",
+ "ref": "client",
+ "name": "Casey Client",
+ "email": "[email protected]",
+ "order": 1,
+ "status": "notified",
+ "viewedAt": null,
+ "signedAt": null,
+ "declinedAt": null,
+ "declineReason": null
+ }
+ ],
+ "copyRecipients": [],
+ "files": { "signed": null, "certificate": null }
+}
+```
+
+- `status` is `draft`, `sent`, `completed`, `declined` or `voided`. A sent
+ envelope past its deadline has `expired: true` until it is voided or the
+ deadline moves.
+- A signer's `status` is `pending` (not their turn yet), `notified` (their
+ turn, invited), `signed` or `declined`. `viewedAt` is when they first
+ opened it.
+- `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.
+
+To know when something happens without asking again and again, use
+webhooks (coming in the next release).
+
## Endpoints
-| Method and path | Access | What it does |
-| ---------------- | ------ | -------------------------------------- |
-| `GET /api/v1/me` | read | Which key this is and whom it acts as. |
+| 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/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
+trail records the key that sent them.
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index 885fbea..9dfd886 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -1216,8 +1216,9 @@ test("a signer signs with a qualified signature in their own name, through the s
});
});
-test("an administrator makes an API key, the API accepts it, and revoking it stops it", async ({
+test("an administrator makes an API key, an app sends and downloads an envelope with it, and revoking it stops it", async ({
baseURL,
+ browser,
page,
playwright,
}) => {
@@ -1284,6 +1285,161 @@ test("an administrator makes an API key, the API accepts it, and revoking it sto
});
});
+ await test.step("an app creates and sends an envelope, a signer signs, and the app downloads it", async () => {
+ const auth = { authorization: `Bearer ${key}` };
+ const signerEmail = `api-signer+${String(Date.now())}@example.com`;
+ const pdfPath = await writeSamplePdf(
+ test.info().outputPath("api-agreement.pdf"),
+ );
+ const { readFile } = await import("node:fs/promises");
+ const data = {
+ fields: [
+ {
+ height: 0.05,
+ page: 1,
+ signer: "client",
+ type: "signature",
+ width: 0.3,
+ x: 0.1,
+ y: 0.7,
+ },
+ ],
+ metadata: { invoice: "INV-1042" },
+ send: { expiresInDays: 7, permittedUseConfirmed: true },
+ signers: [{ email: signerEmail, name: "Casey Client", ref: "client" }],
+ title: "API service agreement",
+ };
+ const created = await api.post("/api/v1/envelopes", {
+ headers: { ...auth, "idempotency-key": "order-1042" },
+ multipart: {
+ data: JSON.stringify(data),
+ file: {
+ buffer: await readFile(pdfPath),
+ mimeType: "application/pdf",
+ name: "agreement.pdf",
+ },
+ },
+ });
+
+ expect(created.status()).toBe(201);
+
+ const envelope = (await created.json()) as {
+ id: string;
+ metadata: unknown;
+ signers: Array<{ ref: string; status: string }>;
+ status: string;
+ };
+
+ expect(envelope).toMatchObject({
+ metadata: { invoice: "INV-1042" },
+ signers: [{ ref: "client", status: "notified" }],
+ status: "sent",
+ });
+
+ // The same request again is the same envelope, not a second one.
+ const retried = await api.post("/api/v1/envelopes", {
+ headers: { ...auth, "idempotency-key": "order-1042" },
+ multipart: {
+ data: JSON.stringify(data),
+ file: {
+ buffer: await readFile(pdfPath),
+ mimeType: "application/pdf",
+ name: "agreement.pdf",
+ },
+ },
+ });
+
+ expect(retried.headers()["idempotent-replayed"]).toBe("true");
+ expect(((await retried.json()) as { id: string }).id).toBe(envelope.id);
+
+ const invitation = await waitForEmail({
+ template: "signing_invitation",
+ to: signerEmail,
+ });
+ const signer = await browser.newContext();
+ const signerPage = await signer.newPage();
+
+ await signerPage.goto(extractLink(invitation.text, "/sign/"));
+
+ const consent = signerPage.getByRole("dialog", { name: "Before you sign" });
+
+ await consent
+ .getByRole("checkbox", {
+ name: "I agree to use electronic records and signatures",
+ })
+ .check();
+ await consent.getByRole("button", { name: "Agree and continue" }).click();
+ await signerPage
+ .getByRole("button", { exact: true, name: "Signature" })
+ .click();
+ await signerPage
+ .getByRole("dialog", { name: "Add your signature" })
+ .getByRole("button", { name: "Apply signature" })
+ .click();
+ await signerPage.getByRole("button", { name: "Finish" }).click();
+ await signerPage
+ .getByRole("dialog", { name: "Finish signing?" })
+ .getByRole("button", { name: "Finish signing" })
+ .click();
+ await expect(signerPage).toHaveURL(/\/sign\/[^/]+\/done/);
+ await signer.close();
+
+ const finished = await api.get(`/api/v1/envelopes/${envelope.id}`, {
+ headers: auth,
+ });
+
+ expect(await finished.json()).toMatchObject({
+ files: {
+ certificate: `/api/v1/envelopes/${envelope.id}/files/certificate`,
+ signed: `/api/v1/envelopes/${envelope.id}/files/signed`,
+ },
+ signers: [{ status: "signed" }],
+ status: "completed",
+ });
+
+ for (const file of ["signed", "certificate"]) {
+ const download = await api.get(
+ `/api/v1/envelopes/${envelope.id}/files/${file}`,
+ { headers: auth },
+ );
+
+ expect(download.status()).toBe(200);
+ expect(download.headers()["content-type"]).toContain("application/pdf");
+ expect((await download.body()).subarray(0, 5).toString()).toBe("%PDF-");
+ }
+
+ const events = (await (
+ await api.get(`/api/v1/envelopes/${envelope.id}/events`, {
+ headers: auth,
+ })
+ ).json()) as { data: Array<{ event: string }> };
+
+ expect(events.data.map((event) => event.event)).toEqual(
+ expect.arrayContaining([
+ "created",
+ "sent",
+ "viewed",
+ "signed",
+ "completed",
+ ]),
+ );
+
+ const list = (await (
+ await api.get("/api/v1/envelopes?status=completed&limit=5", {
+ headers: auth,
+ })
+ ).json()) as { data: Array<{ id: string }> };
+
+ expect(list.data.map((item) => item.id)).toContain(envelope.id);
+
+ const openapi = await api.get("/api/v1/openapi.json");
+
+ expect(openapi.status()).toBe(200);
+ expect(((await openapi.json()) as { openapi: string }).openapi).toBe(
+ "3.1.0",
+ );
+ });
+
await test.step("a revoked key is refused at once", async () => {
await page.getByRole("button", { name: "Revoke Billing app" }).click();
await page.getByRole("button", { name: "Revoke", exact: true }).click();
diff --git a/src/app/api/v1/envelopes/[id]/events/route.ts b/src/app/api/v1/envelopes/[id]/events/route.ts
new file mode 100644
index 0000000..51eaf84
--- /dev/null
+++ b/src/app/api/v1/envelopes/[id]/events/route.ts
@@ -0,0 +1,23 @@
+import { apiError, apiJson } from "@/lib/api/http";
+import { listApiEnvelopeEvents } from "@/lib/api/envelopes";
+import { handleApi } from "@/lib/api/route";
+
+type Context = { params: Promise<{ id: string }> };
+
+// The envelope's audit trail, oldest first.
+export async function GET(request: Request, context: Context) {
+ const { id } = await context.params;
+
+ return handleApi(
+ request,
+ "read",
+ "api_envelope_events_failure",
+ async ({ actor }) => {
+ const events = await listApiEnvelopeEvents(actor.userId, id);
+
+ return events
+ ? apiJson({ data: events, object: "list" })
+ : apiError(404, "not_found", "Envelope not found.");
+ },
+ );
+}
diff --git a/src/app/api/v1/envelopes/[id]/files/[file]/route.ts b/src/app/api/v1/envelopes/[id]/files/[file]/route.ts
new file mode 100644
index 0000000..45094bd
--- /dev/null
+++ b/src/app/api/v1/envelopes/[id]/files/[file]/route.ts
@@ -0,0 +1,35 @@
+import { apiError } from "@/lib/api/http";
+import { handleApi } from "@/lib/api/route";
+import { createDownloadResponse } from "@/lib/download-response";
+import { getSenderEnvelopeDownload } from "@/lib/downloads";
+
+type Context = { params: Promise<{ file: string; id: string }> };
+
+const FILE_TYPES = { certificate: "evidence", signed: "signed" } as const;
+
+// The signed PDF (once completed) or the certificate of completion (once
+// completed, declined or voided).
+export async function GET(request: Request, context: Context) {
+ const { file, id } = await context.params;
+
+ return handleApi(
+ request,
+ "read",
+ "api_envelope_file_failure",
+ async ({ actor }) => {
+ const type = FILE_TYPES[file as keyof typeof FILE_TYPES];
+
+ if (!type) {
+ return apiError(
+ 404,
+ "not_found",
+ "Ask for files/signed or files/certificate.",
+ );
+ }
+
+ return createDownloadResponse(
+ await getSenderEnvelopeDownload(actor.userId, id, type),
+ );
+ },
+ );
+}
diff --git a/src/app/api/v1/envelopes/[id]/remind/route.ts b/src/app/api/v1/envelopes/[id]/remind/route.ts
new file mode 100644
index 0000000..c350fca
--- /dev/null
+++ b/src/app/api/v1/envelopes/[id]/remind/route.ts
@@ -0,0 +1,32 @@
+import { apiError, apiJson } from "@/lib/api/http";
+import { getApiEnvelope } from "@/lib/api/envelopes";
+import { handleApi } from "@/lib/api/route";
+import { sendManualEnvelopeNudge } from "@/lib/reminders";
+
+type Context = { params: Promise<{ id: string }> };
+
+// Emails the signer whose turn it is a reminder, under the same limit as
+// the reminder button in the web app.
+export async function POST(request: Request, context: Context) {
+ const { id } = await context.params;
+
+ return handleApi(
+ request,
+ "write",
+ "api_envelope_remind_failure",
+ async ({ actor }) => {
+ await sendManualEnvelopeNudge(actor.userId, id, {
+ ipAddress: actor.ipAddress,
+ senderEmail: actor.email,
+ senderName: actor.name.trim() ? actor.name : actor.email,
+ userAgent: actor.userAgent,
+ });
+
+ const envelope = await getApiEnvelope(actor.userId, id);
+
+ return envelope
+ ? apiJson(envelope)
+ : apiError(404, "not_found", "Envelope not found.");
+ },
+ );
+}
diff --git a/src/app/api/v1/envelopes/[id]/route.ts b/src/app/api/v1/envelopes/[id]/route.ts
new file mode 100644
index 0000000..69139df
--- /dev/null
+++ b/src/app/api/v1/envelopes/[id]/route.ts
@@ -0,0 +1,53 @@
+import { apiError, apiJson } from "@/lib/api/http";
+import { getApiEnvelope } from "@/lib/api/envelopes";
+import { handleApi } from "@/lib/api/route";
+import { deleteDraftEnvelope } from "@/lib/envelopes";
+
+type Context = { params: Promise<{ id: string }> };
+
+export async function GET(request: Request, context: Context) {
+ const { id } = await context.params;
+
+ return handleApi(
+ request,
+ "read",
+ "api_envelope_read_failure",
+ async ({ actor }) => {
+ const envelope = await getApiEnvelope(actor.userId, id);
+
+ return envelope
+ ? apiJson(envelope)
+ : apiError(404, "not_found", "Envelope not found.");
+ },
+ );
+}
+
+// Deletes a draft. A sent envelope is voided instead, and kept.
+export async function DELETE(request: Request, context: Context) {
+ const { id } = await context.params;
+
+ return handleApi(
+ request,
+ "write",
+ "api_envelope_delete_failure",
+ async ({ actor }) => {
+ const envelope = await getApiEnvelope(actor.userId, id);
+
+ if (!envelope) {
+ return apiError(404, "not_found", "Envelope not found.");
+ }
+
+ if (envelope.status !== "draft") {
+ return apiError(
+ 409,
+ "wrong_state",
+ "Only a draft can be deleted. Void a sent envelope instead.",
+ );
+ }
+
+ await deleteDraftEnvelope(actor.userId, id);
+
+ return apiJson({ deleted: true, id, object: "envelope" });
+ },
+ );
+}
diff --git a/src/app/api/v1/envelopes/[id]/send/route.ts b/src/app/api/v1/envelopes/[id]/send/route.ts
new file mode 100644
index 0000000..578e2c3
--- /dev/null
+++ b/src/app/api/v1/envelopes/[id]/send/route.ts
@@ -0,0 +1,71 @@
+import { apiError } from "@/lib/api/http";
+import {
+ apiSendOptionsSchema,
+ describeZodError,
+ getApiEnvelope,
+ sendEnvelopeForApi,
+} from "@/lib/api/envelopes";
+import { applyAccountLimit, handleApi, runIdempotently } from "@/lib/api/route";
+
+type Context = { params: Promise<{ id: string }> };
+
+// Sends a draft to its first signer.
+export async function POST(request: Request, context: Context) {
+ const { id } = await context.params;
+
+ return handleApi(
+ request,
+ "write",
+ "api_envelope_send_failure",
+ async (api) => {
+ const limited = await applyAccountLimit(api, {
+ key: "api-envelope-send",
+ limit: 100,
+ windowMs: 60 * 60 * 1000,
+ });
+
+ if (limited) {
+ return limited;
+ }
+
+ const text = await request.text();
+ let body: unknown;
+
+ try {
+ body = text.trim() ? (JSON.parse(text) as unknown) : {};
+ } catch {
+ return apiError(400, "invalid_request", "The body is not valid JSON.");
+ }
+
+ const options = apiSendOptionsSchema.safeParse(body);
+
+ if (!options.success) {
+ return apiError(
+ 400,
+ "invalid_request",
+ describeZodError(options.error),
+ );
+ }
+
+ return runIdempotently(
+ api,
+ `POST /api/v1/envelopes/${id}/send`,
+ text,
+ async () => {
+ await sendEnvelopeForApi(api.actor, id, options.data);
+
+ const envelope = await getApiEnvelope(api.actor.userId, id);
+
+ return envelope
+ ? { body: envelope, status: 200 }
+ : {
+ body: {
+ error: { code: "not_found", message: "Envelope not found." },
+ },
+ status: 404,
+ };
+ },
+ );
+ },
+ );
+}
diff --git a/src/app/api/v1/envelopes/[id]/void/route.ts b/src/app/api/v1/envelopes/[id]/void/route.ts
new file mode 100644
index 0000000..f8a1055
--- /dev/null
+++ b/src/app/api/v1/envelopes/[id]/void/route.ts
@@ -0,0 +1,47 @@
+import { apiError, apiJson } from "@/lib/api/http";
+import { getApiEnvelope } from "@/lib/api/envelopes";
+import { handleApi } from "@/lib/api/route";
+import { voidSentEnvelope } from "@/lib/envelopes";
+
+type Context = { params: Promise<{ id: string }> };
+
+// Voids an envelope that is out for signature. The signers are told, and
+// nobody can sign it any more.
+export async function POST(request: Request, context: Context) {
+ const { id } = await context.params;
+
+ return handleApi(
+ request,
+ "write",
+ "api_envelope_void_failure",
+ async ({ actor }) => {
+ const body = (await request.json().catch(() => ({}))) as unknown;
+ const reason =
+ typeof body === "object" && body !== null
+ ? (body as { reason?: unknown }).reason
+ : undefined;
+
+ if (
+ reason !== undefined &&
+ reason !== null &&
+ typeof reason !== "string"
+ ) {
+ return apiError(400, "invalid_request", "reason must be a string.");
+ }
+
+ await voidSentEnvelope(actor.userId, id, {
+ ipAddress: actor.ipAddress,
+ reason: reason ?? null,
+ senderEmail: actor.email,
+ senderName: actor.name.trim() ? actor.name : actor.email,
+ userAgent: actor.userAgent,
+ });
+
+ const envelope = await getApiEnvelope(actor.userId, id);
+
+ return envelope
+ ? apiJson(envelope)
+ : apiError(404, "not_found", "Envelope not found.");
+ },
+ );
+}
diff --git a/src/app/api/v1/envelopes/route.ts b/src/app/api/v1/envelopes/route.ts
new file mode 100644
index 0000000..838812c
--- /dev/null
+++ b/src/app/api/v1/envelopes/route.ts
@@ -0,0 +1,197 @@
+import { createHash } from "node:crypto";
+
+import { apiError, apiJson } from "@/lib/api/http";
+import {
+ apiCreateEnvelopeSchema,
+ apiListQuerySchema,
+ createEnvelopeForApi,
+ describeZodError,
+ listApiEnvelopes,
+} from "@/lib/api/envelopes";
+import { applyAccountLimit, handleApi, runIdempotently } from "@/lib/api/route";
+import { pendingUploadKeyFor } from "@/lib/api/uploads";
+import {
+ discardPendingUpload,
+ readPendingUpload,
+} from "@/lib/services/pending-uploads";
+import { createStorageService } from "@/lib/services/storage";
+import { MAX_UPLOAD_SIZE_BYTES } from "@/lib/types/domain";
+
+// GET lists the key's envelopes, newest first. POST creates one from a PDF
+// with its signers and fields, and sends it too if asked. See docs/api.md.
+
+export async function GET(request: Request) {
+ return handleApi(
+ request,
+ "read",
+ "api_envelope_list_failure",
+ async ({ actor }) => {
+ const url = new URL(request.url);
+ const query = apiListQuerySchema.safeParse({
+ cursor: url.searchParams.get("cursor") ?? undefined,
+ limit: url.searchParams.get("limit") ?? undefined,
+ status: url.searchParams.get("status") ?? undefined,
+ });
+
+ if (!query.success) {
+ return apiError(400, "invalid_request", describeZodError(query.error));
+ }
+
+ const page = await listApiEnvelopes(actor.userId, query.data);
+
+ return apiJson({
+ data: page.data,
+ nextCursor: page.nextCursor,
+ object: "list",
+ });
+ },
+ );
+}
+
+type SourcePdf = { body: Uint8Array; contentType: string; filename: string };
+
+export async function POST(request: Request) {
+ return handleApi(
+ request,
+ "write",
+ "api_envelope_create_failure",
+ async (context) => {
+ const limited = await applyAccountLimit(context, {
+ key: "api-envelope-create",
+ limit: 60,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (limited) {
+ return limited;
+ }
+
+ const raw = new Uint8Array(await request.arrayBuffer());
+
+ // A little room over the PDF limit for the form's own parts.
+ if (raw.byteLength > MAX_UPLOAD_SIZE_BYTES + 256 * 1024) {
+ return apiError(413, "payload_too_large", "The request is too large.");
+ }
+
+ const contentType = request.headers.get("content-type") ?? "";
+ let data: unknown;
+ let readPdf: () => Promise<SourcePdf>;
+ let cleanUp = async () => {};
+ let fingerprint: Uint8Array | string = raw;
+
+ if (contentType.toLowerCase().startsWith("multipart/form-data")) {
+ const form = await new Request(request.url, {
+ body: raw,
+ headers: { "content-type": contentType },
+ method: "POST",
+ })
+ .formData()
+ .catch(() => null);
+ const file = form?.get("file");
+ const json = form?.get("data");
+
+ if (!(file instanceof File) || typeof json !== "string") {
+ return apiError(
+ 400,
+ "invalid_request",
+ 'Send a "file" part with the PDF and a "data" part with the envelope as JSON.',
+ );
+ }
+
+ data = parseJson(json);
+ const fileBytes = new Uint8Array(await file.arrayBuffer());
+
+ // A multipart body differs on every send (its boundary is random),
+ // so a retry is recognised by what it carries instead.
+ fingerprint = `${json}\n${createHash("sha256").update(fileBytes).digest("hex")}`;
+ readPdf = async () => ({
+ body: fileBytes,
+ contentType: file.type || "application/pdf",
+ filename: file.name || "document.pdf",
+ });
+ } else if (contentType.toLowerCase().includes("application/json")) {
+ const body = parseJson(new TextDecoder().decode(raw));
+ const uploadId =
+ typeof body === "object" && body !== null
+ ? (body as { uploadId?: unknown }).uploadId
+ : undefined;
+ const key =
+ typeof uploadId === "string"
+ ? pendingUploadKeyFor(context.actor.userId, uploadId)
+ : null;
+
+ if (!key) {
+ return apiError(
+ 400,
+ "invalid_request",
+ "Send multipart/form-data with the PDF, or JSON with the uploadId from POST /api/v1/uploads.",
+ );
+ }
+
+ const filename =
+ typeof (body as { filename?: unknown }).filename === "string"
+ ? String((body as { filename: string }).filename).slice(0, 255)
+ : "document.pdf";
+ const storageService = createStorageService();
+
+ data = body;
+ readPdf = async () => ({
+ body: await readPendingUpload({
+ key,
+ storageService,
+ userId: context.actor.userId,
+ }),
+ contentType: "application/pdf",
+ filename,
+ });
+ cleanUp = () => discardPendingUpload({ key, storageService });
+ } else {
+ return apiError(
+ 400,
+ "invalid_request",
+ "Send multipart/form-data with the PDF, or JSON with an uploadId.",
+ );
+ }
+
+ if (data === undefined) {
+ return apiError(
+ 400,
+ "invalid_request",
+ "The envelope data is not valid JSON.",
+ );
+ }
+
+ const input = apiCreateEnvelopeSchema.safeParse(data);
+
+ if (!input.success) {
+ return apiError(400, "invalid_request", describeZodError(input.error));
+ }
+
+ try {
+ return await runIdempotently(
+ context,
+ "POST /api/v1/envelopes",
+ fingerprint,
+ async () => ({
+ body: await createEnvelopeForApi(
+ context.actor,
+ input.data,
+ await readPdf(),
+ ),
+ status: 201,
+ }),
+ );
+ } finally {
+ await cleanUp();
+ }
+ },
+ );
+}
+
+function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text) as unknown;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/src/app/api/v1/openapi.json/route.ts b/src/app/api/v1/openapi.json/route.ts
new file mode 100644
index 0000000..1e45eea
--- /dev/null
+++ b/src/app/api/v1/openapi.json/route.ts
@@ -0,0 +1,10 @@
+import { apiJson } from "@/lib/api/http";
+import { buildOpenApiDocument } from "@/lib/api/openapi";
+import { getEnv } from "@/lib/utils/env";
+
+// The OpenAPI description of this API. Needs no key.
+export function GET(request: Request) {
+ const origin = getEnv(process.env).appUrl ?? new URL(request.url).origin;
+
+ return apiJson(buildOpenApiDocument(new URL("/api/v1", origin).toString()));
+}
diff --git a/src/app/api/v1/templates/[id]/envelopes/route.ts b/src/app/api/v1/templates/[id]/envelopes/route.ts
new file mode 100644
index 0000000..bf94184
--- /dev/null
+++ b/src/app/api/v1/templates/[id]/envelopes/route.ts
@@ -0,0 +1,107 @@
+import { z } from "zod";
+
+import { apiError } from "@/lib/api/http";
+import {
+ apiSendOptionsSchema,
+ describeZodError,
+ getApiEnvelope,
+ markEnvelopeAsApiMade,
+ MAX_API_METADATA_BYTES,
+ sendEnvelopeForApi,
+} from "@/lib/api/envelopes";
+import { applyAccountLimit, handleApi, runIdempotently } from "@/lib/api/route";
+import { deleteDraftEnvelope } from "@/lib/envelopes";
+import { createDraftFromTemplate } from "@/lib/templates";
+
+type Context = { params: Promise<{ id: string }> };
+
+const bodySchema = z.object({
+ metadata: z
+ .record(z.string(), z.unknown())
+ .refine(
+ (value) =>
+ Buffer.byteLength(JSON.stringify(value), "utf8") <=
+ MAX_API_METADATA_BYTES,
+ { message: "Metadata must be at most 2048 bytes of JSON." },
+ )
+ .optional(),
+ send: apiSendOptionsSchema.optional(),
+ signers: z.array(z.object({ email: z.string(), name: z.string() })).min(1),
+ title: z.string(),
+});
+
+// Starts an envelope from a saved template: one signer per role, in the
+// template's order. Sends it too when asked.
+export async function POST(request: Request, context: Context) {
+ const { id } = await context.params;
+
+ return handleApi(
+ request,
+ "write",
+ "api_template_use_failure",
+ async (api) => {
+ const limited = await applyAccountLimit(api, {
+ key: "api-envelope-create",
+ limit: 60,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (limited) {
+ return limited;
+ }
+
+ const text = await request.text();
+ let parsed: unknown;
+
+ try {
+ parsed = JSON.parse(text) as unknown;
+ } catch {
+ return apiError(400, "invalid_request", "The body is not valid JSON.");
+ }
+
+ const body = bodySchema.safeParse(parsed);
+
+ if (!body.success) {
+ return apiError(400, "invalid_request", describeZodError(body.error));
+ }
+
+ return runIdempotently(
+ api,
+ `POST /api/v1/templates/${id}/envelopes`,
+ text,
+ async () => {
+ const draft = await createDraftFromTemplate(api.actor.userId, id, {
+ signers: body.data.signers,
+ title: body.data.title,
+ });
+
+ try {
+ await markEnvelopeAsApiMade(
+ draft.envelopeId,
+ api.actor.apiKeyId,
+ body.data.metadata ?? null,
+ );
+
+ if (body.data.send) {
+ await sendEnvelopeForApi(
+ api.actor,
+ draft.envelopeId,
+ body.data.send,
+ );
+ }
+ } catch (error) {
+ await deleteDraftEnvelope(api.actor.userId, draft.envelopeId).catch(
+ () => undefined,
+ );
+ throw error;
+ }
+
+ return {
+ body: await getApiEnvelope(api.actor.userId, draft.envelopeId),
+ status: 201,
+ };
+ },
+ );
+ },
+ );
+}
diff --git a/src/app/api/v1/templates/route.ts b/src/app/api/v1/templates/route.ts
new file mode 100644
index 0000000..a98bc85
--- /dev/null
+++ b/src/app/api/v1/templates/route.ts
@@ -0,0 +1,25 @@
+import { apiJson } from "@/lib/api/http";
+import { handleApi } from "@/lib/api/route";
+import { listTemplatesForUser } from "@/lib/templates";
+
+// The key's saved templates, with their roles in signing order.
+export async function GET(request: Request) {
+ return handleApi(
+ request,
+ "read",
+ "api_template_list_failure",
+ async ({ actor }) => {
+ const templates = await listTemplatesForUser(actor.userId);
+
+ return apiJson({
+ data: templates.map((template) => ({
+ id: template.id,
+ name: template.name,
+ object: "template",
+ roles: template.roleNames,
+ })),
+ object: "list",
+ });
+ },
+ );
+}
diff --git a/src/app/api/v1/uploads/route.ts b/src/app/api/v1/uploads/route.ts
new file mode 100644
index 0000000..9a998d2
--- /dev/null
+++ b/src/app/api/v1/uploads/route.ts
@@ -0,0 +1,30 @@
+import { apiError, apiJson } from "@/lib/api/http";
+import { applyAccountLimit, handleApi } from "@/lib/api/route";
+import { issueApiUpload } from "@/lib/api/uploads";
+import { supportsDirectUploads } from "@/lib/services/storage";
+
+// A signed URL for uploading one large PDF straight to Vercel Blob, for
+// files over the 4.5 MB a request to the app can carry.
+export async function POST(request: Request) {
+ return handleApi(request, "write", "api_upload_failure", async (context) => {
+ if (!supportsDirectUploads()) {
+ return apiError(
+ 404,
+ "not_found",
+ "This install keeps files on its own disk, so send the PDF in the create request instead.",
+ );
+ }
+
+ const limited = await applyAccountLimit(context, {
+ key: "api-upload",
+ limit: 60,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (limited) {
+ return limited;
+ }
+
+ return apiJson(await issueApiUpload(context.actor.userId), { status: 201 });
+ });
+}
diff --git a/src/lib/api/envelopes.dbtest.ts b/src/lib/api/envelopes.dbtest.ts
new file mode 100644
index 0000000..917179c
--- /dev/null
+++ b/src/lib/api/envelopes.dbtest.ts
@@ -0,0 +1,432 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, before, test } from "node:test";
+
+import { PDFDocument } from "pdf-lib";
+import type pg from "pg";
+
+import { createApiKey } from "../api-keys.ts";
+import { openTestDatabase } from "../db/test-database.ts";
+import { EnvelopeMutationError } from "../envelopes.ts";
+import {
+ apiCreateEnvelopeSchema,
+ createEnvelopeForApi,
+ getApiEnvelope,
+ listApiEnvelopes,
+ type ApiActor,
+} from "./envelopes.ts";
+import {
+ claimIdempotencyKey,
+ completeIdempotencyKey,
+ deleteExpiredIdempotencyKeys,
+ IDEMPOTENCY_WINDOW_SECONDS,
+} from "./idempotency.ts";
+
+// The public API's envelopes 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;
+
+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-api-"));
+
+ 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");
+
+ const document = await PDFDocument.create();
+
+ document.addPage([612, 792]);
+ pdf = await document.save();
+});
+
+after(async () => {
+ 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 createActor(): 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, 'Billing App', $2, 'admin', true)
+ `,
+ [userId, email],
+ );
+
+ const { summary } = await createApiKey(
+ { email, userId },
+ { expiresInDays: null, name: "Billing app", scope: "write" },
+ database,
+ );
+
+ return {
+ apiKeyId: summary.id,
+ email,
+ ipAddress: "203.0.113.7",
+ name: "Billing App",
+ userAgent: "billing-app/1.0",
+ userId,
+ };
+}
+
+function request(overrides: Record<string, unknown> = {}) {
+ return apiCreateEnvelopeSchema.parse({
+ fields: [
+ {
+ height: 0.05,
+ page: 1,
+ signer: "client",
+ type: "signature",
+ width: 0.3,
+ x: 0.1,
+ y: 0.8,
+ },
+ {
+ height: 0.05,
+ page: 1,
+ signer: "witness",
+ type: "signature",
+ width: 0.3,
+ x: 0.5,
+ y: 0.8,
+ },
+ {
+ height: 0.03,
+ page: 1,
+ signer: "client",
+ type: "date",
+ width: 0.2,
+ x: 0.1,
+ y: 0.9,
+ },
+ ],
+ metadata: { invoice: "INV-1042" },
+ signers: [
+ { email: "[email protected]", name: "Casey Client", ref: "client" },
+ { email: "[email protected]", name: "Wes Witness", ref: "witness" },
+ ],
+ title: "Service agreement",
+ ...overrides,
+ });
+}
+
+const source = () => ({
+ body: pdf,
+ contentType: "application/pdf",
+ filename: "agreement.pdf",
+});
+
+test("one call creates and sends an envelope, with refs, metadata and the key in the trail", async () => {
+ const actor = await createActor();
+ const envelope = await createEnvelopeForApi(
+ actor,
+ request({ send: { expiresInDays: 14, permittedUseConfirmed: true } }),
+ source(),
+ database,
+ );
+
+ assert.equal(envelope.status, "sent");
+ assert.deepEqual(envelope.metadata, { invoice: "INV-1042" });
+ assert.deepEqual(
+ envelope.signers.map((signer) => [signer.ref, signer.order, signer.status]),
+ [
+ ["client", 1, "notified"],
+ ["witness", 2, "pending"],
+ ],
+ );
+ assert.ok(envelope.expiresAt);
+ assert.equal(envelope.files.signed, null);
+
+ const fields = await database.query<{ signerId: string }>(
+ `select signer_id as "signerId" from fields where envelope_id = $1`,
+ [envelope.id],
+ );
+ const clientId = envelope.signers[0]?.id;
+
+ assert.equal(
+ fields.rows.filter((row) => row.signerId === clientId).length,
+ 2,
+ );
+
+ const sent = await database.query<{ apiKeyId: string; ip: string }>(
+ `
+ select metadata->>'apiKeyId' as "apiKeyId", ip_address as ip
+ from audit_events where envelope_id = $1 and event = 'sent'
+ `,
+ [envelope.id],
+ );
+
+ assert.deepEqual(sent.rows[0], {
+ apiKeyId: actor.apiKeyId,
+ ip: "203.0.113.7",
+ });
+
+ const stored = await database.query<{ apiKeyId: string }>(
+ `select api_key_id as "apiKeyId" from envelopes where id = $1`,
+ [envelope.id],
+ );
+
+ assert.equal(stored.rows[0]?.apiKeyId, actor.apiKeyId);
+});
+
+test("a create that cannot be finished leaves no draft behind", async () => {
+ const actor = await createActor();
+ const countDrafts = async () =>
+ (
+ await database.query(`select 1 from envelopes where user_id = $1`, [
+ actor.userId,
+ ])
+ ).rowCount;
+
+ await assert.rejects(
+ createEnvelopeForApi(
+ actor,
+ request({
+ fields: [
+ {
+ height: 0.05,
+ page: 3,
+ signer: "client",
+ type: "signature",
+ width: 0.3,
+ x: 0.1,
+ y: 0.8,
+ },
+ {
+ height: 0.05,
+ page: 1,
+ signer: "witness",
+ type: "signature",
+ width: 0.3,
+ x: 0.5,
+ y: 0.8,
+ },
+ ],
+ }),
+ source(),
+ database,
+ ),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError && /1 page/.test(error.message),
+ );
+
+ // A witness with no signature field: the send is refused.
+ await assert.rejects(
+ createEnvelopeForApi(
+ actor,
+ request({
+ fields: [
+ {
+ height: 0.05,
+ page: 1,
+ signer: "client",
+ type: "signature",
+ width: 0.3,
+ x: 0.1,
+ y: 0.8,
+ },
+ ],
+ send: { permittedUseConfirmed: true },
+ }),
+ source(),
+ database,
+ ),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError &&
+ /Signature field/.test(error.message),
+ );
+
+ assert.equal(await countDrafts(), 0);
+});
+
+test("the request is checked before anything is written", () => {
+ assert.throws(() =>
+ request({
+ fields: [
+ {
+ height: 0.05,
+ page: 1,
+ signer: "nobody",
+ type: "signature",
+ width: 0.3,
+ x: 0.1,
+ y: 0.8,
+ },
+ ],
+ }),
+ );
+ assert.throws(() =>
+ request({
+ signers: [
+ { email: "[email protected]", name: "A", ref: "same" },
+ { email: "[email protected]", name: "B", ref: "same" },
+ ],
+ }),
+ );
+ assert.throws(() => request({ metadata: { blob: "x".repeat(3000) } }));
+ assert.throws(() => request({ send: { permittedUseConfirmed: false } }));
+});
+
+test("an envelope is visible only to the key's own account", async () => {
+ const owner = await createActor();
+ const stranger = await createActor();
+ const envelope = await createEnvelopeForApi(
+ owner,
+ request(),
+ source(),
+ database,
+ );
+
+ assert.equal(envelope.status, "draft");
+ assert.ok(await getApiEnvelope(owner.userId, envelope.id, database));
+ assert.equal(
+ await getApiEnvelope(stranger.userId, envelope.id, database),
+ null,
+ );
+});
+
+test("the list pages with a cursor, newest first, and filters by status", async () => {
+ const actor = await createActor();
+ const ids: string[] = [];
+
+ for (let index = 0; index < 3; index += 1) {
+ ids.push(
+ (await createEnvelopeForApi(actor, request(), source(), database)).id,
+ );
+ }
+
+ // Same-second creations still come back in a stable order.
+ const first = await listApiEnvelopes(actor.userId, { limit: 2 }, database);
+
+ assert.equal(first.data.length, 2);
+ assert.ok(first.nextCursor);
+
+ const second = await listApiEnvelopes(
+ actor.userId,
+ { cursor: first.nextCursor ?? undefined, limit: 2 },
+ database,
+ );
+
+ assert.equal(second.data.length, 1);
+ assert.equal(second.nextCursor, null);
+ assert.deepEqual(
+ new Set([...first.data, ...second.data].map((envelope) => envelope.id)),
+ new Set(ids),
+ );
+ assert.equal(
+ (
+ await listApiEnvelopes(
+ actor.userId,
+ { limit: 25, status: "sent" },
+ database,
+ )
+ ).data.length,
+ 0,
+ );
+});
+
+test("an idempotency key replays the first response and refuses a different request", async () => {
+ const actor = await createActor();
+ const claim = {
+ apiKeyId: actor.apiKeyId,
+ key: "order-1042",
+ requestHash: "a".repeat(64),
+ };
+
+ assert.deepEqual(await claimIdempotencyKey(claim, database), { kind: "new" });
+ assert.deepEqual(await claimIdempotencyKey(claim, database), {
+ kind: "in_progress",
+ });
+
+ await completeIdempotencyKey(
+ {
+ apiKeyId: actor.apiKeyId,
+ key: "order-1042",
+ response: { id: "env_1" },
+ statusCode: 201,
+ },
+ database,
+ );
+
+ assert.deepEqual(await claimIdempotencyKey(claim, database), {
+ kind: "replay",
+ response: { id: "env_1" },
+ statusCode: 201,
+ });
+ assert.deepEqual(
+ await claimIdempotencyKey(
+ { ...claim, requestHash: "b".repeat(64) },
+ database,
+ ),
+ { kind: "mismatch" },
+ );
+
+ // Another key may use the same value for its own request.
+ const other = await createActor();
+
+ assert.deepEqual(
+ await claimIdempotencyKey({ ...claim, apiKeyId: other.apiKeyId }, database),
+ { kind: "new" },
+ );
+
+ // After the window the value is free again.
+ const later = Math.floor(Date.now() / 1000) + IDEMPOTENCY_WINDOW_SECONDS + 1;
+
+ assert.deepEqual(
+ await claimIdempotencyKey(
+ { ...claim, requestHash: "c".repeat(64) },
+ database,
+ later,
+ ),
+ { kind: "new" },
+ );
+ assert.ok(
+ (await deleteExpiredIdempotencyKeys(
+ database,
+ later + IDEMPOTENCY_WINDOW_SECONDS,
+ )) >= 1,
+ );
+});
diff --git a/src/lib/api/envelopes.ts b/src/lib/api/envelopes.ts
new file mode 100644
index 0000000..57b16ae
--- /dev/null
+++ b/src/lib/api/envelopes.ts
@@ -0,0 +1,675 @@
+import { z } from "zod";
+
+import {
+ getDb,
+ queryMany,
+ queryOne,
+ type DbExecutor,
+ type DbPool,
+} from "../db/connection.ts";
+import {
+ createDraftEnvelope,
+ deleteDraftEnvelope,
+ EnvelopeMutationError,
+ replaceDraftEnvelopeFields,
+ replaceDraftEnvelopeSigners,
+ sendDraftEnvelope,
+} from "../envelopes.ts";
+import {
+ emailSchema,
+ envelopeTitleSchema,
+ nameSchema,
+} from "../schemas/common.ts";
+import {
+ deadlineDaysSchema,
+ reminderIntervalDaysSchema,
+} from "../schemas/envelope.ts";
+import { fieldTypeSchema } from "../schemas/field.ts";
+import {
+ MAX_COPY_RECIPIENTS_PER_ENVELOPE,
+ MAX_SIGNERS_PER_ENVELOPE,
+ signatureMeanings,
+ type EnvelopeStatus,
+ type SignerStatus,
+} from "../types/domain.ts";
+
+// Envelopes as the public API sees them: one shape, ApiEnvelope, returned by
+// every endpoint (and, later, carried by webhooks), and the one-call create.
+// Everything that changes an envelope goes through the same functions the
+// web app uses, so the same rules apply.
+
+export const MAX_API_METADATA_BYTES = 2048;
+export const MAX_API_FIELDS = 500;
+const DEFAULT_PAGE_SIZE = 25;
+const MAX_PAGE_SIZE = 100;
+
+export type ApiSigner = {
+ declinedAt: string | null;
+ declineReason: string | null;
+ email: string;
+ id: string;
+ name: string;
+ order: number;
+ ref: string | null;
+ signedAt: string | null;
+ status: SignerStatus;
+ viewedAt: string | null;
+};
+
+export type ApiEnvelope = {
+ completedAt: string | null;
+ copyRecipients: Array<{ email: string; id: string; name: string }>;
+ createdAt: string;
+ declinedAt: string | null;
+ expired: boolean;
+ expiresAt: string | null;
+ files: { certificate: string | null; signed: string | null };
+ id: string;
+ metadata: Record<string, unknown> | null;
+ object: "envelope";
+ pageCount: number;
+ sentAt: string | null;
+ signatureLevel: string;
+ signers: ApiSigner[];
+ status: EnvelopeStatus;
+ title: string;
+ voidedAt: string | null;
+};
+
+function isoTime(seconds: number | null | undefined): string | null {
+ return typeof seconds === "number"
+ ? new Date(seconds * 1000).toISOString()
+ : null;
+}
+
+const refSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(64)
+ .regex(
+ /^[A-Za-z0-9._:-]+$/,
+ "Use letters, digits, '.', '_', ':' or '-' in a ref.",
+ );
+
+const metadataSchema = z
+ .record(z.string(), z.unknown())
+ .refine(
+ (value) =>
+ Buffer.byteLength(JSON.stringify(value), "utf8") <=
+ MAX_API_METADATA_BYTES,
+ {
+ message: `Metadata must be at most ${String(MAX_API_METADATA_BYTES)} bytes of JSON.`,
+ },
+ );
+
+export const apiSendOptionsSchema = z.object({
+ expiresInDays: deadlineDaysSchema.optional(),
+ permittedUseConfirmed: z.literal(true, {
+ message:
+ "Set permittedUseConfirmed to true to confirm the envelope is an ordinary business agreement (see /electronic-signatures on your install).",
+ }),
+ reminderIntervalDays: reminderIntervalDaysSchema.optional(),
+ signatureLevel: z.enum(["simple", "advanced", "qualified"]).optional(),
+});
+
+const apiSignerSchema = z.object({
+ accessCode: z.string().trim().min(4).max(64).optional(),
+ email: emailSchema,
+ name: nameSchema,
+ ref: refSchema,
+ requireEmailCode: z.boolean().optional(),
+ signatureMeaning: z.enum(signatureMeanings).optional(),
+});
+
+const apiFieldSchema = z.object({
+ groupId: z.string().trim().min(1).max(64).optional(),
+ height: z.number().finite().gt(0).max(1),
+ label: z.string().trim().max(120).optional(),
+ options: z.array(z.string()).optional(),
+ page: z.number().int().positive(),
+ required: z.boolean().optional(),
+ signer: refSchema,
+ type: fieldTypeSchema,
+ width: z.number().finite().gt(0).max(1),
+ x: z.number().finite().min(0).max(1),
+ y: z.number().finite().min(0).max(1),
+});
+
+export const apiCreateEnvelopeSchema = z
+ .object({
+ copyRecipients: z
+ .array(z.object({ email: emailSchema, name: nameSchema }))
+ .max(MAX_COPY_RECIPIENTS_PER_ENVELOPE)
+ .optional(),
+ fields: z.array(apiFieldSchema).min(1).max(MAX_API_FIELDS),
+ metadata: metadataSchema.optional(),
+ send: apiSendOptionsSchema.optional(),
+ signers: z.array(apiSignerSchema).min(1).max(MAX_SIGNERS_PER_ENVELOPE),
+ title: envelopeTitleSchema,
+ })
+ .superRefine((value, ctx) => {
+ const refs = new Set<string>();
+
+ for (const [index, signer] of value.signers.entries()) {
+ if (refs.has(signer.ref)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Each signer needs its own ref.",
+ path: ["signers", index, "ref"],
+ });
+ }
+
+ refs.add(signer.ref);
+ }
+
+ for (const [index, field] of value.fields.entries()) {
+ if (!refs.has(field.signer)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `No signer has the ref "${field.signer}".`,
+ path: ["fields", index, "signer"],
+ });
+ }
+ }
+ });
+
+export type ApiCreateEnvelopeInput = z.infer<typeof apiCreateEnvelopeSchema>;
+export type ApiSendOptions = z.infer<typeof apiSendOptionsSchema>;
+
+export type ApiActor = {
+ apiKeyId: string;
+ email: string;
+ ipAddress: string | null;
+ name: string;
+ userAgent: string | null;
+ userId: string;
+};
+
+/** The first message of a zod error, with where it was. */
+export function describeZodError(error: z.ZodError): string {
+ const issue = error.issues[0];
+
+ if (!issue) {
+ return "The request is not valid.";
+ }
+
+ const where = issue.path.length > 0 ? `${issue.path.join(".")}: ` : "";
+
+ return `${where}${issue.message}`;
+}
+
+export async function sendEnvelopeForApi(
+ actor: ApiActor,
+ envelopeId: string,
+ options: ApiSendOptions,
+ database: DbPool = getDb(),
+) {
+ await sendDraftEnvelope(
+ actor.userId,
+ envelopeId,
+ {
+ apiKeyId: actor.apiKeyId,
+ expiresInDays: options.expiresInDays,
+ ipAddress: actor.ipAddress,
+ reminderIntervalDays: options.reminderIntervalDays,
+ senderEmail: actor.email,
+ senderName: actor.name.trim() ? actor.name : actor.email,
+ signatureLevel: options.signatureLevel,
+ userAgent: actor.userAgent,
+ },
+ { database },
+ );
+}
+
+/**
+ * Creates a draft with its signers, copy recipients and fields, and sends it
+ * if asked. Either all of it happens or none of it does: a draft that cannot
+ * be completed (a field off its page, a send the install refuses) is deleted
+ * again before the error is returned.
+ */
+export async function createEnvelopeForApi(
+ actor: ApiActor,
+ input: ApiCreateEnvelopeInput,
+ sourcePdf: { body: Uint8Array; contentType: string; filename: string },
+ database: DbPool = getDb(),
+): Promise<ApiEnvelope> {
+ const draft = await createDraftEnvelope(
+ actor.userId,
+ { sourcePdf, title: input.title },
+ { database },
+ );
+ const envelopeId = draft.envelope.id;
+
+ try {
+ for (const [index, field] of input.fields.entries()) {
+ if (field.page > draft.envelope.pageCount) {
+ throw new EnvelopeMutationError(
+ `fields.${String(index)}.page: the document has ${String(draft.envelope.pageCount)} page(s).`,
+ 400,
+ );
+ }
+ }
+
+ const signers = await replaceDraftEnvelopeSigners(
+ actor.userId,
+ envelopeId,
+ {
+ copyRecipients: input.copyRecipients ?? [],
+ signers: input.signers.map((signer, index) => ({
+ accessCode: signer.accessCode,
+ email: signer.email,
+ name: signer.name,
+ requireEmailCode: signer.requireEmailCode,
+ signatureMeaning: signer.signatureMeaning,
+ signOrder: index + 1,
+ })),
+ },
+ database,
+ );
+ const idByEmail = new Map(
+ signers.signers.map((signer) => [signer.email.toLowerCase(), signer.id]),
+ );
+ const idByRef = new Map<string, string>();
+
+ for (const signer of input.signers) {
+ const id = idByEmail.get(signer.email.toLowerCase());
+
+ if (!id) {
+ throw new Error("A signer that was just saved could not be found.");
+ }
+
+ idByRef.set(signer.ref, id);
+ await database.query(
+ `UPDATE signers SET api_ref = $1 WHERE id = $2 AND envelope_id = $3`,
+ [signer.ref, id, envelopeId],
+ );
+ }
+
+ await replaceDraftEnvelopeFields(
+ actor.userId,
+ envelopeId,
+ {
+ fields: input.fields.map((field) => ({
+ groupId: field.groupId,
+ height: field.height,
+ label: field.label,
+ options: field.options,
+ page: field.page,
+ required: field.required ?? true,
+ signerId: idByRef.get(field.signer),
+ type: field.type,
+ width: field.width,
+ x: field.x,
+ y: field.y,
+ })),
+ },
+ database,
+ );
+ await database.query(
+ `UPDATE envelopes SET api_key_id = $1, api_metadata = $2 WHERE id = $3`,
+ [actor.apiKeyId, input.metadata ?? null, envelopeId],
+ );
+
+ if (input.send) {
+ await sendEnvelopeForApi(actor, envelopeId, input.send, database);
+ }
+ } catch (error) {
+ await deleteDraftEnvelope(actor.userId, envelopeId, { database }).catch(
+ (cleanupError: unknown) => {
+ console.error(
+ `Deleting the API draft ${envelopeId} after a failed create failed:`,
+ cleanupError,
+ );
+ },
+ );
+ throw error;
+ }
+
+ const envelope = await getApiEnvelope(actor.userId, envelopeId, database);
+
+ if (!envelope) {
+ throw new Error(
+ "An envelope that was just created could not be read back.",
+ );
+ }
+
+ return envelope;
+}
+
+/** Sets what an envelope made from a template keeps for the API. */
+export async function markEnvelopeAsApiMade(
+ envelopeId: string,
+ apiKeyId: string,
+ metadata: Record<string, unknown> | null,
+ database: DbExecutor = getDb(),
+) {
+ await database.query(
+ `UPDATE envelopes SET api_key_id = $1, api_metadata = $2 WHERE id = $3`,
+ [apiKeyId, metadata, envelopeId],
+ );
+}
+
+type EnvelopeRow = {
+ apiMetadata: Record<string, unknown> | null;
+ completedAt: number | null;
+ createdAt: number;
+ declinedAt: number | null;
+ evidenceKey: string | null;
+ expiresAt: number | null;
+ id: string;
+ pageCount: number;
+ sentAt: number | null;
+ signatureLevel: string | null;
+ signedPdfKey: string | null;
+ status: EnvelopeStatus;
+ title: string;
+ voidedAt: number | null;
+};
+
+type SignerRow = {
+ apiRef: string | null;
+ declinedAt: number | null;
+ declineReason: string | null;
+ email: string;
+ envelopeId: string;
+ id: string;
+ name: string;
+ role: "cc" | "signer";
+ signedAt: number | null;
+ signOrder: number;
+ status: SignerStatus;
+ viewedAt: number | null;
+};
+
+const ENVELOPE_COLUMNS = `
+ e.id,
+ e.title,
+ e.status,
+ e.page_count AS "pageCount",
+ e.signed_pdf_key AS "signedPdfKey",
+ e.evidence_key AS "evidenceKey",
+ e.sent_at AS "sentAt",
+ e.completed_at AS "completedAt",
+ e.declined_at AS "declinedAt",
+ e.voided_at AS "voidedAt",
+ e.expires_at AS "expiresAt",
+ e.signature_level AS "signatureLevel",
+ e.api_metadata AS "apiMetadata",
+ e.created_at AS "createdAt"
+`;
+
+async function readSigners(
+ envelopeIds: string[],
+ database: DbExecutor,
+): Promise<Map<string, SignerRow[]>> {
+ const bySignerEnvelope = new Map<string, SignerRow[]>();
+
+ if (envelopeIds.length === 0) {
+ return bySignerEnvelope;
+ }
+
+ const rows = await queryMany<SignerRow>(
+ database,
+ `
+ SELECT
+ s.id,
+ s.envelope_id AS "envelopeId",
+ s.name,
+ s.email,
+ s.role,
+ s.sign_order AS "signOrder",
+ s.status,
+ s.signed_at AS "signedAt",
+ s.declined_at AS "declinedAt",
+ s.decline_reason AS "declineReason",
+ s.api_ref AS "apiRef",
+ (
+ SELECT min(a.created_at)
+ FROM audit_events a
+ WHERE a.envelope_id = s.envelope_id
+ AND a.event = 'viewed'
+ AND a.metadata->>'signerId' = s.id
+ ) AS "viewedAt"
+ FROM signers s
+ WHERE s.envelope_id = ANY($1)
+ ORDER BY s.envelope_id, s.sign_order, s.id
+ `,
+ [envelopeIds],
+ );
+
+ for (const row of rows) {
+ const list = bySignerEnvelope.get(row.envelopeId) ?? [];
+
+ list.push(row);
+ bySignerEnvelope.set(row.envelopeId, list);
+ }
+
+ return bySignerEnvelope;
+}
+
+export function toApiEnvelope(
+ row: EnvelopeRow,
+ signers: SignerRow[],
+ now: number = Math.floor(Date.now() / 1000),
+): ApiEnvelope {
+ const base = `/api/v1/envelopes/${encodeURIComponent(row.id)}/files`;
+ const finished =
+ row.status === "completed" ||
+ row.status === "declined" ||
+ row.status === "voided";
+
+ return {
+ completedAt: isoTime(row.completedAt),
+ copyRecipients: signers
+ .filter((signer) => signer.role === "cc")
+ .map((signer) => ({
+ email: signer.email,
+ id: signer.id,
+ name: signer.name,
+ })),
+ createdAt: isoTime(row.createdAt) ?? new Date(0).toISOString(),
+ declinedAt: isoTime(row.declinedAt),
+ expired:
+ row.status === "sent" && row.expiresAt !== null && row.expiresAt <= now,
+ expiresAt: isoTime(row.expiresAt),
+ files: {
+ certificate: finished ? `${base}/certificate` : null,
+ signed: row.status === "completed" ? `${base}/signed` : null,
+ },
+ id: row.id,
+ metadata: row.apiMetadata,
+ object: "envelope",
+ pageCount: row.pageCount,
+ sentAt: isoTime(row.sentAt),
+ signatureLevel: row.signatureLevel ?? "simple",
+ signers: signers
+ .filter((signer) => signer.role === "signer")
+ .map((signer) => ({
+ declinedAt: isoTime(signer.declinedAt),
+ declineReason: signer.declineReason,
+ email: signer.email,
+ id: signer.id,
+ name: signer.name,
+ order: signer.signOrder,
+ ref: signer.apiRef,
+ signedAt: isoTime(signer.signedAt),
+ status: signer.status,
+ viewedAt: isoTime(signer.viewedAt),
+ })),
+ status: row.status,
+ title: row.title,
+ voidedAt: isoTime(row.voidedAt),
+ };
+}
+
+/** One envelope the account can see, or null. */
+export async function getApiEnvelope(
+ userId: string,
+ envelopeId: string,
+ database: DbExecutor = getDb(),
+): Promise<ApiEnvelope | null> {
+ const row = await queryOne<EnvelopeRow>(
+ database,
+ `SELECT ${ENVELOPE_COLUMNS} FROM envelopes e WHERE e.id = $1 AND e.user_id = $2`,
+ [envelopeId, userId],
+ );
+
+ if (!row) {
+ return null;
+ }
+
+ const signers = await readSigners([row.id], database);
+
+ return toApiEnvelope(row, signers.get(row.id) ?? []);
+}
+
+export function encodeCursor(createdAt: number, id: string): string {
+ return Buffer.from(`${String(createdAt)}:${id}`, "utf8").toString(
+ "base64url",
+ );
+}
+
+export function decodeCursor(
+ cursor: string,
+): { createdAt: number; id: string } | null {
+ const decoded = Buffer.from(cursor, "base64url").toString("utf8");
+ const separator = decoded.indexOf(":");
+
+ if (separator <= 0) {
+ return null;
+ }
+
+ const createdAt = Number(decoded.slice(0, separator));
+ const id = decoded.slice(separator + 1);
+
+ return Number.isSafeInteger(createdAt) && id.length > 0
+ ? { createdAt, id }
+ : null;
+}
+
+export const apiListQuerySchema = z.object({
+ cursor: z.string().max(200).optional(),
+ limit: z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(MAX_PAGE_SIZE)
+ .default(DEFAULT_PAGE_SIZE),
+ status: z
+ .enum(["draft", "sent", "completed", "declined", "voided"])
+ .optional(),
+});
+
+/** The account's envelopes, newest first, a page at a time. */
+export async function listApiEnvelopes(
+ userId: string,
+ query: z.infer<typeof apiListQuerySchema>,
+ database: DbExecutor = getDb(),
+): Promise<{ data: ApiEnvelope[]; nextCursor: string | null }> {
+ const values: unknown[] = [userId];
+ const clauses = ["e.user_id = $1"];
+
+ if (query.status) {
+ values.push(query.status);
+ clauses.push(`e.status = $${String(values.length)}`);
+ }
+
+ if (query.cursor) {
+ const cursor = decodeCursor(query.cursor);
+
+ if (!cursor) {
+ throw new EnvelopeMutationError(
+ "cursor: not a cursor this API gave out.",
+ 400,
+ );
+ }
+
+ values.push(cursor.createdAt, cursor.id);
+ clauses.push(
+ `(e.created_at, e.id) < ($${String(values.length - 1)}, $${String(values.length)})`,
+ );
+ }
+
+ values.push(query.limit + 1);
+
+ const rows = await queryMany<EnvelopeRow>(
+ database,
+ `
+ SELECT ${ENVELOPE_COLUMNS}
+ FROM envelopes e
+ WHERE ${clauses.join(" AND ")}
+ ORDER BY e.created_at DESC, e.id DESC
+ LIMIT $${String(values.length)}
+ `,
+ values,
+ );
+ const page = rows.slice(0, query.limit);
+ const signers = await readSigners(
+ page.map((row) => row.id),
+ database,
+ );
+ const last = page.at(-1);
+
+ return {
+ data: page.map((row) => toApiEnvelope(row, signers.get(row.id) ?? [])),
+ nextCursor:
+ rows.length > query.limit && last
+ ? encodeCursor(last.createdAt, last.id)
+ : null,
+ };
+}
+
+type AuditRow = {
+ actorEmail: string | null;
+ actorType: string;
+ createdAt: number;
+ event: string;
+ id: string;
+ ipAddress: string | null;
+ metadata: Record<string, unknown> | null;
+};
+
+/** The envelope's audit trail, oldest first, as the API returns it. */
+export async function listApiEnvelopeEvents(
+ userId: string,
+ envelopeId: string,
+ database: DbExecutor = getDb(),
+) {
+ const owner = await queryOne<{ id: string }>(
+ database,
+ `SELECT id FROM envelopes WHERE id = $1 AND user_id = $2`,
+ [envelopeId, userId],
+ );
+
+ if (!owner) {
+ return null;
+ }
+
+ const rows = await queryMany<AuditRow>(
+ database,
+ `
+ SELECT
+ id,
+ event,
+ actor_type AS "actorType",
+ actor_email AS "actorEmail",
+ ip_address AS "ipAddress",
+ metadata,
+ created_at AS "createdAt"
+ FROM audit_events
+ WHERE envelope_id = $1
+ ORDER BY sequence ASC
+ `,
+ [envelopeId],
+ );
+
+ return rows.map((row) => ({
+ actor: { email: row.actorEmail, type: row.actorType },
+ at: isoTime(row.createdAt),
+ event: row.event,
+ id: row.id,
+ ipAddress: row.ipAddress,
+ metadata: row.metadata,
+ }));
+}
diff --git a/src/lib/api/idempotency.ts b/src/lib/api/idempotency.ts
new file mode 100644
index 0000000..2dc91aa
--- /dev/null
+++ b/src/lib/api/idempotency.ts
@@ -0,0 +1,155 @@
+import { createHash } from "node:crypto";
+
+import { getDb, queryOne, type DbExecutor } from "../db/connection.ts";
+
+// Idempotency-Key for the API's create and send calls. The first request
+// with a key reserves it; when it finishes, its response is kept for 24
+// hours and a retry with the same key and the same request gets that
+// response again. A different request under the same key is refused, and
+// a retry while the first is still running is told to wait.
+
+export const IDEMPOTENCY_WINDOW_SECONDS = 24 * 60 * 60;
+
+export type IdempotencyClaim =
+ | { kind: "new" }
+ | { kind: "replay"; response: unknown; statusCode: number }
+ | { kind: "in_progress" }
+ | { kind: "mismatch" };
+
+export function readIdempotencyKey(
+ headers: Headers,
+): string | null | undefined {
+ const value = headers.get("idempotency-key");
+
+ if (value === null) {
+ return null;
+ }
+
+ const trimmed = value.trim();
+
+ return trimmed.length >= 1 && trimmed.length <= 255 ? trimmed : undefined;
+}
+
+/** A fingerprint of what was asked: the route and the request body. */
+export function hashRequest(route: string, body: Uint8Array | string): string {
+ return createHash("sha256")
+ .update(route)
+ .update("\n")
+ .update(body)
+ .digest("hex");
+}
+
+/** Reserves the key for this request, or says what happened to it before. */
+export async function claimIdempotencyKey(
+ input: { apiKeyId: string; key: string; requestHash: string },
+ database: DbExecutor = getDb(),
+ now: number = Math.floor(Date.now() / 1000),
+): Promise<IdempotencyClaim> {
+ // A reservation older than the window is forgotten, so the key can be
+ // used again.
+ await database.query(
+ `
+ DELETE FROM api_idempotency
+ WHERE api_key_id = $1 AND idempotency_key = $2 AND created_at <= $3
+ `,
+ [input.apiKeyId, input.key, now - IDEMPOTENCY_WINDOW_SECONDS],
+ );
+
+ const inserted = await database.query(
+ `
+ INSERT INTO api_idempotency (api_key_id, idempotency_key, request_hash, created_at)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT DO NOTHING
+ `,
+ [input.apiKeyId, input.key, input.requestHash, now],
+ );
+
+ if ((inserted.rowCount ?? 0) === 1) {
+ return { kind: "new" };
+ }
+
+ const existing = await queryOne<{
+ requestHash: string;
+ response: unknown;
+ statusCode: number | null;
+ }>(
+ database,
+ `
+ SELECT request_hash AS "requestHash", status_code AS "statusCode", response
+ FROM api_idempotency
+ WHERE api_key_id = $1 AND idempotency_key = $2
+ `,
+ [input.apiKeyId, input.key],
+ );
+
+ if (!existing) {
+ // Deleted between the two statements: treat it as new next time.
+ return { kind: "in_progress" };
+ }
+
+ if (existing.requestHash !== input.requestHash) {
+ return { kind: "mismatch" };
+ }
+
+ if (existing.statusCode === null) {
+ return { kind: "in_progress" };
+ }
+
+ return {
+ kind: "replay",
+ response: existing.response,
+ statusCode: existing.statusCode,
+ };
+}
+
+/** Keeps the response for retries. */
+export async function completeIdempotencyKey(
+ input: {
+ apiKeyId: string;
+ key: string;
+ response: unknown;
+ statusCode: number;
+ },
+ database: DbExecutor = getDb(),
+) {
+ await database.query(
+ `
+ UPDATE api_idempotency
+ SET status_code = $3, response = $4
+ WHERE api_key_id = $1 AND idempotency_key = $2
+ `,
+ [
+ input.apiKeyId,
+ input.key,
+ input.statusCode,
+ JSON.stringify(input.response),
+ ],
+ );
+}
+
+/**
+ * Lets the key go after a failure that a retry might not repeat (the
+ * install had a problem), so the retry runs for real.
+ */
+export async function releaseIdempotencyKey(
+ input: { apiKeyId: string; key: string },
+ database: DbExecutor = getDb(),
+) {
+ await database.query(
+ `DELETE FROM api_idempotency WHERE api_key_id = $1 AND idempotency_key = $2`,
+ [input.apiKeyId, input.key],
+ );
+}
+
+/** For the daily cleanup. */
+export async function deleteExpiredIdempotencyKeys(
+ database: DbExecutor = getDb(),
+ now: number = Math.floor(Date.now() / 1000),
+): Promise<number> {
+ const result = await database.query(
+ `DELETE FROM api_idempotency WHERE created_at <= $1`,
+ [now - IDEMPOTENCY_WINDOW_SECONDS],
+ );
+
+ return result.rowCount ?? 0;
+}
diff --git a/src/lib/api/openapi.test.ts b/src/lib/api/openapi.test.ts
new file mode 100644
index 0000000..ed616f7
--- /dev/null
+++ b/src/lib/api/openapi.test.ts
@@ -0,0 +1,59 @@
+import assert from "node:assert/strict";
+import { readdir } from "node:fs/promises";
+import path from "node:path";
+import { test } from "node:test";
+
+import { buildOpenApiDocument } from "./openapi.ts";
+
+// Every route file under src/app/api/v1 has a path in the OpenAPI
+// description, with the same methods, and nothing is described that does
+// not exist.
+
+const V1_DIR = path.join(import.meta.dirname, "../../app/api/v1");
+
+async function listRouteFiles(dir: string, prefix = ""): Promise<string[]> {
+ const entries = await readdir(dir, { withFileTypes: true });
+ const found: string[] = [];
+
+ for (const entry of entries) {
+ if (entry.isDirectory()) {
+ found.push(
+ ...(await listRouteFiles(
+ path.join(dir, entry.name),
+ `${prefix}/${entry.name.replace(/^\[(.+)\]$/, "{$1}")}`,
+ )),
+ );
+ } else if (entry.name === "route.ts") {
+ found.push(prefix);
+ }
+ }
+
+ return found;
+}
+
+test("the OpenAPI description matches the route files", async () => {
+ const { readFile } = await import("node:fs/promises");
+ const document = buildOpenApiDocument("https://sign.example.com/api/v1");
+ const routes = await listRouteFiles(V1_DIR);
+
+ assert.deepEqual([...routes].sort(), Object.keys(document.paths).sort());
+
+ for (const route of routes) {
+ const source = await readFile(
+ path.join(V1_DIR, route.replace(/\{(\w+)\}/g, "[$1]"), "route.ts"),
+ "utf8",
+ );
+ const methods = [
+ ...source.matchAll(
+ /export (?:async )?function (GET|POST|PUT|PATCH|DELETE)\b/g,
+ ),
+ ]
+ .map((match) => match[1]?.toLowerCase())
+ .sort();
+ const described = Object.keys(
+ document.paths[route as keyof typeof document.paths],
+ ).sort();
+
+ assert.deepEqual(described, methods, `methods for ${route}`);
+ }
+});
diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts
new file mode 100644
index 0000000..a4450e9
--- /dev/null
+++ b/src/lib/api/openapi.ts
@@ -0,0 +1,520 @@
+// The OpenAPI 3.1 description of /api/v1, served at /api/v1/openapi.json.
+// openapi.test.ts checks that every route file has a path here and every
+// path here has a route file, so the two cannot drift apart.
+
+const errorResponse = {
+ content: {
+ "application/json": { schema: { $ref: "#/components/schemas/Error" } },
+ },
+ description: "An error. See the code.",
+};
+
+const errors = {
+ "400": errorResponse,
+ "401": errorResponse,
+ "403": errorResponse,
+ "404": errorResponse,
+ "409": errorResponse,
+ "429": errorResponse,
+};
+
+const envelopeResponse = (description: string) => ({
+ content: {
+ "application/json": { schema: { $ref: "#/components/schemas/Envelope" } },
+ },
+ description,
+});
+
+const idParameter = {
+ in: "path",
+ name: "id",
+ required: true,
+ schema: { type: "string" },
+};
+
+const idempotencyKey = {
+ description:
+ "Any unique string up to 255 characters. A retry with the same key and body within 24 hours gets the first response again.",
+ in: "header",
+ name: "Idempotency-Key",
+ required: false,
+ schema: { maxLength: 255, type: "string" },
+};
+
+const isoTime = { format: "date-time", type: ["string", "null"] };
+
+export function buildOpenApiDocument(serverUrl: string) {
+ return {
+ components: {
+ schemas: {
+ CreateEnvelope: {
+ properties: {
+ copyRecipients: {
+ items: {
+ properties: {
+ email: { format: "email", type: "string" },
+ name: { type: "string" },
+ },
+ required: ["name", "email"],
+ type: "object",
+ },
+ maxItems: 10,
+ type: "array",
+ },
+ fields: {
+ items: { $ref: "#/components/schemas/Field" },
+ maxItems: 500,
+ minItems: 1,
+ type: "array",
+ },
+ filename: {
+ description: "With uploadId: the file name to keep.",
+ type: "string",
+ },
+ metadata: {
+ description:
+ "Up to 2048 bytes of JSON, returned with the envelope.",
+ type: "object",
+ },
+ send: { $ref: "#/components/schemas/SendOptions" },
+ signers: {
+ items: {
+ properties: {
+ accessCode: { maxLength: 64, minLength: 4, type: "string" },
+ email: { format: "email", type: "string" },
+ name: { maxLength: 120, type: "string" },
+ ref: {
+ description: "Your name for this signer, used by fields.",
+ pattern: "^[A-Za-z0-9._:-]{1,64}$",
+ type: "string",
+ },
+ requireEmailCode: { type: "boolean" },
+ signatureMeaning: {
+ description: "Part 11 installs only.",
+ type: "string",
+ },
+ },
+ required: ["ref", "name", "email"],
+ type: "object",
+ },
+ maxItems: 10,
+ minItems: 1,
+ type: "array",
+ },
+ title: { maxLength: 160, type: "string" },
+ uploadId: {
+ description: "With JSON: the id from POST /uploads.",
+ type: "string",
+ },
+ },
+ required: ["title", "signers", "fields"],
+ type: "object",
+ },
+ Envelope: {
+ properties: {
+ completedAt: isoTime,
+ copyRecipients: {
+ items: {
+ properties: {
+ email: { type: "string" },
+ id: { type: "string" },
+ name: { type: "string" },
+ },
+ type: "object",
+ },
+ type: "array",
+ },
+ createdAt: { format: "date-time", type: "string" },
+ declinedAt: isoTime,
+ expired: { type: "boolean" },
+ expiresAt: isoTime,
+ files: {
+ properties: {
+ certificate: { type: ["string", "null"] },
+ signed: { type: ["string", "null"] },
+ },
+ type: "object",
+ },
+ id: { type: "string" },
+ metadata: { type: ["object", "null"] },
+ object: { const: "envelope" },
+ pageCount: { type: "integer" },
+ sentAt: isoTime,
+ signatureLevel: {
+ enum: ["simple", "advanced", "qualified"],
+ type: "string",
+ },
+ signers: {
+ items: { $ref: "#/components/schemas/Signer" },
+ type: "array",
+ },
+ status: {
+ enum: ["draft", "sent", "completed", "declined", "voided"],
+ type: "string",
+ },
+ title: { type: "string" },
+ voidedAt: isoTime,
+ },
+ type: "object",
+ },
+ Error: {
+ properties: {
+ error: {
+ properties: {
+ code: {
+ enum: [
+ "invalid_request",
+ "unauthorized",
+ "forbidden",
+ "not_found",
+ "wrong_state",
+ "payload_too_large",
+ "idempotency_key_reused",
+ "rate_limited",
+ "internal_error",
+ ],
+ type: "string",
+ },
+ message: { type: "string" },
+ },
+ required: ["code", "message"],
+ type: "object",
+ },
+ },
+ required: ["error"],
+ type: "object",
+ },
+ Field: {
+ description:
+ "Position and size are fractions of the page (0 to 1), measured from its top left corner.",
+ properties: {
+ groupId: {
+ description: "Radio buttons in one group.",
+ type: "string",
+ },
+ height: { maximum: 1, type: "number" },
+ label: { maxLength: 120, type: "string" },
+ options: {
+ description: "Dropdowns only.",
+ items: { type: "string" },
+ type: "array",
+ },
+ page: { minimum: 1, type: "integer" },
+ required: { default: true, type: "boolean" },
+ signer: { description: "The signer's ref.", type: "string" },
+ type: {
+ enum: [
+ "signature",
+ "initials",
+ "date",
+ "text",
+ "checkbox",
+ "number",
+ "dropdown",
+ "radio",
+ ],
+ type: "string",
+ },
+ width: { maximum: 1, type: "number" },
+ x: { maximum: 1, minimum: 0, type: "number" },
+ y: { maximum: 1, minimum: 0, type: "number" },
+ },
+ required: ["signer", "type", "page", "x", "y", "width", "height"],
+ type: "object",
+ },
+ SendOptions: {
+ properties: {
+ expiresInDays: { maximum: 365, minimum: 1, type: "integer" },
+ permittedUseConfirmed: {
+ const: true,
+ description:
+ "Confirms the envelope is an ordinary business agreement, as the web app's send button does.",
+ },
+ reminderIntervalDays: { maximum: 30, minimum: 1, type: "integer" },
+ signatureLevel: {
+ enum: ["simple", "advanced", "qualified"],
+ type: "string",
+ },
+ },
+ required: ["permittedUseConfirmed"],
+ type: "object",
+ },
+ Signer: {
+ properties: {
+ declineReason: { type: ["string", "null"] },
+ declinedAt: isoTime,
+ email: { type: "string" },
+ id: { type: "string" },
+ name: { type: "string" },
+ order: { type: "integer" },
+ ref: { type: ["string", "null"] },
+ signedAt: isoTime,
+ status: {
+ description:
+ "pending: not their turn yet. notified: their turn, invited. signed. declined.",
+ enum: ["pending", "notified", "signed", "declined"],
+ type: "string",
+ },
+ viewedAt: isoTime,
+ },
+ type: "object",
+ },
+ },
+ securitySchemes: {
+ apiKey: {
+ description: "An API key from Settings, Organization, API keys.",
+ scheme: "bearer",
+ type: "http",
+ },
+ },
+ },
+ info: {
+ description:
+ "Create, send and track envelopes on a SignuDoc install. See docs/api.md in the SignuDoc repository.",
+ title: "SignuDoc API",
+ version: "1",
+ },
+ openapi: "3.1.0",
+ paths: {
+ "/envelopes": {
+ get: {
+ parameters: [
+ {
+ in: "query",
+ name: "status",
+ schema: {
+ enum: ["draft", "sent", "completed", "declined", "voided"],
+ type: "string",
+ },
+ },
+ {
+ in: "query",
+ name: "limit",
+ schema: {
+ default: 25,
+ maximum: 100,
+ minimum: 1,
+ type: "integer",
+ },
+ },
+ { in: "query", name: "cursor", schema: { type: "string" } },
+ ],
+ responses: {
+ "200": {
+ content: {
+ "application/json": {
+ schema: {
+ properties: {
+ data: {
+ items: { $ref: "#/components/schemas/Envelope" },
+ type: "array",
+ },
+ nextCursor: { type: ["string", "null"] },
+ },
+ type: "object",
+ },
+ },
+ },
+ description: "A page of envelopes, newest first.",
+ },
+ ...errors,
+ },
+ summary: "List envelopes",
+ },
+ post: {
+ parameters: [idempotencyKey],
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: { $ref: "#/components/schemas/CreateEnvelope" },
+ },
+ "multipart/form-data": {
+ schema: {
+ properties: {
+ data: {
+ description: "CreateEnvelope as JSON, without uploadId.",
+ type: "string",
+ },
+ file: { format: "binary", type: "string" },
+ },
+ required: ["file", "data"],
+ type: "object",
+ },
+ },
+ },
+ required: true,
+ },
+ responses: {
+ "201": envelopeResponse("The envelope, sent if send was given."),
+ "413": errorResponse,
+ "422": errorResponse,
+ ...errors,
+ },
+ summary: "Create an envelope, and send it if asked",
+ },
+ },
+ "/envelopes/{id}": {
+ delete: {
+ parameters: [idParameter],
+ responses: { "200": { description: "Deleted." }, ...errors },
+ summary: "Delete a draft",
+ },
+ get: {
+ parameters: [idParameter],
+ responses: { "200": envelopeResponse("The envelope."), ...errors },
+ summary: "Get an envelope",
+ },
+ },
+ "/envelopes/{id}/events": {
+ get: {
+ parameters: [idParameter],
+ responses: {
+ "200": { description: "The audit trail, oldest first." },
+ ...errors,
+ },
+ summary: "Get an envelope's audit trail",
+ },
+ },
+ "/envelopes/{id}/files/{file}": {
+ get: {
+ parameters: [
+ idParameter,
+ {
+ in: "path",
+ name: "file",
+ required: true,
+ schema: { enum: ["signed", "certificate"], type: "string" },
+ },
+ ],
+ responses: {
+ "200": {
+ content: { "application/pdf": {} },
+ description: "The PDF.",
+ },
+ ...errors,
+ },
+ summary: "Download the signed PDF or the certificate of completion",
+ },
+ },
+ "/envelopes/{id}/remind": {
+ post: {
+ parameters: [idParameter],
+ responses: { "200": envelopeResponse("The envelope."), ...errors },
+ summary: "Remind the signer whose turn it is",
+ },
+ },
+ "/envelopes/{id}/send": {
+ post: {
+ parameters: [idParameter, idempotencyKey],
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: { $ref: "#/components/schemas/SendOptions" },
+ },
+ },
+ required: true,
+ },
+ responses: {
+ "200": envelopeResponse("The envelope, now sent."),
+ "422": errorResponse,
+ ...errors,
+ },
+ summary: "Send a draft",
+ },
+ },
+ "/envelopes/{id}/void": {
+ post: {
+ parameters: [idParameter],
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: {
+ properties: { reason: { maxLength: 1000, type: "string" } },
+ type: "object",
+ },
+ },
+ },
+ },
+ responses: {
+ "200": envelopeResponse("The envelope, now voided."),
+ ...errors,
+ },
+ summary: "Void a sent envelope",
+ },
+ },
+ "/me": {
+ get: {
+ responses: {
+ "200": { description: "The key and its administrator." },
+ ...errors,
+ },
+ summary: "Check a key",
+ },
+ },
+ "/openapi.json": {
+ get: {
+ responses: { "200": { description: "This document." } },
+ security: [],
+ summary: "This description",
+ },
+ },
+ "/templates": {
+ get: {
+ responses: { "200": { description: "Saved templates." }, ...errors },
+ summary: "List templates",
+ },
+ },
+ "/templates/{id}/envelopes": {
+ post: {
+ parameters: [idParameter, idempotencyKey],
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: {
+ properties: {
+ metadata: { type: "object" },
+ send: { $ref: "#/components/schemas/SendOptions" },
+ signers: {
+ description: "One per role, in the template's order.",
+ items: {
+ properties: {
+ email: { type: "string" },
+ name: { type: "string" },
+ },
+ type: "object",
+ },
+ type: "array",
+ },
+ title: { type: "string" },
+ },
+ required: ["title", "signers"],
+ type: "object",
+ },
+ },
+ },
+ required: true,
+ },
+ responses: {
+ "201": envelopeResponse("The new envelope."),
+ ...errors,
+ },
+ summary: "Create an envelope from a template",
+ },
+ },
+ "/uploads": {
+ post: {
+ responses: {
+ "201": {
+ description:
+ "Where to PUT the PDF (url, method, headers) and the uploadId to create the envelope with. Only on installs that store files in Vercel Blob.",
+ },
+ ...errors,
+ },
+ summary: "Get an upload URL for a PDF over 4 MB",
+ },
+ },
+ },
+ security: [{ apiKey: [] }],
+ servers: [{ url: serverUrl }],
+ };
+}
diff --git a/src/lib/api/route.ts b/src/lib/api/route.ts
new file mode 100644
index 0000000..c8e1c38
--- /dev/null
+++ b/src/lib/api/route.ts
@@ -0,0 +1,252 @@
+import { ZodError } from "zod";
+
+import type { ApiKeyScope } from "../api-keys.ts";
+import {
+ requireApiKey,
+ withRateLimitHeaders,
+ type RateLimitState,
+} from "../auth/api-key.ts";
+import { DownloadAccessError } from "../downloads.ts";
+import {
+ EnvelopeDocumentAccessError,
+ EnvelopeMutationError,
+} from "../envelopes.ts";
+import { ReminderMutationError } from "../reminders.ts";
+import { logRouteError } from "../security/logging.ts";
+import { consumeRateLimit } from "../security/rate-limit.ts";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "../security/request.ts";
+import { DocumentImportError } from "../services/document-import.ts";
+import { PendingUploadError } from "../services/pending-uploads.ts";
+import { TemplateError } from "../templates.ts";
+import { describeZodError, type ApiActor } from "./envelopes.ts";
+import { apiError, apiJson, codeForStatus } from "./http.ts";
+import {
+ claimIdempotencyKey,
+ completeIdempotencyKey,
+ hashRequest,
+ readIdempotencyKey,
+ releaseIdempotencyKey,
+} from "./idempotency.ts";
+
+// The frame every /api/v1 route runs in: the key is checked, errors the
+// app's own functions throw become API errors, and rate limit headers go
+// on whatever comes back.
+
+export type ApiContext = {
+ actor: ApiActor;
+ rateLimit: RateLimitState;
+ request: Request;
+};
+
+/** Turns an error from the app's functions into an API error, or null. */
+export function apiErrorFor(error: unknown): Response | null {
+ if (error instanceof ZodError) {
+ return apiError(400, "invalid_request", describeZodError(error));
+ }
+
+ if (error instanceof DocumentImportError) {
+ return error.code === "too_large"
+ ? apiError(413, "payload_too_large", error.message)
+ : apiError(400, "invalid_request", error.message);
+ }
+
+ if (error instanceof PendingUploadError) {
+ return apiError(400, "invalid_request", error.message);
+ }
+
+ if (
+ error instanceof EnvelopeMutationError ||
+ error instanceof EnvelopeDocumentAccessError ||
+ error instanceof DownloadAccessError ||
+ error instanceof TemplateError ||
+ error instanceof ReminderMutationError
+ ) {
+ return apiError(
+ error.statusCode,
+ codeForStatus(error.statusCode),
+ error.message,
+ );
+ }
+
+ return null;
+}
+
+export async function handleApi(
+ request: Request,
+ scope: ApiKeyScope,
+ category: string,
+ handler: (context: ApiContext) => Promise<Response>,
+): Promise<Response> {
+ const principal = await requireApiKey(request, scope);
+
+ if (principal instanceof Response) {
+ return principal;
+ }
+
+ const context: ApiContext = {
+ actor: {
+ apiKeyId: principal.apiKey.id,
+ email: principal.user.email,
+ ipAddress: getClientIpAddress(request.headers),
+ name: principal.user.name,
+ userAgent: getRequestUserAgent(request.headers),
+ userId: principal.user.id,
+ },
+ rateLimit: principal.rateLimit,
+ request,
+ };
+
+ try {
+ return withRateLimitHeaders(await handler(context), principal.rateLimit);
+ } catch (error) {
+ const known = apiErrorFor(error);
+
+ if (known) {
+ return withRateLimitHeaders(known, principal.rateLimit);
+ }
+
+ logRouteError(error, {
+ category,
+ ipAddress: context.actor.ipAddress,
+ message: "Unexpected failure in an API request.",
+ metadata: { apiKeyId: principal.apiKey.id },
+ path: getRequestPathname(request),
+ userId: principal.user.id,
+ });
+
+ return withRateLimitHeaders(
+ apiError(
+ 500,
+ "internal_error",
+ "Something went wrong on the install. Try again later.",
+ ),
+ principal.rateLimit,
+ );
+ }
+}
+
+/**
+ * Runs `run` once per Idempotency-Key. Without the header it simply runs.
+ * Only a response the caller can act on is kept: a 5xx lets the key go, so
+ * a retry runs again.
+ */
+export async function runIdempotently(
+ context: ApiContext,
+ route: string,
+ body: Uint8Array | string,
+ run: () => Promise<{ body: unknown; status: number }>,
+): Promise<Response> {
+ const key = readIdempotencyKey(context.request.headers);
+
+ if (key === undefined) {
+ return apiError(
+ 400,
+ "invalid_request",
+ "Idempotency-Key must be 1 to 255 characters.",
+ );
+ }
+
+ if (key === null) {
+ const result = await runCatching(run);
+
+ return apiJson(result.body, { status: result.status });
+ }
+
+ const claim = {
+ apiKeyId: context.actor.apiKeyId,
+ key,
+ requestHash: hashRequest(route, body),
+ };
+ const previous = await claimIdempotencyKey(claim);
+
+ switch (previous.kind) {
+ case "mismatch":
+ return apiError(
+ 422,
+ "idempotency_key_reused",
+ "This Idempotency-Key was used with a different request.",
+ );
+ case "in_progress":
+ return apiError(
+ 409,
+ "wrong_state",
+ "A request with this Idempotency-Key is still being worked on. Try again shortly.",
+ { "retry-after": "2" },
+ );
+ case "replay":
+ return apiJson(previous.response, {
+ headers: { "idempotent-replayed": "true" },
+ status: previous.statusCode,
+ });
+ case "new":
+ break;
+ }
+
+ let result: { body: unknown; status: number };
+
+ try {
+ result = await runCatching(run);
+ } catch (error) {
+ await releaseIdempotencyKey(claim).catch(() => undefined);
+ throw error;
+ }
+
+ if (result.status >= 500) {
+ await releaseIdempotencyKey(claim).catch(() => undefined);
+ } else {
+ await completeIdempotencyKey({
+ apiKeyId: claim.apiKeyId,
+ key,
+ response: result.body,
+ statusCode: result.status,
+ });
+ }
+
+ return apiJson(result.body, { status: result.status });
+}
+
+/** Known errors become a kept response; anything else is thrown on. */
+async function runCatching(
+ run: () => Promise<{ body: unknown; status: number }>,
+): Promise<{ body: unknown; status: number }> {
+ try {
+ return await run();
+ } catch (error) {
+ const known = apiErrorFor(error);
+
+ if (!known) {
+ throw error;
+ }
+
+ return { body: await known.json(), status: known.status };
+ }
+}
+
+/**
+ * Counts this request against a per-key limit on creating or sending. These
+ * are looser than the web app's per-person limits, since an app sends in
+ * bulk, but still stop a leaked key from flooding inboxes.
+ */
+export async function applyAccountLimit(
+ context: ApiContext,
+ input: { key: string; limit: number; windowMs: number },
+): Promise<Response | null> {
+ const decision = await consumeRateLimit({
+ key: `${input.key}:${context.actor.apiKeyId}`,
+ limit: input.limit,
+ windowMs: input.windowMs,
+ });
+
+ return decision.allowed
+ ? null
+ : apiError(
+ 429,
+ "rate_limited",
+ "This key has created or sent too many envelopes for now. Wait and try again.",
+ { "retry-after": String(decision.retryAfterSeconds) },
+ );
+}
diff --git a/src/lib/api/uploads.test.ts b/src/lib/api/uploads.test.ts
new file mode 100644
index 0000000..0d32ae1
--- /dev/null
+++ b/src/lib/api/uploads.test.ts
@@ -0,0 +1,44 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { issueApiUpload, pendingUploadKeyFor } from "./uploads.ts";
+
+const USER = "4f7d0a9e-0d0b-4a43-9b8a-1f1d7e8f2a10";
+
+test("an upload goes to the account's own pending folder, PDFs only", async () => {
+ const issued: unknown[] = [];
+ const presigned: unknown[] = [];
+ const upload = await issueApiUpload(USER, {
+ issueToken: async (options) => {
+ issued.push(options);
+ return { clientSigningToken: "c", delegationToken: "d" } as never;
+ },
+ now: Date.UTC(2026, 10, 17, 12),
+ presign: (async (_token: unknown, options: unknown) => {
+ presigned.push(options);
+ return { presignedUrl: "https://blob.example/upload?sig=1" };
+ }) as never,
+ });
+
+ assert.equal(upload.method, "PUT");
+ assert.equal(upload.url, "https://blob.example/upload?sig=1");
+ assert.equal(upload.expiresAt, "2026-11-17T12:10:00.000Z");
+ assert.equal(
+ pendingUploadKeyFor(USER, upload.uploadId),
+ `uploads/${USER}/${upload.uploadId}.pdf`,
+ );
+ assert.deepEqual(
+ (issued[0] as { allowedContentTypes: string[] }).allowedContentTypes,
+ ["application/pdf"],
+ );
+ assert.equal((presigned[0] as { access: string }).access, "private");
+ assert.equal(
+ (presigned[0] as { allowOverwrite: boolean }).allowOverwrite,
+ false,
+ );
+});
+
+test("an upload id that is not ours does not name a file", () => {
+ assert.equal(pendingUploadKeyFor(USER, "../../etc/passwd"), null);
+ assert.equal(pendingUploadKeyFor(USER, "not-a-uuid"), null);
+});
diff --git a/src/lib/api/uploads.ts b/src/lib/api/uploads.ts
new file mode 100644
index 0000000..0f44cbb
--- /dev/null
+++ b/src/lib/api/uploads.ts
@@ -0,0 +1,97 @@
+import { randomUUID } from "node:crypto";
+
+import {
+ issueSignedToken,
+ presignUrl,
+ type IssuedSignedToken,
+} from "@vercel/blob";
+
+import {
+ buildPendingUploadPrefix,
+ isPendingUploadKey,
+} from "../services/storage-keys.ts";
+import { MAX_UPLOAD_SIZE_BYTES } from "../types/domain.ts";
+
+// Large PDFs for the API. A request to a Vercel Function is capped at
+// 4.5 MB, so a bigger file goes straight to Vercel Blob: the API hands out a
+// signed URL good for one PUT of one PDF, the caller uploads to it, and then
+// names the upload when it creates the envelope. The file is read back and
+// checked like any other upload. One that is never used is deleted by Blob
+// after a day. This is the same signed-URL mechanism the web app's upload
+// page uses.
+
+const UPLOAD_URL_LIFETIME_MS = 10 * 60 * 1000;
+const PENDING_UPLOAD_TTL_DAYS = 1;
+
+type IssueToken = (options: {
+ allowedContentTypes: string[];
+ maximumSizeInBytes: number;
+ operations: ["put"];
+ pathname: string;
+ validUntil: number;
+}) => Promise<IssuedSignedToken>;
+
+type Presign = typeof presignUrl;
+
+export type ApiUpload = {
+ expiresAt: string;
+ headers: Record<string, string>;
+ maxBytes: number;
+ method: "PUT";
+ uploadId: string;
+ url: string;
+};
+
+export function pendingUploadKeyFor(
+ userId: string,
+ uploadId: string,
+): string | null {
+ const key = `${buildPendingUploadPrefix(userId)}${uploadId}.pdf`;
+
+ return isPendingUploadKey(key, userId) ? key : null;
+}
+
+export async function issueApiUpload(
+ userId: string,
+ {
+ issueToken = issueSignedToken,
+ now = Date.now(),
+ presign = presignUrl,
+ }: { issueToken?: IssueToken; now?: number; presign?: Presign } = {},
+): Promise<ApiUpload> {
+ const uploadId = randomUUID();
+ const pathname = pendingUploadKeyFor(userId, uploadId);
+
+ if (!pathname) {
+ throw new Error("Could not build an upload path for this account.");
+ }
+
+ const validUntil = now + UPLOAD_URL_LIFETIME_MS;
+ const token = await issueToken({
+ allowedContentTypes: ["application/pdf"],
+ maximumSizeInBytes: MAX_UPLOAD_SIZE_BYTES,
+ operations: ["put"],
+ pathname,
+ validUntil,
+ });
+ const { presignedUrl } = await presign(token, {
+ access: "private",
+ addRandomSuffix: false,
+ allowedContentTypes: ["application/pdf"],
+ allowOverwrite: false,
+ maximumSizeInBytes: MAX_UPLOAD_SIZE_BYTES,
+ operation: "put",
+ pathname,
+ ttlDays: PENDING_UPLOAD_TTL_DAYS,
+ validUntil,
+ });
+
+ return {
+ expiresAt: new Date(validUntil).toISOString(),
+ headers: { "content-type": "application/pdf" },
+ maxBytes: MAX_UPLOAD_SIZE_BYTES,
+ method: "PUT",
+ uploadId,
+ url: presignedUrl,
+ };
+}
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index 0281fc0..e7d1a0d 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -140,6 +140,8 @@ type CreateDraftEnvelopeInput = {
};
type SendDraftEnvelopeInput = {
+ /** The API key that sent it, recorded in the audit trail. */
+ apiKeyId?: string | null;
/** How many days signers get. The default applies when left out. */
expiresInDays?: number;
/** Days between automatic reminders. Null or left out means none. */
@@ -2598,6 +2600,7 @@ export async function sendDraftEnvelope(
event: "sent",
ipAddress: input.ipAddress ?? null,
metadata: {
+ ...(input.apiKeyId ? { apiKeyId: input.apiKeyId } : {}),
// The send route refuses a send without this confirmation.
expiresAt,
reminderIntervalDays: input.reminderIntervalDays ?? null,
diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.ts
index 4e5641b..a3c4805 100644
--- a/src/lib/retention-job.ts
+++ b/src/lib/retention-job.ts
@@ -1,5 +1,6 @@
import { createHash, timingSafeEqual } from "node:crypto";
+import { deleteExpiredIdempotencyKeys } from "./api/idempotency.ts";
import { getDb, type DbPool } from "./db/connection.ts";
import {
envelopeScheduleFailed,
@@ -171,6 +172,13 @@ export async function runRetentionJob({
}
});
+ await deleteExpiredIdempotencyKeys(database).catch((error: unknown) => {
+ // A database from before the API has no table to clear.
+ if (!isMissingSchemaError(error)) {
+ console.error("Clearing old API idempotency keys failed:", error);
+ }
+ });
+
const schedule = await runEnvelopeSchedule({
database,
emailService,