Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Keep an Idempotency-Key once its envelope is made, and fix four API details
Claudea2dcef4b57a3
diff --git a/docs/api.md b/docs/api.mdindex b580028..6000484 100644--- a/docs/api.md+++ b/docs/api.md@@ -193,7 +193,8 @@ curl https://sign.example.com/api/v1/envelopes \The upload URL works for 10 minutes, and an upload that is never used isdeleted 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.+Vercel) do not need this and answer 404: send PDFs of up to 20 MB in the+form.## The envelope@@ -259,7 +260,7 @@ webhooks (coming in the next release).| `GET /api/v1/envelopes/{id}` | read | One envelope. || `POST /api/v1/envelopes/{id}/send` | write | Sends a draft. Body: the `send` options above. || `POST /api/v1/envelopes/{id}/void` | write | Voids a sent envelope. Body: `{"reason": "…"}`, required on Part 11 installs. |-| `POST /api/v1/envelopes/{id}/remind` | write | Emails a reminder to each signer whose turn it is, at most once a day as in the web app. |+| `POST /api/v1/envelopes/{id}/remind` | write | Emails a reminder to each signer whose turn it is, at most once a day as in the web app. Too soon gets 429 with `Retry-After`. || `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. |diff --git a/src/app/api/v1/envelopes/route.ts b/src/app/api/v1/envelopes/route.tsindex 6885d43..55aa820 100644--- a/src/app/api/v1/envelopes/route.ts+++ b/src/app/api/v1/envelopes/route.ts@@ -15,6 +15,7 @@ import {API_SEND_LIMIT,apiErrorFor,handleApi,+ isKept,runIdempotently,} from "@/lib/api/route";import { pendingUploadKeyFor } from "@/lib/api/uploads";@@ -197,9 +198,13 @@ export async function POST(request: Request) {);} catch (error) {// Only the request that did the work removes the upload, and- // only when a retry would get the same refusal. After a failure- // of the install's own, the retry needs the upload again.- if (apiErrorFor(error)) {+ // only when a retry would get the same refusal: one that is+ // kept for the key. After a failure of the install's own (a+ // 5xx, such as email not being connected) or a 429, the key is+ // let go and the retry needs the upload again.+ const known = apiErrorFor(error);++ if (known && isKept(known.status)) {await cleanUp();}diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.tsindex 6390368..c062863 100644--- a/src/lib/api/openapi.ts+++ b/src/lib/api/openapi.ts@@ -4,7 +4,11 @@// allowed values come from the app's own, so they cannot drift either.import { getMaxSignersPerEnvelope } from "../signer-limit.ts";-import { fieldTypes, signatureMeanings } from "../types/domain.ts";+import {+ fieldTypes,+ MAX_SIGNERS_CEILING,+ signatureMeanings,+} from "../types/domain.ts";const errorResponse = {content: {@@ -39,13 +43,21 @@ const idParameter = {const idempotencyKey = {description:- "Any unique string of 1 to 255 characters, not only spaces (spaces at either end are ignored). A retry with the same key and body within 24 hours gets the first response again.",+ "Any unique string of 1 to 255 characters, not only spaces (spaces at either end are ignored). A retry with the same key and body within 24 hours gets the first response again. While the first request is still running, a retry gets 409 with Retry-After. If the first request made its envelope but failed before answering, a retry gets that envelope as it is now.",in: "header",name: "Idempotency-Key",required: false,schema: { maxLength: 255, minLength: 1, pattern: "\\S", type: "string" },};+/** A person's name: not blank, and spaces at either end are dropped. */+const personNameSchema = {+ maxLength: 120,+ minLength: 1,+ pattern: "\\S",+ type: "string",+};+/** Titles: not blank, and spaces at either end are dropped. */const titleSchema = {maxLength: 160,@@ -83,7 +95,7 @@ export function buildOpenApiDocument(items: {properties: {email: { format: "email", type: "string" },- name: { type: "string" },+ name: personNameSchema,},required: ["name", "email"],type: "object",@@ -112,7 +124,7 @@ export function buildOpenApiDocument(properties: {accessCode: { maxLength: 64, minLength: 4, type: "string" },email: { format: "email", type: "string" },- name: { maxLength: 120, type: "string" },+ name: personNameSchema,ref: {description: "Your name for this signer, used by fields.",pattern: "^[A-Za-z0-9._:-]{1,64}$",@@ -127,6 +139,7 @@ export function buildOpenApiDocument(step: {description:"The step of the signing order. Signers who share a step sign at the same time, and the next step starts once they all have. Give it for every signer or for none; left out, they sign one after the other.",+ maximum: MAX_SIGNERS_CEILING,minimum: 1,type: "integer",},@@ -639,7 +652,7 @@ export function buildOpenApiDocument(items: {properties: {email: { format: "email", type: "string" },- name: { maxLength: 120, type: "string" },+ name: personNameSchema,signatureMeaning: {description: "Part 11 installs only.",enum: [...signatureMeanings],diff --git a/src/lib/api/route.dbtest.ts b/src/lib/api/route.dbtest.tsnew file mode 100644index 0000000..9340c60--- /dev/null+++ b/src/lib/api/route.dbtest.ts@@ -0,0 +1,176 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { registerHooks } from "node:module";+import { after, before, test } from "node:test";++import type pg from "pg";++import { createApiKey } from "../api-keys.ts";+import { replaceDbPoolForTests } from "../db/connection.ts";+import { openTestDatabase } from "../db/test-database.ts";+import { ReminderMutationError } from "../reminders.ts";+import { claimIdempotencyKey, hashRequest } from "./idempotency.ts";+import type * as RouteModule from "./route.ts";++// The API's shared route code against a real Postgres. Run with+// `npm run test:db`.++// The API's responses come from next/server, which Next.js resolves for+// itself. Plain Node needs the file name.+registerHooks({+ resolve(specifier, context, nextResolve) {+ if (/^next\/[a-z-]+$/.test(specifier)) {+ return nextResolve(`${specifier}.js`, context);+ }++ return nextResolve(specifier, context);+ },+});++let database: pg.Pool;+let replaced: pg.Pool | null = null;+let route: typeof RouteModule;+const createdUsers: string[] = [];+const createdKeys: string[] = [];++before(async () => {+ database = await openTestDatabase();+ replaced = replaceDbPoolForTests(database);+ route = await import("./route.ts");+});++after(async () => {+ // api_idempotency has no foreign key to the key, so its rows go first.+ await database.query(+ `delete from public.api_idempotency where api_key_id = any($1)`,+ [createdKeys],+ );+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ replaceDbPoolForTests(replaced ?? database);+ await database.end();+});++async function createContext(idempotencyKey: string) {+ const id = randomUUID();+ const email = `${id}@example.test`;++ createdUsers.push(id);+ await database.query(+ `+ insert into public."user" (id, name, email, role, "emailVerified")+ values ($1, $2, $3, 'admin', true)+ `,+ [id, `Person ${id.slice(0, 4)}`, email],+ );++ const { summary } = await createApiKey(+ { email, userId: id },+ { expiresInDays: null, name: "Route test", scope: "write" },+ database,+ );++ createdKeys.push(summary.id);++ return {+ actor: {+ apiKeyId: summary.id,+ email,+ ipAddress: null,+ name: "Route test",+ userAgent: null,+ userId: id,+ },+ rateLimit: { limit: 120, remaining: 119, resetSeconds: 60 },+ request: new Request("http://localhost:3000/api/v1/envelopes", {+ headers: { "idempotency-key": idempotencyKey },+ method: "POST",+ }),+ };+}++test("a request whose envelope could not be noted keeps its key, so a retry cannot make a second one", async () => {+ const key = `order-${randomUUID()}`;+ const context = await createContext(key);+ const body = '{"title":"Lease"}';++ await assert.rejects(+ route.runIdempotently(+ context,+ "POST /api/v1/envelopes",+ body,+ async (remember) => {+ // Postgres refuses a NUL in text, so noting the envelope fails the+ // way it would if the database went away right after the send.+ await remember("envelope\u0000id");++ return { body: {}, status: 201 };+ },+ ),+ );++ assert.deepEqual(+ await claimIdempotencyKey(+ {+ apiKeyId: context.actor.apiKeyId,+ key,+ requestHash: hashRequest("POST /api/v1/envelopes", body),+ },+ database,+ ),+ { kind: "in_progress" },+ );+});++test("a request that fails before making anything lets its key go", async () => {+ const key = `order-${randomUUID()}`;+ const context = await createContext(key);+ const body = '{"title":"Lease"}';++ await assert.rejects(+ route.runIdempotently(context, "POST /api/v1/envelopes", body, async () => {+ throw new Error("The install had a problem.");+ }),+ );++ const claim = await claimIdempotencyKey(+ {+ apiKeyId: context.actor.apiKeyId,+ key,+ requestHash: hashRequest("POST /api/v1/envelopes", body),+ },+ database,+ );++ assert.equal(claim.kind, "new");+});++test("a reminder sent too soon says when the next one can go", async () => {+ const now = Math.floor(Date.now() / 1000);+ const response = route.apiErrorFor(+ new ReminderMutationError("You can send another reminder later.", 429, {+ nextAvailableAt: now + 3600,+ nextAvailableAtLabel: "later",+ }),+ );++ assert.equal(response?.status, 429);++ const wait = Number(response?.headers.get("retry-after"));++ assert.ok(wait > 3590 && wait <= 3600, `retry-after was ${String(wait)}`);+ assert.deepEqual(await response?.json(), {+ error: {+ code: "rate_limited",+ message: "You can send another reminder later.",+ },+ });+});++test("only refusals a retry would get again are kept for the key", () => {+ assert.equal(route.isKept(400), true);+ assert.equal(route.isKept(409), true);+ assert.equal(route.isKept(429), false);+ assert.equal(route.isKept(503), false);+});diff --git a/src/lib/api/route.ts b/src/lib/api/route.tsindex cb13622..439f8dc 100644--- a/src/lib/api/route.ts+++ b/src/lib/api/route.ts@@ -59,6 +59,23 @@ export function apiErrorFor(error: unknown): Response | null {return apiError(400, "invalid_request", error.message);}+ if (+ error instanceof ReminderMutationError &&+ error.statusCode === 429 &&+ error.nextAvailableAt !== null+ ) {+ // Too soon after the last reminder: Retry-After says when the next one+ // can go, as for every other 429 of the API.+ const waitSeconds = Math.max(+ 1,+ error.nextAvailableAt - Math.floor(Date.now() / 1000),+ );++ return apiError(429, codeForStatus(429), error.message, {+ "retry-after": String(waitSeconds),+ });+ }+if (error instanceof EnvelopeMutationError ||error instanceof EnvelopeDocumentAccessError ||@@ -150,8 +167,12 @@ 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) {+/**+ * Whether a response is kept for retries: not a 5xx, and not a 429. A+ * route that cleans up after a refusal does so only for these, since after+ * any other failure the retry runs again and needs what it was given.+ */+export function isKept(status: number) {return status < 500 && status !== 429;}@@ -163,7 +184,10 @@ function isKept(status: number) {* 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.+ * `recover(id)`, the envelope as it is, instead of a second envelope. If+ * even noting the id fails (the database went away just then), the key is+ * still kept: a retry is told to wait (409) until the key's 24 hours run+ * out, and never makes 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@@ -261,10 +285,14 @@ export async function runIdempotently(key,reservedAt: previous.reservedAt,};- let remembered = false;+ // Set as soon as `remember` is called, before its write: by then the+ // envelope is made (and sent, if asked), so even if noting it fails the+ // key is kept. A retry is told the request is still being worked on+ // rather than being let make and send a second envelope.+ let made = false;const remember = async (resourceId: string) => {+ made = true;await rememberIdempotentResource({ ...reservation, resourceId });- remembered = true;};let result: ApiResult;@@ -279,7 +307,7 @@ export async function runIdempotently(result = await runCatching(() => run(remember));} catch (error) {// Once the envelope exists, the key stays with it (see above).- if (!remembered) {+ if (!made) {await releaseIdempotencyKey(reservation).catch(() => undefined);}@@ -292,7 +320,7 @@ export async function runIdempotently(response: result.body,statusCode: result.status,});- } else if (!remembered) {+ } else if (!made) {await releaseIdempotencyKey(reservation).catch(() => undefined);}