Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Cut sender and seal names at whole characters
Claudea6654d2b8b21
diff --git a/src/lib/downloads.ts b/src/lib/downloads.tsindex 2879fae..3050bcc 100644--- a/src/lib/downloads.ts+++ b/src/lib/downloads.ts@@ -10,6 +10,7 @@ import {envelopeRecordSchema,type EnvelopeRecord,} from "./schemas/envelope.ts";+import { truncateToWholeCharacters } from "./text-truncate.ts";import { fieldRecordSchema, type FieldRecord } from "./schemas/field.ts";import { signerRecordSchema, type SignerRecord } from "./schemas/signer.ts";import { listAuditEventsForEnvelope } from "./services/audit.ts";@@ -508,31 +509,6 @@ async function listPageSizesForEnvelope(const MAX_FILE_NAME_SEGMENT_LENGTH = 120;-const graphemeSegmenter = new Intl.Segmenter(undefined, {- granularity: "grapheme",-});--// Cuts at a whole character, so an emoji (or a letter with its accent) is-// kept or dropped in one piece. A plain slice can leave half of a surrogate-// pair, and encodeURIComponent then throws on the file name.-function truncateToWholeCharacters(value: string, maxLength: number): string {- if (value.length <= maxLength) {- return value;- }-- let result = "";-- for (const { segment } of graphemeSegmenter.segment(value)) {- if (result.length + segment.length > maxLength) {- break;- }-- result += segment;- }-- return result;-}-export function sanitizeFileNameSegment(value: string): string {const cleaned = value.toWellFormed()diff --git a/src/lib/services/email-addresses.test.ts b/src/lib/services/email-addresses.test.tsindex d75214e..b43afc8 100644--- a/src/lib/services/email-addresses.test.ts+++ b/src/lib/services/email-addresses.test.ts@@ -56,6 +56,19 @@ test("characters that mean something in an email header are dropped from the nam);});+test("a long name is cut without splitting an emoji", () => {+ const senderAddress = buildEmailAddresses({+ ...base,+ organizationName: `${"Acme ".repeat(15)}Acmeπ`,+ }).senderAddress;++ assert.equal(+ senderAddress,+ `${"Acme ".repeat(15)}Acme <[email protected]>`,+ );+ assert.equal(senderAddress, senderAddress.toWellFormed());+});+test("an install with no name, and the hosted service, send as SignuDoc", () => {assert.equal(buildEmailAddresses({ ...base, organizationName: null }).senderAddress,diff --git a/src/lib/services/email-addresses.ts b/src/lib/services/email-addresses.tsindex c1dfd42..061dfc2 100644--- a/src/lib/services/email-addresses.ts+++ b/src/lib/services/email-addresses.ts@@ -1,4 +1,5 @@import { SIGNUDOC_NAME } from "../branding.ts";+import { truncateToWholeCharacters } from "../text-truncate.ts";// Which addresses email is sent from and replied to.//@@ -50,11 +51,13 @@ export function isResendTestSender(value: string): boolean {// A display name goes into an email header, so anything with a meaning there// (quotes, angle brackets, separators, line breaks) is dropped.function cleanDisplayName(value: string | null): string {- const cleaned = (value ?? "")- .replace(/[\u0000-\u001f\u007f"<>()[\]\\,;:@]/g, " ")- .replace(/\s+/g, " ")- .trim()- .slice(0, 80);+ const cleaned = truncateToWholeCharacters(+ (value ?? "")+ .replace(/[\u0000-\u001f\u007f"<>()[\]\\,;:@]/g, " ")+ .replace(/\s+/g, " ")+ .trim(),+ 80,+ ).trimEnd();return cleaned || SIGNUDOC_NAME;}diff --git a/src/lib/services/pdf-seal.test.ts b/src/lib/services/pdf-seal.test.tsindex 7061b1f..02bd694 100644--- a/src/lib/services/pdf-seal.test.ts+++ b/src/lib/services/pdf-seal.test.ts@@ -1,6 +1,6 @@import assert from "node:assert/strict";import { execFile } from "node:child_process";-import { generateKeyPairSync } from "node:crypto";+import { generateKeyPairSync, X509Certificate } from "node:crypto";import { mkdtemp, rm, writeFile } from "node:fs/promises";import { createServer } from "node:http";import os from "node:os";@@ -22,7 +22,10 @@ import {const run = promisify(execFile);-function makeIdentity(): SealIdentity {+function makeIdentity(+ commonName = "Test seal",+ organization = "Harbour & Finch",+): SealIdentity {const { privateKey, publicKey } = generateKeyPairSync("rsa", {modulusLength: 2048,privateKeyEncoding: { format: "pem", type: "pkcs8" },@@ -30,13 +33,25 @@ function makeIdentity(): SealIdentity {});return createSelfSignedSealIdentity({- commonName: "Test seal",- organization: "Harbour & Finch",+ commonName,+ organization,privateKeyPem: privateKey,publicKeyPem: publicKey,});}+test("a long seal name is cut without splitting an emoji", () => {+ const name = `${"a".repeat(63)}π`;+ const certificate = new X509Certificate(+ makeIdentity(name, name).certificateChainPem[0]!,+ );++ assert.equal(+ certificate.subject,+ `CN=${"a".repeat(63)}\nO=${"a".repeat(63)}`,+ );+});+async function makePdf(): Promise<PDFDocument> {const pdf = await PDFDocument.create();const page = pdf.addPage([612, 792]);diff --git a/src/lib/services/pdf-seal.ts b/src/lib/services/pdf-seal.tsindex 4509f5b..03721c7 100644--- a/src/lib/services/pdf-seal.ts+++ b/src/lib/services/pdf-seal.ts@@ -6,6 +6,7 @@ import { Signer, SUBFILTER_ETSI_CADES_DETACHED } from "@signpdf/utils";import forge from "node-forge";import type { PDFDocument } from "pdf-lib";+import { truncateToWholeCharacters } from "../text-truncate.ts";import { children, elementBytes, readTlv } from "./der.ts";// A PAdES baseline (B-B, or B-T with a timestamp) seal on a finished PDF.@@ -449,9 +450,14 @@ export function createSelfSignedSealIdentity({certificate.validity.notAfter = notAfter;const subject = [- { name: "commonName", value: commonName.slice(0, 64) },+ { name: "commonName", value: truncateToWholeCharacters(commonName, 64) },...(organization- ? [{ name: "organizationName", value: organization.slice(0, 64) }]+ ? [+ {+ name: "organizationName",+ value: truncateToWholeCharacters(organization, 64),+ },+ ]: []),];diff --git a/src/lib/text-truncate.test.ts b/src/lib/text-truncate.test.tsnew file mode 100644index 0000000..07470de--- /dev/null+++ b/src/lib/text-truncate.test.ts@@ -0,0 +1,26 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import { truncateToWholeCharacters } from "./text-truncate.ts";++test("short text is returned as it is", () => {+ assert.equal(truncateToWholeCharacters("Acme π", 80), "Acme π");+});++test("a cut inside an emoji drops the whole emoji", () => {+ assert.equal(+ truncateToWholeCharacters(`${"a".repeat(63)}π`, 64),+ "a".repeat(63),+ );+});++test("a joined emoji is kept or dropped in one piece", () => {+ const family = "π¨βπ©βπ§";++ assert.equal(truncateToWholeCharacters(`ab${family}`, 5), "ab");+ assert.equal(truncateToWholeCharacters(`ab${family}c`, 10), `ab${family}`);+});++test("a lone surrogate already in the text becomes U+FFFD", () => {+ assert.equal(truncateToWholeCharacters("a\ud83db", 80), "aοΏ½b");+});diff --git a/src/lib/text-truncate.ts b/src/lib/text-truncate.tsnew file mode 100644index 0000000..3fe8a2b--- /dev/null+++ b/src/lib/text-truncate.ts@@ -0,0 +1,30 @@+const graphemeSegmenter = new Intl.Segmenter(undefined, {+ granularity: "grapheme",+});++// Shortens text to at most maxLength UTF-16 code units, cutting only between+// whole characters, so an emoji (or a letter with its accent) is kept or+// dropped in one piece. A plain slice can leave half of a surrogate pair,+// which makes encodeURIComponent and UTF-8 encoders throw.+export function truncateToWholeCharacters(+ value: string,+ maxLength: number,+): string {+ const wellFormed = value.toWellFormed();++ if (wellFormed.length <= maxLength) {+ return wellFormed;+ }++ let result = "";++ for (const { segment } of graphemeSegmenter.segment(wellFormed)) {+ if (result.length + segment.length > maxLength) {+ break;+ }++ result += segment;+ }++ return result;+}