Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Fix the review findings on the API endpoints
Claudebb1dfbdf6d48
diff --git a/db/migrations/20261118100500_api_idempotency_resource.sql b/db/migrations/20261118100500_api_idempotency_resource.sqlnew file mode 100644index 0000000..0279b29--- /dev/null+++ b/db/migrations/20261118100500_api_idempotency_resource.sql@@ -0,0 +1,8 @@+-- api_idempotency.resource_id: the envelope a request made, set as soon as+-- it has made it. If the request then fails (say, reading the envelope+-- back for the answer), the reservation is kept, and a retry with the same+-- Idempotency-Key answers with that envelope instead of making and sending+-- a second one.++alter table public.api_idempotency+ add column if not exists resource_id text;diff --git a/docs/api.md b/docs/api.mdindex e60496d..4e76fb7 100644--- a/docs/api.md+++ b/docs/api.md@@ -89,9 +89,10 @@ 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. 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.+in an hour, counting creates and template calls that also send. 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@@ -152,8 +153,10 @@ Things to know:- **`Idempotency-Key`** makes a retry safe. A request with a key SignuDoc hasseen 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.+ key with a different request is refused with 422. If the install fails+ after the envelope was made, a retry with the same key gets that envelope+ rather than a second one. Use one key per thing you mean to send, such as+ the invoice number.### PDFs over 4 MBdiff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 9dfd886..d113f82 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -1384,6 +1384,14 @@ test("an administrator makes an API key, an app sends and downloads an envelopeawait expect(signerPage).toHaveURL(/\/sign\/[^/]+\/done/);await signer.close();+ // A cut-off body is refused, never read as "no reason given".+ const cutOff = await api.post(`/api/v1/envelopes/${envelope.id}/void`, {+ data: '{"reason":',+ headers: { ...auth, "content-type": "application/json" },+ });++ expect(cutOff.status()).toBe(400);+const finished = await api.get(`/api/v1/envelopes/${envelope.id}`, {headers: auth,});diff --git a/src/app/api/v1/envelopes/[id]/send/route.ts b/src/app/api/v1/envelopes/[id]/send/route.tsindex 578e2c3..d2d7b13 100644--- a/src/app/api/v1/envelopes/[id]/send/route.ts+++ b/src/app/api/v1/envelopes/[id]/send/route.ts@@ -5,7 +5,12 @@ import {getApiEnvelope,sendEnvelopeForApi,} from "@/lib/api/envelopes";-import { applyAccountLimit, handleApi, runIdempotently } from "@/lib/api/route";+import {+ API_SEND_LIMIT,+ applyAccountLimit,+ handleApi,+ runIdempotently,+} from "@/lib/api/route";type Context = { params: Promise<{ id: string }> };@@ -18,11 +23,7 @@ export async function POST(request: Request, context: Context) {"write","api_envelope_send_failure",async (api) => {- const limited = await applyAccountLimit(api, {- key: "api-envelope-send",- limit: 100,- windowMs: 60 * 60 * 1000,- });+ const limited = await applyAccountLimit(api, API_SEND_LIMIT);if (limited) {return limited;@@ -47,24 +48,29 @@ export async function POST(request: Request, context: Context) {);}+ const readBack = async () => {+ 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,+ };+ };+return runIdempotently(api,`POST /api/v1/envelopes/${id}/send`,text,- async () => {+ async (remember) => {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,- };+ await remember(id);+ return readBack();},+ readBack,);},);diff --git a/src/app/api/v1/envelopes/[id]/void/route.ts b/src/app/api/v1/envelopes/[id]/void/route.tsindex f8a1055..fff08a9 100644--- a/src/app/api/v1/envelopes/[id]/void/route.ts+++ b/src/app/api/v1/envelopes/[id]/void/route.ts@@ -15,7 +15,23 @@ export async function POST(request: Request, context: Context) {"write","api_envelope_void_failure",async ({ actor }) => {- const body = (await request.json().catch(() => ({}))) as unknown;+ // No body is fine; a body that is not JSON is refused, so a cut-off+ // request never voids without the reason it meant to give.+ const text = await request.text();+ let body: unknown = {};++ if (text.trim()) {+ try {+ body = JSON.parse(text) as unknown;+ } catch {+ return apiError(+ 400,+ "invalid_request",+ "The body is not valid JSON.",+ );+ }+ }+const reason =typeof body === "object" && body !== null? (body as { reason?: unknown }).reasondiff --git a/src/app/api/v1/envelopes/route.ts b/src/app/api/v1/envelopes/route.tsindex 838812c..c52dec5 100644--- a/src/app/api/v1/envelopes/route.ts+++ b/src/app/api/v1/envelopes/route.ts@@ -6,9 +6,17 @@ import {apiListQuerySchema,createEnvelopeForApi,describeZodError,+ getApiEnvelope,listApiEnvelopes,} from "@/lib/api/envelopes";-import { applyAccountLimit, handleApi, runIdempotently } from "@/lib/api/route";+import {+ API_CREATE_LIMIT,+ API_SEND_LIMIT,+ apiErrorFor,+ applyAccountLimit,+ handleApi,+ runIdempotently,+} from "@/lib/api/route";import { pendingUploadKeyFor } from "@/lib/api/uploads";import {discardPendingUpload,@@ -56,11 +64,7 @@ export async function POST(request: Request) {"write","api_envelope_create_failure",async (context) => {- const limited = await applyAccountLimit(context, {- key: "api-envelope-create",- limit: 60,- windowMs: 10 * 60 * 1000,- });+ const limited = await applyAccountLimit(context, API_CREATE_LIMIT);if (limited) {return limited;@@ -167,23 +171,59 @@ export async function POST(request: Request) {return apiError(400, "invalid_request", describeZodError(input.error));}- try {- return await runIdempotently(- context,- "POST /api/v1/envelopes",- fingerprint,- async () => ({- body: await createEnvelopeForApi(+ if (input.data.send) {+ const sendLimited = await applyAccountLimit(context, API_SEND_LIMIT);++ if (sendLimited) {+ return sendLimited;+ }+ }++ return runIdempotently(+ context,+ "POST /api/v1/envelopes",+ fingerprint,+ async (remember) => {+ let envelope;++ try {+ envelope = await createEnvelopeForApi(context.actor,input.data,await readPdf(),- ),- status: 201,- }),- );- } finally {- await cleanUp();- }+ undefined,+ { onCreated: remember },+ );+ } 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)) {+ await cleanUp();+ }++ throw error;+ }++ await cleanUp();+ return { body: envelope, status: 201 };+ },+ async (envelopeId) => {+ const envelope = await getApiEnvelope(+ context.actor.userId,+ envelopeId,+ );++ return envelope+ ? { body: envelope, status: 201 }+ : {+ body: {+ error: { code: "not_found", message: "Envelope not found." },+ },+ status: 404,+ };+ },+ );},);}diff --git a/src/app/api/v1/templates/[id]/envelopes/route.ts b/src/app/api/v1/templates/[id]/envelopes/route.tsindex bf94184..d4fa50d 100644--- a/src/app/api/v1/templates/[id]/envelopes/route.ts+++ b/src/app/api/v1/templates/[id]/envelopes/route.ts@@ -9,7 +9,13 @@ import {MAX_API_METADATA_BYTES,sendEnvelopeForApi,} from "@/lib/api/envelopes";-import { applyAccountLimit, handleApi, runIdempotently } from "@/lib/api/route";+import {+ API_CREATE_LIMIT,+ API_SEND_LIMIT,+ applyAccountLimit,+ handleApi,+ runIdempotently,+} from "@/lib/api/route";import { deleteDraftEnvelope } from "@/lib/envelopes";import { createDraftFromTemplate } from "@/lib/templates";@@ -40,11 +46,7 @@ export async function POST(request: Request, context: Context) {"write","api_template_use_failure",async (api) => {- const limited = await applyAccountLimit(api, {- key: "api-envelope-create",- limit: 60,- windowMs: 10 * 60 * 1000,- });+ const limited = await applyAccountLimit(api, API_CREATE_LIMIT);if (limited) {return limited;@@ -65,11 +67,32 @@ 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);++ return envelope+ ? { body: envelope, status: 201 }+ : {+ body: {+ error: { code: "not_found", message: "Envelope not found." },+ },+ status: 404,+ };+ };+return runIdempotently(api,`POST /api/v1/templates/${id}/envelopes`,text,- async () => {+ async (remember) => {const draft = await createDraftFromTemplate(api.actor.userId, id, {signers: body.data.signers,title: body.data.title,@@ -96,11 +119,10 @@ export async function POST(request: Request, context: Context) {throw error;}- return {- body: await getApiEnvelope(api.actor.userId, draft.envelopeId),- status: 201,- };+ await remember(draft.envelopeId);+ return readBack(draft.envelopeId);},+ readBack,);},);diff --git a/src/lib/api/envelopes.dbtest.ts b/src/lib/api/envelopes.dbtest.tsindex 917179c..ad414df 100644--- a/src/lib/api/envelopes.dbtest.ts+++ b/src/lib/api/envelopes.dbtest.ts@@ -23,6 +23,7 @@ import {completeIdempotencyKey,deleteExpiredIdempotencyKeys,IDEMPOTENCY_WINDOW_SECONDS,+ rememberIdempotentResource,} from "./idempotency.ts";// The public API's envelopes against a real Postgres and real files. Run@@ -430,3 +431,79 @@ test("an idempotency key replays the first response and refuses a different requ)) >= 1,);});++test("once the envelope is made and sent, a retry is told about it instead of making another", async () => {+ const actor = await createActor();+ const claim = {+ apiKeyId: actor.apiKeyId,+ key: `order-${randomUUID()}`,+ requestHash: "d".repeat(64),+ };+ const remembered: string[] = [];++ assert.deepEqual(await claimIdempotencyKey(claim, database), { kind: "new" });++ const envelope = await createEnvelopeForApi(+ actor,+ request({ send: { permittedUseConfirmed: true } }),+ source(),+ database,+ {+ onCreated: async (envelopeId) => {+ // Only once the send has happened.+ const row = await database.query<{ status: string }>(+ `select status from envelopes where id = $1`,+ [envelopeId],+ );++ assert.equal(row.rows[0]?.status, "sent");+ remembered.push(envelopeId);+ await rememberIdempotentResource(+ { apiKeyId: claim.apiKeyId, key: claim.key, resourceId: envelopeId },+ database,+ );+ },+ },+ );++ 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), {+ kind: "recover",+ resourceId: envelope.id,+ });+});++test("a create that fails is not remembered, so its retry runs for real", async () => {+ const actor = await createActor();+ let called = false;++ await assert.rejects(+ createEnvelopeForApi(+ actor,+ request({+ fields: [+ {+ height: 0.05,+ page: 9,+ signer: "client",+ type: "signature",+ width: 0.3,+ x: 0.1,+ y: 0.7,+ },+ ],+ }),+ source(),+ database,+ {+ onCreated: async () => {+ called = true;+ },+ },+ ),+ EnvelopeMutationError,+ );+ assert.equal(called, false);+});diff --git a/src/lib/api/envelopes.ts b/src/lib/api/envelopes.tsindex 57b16ae..86f2017 100644--- a/src/lib/api/envelopes.ts+++ b/src/lib/api/envelopes.ts@@ -233,6 +233,10 @@ export async function createEnvelopeForApi(input: ApiCreateEnvelopeInput,sourcePdf: { body: Uint8Array; contentType: string; filename: string },database: DbPool = getDb(),+ options: {+ /** Called once the envelope is made, and sent if asked, for good. */+ onCreated?: (envelopeId: string) => Promise<void>;+ } = {},): Promise<ApiEnvelope> {const draft = await createDraftEnvelope(actor.userId,@@ -326,6 +330,8 @@ export async function createEnvelopeForApi(throw error;}+ await options.onCreated?.(envelopeId);+const envelope = await getApiEnvelope(actor.userId, envelopeId, database);if (!envelope) {diff --git a/src/lib/api/idempotency.ts b/src/lib/api/idempotency.tsindex 2dc91aa..4707d17 100644--- a/src/lib/api/idempotency.ts+++ b/src/lib/api/idempotency.ts@@ -13,6 +13,7 @@ export const IDEMPOTENCY_WINDOW_SECONDS = 24 * 60 * 60;export type IdempotencyClaim =| { kind: "new" }| { kind: "replay"; response: unknown; statusCode: number }+ | { kind: "recover"; resourceId: string }| { kind: "in_progress" }| { kind: "mismatch" };@@ -70,12 +71,14 @@ export async function claimIdempotencyKey(const existing = await queryOne<{requestHash: string;+ resourceId: string | null;response: unknown;statusCode: number | null;}>(database,`- SELECT request_hash AS "requestHash", status_code AS "statusCode", response+ SELECT request_hash AS "requestHash", status_code AS "statusCode",+ response, resource_id AS "resourceId"FROM api_idempotencyWHERE api_key_id = $1 AND idempotency_key = $2`,@@ -92,7 +95,11 @@ export async function claimIdempotencyKey(}if (existing.statusCode === null) {- return { kind: "in_progress" };+ // 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: "in_progress" };}return {@@ -127,6 +134,24 @@ export async function completeIdempotencyKey();}+/**+ * Notes what the request has made, as soon as it has made it, so a later+ * failure cannot lead a retry to make it again.+ */+export async function rememberIdempotentResource(+ input: { apiKeyId: string; key: string; resourceId: string },+ database: DbExecutor = getDb(),+) {+ await database.query(+ `+ UPDATE api_idempotency+ SET resource_id = $3+ WHERE api_key_id = $1 AND idempotency_key = $2+ `,+ [input.apiKeyId, input.key, input.resourceId],+ );+}+/*** Lets the key go after a failure that a retry might not repeat (the* install had a problem), so the retry runs for real.diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.tsindex a4450e9..4449ab4 100644--- a/src/lib/api/openapi.ts+++ b/src/lib/api/openapi.ts@@ -43,6 +43,16 @@ const idempotencyKey = {const isoTime = { format: "date-time", type: ["string", "null"] };+/** A {"object": "list", "data": [...]} answer of `item`s. */+const listOf = (item: Record<string, unknown>) => ({+ properties: {+ data: { items: item, type: "array" },+ object: { const: "list", type: "string" },+ },+ required: ["object", "data"],+ type: "object",+});+export function buildOpenApiDocument(serverUrl: string) {return {components: {@@ -259,6 +269,39 @@ export function buildOpenApiDocument(serverUrl: string) {},type: "object",},+ Template: {+ properties: {+ id: { type: "string" },+ name: { type: "string" },+ object: { const: "template", type: "string" },+ roles: {+ description: "Its roles, in signing order.",+ items: { type: "string" },+ type: "array",+ },+ },+ required: ["object", "id", "name", "roles"],+ type: "object",+ },+ Upload: {+ properties: {+ expiresAt: { format: "date-time", type: "string" },+ headers: {+ additionalProperties: { type: "string" },+ description: "Send these headers with the PUT.",+ type: "object",+ },+ maxBytes: { type: "integer" },+ method: { const: "PUT", type: "string" },+ uploadId: {+ description: "Pass it to POST /envelopes once the PUT is done.",+ type: "string",+ },+ url: { format: "uri", type: "string" },+ },+ required: ["uploadId", "url", "method", "headers", "expiresAt"],+ type: "object",+ },},securitySchemes: {apiKey: {@@ -369,7 +412,31 @@ export function buildOpenApiDocument(serverUrl: string) {get: {parameters: [idParameter],responses: {- "200": { description: "The audit trail, oldest first." },+ "200": {+ content: {+ "application/json": {+ schema: listOf({+ properties: {+ actor: {+ properties: {+ email: { type: ["string", "null"] },+ type: { type: "string" },+ },+ type: "object",+ },+ at: { format: "date-time", type: "string" },+ event: { type: "string" },+ id: { type: "string" },+ ipAddress: { type: ["string", "null"] },+ metadata: { type: ["object", "null"] },+ },+ required: ["id", "event", "at", "actor"],+ type: "object",+ }),+ },+ },+ description: "The audit trail, oldest first.",+ },...errors,},summary: "Get an envelope's audit trail",@@ -445,7 +512,34 @@ export function buildOpenApiDocument(serverUrl: string) {"/me": {get: {responses: {- "200": { description: "The key and its administrator." },+ "200": {+ content: {+ "application/json": {+ schema: {+ properties: {+ key: {+ properties: {+ id: { type: "string" },+ name: { type: "string" },+ scope: { enum: ["read", "write"], type: "string" },+ },+ type: "object",+ },+ user: {+ properties: {+ email: { type: "string" },+ id: { type: "string" },+ name: { type: "string" },+ },+ type: "object",+ },+ },+ type: "object",+ },+ },+ },+ description: "The key and its administrator.",+ },...errors,},summary: "Check a key",@@ -460,7 +554,17 @@ export function buildOpenApiDocument(serverUrl: string) {},"/templates": {get: {- responses: { "200": { description: "Saved templates." }, ...errors },+ responses: {+ "200": {+ content: {+ "application/json": {+ schema: listOf({ $ref: "#/components/schemas/Template" }),+ },+ },+ description: "Saved templates.",+ },+ ...errors,+ },summary: "List templates",},},@@ -505,6 +609,11 @@ export function buildOpenApiDocument(serverUrl: string) {post: {responses: {"201": {+ content: {+ "application/json": {+ schema: { $ref: "#/components/schemas/Upload" },+ },+ },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.",},diff --git a/src/lib/api/route.ts b/src/lib/api/route.tsindex c8e1c38..5424d47 100644--- a/src/lib/api/route.ts+++ b/src/lib/api/route.ts@@ -30,6 +30,7 @@ import {hashRequest,readIdempotencyKey,releaseIdempotencyKey,+ rememberIdempotentResource,} from "./idempotency.ts";// The frame every /api/v1 route runs in: the key is checked, errors the@@ -129,16 +130,24 @@ export async function handleApi(}}+type ApiResult = { body: unknown; status: number };+/*** 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.+ *+ * 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.*/export async function runIdempotently(context: ApiContext,route: string,body: Uint8Array | string,- run: () => Promise<{ body: unknown; status: number }>,+ run: (remember: (resourceId: string) => Promise<void>) => Promise<ApiResult>,+ recover?: (resourceId: string) => Promise<ApiResult>,): Promise<Response> {const key = readIdempotencyKey(context.request.headers);@@ -151,7 +160,7 @@ export async function runIdempotently(}if (key === null) {- const result = await runCatching(run);+ const result = await runCatching(() => run(async () => {}));return apiJson(result.body, { status: result.status });}@@ -182,21 +191,62 @@ export async function runIdempotently(headers: { "idempotent-replayed": "true" },status: previous.statusCode,});+ case "recover": {+ if (!recover) {+ return apiError(+ 409,+ "wrong_state",+ "A request with this Idempotency-Key is still being worked on. Try again shortly.",+ { "retry-after": "2" },+ );+ }++ const recovered = await runCatching(() => recover(previous.resourceId));++ if (recovered.status < 500) {+ await completeIdempotencyKey({+ apiKeyId: claim.apiKeyId,+ key,+ response: recovered.body,+ statusCode: recovered.status,+ });+ }++ return apiJson(recovered.body, {+ headers: { "idempotent-replayed": "true" },+ status: recovered.status,+ });+ }case "new":break;}- let result: { body: unknown; status: number };+ let remembered = false;+ const remember = async (resourceId: string) => {+ await rememberIdempotentResource({+ apiKeyId: claim.apiKeyId,+ key,+ resourceId,+ });+ remembered = true;+ };+ let result: ApiResult;try {- result = await runCatching(run);+ result = await runCatching(() => run(remember));} catch (error) {- await releaseIdempotencyKey(claim).catch(() => undefined);+ // Once the envelope exists, the key stays with it (see above).+ if (!remembered) {+ await releaseIdempotencyKey(claim).catch(() => undefined);+ }+throw error;}if (result.status >= 500) {- await releaseIdempotencyKey(claim).catch(() => undefined);+ if (!remembered) {+ await releaseIdempotencyKey(claim).catch(() => undefined);+ }} else {await completeIdempotencyKey({apiKeyId: claim.apiKeyId,@@ -210,9 +260,7 @@ export async function runIdempotently(}/** 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 }> {+async function runCatching(run: () => Promise<ApiResult>): Promise<ApiResult> {try {return await run();} catch (error) {@@ -226,6 +274,23 @@ async function runCatching(}}+/** Creating envelopes: per key, every 10 minutes. */+export const API_CREATE_LIMIT = {+ key: "api-envelope-create",+ limit: 60,+ windowMs: 10 * 60 * 1000,+};++/**+ * Sending envelopes, whichever route sends them: per key, every hour. A+ * create or template call that also sends counts here too.+ */+export const API_SEND_LIMIT = {+ key: "api-envelope-send",+ limit: 100,+ windowMs: 60 * 60 * 1000,+};+/*** 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