Skip to content

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

TypeScript

Answer the review notes on the API endpoints

Claude200f2cec9b44
diff --git a/docs/api.md b/docs/api.md
index 6906261..38e4023 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -76,7 +76,7 @@ Every error has the same shape, and the code is meant for your program:
| 403 | `forbidden` | The key may not do this, such as a read-only key asked to send. |
| 404 | `not_found` | There is no such thing, or the key's administrator cannot see it. |
| 409 | `wrong_state` | Not possible in the envelope's current state, such as sending one that was sent already. |
-| 413 | `payload_too_large` | The file is too big. |
+| 413 | `payload_too_large` | The file is too big, or a JSON-only request is over 64 KB. |
| 422 | `idempotency_key_reused` | An `Idempotency-Key` was used before with a different request. |
| 429 | `rate_limited` | Too many requests. Wait the number of seconds in `Retry-After`. |
| 500 | `internal_error` | Something went wrong on the install. Try again later. |
@@ -91,7 +91,9 @@ stands:
- `RateLimit-Reset`: seconds until the window starts again.
On top of that, each key may create 60 envelopes in 10 minutes and send 100
-in an hour, counting creates and template calls that also send. Your email
+in an hour, counting creates and template calls that also send. A retry that
+gets its first answer again, through an `Idempotency-Key`, counts against
+neither. 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 gets 429 for
any more bad keys until the 10 minutes are up. Good keys from it keep
@@ -134,12 +136,13 @@ Things to know:
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.
+ app offers. On a Part 11 install, give each signer a `signatureMeaning`
+ (`approval`, `review`, `responsibility` or `authorship`) before sending.
- **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
+ down. Types: `signature`, `initials`, `date`, `name` (filled in with the
+ signer's name when they sign), `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
@@ -240,23 +243,23 @@ 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. |
-| `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. |
+| 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`, and `signatureMeaning` on Part 11 installs, 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
diff --git a/src/app/api/v1/envelopes/[id]/files/[file]/route.ts b/src/app/api/v1/envelopes/[id]/files/[file]/route.ts
index 45094bd..07c150d 100644
--- a/src/app/api/v1/envelopes/[id]/files/[file]/route.ts
+++ b/src/app/api/v1/envelopes/[id]/files/[file]/route.ts
@@ -17,7 +17,10 @@ export async function GET(request: Request, context: Context) {
"read",
"api_envelope_file_failure",
async ({ actor }) => {
- const type = FILE_TYPES[file as keyof typeof FILE_TYPES];
+ // Own keys only, so a name like "constructor" is a 404 too.
+ const type = Object.hasOwn(FILE_TYPES, file)
+ ? FILE_TYPES[file as keyof typeof FILE_TYPES]
+ : undefined;
if (!type) {
return apiError(
diff --git a/src/app/api/v1/envelopes/[id]/send/route.ts b/src/app/api/v1/envelopes/[id]/send/route.ts
index d2d7b13..7bd45e2 100644
--- a/src/app/api/v1/envelopes/[id]/send/route.ts
+++ b/src/app/api/v1/envelopes/[id]/send/route.ts
@@ -1,16 +1,12 @@
-import { apiError } from "@/lib/api/http";
+import { MAX_JSON_BODY_BYTES, readBodyWithin } from "@/lib/api/body";
+import { apiError, bodyTooLarge } from "@/lib/api/http";
import {
apiSendOptionsSchema,
describeZodError,
getApiEnvelope,
sendEnvelopeForApi,
} from "@/lib/api/envelopes";
-import {
- API_SEND_LIMIT,
- applyAccountLimit,
- handleApi,
- runIdempotently,
-} from "@/lib/api/route";
+import { API_SEND_LIMIT, handleApi, runIdempotently } from "@/lib/api/route";
type Context = { params: Promise<{ id: string }> };
@@ -23,13 +19,13 @@ export async function POST(request: Request, context: Context) {
"write",
"api_envelope_send_failure",
async (api) => {
- const limited = await applyAccountLimit(api, API_SEND_LIMIT);
+ const raw = await readBodyWithin(request, MAX_JSON_BODY_BYTES);
- if (limited) {
- return limited;
+ if (!raw) {
+ return bodyTooLarge();
}
- const text = await request.text();
+ const text = new TextDecoder().decode(raw);
let body: unknown;
try {
@@ -71,6 +67,7 @@ export async function POST(request: Request, context: Context) {
return readBack();
},
readBack,
+ [API_SEND_LIMIT],
);
},
);
diff --git a/src/app/api/v1/envelopes/[id]/void/route.ts b/src/app/api/v1/envelopes/[id]/void/route.ts
index 08e149c..ccc25e6 100644
--- a/src/app/api/v1/envelopes/[id]/void/route.ts
+++ b/src/app/api/v1/envelopes/[id]/void/route.ts
@@ -1,10 +1,15 @@
-import { apiError, apiJson } from "@/lib/api/http";
+import { MAX_JSON_BODY_BYTES, readBodyWithin } from "@/lib/api/body";
+import { apiError, apiJson, bodyTooLarge } 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 }> };
+// As long as a reason the app keeps. A longer one is refused rather than
+// cut short, so the audit trail has the reason exactly as it was sent.
+const MAX_REASON_LENGTH = 1000;
+
// 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) {
@@ -17,7 +22,13 @@ export async function POST(request: Request, context: Context) {
async ({ actor }) => {
// No body is fine; a body that is not a JSON object is refused, so a
// cut-off request never voids without the reason it meant to give.
- const text = await request.text();
+ const raw = await readBodyWithin(request, MAX_JSON_BODY_BYTES);
+
+ if (!raw) {
+ return bodyTooLarge();
+ }
+
+ const text = new TextDecoder().decode(raw);
let body: unknown = {};
if (text.trim()) {
@@ -45,9 +56,13 @@ export async function POST(request: Request, context: Context) {
if (
reason !== undefined &&
reason !== null &&
- typeof reason !== "string"
+ (typeof reason !== "string" || reason.length > MAX_REASON_LENGTH)
) {
- return apiError(400, "invalid_request", "reason must be a string.");
+ return apiError(
+ 400,
+ "invalid_request",
+ "reason must be a string of at most 1,000 characters.",
+ );
}
await voidSentEnvelope(actor.userId, id, {
diff --git a/src/app/api/v1/envelopes/route.ts b/src/app/api/v1/envelopes/route.ts
index 5b3dafe..d265fa6 100644
--- a/src/app/api/v1/envelopes/route.ts
+++ b/src/app/api/v1/envelopes/route.ts
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
-import { apiError, apiJson } from "@/lib/api/http";
+import { readBodyWithin } from "@/lib/api/body";
+import { apiError, apiJson, bodyTooLarge } from "@/lib/api/http";
import {
apiCreateEnvelopeSchema,
apiListQuerySchema,
@@ -13,7 +14,6 @@ import {
API_CREATE_LIMIT,
API_SEND_LIMIT,
apiErrorFor,
- applyAccountLimit,
handleApi,
runIdempotently,
} from "@/lib/api/route";
@@ -64,17 +64,15 @@ export async function POST(request: Request) {
"write",
"api_envelope_create_failure",
async (context) => {
- const limited = await applyAccountLimit(context, API_CREATE_LIMIT);
-
- if (limited) {
- return limited;
- }
-
- const raw = new Uint8Array(await request.arrayBuffer());
+ // A little room over the PDF limit for the form's own parts. Reading
+ // stops there, so an oversized request is never held whole.
+ const raw = await readBodyWithin(
+ request,
+ MAX_UPLOAD_SIZE_BYTES + 256 * 1024,
+ );
- // 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.");
+ if (!raw) {
+ return bodyTooLarge();
}
const contentType = request.headers.get("content-type") ?? "";
@@ -177,14 +175,6 @@ export async function POST(request: Request) {
return apiError(400, "invalid_request", describeZodError(input.error));
}
- if (input.data.send) {
- const sendLimited = await applyAccountLimit(context, API_SEND_LIMIT);
-
- if (sendLimited) {
- return sendLimited;
- }
- }
-
return runIdempotently(
context,
"POST /api/v1/envelopes",
@@ -229,6 +219,9 @@ export async function POST(request: Request) {
status: 404,
};
},
+ input.data.send
+ ? [API_CREATE_LIMIT, API_SEND_LIMIT]
+ : [API_CREATE_LIMIT],
);
},
);
diff --git a/src/app/api/v1/templates/[id]/envelopes/route.ts b/src/app/api/v1/templates/[id]/envelopes/route.ts
index d4fa50d..b58e8c2 100644
--- a/src/app/api/v1/templates/[id]/envelopes/route.ts
+++ b/src/app/api/v1/templates/[id]/envelopes/route.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
-import { apiError } from "@/lib/api/http";
+import { MAX_JSON_BODY_BYTES, readBodyWithin } from "@/lib/api/body";
+import { apiError, bodyTooLarge } from "@/lib/api/http";
import {
apiSendOptionsSchema,
describeZodError,
@@ -12,12 +13,12 @@ import {
import {
API_CREATE_LIMIT,
API_SEND_LIMIT,
- applyAccountLimit,
handleApi,
runIdempotently,
} from "@/lib/api/route";
import { deleteDraftEnvelope } from "@/lib/envelopes";
import { createDraftFromTemplate } from "@/lib/templates";
+import { signatureMeanings } from "@/lib/types/domain";
type Context = { params: Promise<{ id: string }> };
@@ -32,7 +33,16 @@ const bodySchema = z.object({
)
.optional(),
send: apiSendOptionsSchema.optional(),
- signers: z.array(z.object({ email: z.string(), name: z.string() })).min(1),
+ signers: z
+ .array(
+ z.object({
+ email: z.string(),
+ name: z.string(),
+ // Part 11 installs need one for each signer before sending.
+ signatureMeaning: z.enum(signatureMeanings).optional(),
+ }),
+ )
+ .min(1),
title: z.string(),
});
@@ -46,13 +56,13 @@ export async function POST(request: Request, context: Context) {
"write",
"api_template_use_failure",
async (api) => {
- const limited = await applyAccountLimit(api, API_CREATE_LIMIT);
+ const raw = await readBodyWithin(request, MAX_JSON_BODY_BYTES);
- if (limited) {
- return limited;
+ if (!raw) {
+ return bodyTooLarge();
}
- const text = await request.text();
+ const text = new TextDecoder().decode(raw);
let parsed: unknown;
try {
@@ -67,14 +77,6 @@ export async function POST(request: Request, context: Context) {
return apiError(400, "invalid_request", describeZodError(body.error));
}
- if (body.data.send) {
- const sendLimited = await applyAccountLimit(api, API_SEND_LIMIT);
-
- if (sendLimited) {
- return sendLimited;
- }
- }
-
const readBack = async (envelopeId: string) => {
const envelope = await getApiEnvelope(api.actor.userId, envelopeId);
@@ -123,6 +125,9 @@ export async function POST(request: Request, context: Context) {
return readBack(draft.envelopeId);
},
readBack,
+ body.data.send
+ ? [API_CREATE_LIMIT, API_SEND_LIMIT]
+ : [API_CREATE_LIMIT],
);
},
);
diff --git a/src/lib/api/body.test.ts b/src/lib/api/body.test.ts
new file mode 100644
index 0000000..9ed6785
--- /dev/null
+++ b/src/lib/api/body.test.ts
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { readBodyWithin } from "./body.ts";
+
+function streamOf(chunks: string[], onCancel: () => void) {
+ const encoder = new TextEncoder();
+ let index = 0;
+
+ return new ReadableStream<Uint8Array>({
+ cancel: onCancel,
+ pull(controller) {
+ if (index < chunks.length) {
+ controller.enqueue(encoder.encode(chunks[index]));
+ index += 1;
+ } else {
+ controller.close();
+ }
+ },
+ });
+}
+
+function requestWith(body: ReadableStream<Uint8Array>, headers = {}) {
+ return new Request("https://sign.example.test/api/v1/envelopes", {
+ body,
+ // Needed by Node for a streamed body.
+ duplex: "half",
+ headers,
+ method: "POST",
+ } as RequestInit);
+}
+
+test("a body within the limit is read whole", async () => {
+ const body = await readBodyWithin(
+ requestWith(streamOf(['{"a":', "1}"], () => undefined)),
+ 16,
+ );
+
+ assert.equal(new TextDecoder().decode(body ?? undefined), '{"a":1}');
+});
+
+test("a body over the limit is refused without reading the rest", async () => {
+ let cancelled = false;
+ const body = await readBodyWithin(
+ requestWith(
+ streamOf(["12345678", "12345678", "never read"], () => {
+ cancelled = true;
+ }),
+ ),
+ 10,
+ );
+
+ assert.equal(body, null);
+ assert.equal(cancelled, true);
+});
+
+test("a declared length over the limit is refused before reading", async () => {
+ const request = requestWith(
+ streamOf(["12345678901234567890"], () => undefined),
+ { "content-length": "100" },
+ );
+
+ assert.equal(await readBodyWithin(request, 10), null);
+ assert.equal(request.bodyUsed, false);
+});
+
+test("no body reads as empty", async () => {
+ const body = await readBodyWithin(
+ new Request("https://sign.example.test/api/v1/envelopes/x/void", {
+ method: "POST",
+ }),
+ 10,
+ );
+
+ assert.equal(body?.byteLength, 0);
+});
diff --git a/src/lib/api/body.ts b/src/lib/api/body.ts
new file mode 100644
index 0000000..b354574
--- /dev/null
+++ b/src/lib/api/body.ts
@@ -0,0 +1,55 @@
+// Reading an API request's body with a size limit.
+
+/** The most a JSON-only API request may carry. */
+export const MAX_JSON_BODY_BYTES = 64 * 1024;
+
+/**
+ * Reads the request body, or returns null as soon as it passes `maxBytes`.
+ * The rest is not read, so an oversized request never sits whole in
+ * memory, wherever the install runs.
+ */
+export async function readBodyWithin(
+ request: Request,
+ maxBytes: number,
+): Promise<Uint8Array<ArrayBuffer> | null> {
+ const declared = Number(request.headers.get("content-length"));
+
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ return null;
+ }
+
+ if (!request.body) {
+ return new Uint8Array(0);
+ }
+
+ const reader = request.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+
+ for (;;) {
+ const { done, value } = await reader.read();
+
+ if (done) {
+ break;
+ }
+
+ total += value.byteLength;
+
+ if (total > maxBytes) {
+ await reader.cancel().catch(() => undefined);
+ return null;
+ }
+
+ chunks.push(value);
+ }
+
+ const body = new Uint8Array(total);
+ let offset = 0;
+
+ for (const chunk of chunks) {
+ body.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+
+ return body;
+}
diff --git a/src/lib/api/envelopes.dbtest.ts b/src/lib/api/envelopes.dbtest.ts
index 2fc1cf5..a1c0043 100644
--- a/src/lib/api/envelopes.dbtest.ts
+++ b/src/lib/api/envelopes.dbtest.ts
@@ -285,28 +285,31 @@ test("a create that cannot be finished leaves no draft behind", async () => {
});
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,
- },
- ],
- }),
+ const signatureFor = (signer: string) => ({
+ height: 0.05,
+ page: 1,
+ signer,
+ type: "signature",
+ width: 0.3,
+ x: 0.1,
+ y: 0.8,
+ });
+
+ assert.throws(
+ () => request({ fields: [signatureFor("nobody")] }),
+ /No signer has the ref/,
);
- assert.throws(() =>
- request({
- signers: [
- { email: "[email protected]", name: "A", ref: "same" },
- { email: "[email protected]", name: "B", ref: "same" },
- ],
- }),
+ // Every field names "same", so the only thing wrong is the repeated ref.
+ assert.throws(
+ () =>
+ request({
+ fields: [signatureFor("same")],
+ signers: [
+ { email: "[email protected]", name: "A", ref: "same" },
+ { email: "[email protected]", name: "B", ref: "same" },
+ ],
+ }),
+ /Each signer needs its own ref/,
);
assert.throws(() => request({ metadata: { blob: "x".repeat(3000) } }));
assert.throws(() => request({ send: { permittedUseConfirmed: false } }));
@@ -334,13 +337,32 @@ 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) {
+ for (let index = 0; index < 4; index += 1) {
ids.push(
(await createEnvelopeForApi(actor, request(), source(), database)).id,
);
}
- // Same-second creations still come back in a stable order.
+ // One envelope is older, and three were made in the same second, so the
+ // id must keep their order stable across pages.
+ const [older, ...sameSecond] = ids as [string, ...string[]];
+
+ await database.query(`update envelopes set created_at = $2 where id = $1`, [
+ older,
+ 1_000,
+ ]);
+ await database.query(
+ `update envelopes set created_at = $2 where id = any($1::text[])`,
+ [sameSecond, 2_000],
+ );
+
+ const expected = await database.query<{ id: string }>(
+ `
+ select id from envelopes where id = any($1::text[])
+ order by created_at desc, id desc
+ `,
+ [ids],
+ );
const first = await listApiEnvelopes(actor.userId, { limit: 2 }, database);
assert.equal(first.data.length, 2);
@@ -352,12 +374,13 @@ test("the list pages with a cursor, newest first, and filters by status", async
database,
);
- assert.equal(second.data.length, 1);
+ assert.equal(second.data.length, 2);
assert.equal(second.nextCursor, null);
assert.deepEqual(
- new Set([...first.data, ...second.data].map((envelope) => envelope.id)),
- new Set(ids),
+ [...first.data, ...second.data].map((envelope) => envelope.id),
+ expected.rows.map((row) => row.id),
);
+ assert.equal(expected.rows.at(-1)?.id, older);
assert.equal(
(
await listApiEnvelopes(
@@ -378,8 +401,13 @@ test("an idempotency key replays the first response and refuses a different requ
requestHash: "a".repeat(64),
};
- assert.deepEqual(await claimIdempotencyKey(claim, database), { kind: "new" });
- assert.deepEqual(await claimIdempotencyKey(claim, database), {
+ const now = Math.floor(Date.now() / 1000);
+
+ assert.deepEqual(await claimIdempotencyKey(claim, database, now), {
+ kind: "new",
+ reservedAt: now,
+ });
+ assert.deepEqual(await claimIdempotencyKey(claim, database, now), {
kind: "in_progress",
});
@@ -387,6 +415,7 @@ test("an idempotency key replays the first response and refuses a different requ
{
apiKeyId: actor.apiKeyId,
key: "order-1042",
+ reservedAt: now,
response: { id: "env_1" },
statusCode: 201,
},
@@ -410,12 +439,16 @@ test("an idempotency key replays the first response and refuses a different requ
const other = await createActor();
assert.deepEqual(
- await claimIdempotencyKey({ ...claim, apiKeyId: other.apiKeyId }, database),
- { kind: "new" },
+ await claimIdempotencyKey(
+ { ...claim, apiKeyId: other.apiKeyId },
+ database,
+ now,
+ ),
+ { kind: "new", reservedAt: now },
);
// After the window the value is free again.
- const later = Math.floor(Date.now() / 1000) + IDEMPOTENCY_WINDOW_SECONDS + 1;
+ const later = now + IDEMPOTENCY_WINDOW_SECONDS + 1;
assert.deepEqual(
await claimIdempotencyKey(
@@ -423,14 +456,52 @@ test("an idempotency key replays the first response and refuses a different requ
database,
later,
),
- { kind: "new" },
+ { kind: "new", reservedAt: later },
+ );
+
+ // Work left over from the old reservation does not touch the new one.
+ await completeIdempotencyKey(
+ {
+ apiKeyId: actor.apiKeyId,
+ key: "order-1042",
+ reservedAt: now,
+ response: { id: "env_old" },
+ statusCode: 201,
+ },
+ database,
);
- assert.ok(
- (await deleteExpiredIdempotencyKeys(
+ assert.deepEqual(
+ await claimIdempotencyKey(
+ { ...claim, requestHash: "c".repeat(64) },
database,
- later + IDEMPOTENCY_WINDOW_SECONDS,
- )) >= 1,
+ later,
+ ),
+ { kind: "in_progress" },
);
+
+ // The daily cleanup, in a transaction that is rolled back, so it cannot
+ // take other tests' keys with it.
+ const client = await database.connect();
+
+ try {
+ await client.query("begin");
+ assert.ok(
+ (await deleteExpiredIdempotencyKeys(
+ client,
+ later + IDEMPOTENCY_WINDOW_SECONDS,
+ )) >= 1,
+ );
+
+ const left = await client.query(
+ `select 1 from api_idempotency where api_key_id = $1`,
+ [actor.apiKeyId],
+ );
+
+ assert.equal(left.rowCount, 0);
+ } finally {
+ await client.query("rollback");
+ client.release();
+ }
});
test("once the envelope is made and sent, a retry is told about it instead of making another", async () => {
@@ -441,8 +512,12 @@ test("once the envelope is made and sent, a retry is told about it instead of ma
requestHash: "d".repeat(64),
};
const remembered: string[] = [];
+ const now = Math.floor(Date.now() / 1000);
- assert.deepEqual(await claimIdempotencyKey(claim, database), { kind: "new" });
+ assert.deepEqual(await claimIdempotencyKey(claim, database, now), {
+ kind: "new",
+ reservedAt: now,
+ });
const envelope = await createEnvelopeForApi(
actor,
@@ -460,7 +535,12 @@ test("once the envelope is made and sent, a retry is told about it instead of ma
assert.equal(row.rows[0]?.status, "sent");
remembered.push(envelopeId);
await rememberIdempotentResource(
- { apiKeyId: claim.apiKeyId, key: claim.key, resourceId: envelopeId },
+ {
+ apiKeyId: claim.apiKeyId,
+ key: claim.key,
+ reservedAt: now,
+ resourceId: envelopeId,
+ },
database,
);
},
@@ -470,8 +550,9 @@ test("once the envelope is made and sent, a retry is told about it instead of ma
assert.deepEqual(remembered, [envelope.id]);
// Say the answer could not be read back and the request failed here: the
// key is kept, and the retry is pointed at the envelope.
- assert.deepEqual(await claimIdempotencyKey(claim, database), {
+ assert.deepEqual(await claimIdempotencyKey(claim, database, now), {
kind: "recover",
+ reservedAt: now,
resourceId: envelope.id,
});
});
diff --git a/src/lib/api/http.ts b/src/lib/api/http.ts
index b9b512d..5bd953e 100644
--- a/src/lib/api/http.ts
+++ b/src/lib/api/http.ts
@@ -60,3 +60,8 @@ export function codeForStatus(status: number): ApiErrorCode {
return status >= 500 ? "internal_error" : "invalid_request";
}
}
+
+/** The answer when a body is over its limit. */
+export function bodyTooLarge() {
+ return apiError(413, "payload_too_large", "The request is too large.");
+}
diff --git a/src/lib/api/idempotency.ts b/src/lib/api/idempotency.ts
index 4707d17..7759573 100644
--- a/src/lib/api/idempotency.ts
+++ b/src/lib/api/idempotency.ts
@@ -7,13 +7,18 @@ import { getDb, queryOne, type DbExecutor } from "../db/connection.ts";
// 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.
+//
+// Each reservation is known by when it was made (`reservedAt`), and every
+// later write names it. So work left over from an old reservation, such as
+// a slow recovery just as its 24 hours run out, never touches the newer
+// reservation of a request that reused the key.
export const IDEMPOTENCY_WINDOW_SECONDS = 24 * 60 * 60;
export type IdempotencyClaim =
- | { kind: "new" }
+ | { kind: "new"; reservedAt: number }
| { kind: "replay"; response: unknown; statusCode: number }
- | { kind: "recover"; resourceId: string }
+ | { kind: "recover"; reservedAt: number; resourceId: string }
| { kind: "in_progress" }
| { kind: "mismatch" };
@@ -66,11 +71,12 @@ export async function claimIdempotencyKey(
);
if ((inserted.rowCount ?? 0) === 1) {
- return { kind: "new" };
+ return { kind: "new", reservedAt: now };
}
const existing = await queryOne<{
requestHash: string;
+ reservedAt: number;
resourceId: string | null;
response: unknown;
statusCode: number | null;
@@ -78,7 +84,7 @@ export async function claimIdempotencyKey(
database,
`
SELECT request_hash AS "requestHash", status_code AS "statusCode",
- response, resource_id AS "resourceId"
+ response, resource_id AS "resourceId", created_at AS "reservedAt"
FROM api_idempotency
WHERE api_key_id = $1 AND idempotency_key = $2
`,
@@ -98,7 +104,11 @@ export async function claimIdempotencyKey(
// The first request made its envelope and then failed, or is still
// finishing: either way the answer is that envelope.
return existing.resourceId
- ? { kind: "recover", resourceId: existing.resourceId }
+ ? {
+ kind: "recover",
+ reservedAt: Number(existing.reservedAt),
+ resourceId: existing.resourceId,
+ }
: { kind: "in_progress" };
}
@@ -109,25 +119,28 @@ export async function claimIdempotencyKey(
};
}
+/** One reservation of a key, as a claim made it. */
+export type IdempotencyReservation = {
+ apiKeyId: string;
+ key: string;
+ reservedAt: number;
+};
+
/** Keeps the response for retries. */
export async function completeIdempotencyKey(
- input: {
- apiKeyId: string;
- key: string;
- response: unknown;
- statusCode: number;
- },
+ input: IdempotencyReservation & { 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
+ SET status_code = $4, response = $5
+ WHERE api_key_id = $1 AND idempotency_key = $2 AND created_at = $3
`,
[
input.apiKeyId,
input.key,
+ input.reservedAt,
input.statusCode,
JSON.stringify(input.response),
],
@@ -139,16 +152,16 @@ export async function completeIdempotencyKey(
* failure cannot lead a retry to make it again.
*/
export async function rememberIdempotentResource(
- input: { apiKeyId: string; key: string; resourceId: string },
+ input: IdempotencyReservation & { resourceId: string },
database: DbExecutor = getDb(),
) {
await database.query(
`
UPDATE api_idempotency
- SET resource_id = $3
- WHERE api_key_id = $1 AND idempotency_key = $2
+ SET resource_id = $4
+ WHERE api_key_id = $1 AND idempotency_key = $2 AND created_at = $3
`,
- [input.apiKeyId, input.key, input.resourceId],
+ [input.apiKeyId, input.key, input.reservedAt, input.resourceId],
);
}
@@ -157,12 +170,15 @@ export async function rememberIdempotentResource(
* install had a problem), so the retry runs for real.
*/
export async function releaseIdempotencyKey(
- input: { apiKeyId: string; key: string },
+ input: IdempotencyReservation,
database: DbExecutor = getDb(),
) {
await database.query(
- `DELETE FROM api_idempotency WHERE api_key_id = $1 AND idempotency_key = $2`,
- [input.apiKeyId, input.key],
+ `
+ DELETE FROM api_idempotency
+ WHERE api_key_id = $1 AND idempotency_key = $2 AND created_at = $3
+ `,
+ [input.apiKeyId, input.key, input.reservedAt],
);
}
diff --git a/src/lib/api/openapi.test.ts b/src/lib/api/openapi.test.ts
index ed616f7..5a042e2 100644
--- a/src/lib/api/openapi.test.ts
+++ b/src/lib/api/openapi.test.ts
@@ -3,6 +3,8 @@ import { readdir } from "node:fs/promises";
import path from "node:path";
import { test } from "node:test";
+import { fieldTypeSchema } from "../schemas/field.ts";
+import { signatureMeanings } from "../types/domain.ts";
import { buildOpenApiDocument } from "./openapi.ts";
// Every route file under src/app/api/v1 has a path in the OpenAPI
@@ -57,3 +59,19 @@ test("the OpenAPI description matches the route files", async () => {
assert.deepEqual(described, methods, `methods for ${route}`);
}
});
+
+test("the OpenAPI description allows the values the API accepts", () => {
+ const document = buildOpenApiDocument("https://sign.example.com/api/v1");
+ const { CreateEnvelope, Field } = document.components.schemas;
+ const fromTemplate =
+ document.paths["/templates/{id}/envelopes"].post.requestBody.content[
+ "application/json"
+ ].schema.properties.signers.items.properties;
+
+ assert.deepEqual(Field.properties.type.enum, fieldTypeSchema.options);
+ assert.deepEqual(
+ CreateEnvelope.properties.signers.items.properties.signatureMeaning.enum,
+ [...signatureMeanings],
+ );
+ assert.deepEqual(fromTemplate.signatureMeaning.enum, [...signatureMeanings]);
+});
diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts
index 9072703..46875b3 100644
--- a/src/lib/api/openapi.ts
+++ b/src/lib/api/openapi.ts
@@ -1,6 +1,9 @@
// 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.
+// path here has a route file, so the two cannot drift apart. Lists of
+// allowed values come from the app's own, so they cannot drift either.
+
+import { fieldTypes, signatureMeanings } from "../types/domain.ts";
const errorResponse = {
content: {
@@ -101,12 +104,7 @@ export function buildOpenApiDocument(serverUrl: string) {
requireEmailCode: { type: "boolean" },
signatureMeaning: {
description: "Part 11 installs only.",
- enum: [
- "approval",
- "review",
- "responsibility",
- "authorship",
- ],
+ enum: [...signatureMeanings],
type: "string",
},
},
@@ -218,19 +216,7 @@ export function buildOpenApiDocument(serverUrl: string) {
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",
- },
+ type: { enum: [...fieldTypes], type: "string" },
width: { exclusiveMinimum: 0, maximum: 1, type: "number" },
x: { maximum: 1, minimum: 0, type: "number" },
y: { maximum: 1, minimum: 0, type: "number" },
@@ -364,7 +350,9 @@ export function buildOpenApiDocument(serverUrl: string) {
type: "array",
},
nextCursor: { type: ["string", "null"] },
+ object: { const: "list", type: "string" },
},
+ required: ["object", "data", "nextCursor"],
type: "object",
},
},
@@ -380,7 +368,12 @@ export function buildOpenApiDocument(serverUrl: string) {
requestBody: {
content: {
"application/json": {
- schema: { $ref: "#/components/schemas/CreateEnvelope" },
+ schema: {
+ allOf: [
+ { $ref: "#/components/schemas/CreateEnvelope" },
+ { required: ["uploadId"] },
+ ],
+ },
},
"multipart/form-data": {
schema: {
@@ -410,7 +403,25 @@ export function buildOpenApiDocument(serverUrl: string) {
"/envelopes/{id}": {
delete: {
parameters: [idParameter],
- responses: { "200": { description: "Deleted." }, ...errors },
+ responses: {
+ "200": {
+ content: {
+ "application/json": {
+ schema: {
+ properties: {
+ deleted: { const: true, type: "boolean" },
+ id: { type: "string" },
+ object: { const: "envelope", type: "string" },
+ },
+ required: ["deleted", "id", "object"],
+ type: "object",
+ },
+ },
+ },
+ description: "Deleted.",
+ },
+ ...errors,
+ },
summary: "Delete a draft",
},
get: {
@@ -494,6 +505,7 @@ export function buildOpenApiDocument(serverUrl: string) {
},
responses: {
"200": envelopeResponse("The envelope, now sent."),
+ "413": errorResponse,
"422": errorResponse,
...errors,
},
@@ -515,6 +527,7 @@ export function buildOpenApiDocument(serverUrl: string) {
},
responses: {
"200": envelopeResponse("The envelope, now voided."),
+ "413": errorResponse,
...errors,
},
summary: "Void a sent envelope",
@@ -587,20 +600,32 @@ export function buildOpenApiDocument(serverUrl: string) {
"application/json": {
schema: {
properties: {
- metadata: { type: "object" },
+ metadata: {
+ description:
+ "Up to 2048 bytes of JSON, returned with the envelope.",
+ 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" },
+ email: { format: "email", type: "string" },
+ name: { maxLength: 120, type: "string" },
+ signatureMeaning: {
+ description: "Part 11 installs only.",
+ enum: [...signatureMeanings],
+ type: "string",
+ },
},
+ required: ["name", "email"],
type: "object",
},
+ maxItems: 10,
+ minItems: 1,
type: "array",
},
- title: { type: "string" },
+ title: { maxLength: 160, type: "string" },
},
required: ["title", "signers"],
type: "object",
@@ -611,6 +636,8 @@ export function buildOpenApiDocument(serverUrl: string) {
},
responses: {
"201": envelopeResponse("The new envelope."),
+ "413": errorResponse,
+ "422": errorResponse,
...errors,
},
summary: "Create an envelope from a template",
diff --git a/src/lib/api/route.ts b/src/lib/api/route.ts
index 5424d47..49b84ff 100644
--- a/src/lib/api/route.ts
+++ b/src/lib/api/route.ts
@@ -132,15 +132,26 @@ export async function handleApi(
type ApiResult = { body: unknown; status: number };
+type AccountLimit = { key: string; limit: number; windowMs: number };
+
+/** Whether a response is kept for retries: not a 5xx, and not a 429. */
+function isKept(status: number) {
+ return status < 500 && status !== 429;
+}
+
/**
* 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.
+ * Only a response the caller can act on is kept: a 5xx or a 429 lets the
+ * key go, so a retry runs again.
*
* Except once `run` has done what cannot be undone: it calls `remember`
* with the envelope's id as soon as the envelope is made (and sent, if
* asked). From then on a failure keeps the key, and a retry gets
* `recover(id)`, the envelope as it is, instead of a second envelope.
+ *
+ * `limits` count only a request that does the work now. A replay or a
+ * recovery costs nothing, so a retry of a request that worked is never
+ * refused for being over a limit.
*/
export async function runIdempotently(
context: ApiContext,
@@ -148,6 +159,7 @@ export async function runIdempotently(
body: Uint8Array | string,
run: (remember: (resourceId: string) => Promise<void>) => Promise<ApiResult>,
recover?: (resourceId: string) => Promise<ApiResult>,
+ limits: AccountLimit[] = [],
): Promise<Response> {
const key = readIdempotencyKey(context.request.headers);
@@ -160,6 +172,12 @@ export async function runIdempotently(
}
if (key === null) {
+ const refused = await applyAccountLimits(context, limits);
+
+ if (refused) {
+ return refused;
+ }
+
const result = await runCatching(() => run(async () => {}));
return apiJson(result.body, { status: result.status });
@@ -203,10 +221,11 @@ export async function runIdempotently(
const recovered = await runCatching(() => recover(previous.resourceId));
- if (recovered.status < 500) {
+ if (isKept(recovered.status)) {
await completeIdempotencyKey({
apiKeyId: claim.apiKeyId,
key,
+ reservedAt: previous.reservedAt,
response: recovered.body,
statusCode: recovered.status,
});
@@ -221,44 +240,65 @@ export async function runIdempotently(
break;
}
+ const reservation = {
+ apiKeyId: claim.apiKeyId,
+ key,
+ reservedAt: previous.reservedAt,
+ };
let remembered = false;
const remember = async (resourceId: string) => {
- await rememberIdempotentResource({
- apiKeyId: claim.apiKeyId,
- key,
- resourceId,
- });
+ await rememberIdempotentResource({ ...reservation, resourceId });
remembered = true;
};
let result: ApiResult;
try {
+ const refused = await applyAccountLimits(context, limits);
+
+ if (refused) {
+ await releaseIdempotencyKey(reservation).catch(() => undefined);
+ return refused;
+ }
+
result = await runCatching(() => run(remember));
} catch (error) {
// Once the envelope exists, the key stays with it (see above).
if (!remembered) {
- await releaseIdempotencyKey(claim).catch(() => undefined);
+ await releaseIdempotencyKey(reservation).catch(() => undefined);
}
throw error;
}
- if (result.status >= 500) {
- if (!remembered) {
- await releaseIdempotencyKey(claim).catch(() => undefined);
- }
- } else {
+ if (isKept(result.status)) {
await completeIdempotencyKey({
- apiKeyId: claim.apiKeyId,
- key,
+ ...reservation,
response: result.body,
statusCode: result.status,
});
+ } else if (!remembered) {
+ await releaseIdempotencyKey(reservation).catch(() => undefined);
}
return apiJson(result.body, { status: result.status });
}
+/** The first of `limits` this request is over, as a 429, or null. */
+async function applyAccountLimits(
+ context: ApiContext,
+ limits: AccountLimit[],
+): Promise<Response | null> {
+ for (const limit of limits) {
+ const refused = await applyAccountLimit(context, limit);
+
+ if (refused) {
+ return refused;
+ }
+ }
+
+ return null;
+}
+
/** Known errors become a kept response; anything else is thrown on. */
async function runCatching(run: () => Promise<ApiResult>): Promise<ApiResult> {
try {
@@ -298,7 +338,7 @@ export const API_SEND_LIMIT = {
*/
export async function applyAccountLimit(
context: ApiContext,
- input: { key: string; limit: number; windowMs: number },
+ input: AccountLimit,
): Promise<Response | null> {
const decision = await consumeRateLimit({
key: `${input.key}:${context.actor.apiKeyId}`,
diff --git a/src/lib/schemas/template.ts b/src/lib/schemas/template.ts
index 8198d91..7ec6f70 100644
--- a/src/lib/schemas/template.ts
+++ b/src/lib/schemas/template.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
-import { MAX_SIGNERS_PER_ENVELOPE } from "../types/domain.ts";
+import {
+ MAX_SIGNERS_PER_ENVELOPE,
+ signatureMeanings,
+} from "../types/domain.ts";
import {
emailSchema,
envelopeTitleSchema,
@@ -73,7 +76,16 @@ export const saveTemplateSchema = z.object({
/** Starting an envelope from a template: who fills each role, in order. */
export const useTemplateSchema = z.object({
signers: z
- .array(z.object({ email: emailSchema, name: nameSchema }))
+ .array(
+ z.object({
+ email: emailSchema,
+ name: nameSchema,
+ // What the signature means, for Part 11 envelopes. The web app
+ // asks for it later; the API can give it here, so the draft can be
+ // sent at once.
+ signatureMeaning: z.enum(signatureMeanings).optional(),
+ }),
+ )
.min(1)
.max(MAX_SIGNERS_PER_ENVELOPE)
.superRefine((signers, ctx) => {
diff --git a/src/lib/templates.dbtest.ts b/src/lib/templates.dbtest.ts
index ba0b29f..1716892 100644
--- a/src/lib/templates.dbtest.ts
+++ b/src/lib/templates.dbtest.ts
@@ -210,6 +210,44 @@ test("a template keeps the document, the fields and the order, and no one's name
);
});
+test("a meaning given for a signer is kept on the draft made from a template", async () => {
+ // Part 11 installs need one for each signer before sending, and the API
+ // gives them here so it can send the draft at once.
+ const userId = await createUser();
+ const { envelopeId: originalId } = await createPreparedDraft(userId);
+ const template = await saveEnvelopeAsTemplate(
+ userId,
+ originalId,
+ { name: "Lease" },
+ { database, storageService },
+ );
+ const made = await createDraftFromTemplate(
+ userId,
+ template.id,
+ {
+ signers: [
+ {
+ email: "[email protected]",
+ name: "Tess Tenant",
+ signatureMeaning: "approval",
+ },
+ { email: "[email protected]", name: "Lou Landlord" },
+ ],
+ title: "Lease for 4 Mill Lane",
+ },
+ { database, storageService },
+ );
+ const saved = await database.query<{ signature_meaning: string | null }>(
+ `select signature_meaning from signers where envelope_id = $1 order by sign_order`,
+ [made.envelopeId],
+ );
+
+ assert.deepEqual(
+ saved.rows.map((row) => row.signature_meaning),
+ ["approval", null],
+ );
+});
+
test("a draft made from a template has the fields on the people named for it", async () => {
const userId = await createUser();
const { envelopeId: originalId } = await createPreparedDraft(userId);