Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Cut download file names at whole characters (#89)

Claudea5340fa93c0c
diff --git a/src/lib/downloads.ts b/src/lib/downloads.ts
index 7606479..2879fae 100644
--- a/src/lib/downloads.ts
+++ b/src/lib/downloads.ts
@@ -506,13 +506,44 @@ 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 {
- return value
+ const cleaned = value
+ .toWellFormed()
.trim()
.replace(/[<>:"/\\|?*\u0000-\u001F]+/g, " ")
.replace(/\s+/g, " ")
- .replace(/\.+$/g, "")
- .slice(0, 120);
+ .replace(/\.+$/g, "");
+
+ return truncateToWholeCharacters(cleaned, MAX_FILE_NAME_SEGMENT_LENGTH)
+ .trimEnd()
+ .replace(/\.+$/g, "");
}
function buildDownloadFileName(
diff --git a/src/lib/file-name-segment.test.ts b/src/lib/file-name-segment.test.ts
new file mode 100644
index 0000000..8d4bfe9
--- /dev/null
+++ b/src/lib/file-name-segment.test.ts
@@ -0,0 +1,69 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { sanitizeFileNameSegment } from "./downloads.ts";
+import { buildContentDisposition } from "./services/storage.ts";
+
+function isWellFormed(value: string): boolean {
+ return value === value.toWellFormed();
+}
+
+// The title from issue #89: the cut at 120 lands inside the emoji.
+const splitTitle = `${"Example ".repeat(14)}TitleAA😀A`;
+const controlTitle = `B${"Example ".repeat(14)}TitleAA😀`;
+
+test("a cut that lands inside an emoji drops the whole emoji", () => {
+ const segment = sanitizeFileNameSegment(splitTitle);
+
+ assert.ok(isWellFormed(segment), JSON.stringify(segment));
+ assert.ok(segment.length <= 120);
+ assert.equal(segment, `${"Example ".repeat(14)}TitleAA`);
+});
+
+test("a joined emoji is kept or dropped in one piece", () => {
+ const family = "👨‍👩‍👧";
+ const segment = sanitizeFileNameSegment(`${"a".repeat(117)}${family}`);
+
+ assert.equal(segment, "a".repeat(117));
+ assert.equal(
+ sanitizeFileNameSegment(`${"a".repeat(112)}${family}`),
+ `${"a".repeat(112)}${family}`,
+ );
+});
+
+test("a cut leaves no space or dot at the end of the name", () => {
+ assert.equal(
+ sanitizeFileNameSegment(`${"a".repeat(119)} b`),
+ "a".repeat(119),
+ );
+ assert.equal(
+ sanitizeFileNameSegment(`${"a".repeat(118)}..b`),
+ "a".repeat(118),
+ );
+});
+
+test("a short title is left as it is", () => {
+ assert.equal(sanitizeFileNameSegment("NDA 😀 Acme"), "NDA 😀 Acme");
+});
+
+test("both issue titles give a download header a response accepts", () => {
+ for (const title of [splitTitle, controlTitle]) {
+ for (const suffix of [" - signed.pdf", " - certificate.pdf"]) {
+ const fileName = `${sanitizeFileNameSegment(title)}${suffix}`;
+ const value = buildContentDisposition(fileName);
+ const response = new Response("", {
+ headers: { "content-disposition": value },
+ });
+
+ assert.equal(response.headers.get("content-disposition"), value);
+ const encoded = value.split("filename*=UTF-8''")[1] ?? "";
+ assert.equal(decodeURIComponent(encoded), fileName);
+ }
+ }
+});
+
+test("a lone surrogate in a file name does not make the header throw", () => {
+ const value = buildContentDisposition("Report \ud83d.pdf");
+
+ assert.ok(value.endsWith("filename*=UTF-8''Report%20%EF%BF%BD.pdf"), value);
+});
diff --git a/src/lib/services/storage.ts b/src/lib/services/storage.ts
index 24a8b08..c9bcb39 100644
--- a/src/lib/services/storage.ts
+++ b/src/lib/services/storage.ts
@@ -31,8 +31,11 @@ export function buildContentDisposition(
// Header values must be Latin-1, and the quoted fallback is safest as plain
// ASCII. Browsers that understand filename* (all current ones) use the
// UTF-8 name instead.
- const fallbackName = fileName.replace(/[^\x20-\x7e]+|["\\]+/g, "_");
- const encodedName = encodeURIComponent(fileName).replace(
+ // toWellFormed() swaps a lone surrogate for U+FFFD, since
+ // encodeURIComponent throws on one.
+ const wellFormedName = fileName.toWellFormed();
+ const fallbackName = wellFormedName.replace(/[^\x20-\x7e]+|["\\]+/g, "_");
+ const encodedName = encodeURIComponent(wellFormedName).replace(
/['()*]/g,
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
);