Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(templates): validate dropdown readability before bulk-send preview (#223)
Kevin Rose325398936f30
diff --git a/src/lib/bulk-send-dropdown.test.ts b/src/lib/bulk-send-dropdown.test.tsnew file mode 100644index 0000000..a3dda51--- /dev/null+++ b/src/lib/bulk-send-dropdown.test.ts@@ -0,0 +1,245 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { test } from "node:test";++import { PDFDocument } from "pdf-lib";+import type { Pool, QueryResult } from "pg";++import { bulkSendFromTemplate, BulkSendError } from "./bulk-send.ts";+import {+ StorageObjectNotFoundError,+ type StorageService,+} from "./services/storage.ts";++// Unit tests for issue #223: bulk-send preview and confirm must refuse a+// template whose dropdown choices cannot be rendered at a readable size,+// before marking any row Ready or creating any draft envelopes or batches.++const LONG_CHOICES = [+ "Approved with the conditions listed in the schedule",+ "Rejected until the landlord answers the open questions",+];++async function makeLetterPdf(): Promise<Uint8Array> {+ const pdf = await PDFDocument.create();+ pdf.addPage([612, 792]);+ return pdf.save();+}++function makeMemoryStorage(files: Record<string, Uint8Array>): StorageService {+ const refuse = async (): Promise<never> => {+ throw new Error("unexpected storage write/delete");+ };++ return {+ deleteObject: refuse,+ async getObject(key) {+ const body = files[key];++ if (!body) {+ throw new StorageObjectNotFoundError(key);+ }++ return {+ body,+ bucketName: "test-bucket",+ contentLength: body.byteLength,+ contentType: "application/pdf",+ key,+ };+ },+ getObjectStream: refuse,+ headObject: refuse,+ putObject: refuse,+ };+}++function makeBulkSendDb(templateRow: {+ fields: unknown;+ id: string;+ name: string;+ pageCount: number;+ roles: unknown;+ sourcePdfFilename: string;+ sourcePdfKey: string;+}) {+ const executedSql: string[] = [];++ const pool = {+ async connect() {+ throw new Error("unexpected transaction before template validation");+ },+ async query(text: string): Promise<QueryResult> {+ const sql = text.replace(/\s+/g, " ").trim();+ executedSql.push(sql);++ if (sql.includes("FROM templates WHERE id = $1 AND user_id = $2")) {+ return {+ command: "",+ fields: [],+ oid: 0,+ rowCount: 1,+ rows: [{ ...templateRow, createdAt: 1_800_000_000 }],+ } as unknown as QueryResult;+ }++ if (sql.toLowerCase().includes("app_settings")) {+ return {+ command: "",+ fields: [],+ oid: 0,+ rowCount: 1,+ rows: [{ part11_mode: false }],+ } as unknown as QueryResult;+ }++ throw new Error(`Unexpected SQL executed: ${sql}`);+ },+ totalCount: 1,+ } as unknown as Pool;++ return { executedSql, pool };+}++test("bulkSendFromTemplate refuses preview and confirm for an unreadable dropdown without creating drafts or batches (issue #223)", async () => {+ const pdfBytes = await makeLetterPdf();+ const key = "templates/narrow-dropdown.pdf";+ const storageService = makeMemoryStorage({ [key]: pdfBytes });+ const role = { id: "role-1", name: "Signer" };+ const { executedSql, pool } = makeBulkSendDb({+ fields: [+ {+ height: 0.04,+ page: 1,+ required: true,+ signerId: role.id,+ type: "signature",+ width: 0.25,+ x: 0.1,+ y: 0.1,+ },+ {+ height: 0.012,+ options: LONG_CHOICES,+ page: 1,+ required: true,+ signerId: role.id,+ type: "dropdown",+ width: 0.05,+ x: 0.1,+ y: 0.3,+ },+ ],+ id: "tpl-narrow",+ name: "Narrow dropdown",+ pageCount: 1,+ roles: [role],+ sourcePdfFilename: "narrow-dropdown.pdf",+ sourcePdfKey: key,+ });+ const csv = "name,email\nAnn,[email protected]\nBen,[email protected]\n";++ // Preview (confirm: false) must reject instead of marking rows Ready.+ await assert.rejects(+ bulkSendFromTemplate(+ "user-1",+ "tpl-narrow",+ { confirm: false, csv },+ { database: pool, storageService },+ ),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.statusCode === 400 &&+ /A dropdown for Signer on page 1 is too small to show its choices at a readable size/.test(+ error.message,+ ),+ );++ // Confirm (confirm: true) must also reject before claiming a batch or+ // creating any draft envelope.+ await assert.rejects(+ bulkSendFromTemplate(+ "user-1",+ "tpl-narrow",+ {+ batchKey: randomUUID(),+ confirm: true,+ csv,+ permittedUseConfirmed: true,+ },+ {+ database: pool,+ sender: { email: "[email protected]", name: "Sam Sender" },+ storageService,+ },+ ),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.statusCode === 400 &&+ /A dropdown for Signer on page 1 is too small to show its choices at a readable size/.test(+ error.message,+ ),+ );++ assert.equal(+ executedSql.some(+ (sql) =>+ sql.includes("INSERT INTO envelopes") ||+ sql.includes("INSERT INTO bulk_send_batches"),+ ),+ false,+ );+});++test("bulkSendFromTemplate marks rows Ready on preview when the template's dropdown is wide enough (issue #223)", async () => {+ const pdfBytes = await makeLetterPdf();+ const key = "templates/wide-dropdown.pdf";+ const storageService = makeMemoryStorage({ [key]: pdfBytes });+ const role = { id: "role-1", name: "Signer" };+ const { pool } = makeBulkSendDb({+ fields: [+ {+ height: 0.04,+ page: 1,+ required: true,+ signerId: role.id,+ type: "signature",+ width: 0.25,+ x: 0.1,+ y: 0.1,+ },+ {+ height: 0.03,+ options: LONG_CHOICES,+ page: 1,+ required: true,+ signerId: role.id,+ type: "dropdown",+ width: 0.6,+ x: 0.1,+ y: 0.3,+ },+ ],+ id: "tpl-wide",+ name: "Wide dropdown",+ pageCount: 1,+ roles: [role],+ sourcePdfFilename: "wide-dropdown.pdf",+ sourcePdfKey: key,+ });+ const csv = "name,email\nAnn,[email protected]\nBen,[email protected]\n";++ const preview = await bulkSendFromTemplate(+ "user-1",+ "tpl-wide",+ { confirm: false, csv },+ { database: pool, storageService },+ );++ assert.equal(preview.summary.ok, 2);+ assert.equal(preview.summary.skipped, 0);+ assert.deepEqual(+ preview.rows.map((row) => row.status),+ ["ok", "ok"],+ );+});diff --git a/src/lib/bulk-send.dbtest.ts b/src/lib/bulk-send.dbtest.tsindex e4b3562..bd4f142 100644--- a/src/lib/bulk-send.dbtest.ts+++ b/src/lib/bulk-send.dbtest.ts@@ -949,6 +949,110 @@ test("a template with no signature field is refused before any row is ready", asassert.equal(await countEnvelopes(userId), 1);});+async function createDropdownTemplate(+ userId: string,+ dropdown: { height: number; width: number },+) {+ const choices = [+ "Approved with the conditions listed in the schedule",+ "Rejected until the landlord answers the open questions",+ ];+ const draft = await createDraftEnvelope(+ userId,+ {+ sourcePdf: { body: sourcePdf, filename: "dropdown.pdf" },+ title: "Dropdown Agreement",+ },+ options(),+ );+ const saved = await replaceDraftEnvelopeSigners(+ userId,+ draft.envelope.id,+ {+ signers: [{ email: "[email protected]", name: "Riley Recipient" }],+ },+ database,+ );+ const signerId = saved.signers[0]!.id;++ await replaceDraftEnvelopeFields(+ userId,+ draft.envelope.id,+ {+ fields: [+ field(signerId, "signature", 0.1),+ field(signerId, "dropdown", 0.3, { options: choices, ...dropdown }),+ ],+ },+ database,+ );++ return saveEnvelopeAsTemplate(+ userId,+ draft.envelope.id,+ { name: "Dropdown Agreement", roleNames: ["Signer"] },+ options(),+ );+}++test("a template with an unreadable dropdown is refused on preview and leaves zero orphan drafts (issue #223)", async () => {+ const userId = await createUser();+ const narrowTemplate = await createDropdownTemplate(userId, {+ height: 0.012,+ width: 0.05,+ });+ const invitationsBefore = (await capturedInvitations()).length;+ const csv = `name,email\nAnn,ann-${randomUUID()}@example.test\nBen,ben-${randomUUID()}@example.test\n`;++ await assert.rejects(+ bulkSendFromTemplate(userId, narrowTemplate.id, { csv }, options()),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.statusCode === 400 &&+ /dropdown for Signer on page 1 is too small/.test(error.message),+ );+ await assert.rejects(+ bulkSendFromTemplate(userId, narrowTemplate.id, confirmBody(csv), {+ ...options(),+ sender: senderFor(userId),+ }),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.statusCode === 400 &&+ /dropdown for Signer on page 1 is too small/.test(error.message),+ );+ assert.equal(await countEnvelopes(userId), 1);+ assert.equal((await capturedInvitations()).length, invitationsBefore);++ // Wider dropdown control marks all rows Ready on preview and sends cleanly.+ const wideTemplate = await createDropdownTemplate(userId, {+ height: 0.03,+ width: 0.6,+ });+ const preview = await bulkSendFromTemplate(+ userId,+ wideTemplate.id,+ { csv },+ options(),+ );++ assert.equal(preview.summary.ok, 2);+ assert.deepEqual(+ preview.rows.map((row) => row.status),+ ["ok", "ok"],+ );++ const sent = await bulkSendFromTemplate(+ userId,+ wideTemplate.id,+ confirmBody(csv),+ { ...options(), sender: senderFor(userId) },+ );++ assert.equal(sent.summary.sent, 2);+ assert.equal((await capturedInvitations()).length, invitationsBefore + 2);+});+test("confirming the same batch key does not send the envelopes again", async () => {const userId = await createUser();const template = await createOneRoleTemplate(userId);diff --git a/src/lib/bulk-send.ts b/src/lib/bulk-send.tsindex 66fca8b..4f3daff 100644--- a/src/lib/bulk-send.ts+++ b/src/lib/bulk-send.ts@@ -40,6 +40,7 @@ import {import { readStoredSettings } from "./settings.ts";import {createDraftFromTemplate,+ describeTemplateDropdownProblem,describeUnsendableTemplate,getTemplateForBulkSend,TemplateError,@@ -754,16 +755,25 @@ export async function bulkSendFromTemplate(}: BulkSendOptions = {},): Promise<BulkSendResult> {const parsedInput = bulkSendRequestSchema.parse(input);- const template = await getTemplateForBulkSend(userId, templateId, database);+ const template = await getTemplateForBulkSend(userId, templateId, database, {+ checkDropdownReadability: false,+ });if (!template) {throw new TemplateError("Template not found.", 404);}- const unsendable = describeUnsendableTemplate(- template.roles,- template.fields,- );+ const unsendable =+ describeUnsendableTemplate(template.roles, template.fields) ??+ (await describeTemplateDropdownProblem(+ template.roles,+ template.fields,+ {+ filename: template.sourcePdfFilename,+ key: template.sourcePdfKey,+ },+ storageService,+ ));if (unsendable) {throw new BulkSendError(unsendable, 400);diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 07bcb29..8fd26ee 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -1616,9 +1616,14 @@ function describeChoiceProblem(* and on the signed document that can be too small to read. The sender* fixes it before sending instead.*/-async function findUnreadableDropdown(- signers: readonly PersistedSignerRecord[],- fields: readonly FieldRecord[],+export async function findUnreadableDropdown(+ signers: ReadonlyArray<{ id: string; name: string }>,+ fields: ReadonlyArray<+ Pick<+ FieldRecord,+ "height" | "options" | "page" | "signerId" | "type" | "width" | "x" | "y"+ >+ >,pages: Parameters<typeof findTypedValueTooLongForField>[1],): Promise<string | null> {for (const field of fields) {diff --git a/src/lib/templates.test.ts b/src/lib/templates.test.tsindex 3ee070e..c9eb6db 100644--- a/src/lib/templates.test.ts+++ b/src/lib/templates.test.ts@@ -1,7 +1,21 @@import assert from "node:assert/strict";import { test } from "node:test";-import { describeUnsendableTemplate } from "./templates.ts";+import { degrees, PDFDocument } from "pdf-lib";+import type { QueryResult } from "pg";++import type { DbExecutor } from "./db/connection.ts";+import {+ StorageObjectNotFoundError,+ type StorageService,+} from "./services/storage.ts";+import {+ describeTemplateDropdownProblem,+ describeUnsendableTemplate,+ getTemplateForBulkSend,+ getUseTemplateDataForUser,+ TemplateError,+} from "./templates.ts";const role = { id: "role-1", name: "Signer" };@@ -80,3 +94,241 @@ test("approver roles need no Signature field, but someone has to sign", () => {/approvers have no fields/,);});++const LONG_DROPDOWN_CHOICES = [+ "Approved with the conditions listed in the schedule",+ "Rejected until the landlord answers the open questions",+];++async function makeLetterPdf(rotationDegrees = 0): Promise<Uint8Array> {+ const pdf = await PDFDocument.create();+ const page = pdf.addPage([612, 792]);++ if (rotationDegrees !== 0) {+ page.setRotation(degrees(rotationDegrees));+ }++ return pdf.save();+}++function makeMemoryStorage(+ files: Record<string, Uint8Array>,+ onRead?: (key: string) => void,+): StorageService {+ const refuse = async (): Promise<never> => {+ throw new Error("unexpected storage call");+ };++ return {+ deleteObject: refuse,+ async getObject(key) {+ onRead?.(key);+ const body = files[key];++ if (!body) {+ throw new StorageObjectNotFoundError(key);+ }++ return {+ body,+ bucketName: "test-bucket",+ contentLength: body.byteLength,+ contentType: "application/pdf",+ key,+ };+ },+ getObjectStream: refuse,+ headObject: refuse,+ putObject: refuse,+ };+}++function makeTemplateDb(row: {+ fields: unknown;+ id: string;+ name: string;+ pageCount: number;+ roles: unknown;+ sourcePdfFilename: string;+ sourcePdfKey: string;+}): DbExecutor {+ return {+ async query() {+ return {+ command: "",+ fields: [],+ oid: 0,+ rowCount: 1,+ rows: [{ ...row, createdAt: 1_800_000_000 }],+ } as unknown as QueryResult;+ },+ };+}++test("describeTemplateDropdownProblem flags unreadable dropdowns and allows readable ones (issue #223)", async () => {+ const key = "templates/letter.pdf";+ let storageReads = 0;+ const storage = makeMemoryStorage({ [key]: await makeLetterPdf() }, () => {+ storageReads += 1;+ });++ // Templates with no dropdowns never touch storage.+ assert.equal(+ await describeTemplateDropdownProblem(+ [role],+ [signatureField()],+ { filename: "letter.pdf", key },+ storage,+ ),+ null,+ );+ assert.equal(storageReads, 0);++ // Narrow dropdown (5% x 1.2% on Letter) with long choices is rejected.+ const narrowProblem = await describeTemplateDropdownProblem(+ [role],+ [+ signatureField(),+ {+ ...signatureField(),+ height: 0.012,+ options: LONG_DROPDOWN_CHOICES,+ type: "dropdown",+ width: 0.05,+ y: 0.3,+ },+ ],+ { filename: "letter.pdf", key },+ storage,+ );++ assert.match(+ narrowProblem ?? "",+ /A dropdown for Signer on page 1 is too small to show its choices at a readable size/,+ );++ // Wider dropdown control with the same choices passes cleanly.+ const wideProblem = await describeTemplateDropdownProblem(+ [role],+ [+ signatureField(),+ {+ ...signatureField(),+ height: 0.03,+ options: LONG_DROPDOWN_CHOICES,+ type: "dropdown",+ width: 0.6,+ y: 0.3,+ },+ ],+ { filename: "letter.pdf", key },+ storage,+ );++ assert.equal(wideProblem, null);++ // Missing PDF in storage surfaces a 409 TemplateError.+ await assert.rejects(+ describeTemplateDropdownProblem(+ [role],+ [+ signatureField(),+ {+ ...signatureField(),+ options: ["Yes", "No"],+ type: "dropdown",+ y: 0.3,+ },+ ],+ { filename: "missing.pdf", key: "templates/missing.pdf" },+ storage,+ ),+ (error: unknown) =>+ error instanceof TemplateError && error.statusCode === 409,+ );+});++test("describeTemplateDropdownProblem uses displayed page geometry for rotated PDFs (issue #223)", async () => {+ const key = "templates/rotated.pdf";+ const storage = makeMemoryStorage({ [key]: await makeLetterPdf(90) });++ // Rotated 90 degrees: displayed size is 792 x 612. A 5% x 1.2% box is still+ // too small for long choices, while a 60% x 4% box fits cleanly.+ assert.match(+ (await describeTemplateDropdownProblem(+ [role],+ [+ signatureField(),+ {+ ...signatureField(),+ height: 0.012,+ options: LONG_DROPDOWN_CHOICES,+ type: "dropdown",+ width: 0.05,+ y: 0.3,+ },+ ],+ { filename: "rotated.pdf", key },+ storage,+ )) ?? "",+ /too small to show its choices at a readable size/,+ );++ assert.equal(+ await describeTemplateDropdownProblem(+ [role],+ [+ signatureField(),+ {+ ...signatureField(),+ height: 0.04,+ options: LONG_DROPDOWN_CHOICES,+ type: "dropdown",+ width: 0.6,+ y: 0.3,+ },+ ],+ { filename: "rotated.pdf", key },+ storage,+ ),+ null,+ );+});++test("getTemplateForBulkSend rejects unreadable dropdowns while getUseTemplateDataForUser still opens the template (issue #223)", async () => {+ const key = "templates/narrow.pdf";+ const storage = makeMemoryStorage({ [key]: await makeLetterPdf() });+ const db = makeTemplateDb({+ fields: [+ signatureField(),+ {+ ...signatureField(),+ height: 0.012,+ options: LONG_DROPDOWN_CHOICES,+ type: "dropdown",+ width: 0.05,+ y: 0.3,+ },+ ],+ id: "tpl-1",+ name: "Narrow dropdown template",+ pageCount: 1,+ roles: [role],+ sourcePdfFilename: "narrow.pdf",+ sourcePdfKey: key,+ });++ await assert.rejects(+ getTemplateForBulkSend("user-1", "tpl-1", db, { storageService: storage }),+ (error: unknown) =>+ error instanceof TemplateError &&+ error.statusCode === 400 &&+ /dropdown for Signer on page 1 is too small/.test(error.message),+ );++ // Use template creates an editable draft, so it must still load.+ const useData = await getUseTemplateDataForUser("user-1", "tpl-1", db);++ assert.equal(useData?.id, "tpl-1");+ assert.equal(useData?.name, "Narrow dropdown template");+});diff --git a/src/lib/templates.ts b/src/lib/templates.tsindex 6bcb69d..178fc11 100644--- a/src/lib/templates.ts+++ b/src/lib/templates.ts@@ -12,6 +12,7 @@ import {createDraftEnvelope,deleteDraftEnvelope,EnvelopeDocumentAccessError,+ findUnreadableDropdown,getDraftEnvelopeDocumentForUser,getPrepareEnvelopeDataForUser,replaceDraftEnvelopeFields,@@ -29,6 +30,10 @@ import {useTemplateSchema,type TemplateRole,} from "./schemas/template.ts";+import {+ DocumentImportError,+ importPdfDocument,+} from "./services/document-import.ts";import { buildTemplatePdfKey } from "./services/storage-keys.ts";import { normalizeSigningSteps } from "./signing-steps.ts";import {@@ -225,6 +230,8 @@ export async function listTemplatesForUser(export type TemplateForBulkSend = UseTemplateData & {fields: unknown;+ sourcePdfFilename: string;+ sourcePdfKey: string;};/**@@ -296,10 +303,75 @@ export function describeUnsendableTemplate();}+/**+ * Whether any dropdown on the template is too small to show one of its+ * choices at a readable size on the template's PDF, in words for the+ * sender, or null. Mirrors sendDraftEnvelope so Send to many rejects an+ * unreadable dropdown before preview marks rows Ready or creates drafts.+ */+export async function describeTemplateDropdownProblem(+ roles: readonly TemplateRole[],+ fields: unknown,+ sourcePdf: { filename: string; key: string },+ storageService?: StorageService,+): Promise<string | null> {+ const parsed = fieldPlacementListSchema.safeParse(fields);++ if (!parsed.success) {+ return UNUSABLE_TEMPLATE_MESSAGE;+ }++ if (+ !parsed.data.some(+ (field) => field.type === "dropdown" && (field.options?.length ?? 0) > 0,+ )+ ) {+ return null;+ }++ const resolvedStorage = storageService ?? createStorageService();+ let sourcePdfBody: Uint8Array;++ try {+ sourcePdfBody = (await resolvedStorage.getObject(sourcePdf.key)).body;+ } catch (error) {+ if (error instanceof StorageObjectNotFoundError) {+ throw new TemplateError(UNUSABLE_TEMPLATE_MESSAGE, 409);+ }++ throw error;+ }++ let imported: Awaited<ReturnType<typeof importPdfDocument>>;++ try {+ imported = await importPdfDocument({+ body: sourcePdfBody,+ contentType: "application/pdf",+ filename: sourcePdf.filename,+ });+ } catch (error) {+ if (error instanceof DocumentImportError) {+ throw new TemplateError(error.message, 400);+ }++ throw error;+ }++ return findUnreadableDropdown(roles, parsed.data, imported.pages);+}+export async function getTemplateForBulkSend(userId: string,templateId: string,database: DbExecutor = getDb(),+ {+ checkDropdownReadability = true,+ storageService,+ }: {+ checkDropdownReadability?: boolean;+ storageService?: StorageService;+ } = {},): Promise<TemplateForBulkSend | null> {const row = await getTemplateRow(userId, templateId, database);@@ -313,6 +385,25 @@ export async function getTemplateForBulkSend(throw new TemplateError(UNUSABLE_TEMPLATE_MESSAGE, 409);}+ if (+ checkDropdownReadability &&+ describeUnsendableTemplate(roles.data, row.fields) === null+ ) {+ const dropdownProblem = await describeTemplateDropdownProblem(+ roles.data,+ row.fields,+ {+ filename: row.sourcePdfFilename,+ key: row.sourcePdfKey,+ },+ storageService,+ );++ if (dropdownProblem) {+ throw new TemplateError(dropdownProblem, 400);+ }+ }+return {fieldCountLabel: countLabel(countFields(row.fields), "field"),fields: row.fields,@@ -320,6 +411,8 @@ export async function getTemplateForBulkSend(name: row.name,pageCountLabel: countLabel(row.pageCount, "page"),roles: roles.data,+ sourcePdfFilename: row.sourcePdfFilename,+ sourcePdfKey: row.sourcePdfKey,};}@@ -328,7 +421,9 @@ export async function getUseTemplateDataForUser(templateId: string,database: DbExecutor = getDb(),): Promise<UseTemplateData | null> {- const template = await getTemplateForBulkSend(userId, templateId, database);+ const template = await getTemplateForBulkSend(userId, templateId, database, {+ checkDropdownReadability: false,+ });if (!template) {return null;