Skip to content

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

TypeScript

fix(fields): preserve whole Unicode characters in dropdown choices (#233)

Kevin Rosef528a03cd70e
diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsx
index 1c4096b..41e0d9b 100644
--- a/src/components/envelopes/prepare-live-shell.tsx
+++ b/src/components/envelopes/prepare-live-shell.tsx
@@ -37,6 +37,7 @@ import {
parseOptionLines,
} from "@/lib/field-choices";
import { getInitials } from "@/lib/initials";
+import { toWellFormedText } from "@/lib/whole-characters";
import {
type FieldPlacement,
type ReplaceFieldsResponse,
@@ -1830,7 +1831,9 @@ function FieldEditor({
maxLength={MAX_FIELD_OPTION_LENGTH}
onChange={(event) => {
setLabelDraft(event.target.value);
- onSetLabel(event.target.value.trim() || undefined);
+ onSetLabel(
+ toWellFormedText(event.target.value).trim() || undefined,
+ );
}}
placeholder="Yes"
value={shownLabel}
diff --git a/src/lib/field-choices.test.ts b/src/lib/field-choices.test.ts
index 3daa918..1918ab4 100644
--- a/src/lib/field-choices.test.ts
+++ b/src/lib/field-choices.test.ts
@@ -93,6 +93,65 @@ test("choices are read one per line, without blanks or repeats", () => {
assert.equal(parseOptionLines("x".repeat(200))[0].length, 80);
});
+test("choices truncate on whole-character boundaries without splitting surrogate pairs", () => {
+ const eightyWithEmoji = `${"a".repeat(79)}πŸ˜€`;
+ const eightyOneWithTrailingAscii = `${"a".repeat(79)}πŸ˜€Z`;
+ const eightyOneWithTrailingEmoji = `${"a".repeat(80)}πŸ˜€`;
+ const family = "πŸ‘¨β€πŸ‘©β€πŸ‘§"; // 5 code points in one grapheme cluster
+ const eightyWithFamily = `${"a".repeat(75)}${family}`;
+ const eightyOneWithFamily = `${"a".repeat(76)}${family}`;
+ const heart = "❀️"; // 2 code points (U+2764 U+FE0F)
+ const flag = "πŸ‡ΊπŸ‡Έ"; // 2 regional-indicator code points
+
+ // 80 code points ending in an astral emoji (81 UTF-16 code units) stays intact.
+ const kept = parseOptionLines(eightyWithEmoji);
+ assert.deepEqual(kept, [eightyWithEmoji]);
+ assert.equal(kept[0].isWellFormed(), true);
+
+ // 81 code points keeps the emoji at code point 80 and drops the 81st.
+ const trimmedAfterEmoji = parseOptionLines(eightyOneWithTrailingAscii);
+ assert.deepEqual(trimmedAfterEmoji, [eightyWithEmoji]);
+ assert.equal(trimmedAfterEmoji[0].isWellFormed(), true);
+
+ // 80 ASCII chars followed by an emoji drops the emoji cleanly.
+ const droppedEmoji = parseOptionLines(eightyOneWithTrailingEmoji);
+ assert.deepEqual(droppedEmoji, ["a".repeat(80)]);
+ assert.equal(droppedEmoji[0].isWellFormed(), true);
+
+ // Multi-code-point grapheme clusters stay whole or are dropped together.
+ assert.deepEqual(parseOptionLines(eightyWithFamily), [eightyWithFamily]);
+ assert.deepEqual(parseOptionLines(`${eightyWithFamily}Z`), [
+ eightyWithFamily,
+ ]);
+ assert.deepEqual(parseOptionLines(eightyOneWithFamily), ["a".repeat(76)]);
+ assert.deepEqual(parseOptionLines(`${"a".repeat(78)}${heart}`), [
+ `${"a".repeat(78)}${heart}`,
+ ]);
+ assert.deepEqual(parseOptionLines(`${"a".repeat(79)}${heart}`), [
+ "a".repeat(79),
+ ]);
+ assert.deepEqual(parseOptionLines(`${"a".repeat(78)}${flag}`), [
+ `${"a".repeat(78)}${flag}`,
+ ]);
+ assert.deepEqual(parseOptionLines(`${"a".repeat(79)}${flag}`), [
+ "a".repeat(79),
+ ]);
+
+ // Lone surrogates already present in input are replaced so JSONB saves never fail.
+ const sanitized = parseOptionLines(`${"a".repeat(79)}\ud83d`);
+ assert.deepEqual(sanitized, [`${"a".repeat(79)}\ufffd`]);
+ assert.equal(sanitized[0].isWellFormed(), true);
+
+ // Trailing whitespace exposed by truncation is still trimmed.
+ assert.deepEqual(parseOptionLines(`${"a".repeat(79)} πŸ˜€`), ["a".repeat(79)]);
+
+ // Editor round-trip preserves typed text for 80-code-point emoji choices.
+ assert.equal(
+ optionsTextToShow(`${eightyWithEmoji}\nNo`, [eightyWithEmoji, "No"]),
+ `${eightyWithEmoji}\nNo`,
+ );
+});
+
test("a dropdown needs two choices and a radio button needs company", () => {
const signerId = "signer-1";
diff --git a/src/lib/field-choices.ts b/src/lib/field-choices.ts
index e10023a..6ef7f66 100644
--- a/src/lib/field-choices.ts
+++ b/src/lib/field-choices.ts
@@ -2,6 +2,11 @@
// number: dropdowns, radio buttons and number fields. Shared by the field
// editor, the signing page and the server, so all three agree.
+import {
+ splitIntoWholeCharacters,
+ toWellFormedText,
+} from "./whole-characters.ts";
+
export const MAX_FIELD_OPTIONS = 20;
export const MAX_FIELD_OPTION_LENGTH = 80;
export const MIN_FIELD_OPTIONS = 2;
@@ -27,6 +32,51 @@ export function isNumberEntry(value: string): boolean {
);
}
+function countCodePoints(value: string): number {
+ let count = 0;
+
+ for (let index = 0; index < value.length; index += 1) {
+ if ((value.codePointAt(index) ?? 0) > 0xffff) {
+ index += 1;
+ }
+
+ count += 1;
+ }
+
+ return count;
+}
+
+// Shortens a choice to at most maxCodePoints Unicode code points (matching the
+// server's limit), cutting only between whole characters so a surrogate pair
+// or joined emoji is never split in half.
+function truncateChoiceText(value: string, maxCodePoints: number): string {
+ const wellFormed = toWellFormedText(value);
+
+ if (wellFormed.length <= maxCodePoints) {
+ return wellFormed;
+ }
+
+ if (countCodePoints(wellFormed) <= maxCodePoints) {
+ return wellFormed;
+ }
+
+ let result = "";
+ let usedCodePoints = 0;
+
+ for (const segment of splitIntoWholeCharacters(wellFormed)) {
+ const segmentCodePoints = countCodePoints(segment);
+
+ if (usedCodePoints + segmentCodePoints > maxCodePoints) {
+ break;
+ }
+
+ result += segment;
+ usedCodePoints += segmentCodePoints;
+ }
+
+ return result;
+}
+
/**
* The choices typed into the editor, one per line: trimmed, with empty
* lines and repeats dropped, and no more than a dropdown can hold.
@@ -35,7 +85,10 @@ export function parseOptionLines(text: string): string[] {
const options: string[] = [];
for (const line of text.split(/\r?\n/)) {
- const option = line.trim().slice(0, MAX_FIELD_OPTION_LENGTH).trim();
+ const option = truncateChoiceText(
+ line.trim(),
+ MAX_FIELD_OPTION_LENGTH,
+ ).trim();
if (option && !options.includes(option)) {
options.push(option);
diff --git a/src/lib/schemas/field.test.ts b/src/lib/schemas/field.test.ts
index eee980c..95bbdc0 100644
--- a/src/lib/schemas/field.test.ts
+++ b/src/lib/schemas/field.test.ts
@@ -1,7 +1,11 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { fieldPlacementSchema } from "./field.ts";
+import {
+ fieldPlacementSchema,
+ replaceFieldsResponseSchema,
+ signingFieldSubmissionSchema,
+} from "./field.ts";
const placement = {
height: 0.05,
@@ -38,3 +42,85 @@ test("a text field may be optional", () => {
true,
);
});
+
+test("dropdown choices accept 80-code-point emoji strings and refuse lone surrogates", () => {
+ const eightyWithEmoji = `${"a".repeat(79)}πŸ˜€`;
+ const eightyOneWithEmoji = `${"a".repeat(80)}πŸ˜€`;
+ const loneHighSurrogate = `${"a".repeat(79)}\ud83d`;
+ const loneLowSurrogate = `${"a".repeat(79)}\ude00`;
+
+ assert.equal(
+ fieldPlacementSchema.safeParse({
+ ...placement,
+ options: [eightyWithEmoji, "No"],
+ type: "dropdown",
+ }).success,
+ true,
+ );
+
+ assert.equal(
+ signingFieldSubmissionSchema.safeParse({
+ fieldId: "field-1",
+ type: "dropdown",
+ value: eightyWithEmoji,
+ }).success,
+ true,
+ );
+
+ assert.equal(
+ replaceFieldsResponseSchema.safeParse({
+ envelopeId: "env-1",
+ fields: [
+ {
+ ...placement,
+ id: "field-1",
+ options: [eightyWithEmoji, "No"],
+ type: "dropdown",
+ },
+ ],
+ fieldsRevision: 1,
+ redirectPath: "/envelopes/env-1/review",
+ updatedAt: 1700000000,
+ }).success,
+ true,
+ );
+
+ assert.equal(
+ fieldPlacementSchema.safeParse({
+ ...placement,
+ options: [eightyOneWithEmoji],
+ type: "dropdown",
+ }).success,
+ false,
+ );
+
+ for (const broken of [loneHighSurrogate, loneLowSurrogate]) {
+ assert.equal(
+ fieldPlacementSchema.safeParse({
+ ...placement,
+ options: [broken],
+ type: "dropdown",
+ }).success,
+ false,
+ );
+
+ assert.equal(
+ signingFieldSubmissionSchema.safeParse({
+ fieldId: "field-1",
+ type: "dropdown",
+ value: broken,
+ }).success,
+ false,
+ );
+
+ assert.equal(
+ fieldPlacementSchema.safeParse({
+ ...placement,
+ groupId: "group-1",
+ label: broken,
+ type: "radio",
+ }).success,
+ false,
+ );
+ }
+});
diff --git a/src/lib/schemas/field.ts b/src/lib/schemas/field.ts
index b9e93d5..7c19e9f 100644
--- a/src/lib/schemas/field.ts
+++ b/src/lib/schemas/field.ts
@@ -7,6 +7,7 @@ import {
MAX_RADIO_GROUP_BUTTONS,
} from "../field-choices.ts";
import { fieldInputMethods, fieldTypes } from "../types/domain.ts";
+import { toWellFormedText } from "../whole-characters.ts";
import {
idSchema,
normalizedCoordinateSchema,
@@ -18,6 +19,19 @@ import {
export const fieldTypeSchema = z.enum(fieldTypes);
export const fieldInputMethodSchema = z.enum(fieldInputMethods);
+function isWellFormedUnicode(value: string): boolean {
+ return typeof value.isWellFormed === "function"
+ ? value.isWellFormed()
+ : toWellFormedText(value) === value;
+}
+
+const fieldOptionSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(MAX_FIELD_OPTION_LENGTH)
+ .refine(isWellFormedUnicode, "Each choice must contain valid Unicode text");
+
export const MAX_DRAWN_SIGNATURE_BYTES = 256 * 1024;
const MAX_DRAWN_SIGNATURE_DATA_URL_LENGTH =
"data:image/png;base64,".length +
@@ -38,14 +52,19 @@ export const fieldPlacementSchema = z
label: optionalTrimmedString(120),
// The choices of a dropdown. A draft may hold fewer than two while the
// sender is still typing them; sending checks for that.
- options: z
- .array(z.string().trim().min(1).max(MAX_FIELD_OPTION_LENGTH))
- .max(MAX_FIELD_OPTIONS)
- .optional(),
+ options: z.array(fieldOptionSchema).max(MAX_FIELD_OPTIONS).optional(),
// The group a radio button belongs to. The signer picks one per group.
groupId: z.string().trim().min(1).max(64).optional(),
})
.superRefine((field, ctx) => {
+ if (field.label !== undefined && !isWellFormedUnicode(field.label)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Field label must contain valid Unicode text",
+ path: ["label"],
+ });
+ }
+
if (field.options !== undefined && field.type !== "dropdown") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
@@ -234,7 +253,7 @@ const numberSubmissionSchema = z.object({
const dropdownSubmissionSchema = z.object({
fieldId: idSchema,
type: z.literal("dropdown"),
- value: z.string().trim().min(1).max(MAX_FIELD_OPTION_LENGTH),
+ value: fieldOptionSchema,
});
const radioSubmissionSchema = z.object({