Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Answer the second review round on the API endpoints
Claude2493f6f8aa39
diff --git a/src/app/api/v1/envelopes/route.ts b/src/app/api/v1/envelopes/route.tsindex d265fa6..6885d43 100644--- a/src/app/api/v1/envelopes/route.ts+++ b/src/app/api/v1/envelopes/route.ts@@ -1,6 +1,6 @@import { createHash } from "node:crypto";-import { readBodyWithin } from "@/lib/api/body";+import { MAX_JSON_BODY_BYTES, readBodyWithin } from "@/lib/api/body";import { apiError, apiJson, bodyTooLarge } from "@/lib/api/http";import {apiCreateEnvelopeSchema,@@ -64,24 +64,29 @@ export async function POST(request: Request) {"write","api_envelope_create_failure",async (context) => {- // 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 contentType = request.headers.get("content-type") ?? "";+ const isMultipart = contentType+ .toLowerCase()+ .startsWith("multipart/form-data");+ // A PDF comes as multipart, allowed a little over the PDF limit for+ // the form's own parts. Anything else is JSON and held to the JSON+ // limit. Reading stops at the limit, so an oversized request is+ // never held whole.const raw = await readBodyWithin(request,- MAX_UPLOAD_SIZE_BYTES + 256 * 1024,+ isMultipart ? MAX_UPLOAD_SIZE_BYTES + 256 * 1024 : MAX_JSON_BODY_BYTES,);if (!raw) {return bodyTooLarge();}- 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")) {+ if (isMultipart) {const form = await new Request(request.url, {body: raw,headers: { "content-type": contentType },diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.tsindex 46875b3..cb0c961 100644--- a/src/lib/api/openapi.ts+++ b/src/lib/api/openapi.ts@@ -19,6 +19,7 @@ const errors = {"404": errorResponse,"409": errorResponse,"429": errorResponse,+ "500": errorResponse,};const envelopeResponse = (description: string) => ({@@ -37,11 +38,19 @@ const idParameter = {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.",+ "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.",in: "header",name: "Idempotency-Key",required: false,- schema: { maxLength: 255, type: "string" },+ schema: { maxLength: 255, minLength: 1, pattern: "\\S", type: "string" },+};++/** Titles: not blank, and spaces at either end are dropped. */+const titleSchema = {+ maxLength: 160,+ minLength: 1,+ pattern: "\\S",+ type: "string",};const isoTime = { format: "date-time", type: ["string", "null"] };@@ -115,7 +124,7 @@ export function buildOpenApiDocument(serverUrl: string) {minItems: 1,type: "array",},- title: { maxLength: 160, type: "string" },+ title: titleSchema,uploadId: {description: "With JSON: the id from POST /uploads.",type: "string",@@ -625,7 +634,7 @@ export function buildOpenApiDocument(serverUrl: string) {minItems: 1,type: "array",},- title: { maxLength: 160, type: "string" },+ title: titleSchema,},required: ["title", "signers"],type: "object",diff --git a/src/lib/api/route.ts b/src/lib/api/route.tsindex 49b84ff..cb13622 100644--- a/src/lib/api/route.ts+++ b/src/lib/api/route.ts@@ -13,7 +13,7 @@ import {} from "../envelopes.ts";import { ReminderMutationError } from "../reminders.ts";import { logRouteError } from "../security/logging.ts";-import { consumeRateLimit } from "../security/rate-limit.ts";+import { consumeRateLimit, peekRateLimit } from "../security/rate-limit.ts";import {getClientIpAddress,getRequestPathname,@@ -76,13 +76,36 @@ export function apiErrorFor(error: unknown): Response | null {return null;}+function internalError(): Response {+ return apiError(+ 500,+ "internal_error",+ "Something went wrong on the install. Try again later.",+ );+}+export async function handleApi(request: Request,scope: ApiKeyScope,category: string,handler: (context: ApiContext) => Promise<Response>,): Promise<Response> {- const principal = await requireApiKey(request, scope);+ let principal: Awaited<ReturnType<typeof requireApiKey>>;++ // Checking the key can fail too (the database is down). That gets the+ // same JSON answer and the same log line as a failure further on.+ try {+ principal = await requireApiKey(request, scope);+ } catch (error) {+ logRouteError(error, {+ category,+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while checking an API key.",+ path: getRequestPathname(request),+ });++ return internalError();+ }if (principal instanceof Response) {return principal;@@ -119,14 +142,7 @@ export async function handleApi(userId: principal.user.id,});- return withRateLimitHeaders(- apiError(- 500,- "internal_error",- "Something went wrong on the install. Try again later.",- ),- principal.rateLimit,- );+ return withRateLimitHeaders(internalError(), principal.rateLimit);}}@@ -283,11 +299,29 @@ export async function runIdempotently(return apiJson(result.body, { status: result.status });}-/** The first of `limits` this request is over, as a 429, or null. */+/**+ * The first of `limits` this request is over, as a 429, or null. With more+ * than one, all are checked before any is counted, so a request that one+ * limit refuses does not use up the others (a create that would also send,+ * refused for sending, still leaves the key its creates).+ */async function applyAccountLimits(context: ApiContext,limits: AccountLimit[],): Promise<Response | null> {+ if (limits.length > 1) {+ for (const limit of limits) {+ const state = await peekRateLimit({+ key: accountLimitKey(context, limit),+ limit: limit.limit,+ });++ if (!state.allowed) {+ return accountLimitRefusal(state.retryAfterSeconds);+ }+ }+ }+for (const limit of limits) {const refused = await applyAccountLimit(context, limit);@@ -341,17 +375,25 @@ export async function applyAccountLimit(input: AccountLimit,): Promise<Response | null> {const decision = await consumeRateLimit({- key: `${input.key}:${context.actor.apiKeyId}`,+ key: accountLimitKey(context, input),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) },- );+ : accountLimitRefusal(decision.retryAfterSeconds);+}++function accountLimitKey(context: ApiContext, input: AccountLimit) {+ return `${input.key}:${context.actor.apiKeyId}`;+}++function accountLimitRefusal(retryAfterSeconds: number): Response {+ return apiError(+ 429,+ "rate_limited",+ "This key has created or sent too many envelopes for now. Wait and try again.",+ { "retry-after": String(retryAfterSeconds) },+ );}