Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Address review feedback
Matt Van Horn7c0dec768afb
diff --git a/.prettierignore b/.prettierignoreindex ec4e6c8..a9d7454 100644--- a/.prettierignore+++ b/.prettierignore@@ -1,3 +1,4 @@.nextnode_modules+public/pdfjstsconfig.tsbuildinfodiff --git a/db/migrations/20261120090000_bulk_send_skipped_rows.sql b/db/migrations/20261120090000_bulk_send_skipped_rows.sqlnew file mode 100644index 0000000..0138534--- /dev/null+++ b/db/migrations/20261120090000_bulk_send_skipped_rows.sql@@ -0,0 +1,15 @@+-- Rows skipped by Part 11 account checks when a "send to many" batch is+-- confirmed are now stored on the batch with status 'skipped' (updating the+-- historical note in 20261118090000_bulk_send_batches.sql that skipped rows+-- are never stored). A retry with the same batch_key restores those rows as+-- skipped instead of sending them if an administrator creates, verifies or+-- unlocks the signer's account in between. envelope_id and reason stay null so+-- no personal details are kept, while rows skipped by CSV validation stay+-- unsaved because the fingerprinted CSV determines them on every run.++alter table public.bulk_send_batch_rows+ drop constraint if exists bulk_send_batch_rows_status_check;++alter table public.bulk_send_batch_rows+ add constraint bulk_send_batch_rows_status_check+ check (status in ('processing', 'sent', 'failed', 'skipped'));diff --git a/src/app/api/envelopes/[id]/route.ts b/src/app/api/envelopes/[id]/route.tsindex 72a0f88..86b8f9b 100644--- a/src/app/api/envelopes/[id]/route.ts+++ b/src/app/api/envelopes/[id]/route.ts@@ -2,10 +2,7 @@ import { NextResponse } from "next/server";import { requireVerifiedSenderSession } from "@/lib/auth/route-session";import { getDb } from "@/lib/db/connection";-import {- deleteDraftEnvelope,- EnvelopeMutationError,-} from "@/lib/envelopes";+import { deleteDraftEnvelope, EnvelopeMutationError } from "@/lib/envelopes";import { logRouteError } from "@/lib/security/logging";import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";diff --git a/src/components/contact/contact-form.tsx b/src/components/contact/contact-form.tsxindex 105f9d6..9a2837a 100644--- a/src/components/contact/contact-form.tsx+++ b/src/components/contact/contact-form.tsx@@ -3,11 +3,7 @@import { useState, type ChangeEvent, type FormEvent } from "react";import { FieldShell, ShellButton } from "@/components/shared/form-shell";-import {- Field,- FieldError,- FieldLabel,-} from "@/components/ui/field";+import { Field, FieldError, FieldLabel } from "@/components/ui/field";import { Textarea } from "@/components/ui/textarea";import { contactFormSchema } from "@/lib/schemas/contact";@@ -183,15 +179,11 @@ export function ContactForm() {</div>{successMessage ? (- <div className="notice notice-success">- {successMessage}- </div>+ <div className="notice notice-success">{successMessage}</div>) : null}{submitError ? (- <div className="notice notice-danger">- {submitError}- </div>+ <div className="notice notice-danger">{submitError}</div>) : null}<div className="grid gap-5 sm:grid-cols-2">diff --git a/src/components/envelopes/interactive-placed-field.tsx b/src/components/envelopes/interactive-placed-field.tsxindex 70abb50..43705ca 100644--- a/src/components/envelopes/interactive-placed-field.tsx+++ b/src/components/envelopes/interactive-placed-field.tsx@@ -1,6 +1,10 @@"use client";-import { useRef, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from "react";+import {+ useRef,+ type KeyboardEvent,+ type PointerEvent as ReactPointerEvent,+} from "react";import { type FieldResizeHandle } from "@/lib/utils/pdf-coords";@@ -159,7 +163,8 @@ export function InteractivePlacedField({onInteractionChange?.(true);}- const scaledDeltaX = (deltaClientX / gesture.viewportWidth) * coordinateScale;+ const scaledDeltaX =+ (deltaClientX / gesture.viewportWidth) * coordinateScale;const scaledDeltaY =(deltaClientY / gesture.viewportHeight) * coordinateScale;@@ -242,7 +247,9 @@ export function InteractivePlacedField({className={`absolute ${handle.positionClassName} ${handle.cursorClassName} z-1 size-4 rounded-full bg-white shadow-[0_4px_10px_rgba(28,29,43,0.18)]`}key={handle.corner}onPointerCancel={endGesture}- onPointerDown={(event) => beginGesture(event, "resize", handle.corner)}+ onPointerDown={(event) =>+ beginGesture(event, "resize", handle.corner)+ }onPointerMove={handlePointerMove}onPointerUp={endGesture}style={{diff --git a/src/lib/bulk-send.dbtest.ts b/src/lib/bulk-send.dbtest.tsindex fd7f593..bf7a8ed 100644--- a/src/lib/bulk-send.dbtest.ts+++ b/src/lib/bulk-send.dbtest.ts@@ -15,6 +15,7 @@ import {bulkSendBatchMismatchMessage,bulkSendFromTemplate,bulkSendInvitationUnconfirmedMessage,+ bulkSendSkippedRowMessage,BulkSendError,missingBulkSendBatchKeyMessage,} from "./bulk-send.ts";@@ -637,6 +638,123 @@ test("Part 11 mode skips a row whose signer has no verified account", async () =}});+test("retrying a confirmed Part 11 batch keeps a skipped row skipped after the signer's account is fixed", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const readyEmail = `ann-${randomUUID()}@example.test`;+ const skippedEmail = `ada-${randomUUID()}@example.test`;+ const readyUserId = randomUUID();++ createdUsers.push(readyUserId);+ await database.query(+ `+ insert into public."user" (+ id, name, email, role, "emailVerified", identity_verified_at, signing_locked_at+ ) values ($1, 'Ann Ready', $2, 'user', true, 1, null)+ `,+ [readyUserId, readyEmail],+ );++ const before = await countEnvelopes(userId);+ const previous = await database.query<{ part11_mode: boolean }>(+ `select part11_mode from app_settings where id`,+ );++ await database.query(+ `+ insert into app_settings (id, signup_mode, created_at, updated_at, part11_mode)+ values (true, 'open', 1, 1, true)+ on conflict (id) do update set part11_mode = true+ `,+ );++ try {+ const body = confirmBody(+ `name,email\nAnn Ready,${readyEmail}\nAda Later,${skippedEmail}\n`,+ { signatureMeaning: "approval" },+ );+ const first = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });+ const afterFirst = await countEnvelopes(userId);++ assert.equal(first.summary.sent, 1);+ assert.equal(first.summary.skipped, 1);+ assert.equal(first.summary.failed, 0);+ assert.equal(first.rows[0]?.status, "sent");+ assert.ok(first.rows[0]?.envelopeId);+ assert.equal(first.rows[1]?.status, "skipped");+ assert.equal(first.rows[1]?.envelopeId, null);+ assert.match(first.rows[1]?.reason ?? "", /needs an account/);+ assert.equal(afterFirst, before + 1);++ const storedSkipped = await database.query<{+ envelopeId: string | null;+ reason: string | null;+ status: string;+ }>(+ `+ select r.envelope_id as "envelopeId", r.reason, r.status+ from bulk_send_batches b+ join bulk_send_batch_rows r on r.batch_id = b.id+ where b.user_id = $1 and b.batch_key = $2 and r.row_number = 2+ `,+ [userId, body.batchKey],+ );++ assert.deepEqual(storedSkipped.rows, [+ { envelopeId: null, reason: null, status: "skipped" },+ ]);++ const skippedUserId = randomUUID();++ createdUsers.push(skippedUserId);+ await database.query(+ `+ insert into public."user" (+ id, name, email, role, "emailVerified", identity_verified_at, signing_locked_at+ ) values ($1, 'Ada Later', $2, 'user', true, 1, null)+ `,+ [skippedUserId, skippedEmail],+ );++ const retry = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });++ assert.equal(retry.summary.sent, 1);+ assert.equal(retry.summary.skipped, 1);+ assert.equal(retry.summary.failed, 0);+ assert.equal(retry.rows[0]?.status, "sent");+ assert.equal(retry.rows[0]?.envelopeId, first.rows[0]?.envelopeId);+ assert.equal(retry.rows[1]?.status, "skipped");+ assert.equal(retry.rows[1]?.reason, bulkSendSkippedRowMessage);+ assert.equal(retry.rows[1]?.envelopeId, null);+ assert.equal(retry.rows[1]?.envelopePath, null);+ assert.equal(await countEnvelopes(userId), afterFirst);+ assert.equal(+ (+ await database.query(+ `select 1 from signers where lower(email) = lower($1)`,+ [skippedEmail],+ )+ ).rowCount,+ 0,+ );+ } finally {+ if (previous.rowCount) {+ await database.query(+ `update app_settings set part11_mode = $1 where id`,+ [previous.rows[0]!.part11_mode],+ );+ } else {+ await database.query(`delete from app_settings where id`);+ }+ }+});+test("sending without the permitted-use confirmation is refused, and so is an empty CSV", async () => {const userId = await createUser();const template = await createOneRoleTemplate(userId);diff --git a/src/lib/bulk-send.ts b/src/lib/bulk-send.tsindex 4a28e8c..1f17c72 100644--- a/src/lib/bulk-send.ts+++ b/src/lib/bulk-send.ts@@ -64,6 +64,9 @@ export const bulkSendBatchBusyMessage =export const bulkSendInvitationUnconfirmedMessage ="This envelope was marked sent but the invitation was not recorded. Check your documents before sending this row again.";+export const bulkSendSkippedRowMessage =+ "This row was skipped when this batch was first confirmed. Preview the list again and send it as a new batch to include it.";+export class BulkSendError extends Error {readonly statusCode: number;@@ -109,7 +112,7 @@ type StoredBatch = {type StoredBatchRow = {envelopeId: string | null;reason: string | null;- status: "failed" | "processing" | "sent";+ status: "failed" | "processing" | "sent" | "skipped";};type SendRowContext = {@@ -127,7 +130,11 @@ type SendRowContext = {userId: string;};-const TERMINAL_ROW_STATUSES = new Set(["failed", "sent"]);+const TERMINAL_ROW_STATUSES = new Set<StoredBatchRow["status"]>([+ "failed",+ "sent",+ "skipped",+]);/*** How long a claim on a batch lasts without being refreshed. The request@@ -452,6 +459,61 @@ async function saveBatchRow(}}+/**+ * Saves every row skipped by Part 11 checks that has not been recorded yet,+ * guarded by the batch claim like saveBatchRow. Neither envelope_id nor+ * reason is stored, so no personal details are kept on the batch.+ */+async function saveSkippedBatchRows(+ batch: StoredBatch,+ rowNumbers: readonly number[],+ database: DbExecutor,+): Promise<void> {+ if (rowNumbers.length === 0) {+ return;+ }++ const saved = await database.query(+ `+ WITH claim AS (+ UPDATE bulk_send_batches+ SET claimed_at = extract(epoch from now())::bigint+ WHERE id = $1 AND claim_token = $3+ RETURNING id+ ),+ inserted AS (+ INSERT INTO bulk_send_batch_rows (+ batch_id,+ row_number,+ status,+ envelope_id,+ reason+ )+ SELECT claim.id, skipped.row_number, 'skipped', NULL, NULL+ FROM claim+ CROSS JOIN unnest($2::int[]) AS skipped(row_number)+ ON CONFLICT (batch_id, row_number) DO NOTHING+ )+ SELECT id FROM claim+ `,+ [batch.id, rowNumbers, batch.claimToken],+ );++ if (saved.rowCount === 0) {+ throw new BulkSendClaimLostError();+ }++ for (const rowNumber of rowNumbers) {+ if (!batch.rows.has(rowNumber)) {+ batch.rows.set(rowNumber, {+ envelopeId: null,+ reason: null,+ status: "skipped",+ });+ }+ }+}+async function invitationWasRecorded(envelopeId: string,database: DbExecutor,@@ -480,6 +542,15 @@ function restoreStoredRow(return sentRow(row, stored.envelopeId);}+ if (stored.status === "skipped") {+ return withReason(+ row,+ row.status === "skipped" && row.reason+ ? row.reason+ : bulkSendSkippedRowMessage,+ );+ }+return {...row,envelopeId: stored.envelopeId,@@ -724,16 +795,18 @@ export async function bulkSendFromTemplate(const copyRecipientEmails = (parsedInput.copyRecipients ?? []).map((recipient) => recipient.email,);- let rows = validateBulkSendRows(parsedCsv.rows, copyRecipientEmails);+ const validatedRows = validateBulkSendRows(+ parsedCsv.rows,+ copyRecipientEmails,+ );const part11 = (await readStoredSettings(database))?.part11Mode ?? false;-- if (part11) {- rows = await applyPart11Problems(- rows,- parsedInput.signatureMeaning,- database,- );- }+ const rows = part11+ ? await applyPart11Problems(+ validatedRows,+ parsedInput.signatureMeaning,+ database,+ )+ : validatedRows;const resultFor = (nextRows: BulkSendRowResult[]): BulkSendResult => ({error: null,@@ -763,6 +836,19 @@ export async function bulkSendFromTemplate();try {+ const part11SkippedRowNumbers = part11+ ? rows+ .filter(+ (row, index) =>+ validatedRows[index]?.status === "ok" &&+ row.status === "skipped" &&+ !batch.rows.has(row.rowNumber),+ )+ .map((row) => row.rowNumber)+ : [];++ await saveSkippedBatchRows(batch, part11SkippedRowNumbers, database);+const sent: BulkSendRowResult[] = [];for (const row of rows) {@@ -773,10 +859,13 @@ export async function bulkSendFromTemplate(continue;}- // A skipped row is worked out again from the same list on a retry,- // so it is not saved. That keeps a long list past the cap from- // costing a write per row, and keeps the reasons, which can name the- // person, out of the batch table.+ // Rows skipped by Part 11 checks are saved above without their reason+ // and restored by restoreStoredRow so a retry never sends them if an+ // account changes in between. Rows that reach here were skipped by CSV+ // validation (past the cap, bad email, duplicates), which the+ // fingerprinted CSV works out the same way on every retry, so they are+ // not saved: a long list past the cap does not cost a write per row,+ // and reasons that can name the person stay out of the batch table.if (row.status !== "ok") {sent.push(row);continue;diff --git a/src/lib/draft-pdf-cache.ts b/src/lib/draft-pdf-cache.tsindex bda44b2..30892ef 100644--- a/src/lib/draft-pdf-cache.ts+++ b/src/lib/draft-pdf-cache.ts@@ -27,9 +27,7 @@ async function openDraftPdfCacheDatabase(): Promise<IDBDatabase | null> {);request.onerror = () => {- reject(- request.error ?? new Error("Unable to open the draft PDF cache."),- );+ reject(request.error ?? new Error("Unable to open the draft PDF cache."));};request.onupgradeneeded = () => {@@ -63,7 +61,8 @@ function runDraftPdfCacheTransaction<T>(request.onerror = () => {reject(- request.error ?? new Error("Unable to complete the draft PDF cache request."),+ request.error ??+ new Error("Unable to complete the draft PDF cache request."),);};@@ -128,9 +127,7 @@ export async function getCachedDraftPdfBlob(return record.blob;}-async function deleteCachedDraftPdfBlob(- envelopeId: string,-): Promise<void> {+async function deleteCachedDraftPdfBlob(envelopeId: string): Promise<void> {const database = await openDraftPdfCacheDatabase();if (!database) {diff --git a/src/lib/pdfjs-client.ts b/src/lib/pdfjs-client.tsindex 4d7535c..d6cbe86 100644--- a/src/lib/pdfjs-client.ts+++ b/src/lib/pdfjs-client.ts@@ -6,10 +6,8 @@ type PdfPageProxy = Awaited<ReturnType<PdfDocumentProxy["getPage"]>>;type PdfRenderTask = ReturnType<PdfPageProxy["render"]>;const PDF_JS_ASSET_BASE = "/pdfjs/5.5.207";-export const PDF_JS_STANDARD_FONT_DATA_URL =- `${PDF_JS_ASSET_BASE}/standard_fonts/`;-export const PDF_JS_WORKER_SRC =- `${PDF_JS_ASSET_BASE}/legacy/build/pdf.worker.min.mjs`;+export const PDF_JS_STANDARD_FONT_DATA_URL = `${PDF_JS_ASSET_BASE}/standard_fonts/`;+export const PDF_JS_WORKER_SRC = `${PDF_JS_ASSET_BASE}/legacy/build/pdf.worker.min.mjs`;let pdfJsModulePromise: Promise<PdfJsModule> | null = null;@@ -43,11 +41,13 @@ function createRenderContext(width: number, height: number) {}export async function loadPdfJsModule(): Promise<PdfJsModule> {- pdfJsModulePromise ??= import("pdfjs-dist/legacy/build/pdf.mjs").then((pdfjs) => {- pdfjs.GlobalWorkerOptions.workerSrc = PDF_JS_WORKER_SRC;+ pdfJsModulePromise ??= import("pdfjs-dist/legacy/build/pdf.mjs").then(+ (pdfjs) => {+ pdfjs.GlobalWorkerOptions.workerSrc = PDF_JS_WORKER_SRC;- return pdfjs;- });+ return pdfjs;+ },+ );return pdfJsModulePromise;}@@ -56,7 +56,9 @@ export async function assertPdfPreviewRenderable(file: File | Uint8Array,): Promise<void> {const pdfBytes =- file instanceof Uint8Array ? file.slice() : new Uint8Array(await file.arrayBuffer());+ file instanceof Uint8Array+ ? file.slice()+ : new Uint8Array(await file.arrayBuffer());const pdfjs = await loadPdfJsModule();let loadingTask: ReturnType<PdfJsModule["getDocument"]> | null = null;let documentProxy: PdfDocumentProxy | null = null;diff --git a/src/lib/services/pki-test-support.ts b/src/lib/services/pki-test-support.tsindex e7336aa..b5962e5 100644--- a/src/lib/services/pki-test-support.ts+++ b/src/lib/services/pki-test-support.ts@@ -42,6 +42,7 @@ const OID = {sha256: "2.16.840.1.101.3.4.2.1",sha256WithRsa: "1.2.840.113549.1.1.11",signedData: "1.2.840.113549.1.7.2",+ signingCertificate: "1.2.840.113549.1.9.16.2.12",signingCertificateV2: "1.2.840.113549.1.9.16.2.47",tstInfo: "1.2.840.113549.1.9.16.1.4",} as const;@@ -444,6 +445,20 @@ export async function startTestPki(): Promise<TestPki> {der.oid(OID.messageDigest),der.set(der.octets(createHash("sha256").update(tstInfo).digest())),),+ // macOS ships LibreSSL's openssl ts -verify, which checks ESSCertID+ // (v1), while OpenSSL checks ESSCertIDv2.+ der.sequence(+ der.oid(OID.signingCertificate),+ der.set(+ der.sequence(+ der.sequence(+ der.sequence(+ der.octets(createHash("sha1").update(tsaDer).digest()),+ ),+ ),+ ),+ ),+ ),der.sequence(der.oid(OID.signingCertificateV2),der.set(diff --git a/src/lib/utils/pdf-coords.ts b/src/lib/utils/pdf-coords.tsindex 641852b..1287d5d 100644--- a/src/lib/utils/pdf-coords.ts+++ b/src/lib/utils/pdf-coords.ts@@ -15,10 +15,7 @@ export type PdfFieldRect = {};export type FieldResizeHandle =- | "bottom-left"- | "bottom-right"- | "top-left"- | "top-right";+ "bottom-left" | "bottom-right" | "top-left" | "top-right";type RelativeFieldRect = {height: number;diff --git a/tsconfig.json b/tsconfig.jsonindex 88fcd7f..6d34279 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,11 +1,7 @@{"compilerOptions": {"target": "ES2017",- "lib": [- "dom",- "dom.iterable",- "esnext"- ],+ "lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"allowImportingTsExtensions": true,"skipLibCheck": true,@@ -24,9 +20,7 @@}],"paths": {- "@/*": [- "./src/*"- ]+ "@/*": ["./src/*"]}},"include": [@@ -37,7 +31,5 @@".next/types/**/*.ts",".next/dev/types/**/*.ts"],- "exclude": [- "node_modules"- ]+ "exclude": ["node_modules"]}