Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Keep long Text answers whole on the signed PDF (#90)
Claude63dc783729e9
diff --git a/src/lib/long-text-field.dbtest.ts b/src/lib/long-text-field.dbtest.tsnew file mode 100644index 0000000..6b659c7--- /dev/null+++ b/src/lib/long-text-field.dbtest.ts@@ -0,0 +1,184 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { after, before, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";+import type { EmailService } from "./services/email.ts";+import { issueSigningLink } from "./services/signing-links.ts";+import type { StorageService } from "./services/storage.ts";+import {+ recordSignerConsent,+ SigningMutationError,+ submitSigningForToken,+} from "./signing.ts";++// A long answer in a Text field against a real Postgres (issue #90): one+// too long to read in its box on the finished document is refused before+// anything is saved, and one that fits after wrapping is taken.+// Run with `npm run test:db`.++process.env.APP_URL ??= "https://sign.example.test";++let database: pg.Pool;+const createdUsers: string[] = [];++before(async () => {+ database = await openTestDatabase();+ // The next signer's invitation reads the install's name through the shared pool.+ globalThis.__signudocPgPool = database;+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();+});++function unixNow() {+ return Math.floor(Date.now() / 1000);+}++const refuse = async (): Promise<never> => {+ throw new Error("not used");+};++// A typed signature from the first of two signers stores no file and does+// not finish the envelope, so nothing here touches storage.+const storageService: StorageService = {+ deleteObject: refuse,+ getObject: refuse,+ getObjectStream: refuse,+ headObject: refuse,+ putObject: refuse,+};++const emailService: EmailService = {+ async send(message) {+ return { accepted: [message.to], messageId: "m-1", rejected: [] };+ },+ async sendBatch() {+ throw new Error("not used");+ },+};++test("an answer too long for its box is refused, one that wraps to fit is taken", async () => {+ const userId = randomUUID();+ const envelopeId = randomUUID();+ const rileyId = randomUUID();+ const caseyId = randomUUID();+ const signatureId = randomUUID();+ const textId = randomUUID();+ const now = unixNow();+ const link = await issueSigningLink({ expiresInSeconds: 60, issuedAt: now });++ createdUsers.push(userId);+ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,+ [userId, `${userId}@example.test`],+ );+ await database.query(+ `+ insert into envelopes (+ id, user_id, title, status, source_pdf_key, source_pdf_filename,+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at+ ) values ($1, $2, 'Lease', 'sent', $3, 'lease.pdf', 10, 1, $4, $5)+ `,+ [envelopeId, userId, `test/${envelopeId}.pdf`, "a".repeat(64), now],+ );+ await database.query(+ `+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)+ values ($1, $2, 1, 612, 792)+ `,+ [randomUUID(), envelopeId],+ );+ await database.query(+ `+ insert into signers (+ id, envelope_id, name, email, sign_order, status,+ signing_token_hash, signing_token_expires_at, last_notified_at+ ) values ($1, $2, 'Riley Recipient', $3, 1, 'notified', $4, $5, $6)+ `,+ [+ rileyId,+ envelopeId,+ `${rileyId}@example.test`,+ link.tokenHash,+ link.exp,+ now,+ ],+ );+ await database.query(+ `+ insert into signers (id, envelope_id, name, email, sign_order, status)+ values ($1, $2, 'Casey Second', $3, 2, 'pending')+ `,+ [caseyId, envelopeId, `${caseyId}@example.test`],+ );+ // The Text field's place and size from the issue.+ await database.query(+ `+ insert into fields (+ id, envelope_id, signer_id, type, page, x, y, width, height+ ) values+ ($1, $3, $4, 'signature', 1, 0.1, 0.1, 0.2, 0.1),+ ($2, $3, $4, 'text', 1, 0.69, 0.32, 0.19, 0.06)+ `,+ [signatureId, textId, envelopeId, rileyId],+ );+ await recordSignerConsent(+ link.token,+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },+ { database },+ );++ const sign = (answer: string) =>+ submitSigningForToken(+ link.token,+ {+ clientTimezoneOffsetMinutes: 0,+ fields: [+ {+ fieldId: signatureId,+ inputMethod: "typed",+ type: "signature",+ value: "Riley Recipient",+ },+ { fieldId: textId, type: "text", value: answer },+ ],+ },+ { database, emailService, storageService },+ );+ const readState = async () => {+ const field = await database.query<{ value: string | null }>(+ `select value from fields where id = $1`,+ [textId],+ );+ const signer = await database.query<{ status: string }>(+ `select status from signers where id = $1`,+ [rileyId],+ );++ return { status: signer.rows[0]?.status, value: field.rows[0]?.value };+ };++ await assert.rejects(+ sign(`BEGIN ${"W".repeat(240)} FINISH-MARKER`),+ (error: unknown) =>+ error instanceof SigningMutationError &&+ error.statusCode === 400 &&+ /page 1 is too long to fit in its box/.test(error.message) &&+ /Shorten it to \d+ characters or fewer/.test(error.message),+ );+ assert.deepEqual(await readState(), { status: "notified", value: null });++ const answer =+ "BEGIN The tenant agrees to keep the garden tidy, to water the plants twice a week in summer, and to tell the landlord about any leak within two days of finding it. FINISH-MARKER";++ await sign(answer);+ assert.deepEqual(await readState(), { status: "signed", value: answer });+});diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.tsindex cf3adf2..ca2a7af 100644--- a/src/lib/services/pdf-finalize.test.ts+++ b/src/lib/services/pdf-finalize.test.ts@@ -8,6 +8,7 @@ import type { FieldRecord } from "../schemas/field.ts";import type { SignerRecord } from "../schemas/signer.ts";import {describeAuditActor,+ findTypedValueTooLongForField,renderEnvelopeCertificatePdf,renderFinalizedEnvelopePdf,} from "./pdf-finalize.ts";@@ -673,3 +674,162 @@ test("describeAuditActor keeps the signer's name on the signer's own rows", () ="system",);});++// A Text field in the place and size from issue #90: right of centre on a+// US Letter page, 19% of the page wide and 6% high.+const NARROW_FIELD = { height: 0.06, page: 1, width: 0.19, x: 0.69, y: 0.32 };+const LETTER_PAGE = { heightPt: 792, pageNumber: 1, widthPt: 612 };++async function extractTextItems(pdfBytes: Uint8Array) {+ const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");+ const document = await pdfjs.getDocument({+ data: new Uint8Array(pdfBytes),+ useSystemFonts: false,+ verbosity: 0,+ }).promise;+ const page = await document.getPage(1);+ const content = await page.getTextContent();+ const items = (+ content.items as Array<{+ str?: string;+ transform?: number[];+ width?: number;+ }>+ )+ .filter((item) => item.str && item.transform)+ .map((item) => ({+ left: item.transform![4]!,+ right: item.transform![4]! + (item.width ?? 0),+ text: item.str!,+ y: item.transform![5]!,+ }));++ await document.destroy();++ return items;+}++async function renderOneTextField(value: string) {+ const fixture = await makeFixture();+ const field: FieldRecord = {+ ...NARROW_FIELD,+ createdAt: 1_800_000_000,+ envelopeId: fixture.envelope.id,+ id: "long-text",+ required: true,+ signerId: "signer-1",+ submittedAt: 1_800_000_000,+ type: "text",+ updatedAt: 1_800_000_000,+ value,+ };++ return renderFinalizedEnvelopePdf(+ {+ auditEvents: fixture.auditEvents,+ completedAt: fixture.envelope.completedAt!,+ envelope: fixture.envelope,+ fields: [field],+ pages: [LETTER_PAGE],+ signers: fixture.signers,+ sourcePdfKey: fixture.envelope.sourcePdfKey,+ },+ { seal: saveUnsealed, storageService: fixture.storageService },+ );+}++const LONG_ANSWER = [+ "BEGIN",+ "The tenant agrees to keep the garden tidy, to water the plants",+ "twice a week in summer, and to tell the landlord about any leak",+ "within two days of finding it.",+ "FINISH-MARKER",+].join(" ");++test("a long text answer wraps inside its box and is kept whole", async () => {+ const items = await extractTextItems(await renderOneTextField(LONG_ANSWER));+ const fieldLeft = NARROW_FIELD.x * 612;+ const fieldRight = (NARROW_FIELD.x + NARROW_FIELD.width) * 612;+ const fieldTop = 792 - NARROW_FIELD.y * 792;+ const fieldBottom = fieldTop - NARROW_FIELD.height * 792;+ const joined = items+ .map((item) => item.text)+ .join(" ")+ .replace(/\s+/g, " ");++ assert.ok(joined.includes("BEGIN"));+ assert.ok(joined.includes("FINISH-MARKER"));+ assert.ok(new Set(items.map((item) => Math.round(item.y))).size > 1);++ for (const item of items) {+ assert.ok(item.left >= fieldLeft, `${item.text} starts left of its box`);+ assert.ok(item.right <= fieldRight + 0.5, `${item.text} runs past its box`);+ assert.ok(item.y >= fieldBottom && item.y <= fieldTop);+ }+});++test("a short text answer is still drawn on one line", async () => {+ const items = await extractTextItems(await renderOneTextField("Approved"));++ assert.deepEqual(+ items.map((item) => item.text),+ ["Approved"],+ );+});++const ISSUE_90_ANSWER = `BEGIN ${"W".repeat(240)} FINISH-MARKER`;++test("an answer already accepted that is too long is drawn whole, not cut off", async () => {+ const items = await extractTextItems(+ await renderOneTextField(ISSUE_90_ANSWER),+ );+ const joined = items.map((item) => item.text).join("");++ assert.ok(joined.includes("FINISH-MARKER"));+ assert.equal(joined.replace(/[^W]/g, "").length, 240);++ for (const item of items) {+ assert.ok(item.right <= 612, `${item.text} runs off the page`);+ }+});++test("signing is told when an answer cannot fit its box at a readable size", async () => {+ const field = { ...NARROW_FIELD };++ assert.equal(+ await findTypedValueTooLongForField(+ [{ field, value: LONG_ANSWER }],+ [LETTER_PAGE],+ ),+ null,+ );++ const tooLong = await findTypedValueTooLongForField(+ [+ { field, value: "Approved" },+ { field, value: ISSUE_90_ANSWER },+ ],+ [LETTER_PAGE],+ );++ assert.ok(tooLong);+ assert.equal(tooLong.page, 1);+ assert.ok(tooLong.maxCharacters > 0);+ assert.ok(tooLong.maxCharacters < ISSUE_90_ANSWER.length);++ // The length it names does fit.+ assert.equal(+ await findTypedValueTooLongForField(+ [+ {+ field,+ value: Array.from(ISSUE_90_ANSWER)+ .slice(0, tooLong.maxCharacters)+ .join(""),+ },+ ],+ [LETTER_PAGE],+ ),+ null,+ );+});diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex e199ceb..410dcaa 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -297,6 +297,191 @@ function getFieldPadding(widthPt: number, heightPt: number): number {return Math.max(2, Math.min(widthPt, heightPt) * 0.12);}+/**+ * The smallest size an answer typed into a field is allowed to need. Signing+ * refuses an answer that only fits its box below this, so every answer on a+ * finished document can be read.+ */+export const MIN_FIELD_TEXT_SIZE = 4;++/** Below this, a value already accepted is still drawn whole, however small. */+const LAST_RESORT_FIELD_TEXT_SIZE = 0.5;++const FIELD_TEXT_LINE_HEIGHT = 1.15;++type FieldTextLayout = {+ /** From the top of the first line to the foot of the last, in points. */+ blockHeight: number;+ fits: boolean;+ lines: string[];+ size: number;+};++function layoutAtSize(+ font: TextFace,+ text: string,+ maxWidth: number,+ maxHeight: number,+ size: number,+): FieldTextLayout {+ const lines = wrapText(font, size, maxWidth, text).map((line) => line.text);+ const blockHeight =+ lines.length === 0+ ? 0+ : (lines.length - 1) * size * FIELD_TEXT_LINE_HEIGHT + size;++ return { blockHeight, fits: blockHeight <= maxHeight, lines, size };+}++/**+ * Lays a value out in its box: one line at the preferred size when it fits,+ * otherwise wrapped onto as many lines as it needs, at the largest size, no+ * smaller than minSize, at which every line fits. When even minSize is too+ * big, the layout at minSize is returned with fits false.+ */+function layoutFieldText(+ font: TextFace,+ text: string,+ maxWidth: number,+ maxHeight: number,+ preferredSize: number,+ minSize: number,+): FieldTextLayout {+ const largest = Math.max(minSize, Math.min(preferredSize, maxHeight));+ const atLargest = layoutAtSize(font, text, maxWidth, maxHeight, largest);++ if (atLargest.fits) {+ return atLargest;+ }++ const atSmallest = layoutAtSize(font, text, maxWidth, maxHeight, minSize);++ if (!atSmallest.fits) {+ return atSmallest;+ }++ // A smaller size never needs more room, so the size is found by halving.+ let best = atSmallest;+ let low = minSize;+ let high = largest;++ while (high - low > 0.1) {+ const middle = (low + high) / 2;+ const layout = layoutAtSize(font, text, maxWidth, maxHeight, middle);++ if (layout.fits) {+ best = layout;+ low = middle;+ } else {+ high = middle;+ }+ }++ return best;+}++/** The room a text value has inside its field, as the stamp lays it out. */+function getTextFieldBox(rect: { heightPt: number; widthPt: number }) {+ const padding = getFieldPadding(rect.widthPt, rect.heightPt);++ return {+ maxHeight: Math.max(10, rect.heightPt - padding * 2),+ maxWidth: Math.max(12, rect.widthPt - padding * 2),+ padding,+ preferredSize: Math.min(+ Math.max(10, rect.heightPt - padding * 2),+ rect.heightPt * 0.64,+ ),+ };+}++/**+ * Whether a value typed into a field fits its box at a readable size on the+ * page it is placed on. When it does not, also the most of its characters+ * that would.+ */+export function measureFieldTextFit(+ font: TextFace,+ field: Pick<FieldRecord, "height" | "width" | "x" | "y">,+ page: Pick<StoredPageSize, "heightPt" | "widthPt">,+ value: string,+): { fits: true } | { fits: false; maxCharacters: number } {+ const text = value.trim();+ const box = getTextFieldBox(normalizedRectToPdfRect(field, page));+ const fitsText = (candidate: string) =>+ layoutFieldText(+ font,+ candidate,+ box.maxWidth,+ box.maxHeight,+ box.preferredSize,+ MIN_FIELD_TEXT_SIZE,+ ).fits;++ if (fitsText(text)) {+ return { fits: true };+ }++ const characters = Array.from(text);+ let low = 0;+ let high = characters.length - 1;++ while (low < high) {+ const middle = Math.ceil((low + high) / 2);++ if (fitsText(characters.slice(0, middle).join(""))) {+ low = middle;+ } else {+ high = middle - 1;+ }+ }++ return { fits: false, maxCharacters: low };+}++/**+ * The first value a signer typed that would not fit its box at a readable+ * size, with the most of its characters that would, or null when all fit.+ * Measured with the fonts the finished document is drawn with.+ */+export async function findTypedValueTooLongForField(+ entries: ReadonlyArray<{+ field: Pick<FieldRecord, "height" | "page" | "width" | "x" | "y">;+ value: string;+ }>,+ pages: readonly StoredPageSize[],+): Promise<{ maxCharacters: number; page: number } | null> {+ const measurable = entries.flatMap((entry) => {+ const page = pages.find((stored) => stored.pageNumber === entry.field.page);++ return page && entry.value.trim() ? [{ ...entry, pageSize: page }] : [];+ });++ if (measurable.length === 0) {+ return null;+ }++ const faces = await embedTextFaces(+ await PDFDocument.create(),+ measurable.map((entry) => entry.value),+ );++ for (const entry of measurable) {+ const fit = measureFieldTextFit(+ faces.regular,+ entry.field,+ entry.pageSize,+ entry.value,+ );++ if (!fit.fits) {+ return { maxCharacters: fit.maxCharacters, page: entry.field.page };+ }+ }++ return null;+}+export function shouldStampField(field: FieldRecord): boolean {if (field.type === "checkbox" || field.type === "radio") {return typeof field.checked === "boolean";@@ -530,21 +715,40 @@ async function drawFieldValue(return;}- const maxWidth = Math.max(12, rect.widthPt - padding * 2);- const maxHeight = Math.max(10, rect.heightPt - padding * 2);- const fontSize = fitTextSize(+ // Wrapped and made smaller until the whole value is inside the box.+ // Signing refuses a value that would only fit below a readable size,+ // but one accepted earlier is still drawn whole, never cut off.+ const box = getTextFieldBox(rect);+ let layout = layoutFieldText(fonts.auditRegular,textValue,- maxWidth,- maxHeight,- Math.min(maxHeight, rect.heightPt * 0.64),+ box.maxWidth,+ box.maxHeight,+ box.preferredSize,+ MIN_FIELD_TEXT_SIZE,);- fonts.auditRegular.drawText(page, textValue, {- color: rgb(0.12, 0.12, 0.12),- size: fontSize,- x: rect.xPt + padding,- y: rect.yPt + (rect.heightPt - fontSize) / 2 + fontSize * 0.2,+ if (!layout.fits) {+ layout = layoutFieldText(+ fonts.auditRegular,+ textValue,+ box.maxWidth,+ box.maxHeight,+ MIN_FIELD_TEXT_SIZE,+ LAST_RESORT_FIELD_TEXT_SIZE,+ );+ }++ const { size } = layout;+ const top = rect.yPt + (rect.heightPt + layout.blockHeight) / 2;++ layout.lines.forEach((line, index) => {+ fonts.auditRegular.drawText(page, line, {+ color: rgb(0.12, 0.12, 0.12),+ size,+ x: rect.xPt + box.padding,+ y: top - size * 0.8 - index * size * FIELD_TEXT_LINE_HEIGHT,+ });});return;diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex a70a14d..a8097d2 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -66,6 +66,7 @@ import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";import { hashOpaqueToken } from "./services/opaque-tokens.ts";import {finalizeEnvelope,+ findTypedValueTooLongForField,loadInstallSealer,storeEnvelopeCertificatePdf,storeRecipientEnvelopeCertificatePdf,@@ -2104,6 +2105,35 @@ async function assertStillSignersTurn(type SigningContext = Awaited<ReturnType<typeof resolveSigningContext>>;+/**+ * Refuses an answer too long to be read in its box on the finished document,+ * before anything is saved, so the signer can shorten it. Without this the+ * value would be drawn so small that no one could read it.+ */+async function assertTypedValuesFitTheirFields(+ context: SigningContext,+ fieldUpdates: ReadonlyMap<string, FieldPersistenceUpdate>,+) {+ const entries = context.fields.flatMap((field) => {+ const value = field.id ? fieldUpdates.get(field.id)?.value : null;++ return (field.type === "text" ||+ field.type === "number" ||+ field.type === "dropdown") &&+ value+ ? [{ field, value }]+ : [];+ });+ const tooLong = await findTypedValueTooLongForField(entries, context.pages);++ if (tooLong) {+ throw new SigningMutationError(+ `An answer on page ${tooLong.page} is too long to fit in its box on the document. Shorten it to ${tooLong.maxCharacters} characters or fewer, or ask the sender for a bigger box.`,+ 400,+ );+ }+}+/*** What the signer's submission changes: each of their fields' new value,* checked against what the field accepts, and the drawn signatures to store.@@ -2382,6 +2412,8 @@ export async function submitSigningForToken(drawnSignatureUploads,fieldUpdates,} = buildSignerSubmission(context, parsedInput, submittedAt);++ await assertTypedValuesFitTheirFields(context, fieldUpdates);const presentedTokenHash = hashOpaqueToken(token);let signingStatePersisted = false;@@ -3010,6 +3042,8 @@ export async function prepareSignerSubmission(const { currentSignerId, drawnSignatureUploads, fieldUpdates } =buildSignerSubmission(context, parsedInput, submittedAt);+ await assertTypedValuesFitTheirFields(context, fieldUpdates);+return {context,images: new Map(