Skip to content

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

TypeScript

fix(envelopes): enforce title length limit and keep PDF on non-file upload errors (#210)

Kevin Rosebf53f41349de
diff --git a/src/components/envelopes/upload-shell.tsx b/src/components/envelopes/upload-shell.tsx
index 44deee3..af8e5ea 100644
--- a/src/components/envelopes/upload-shell.tsx
+++ b/src/components/envelopes/upload-shell.tsx
@@ -29,6 +29,14 @@ import {
} from "@/lib/pdf-preview-error";
import { assertPdfPreviewRenderable } from "@/lib/pdfjs-client";
import { type CreateEnvelopeResponse } from "@/lib/schemas/envelope";
+import {
+ classifyEnvelopeCreateFailure,
+ ENVELOPE_TITLE_LIMIT_REACHED_MESSAGE,
+ ENVELOPE_TITLE_MAX_LENGTH,
+ getEnvelopeTitleLengthError,
+ suggestEnvelopeTitle,
+ validateEnvelopeTitle,
+} from "@/lib/upload-validation";
const envelopeSteps = ["Upload", "Signers", "Place fields", "Review"];
const MAX_FILE_SIZE_BYTES = 20 * 1024 * 1024;
@@ -47,12 +55,6 @@ const errorMessageMap: Record<UploadErrorCode, string> = {
"too-large": "This file exceeds the 20 MB limit.",
};
-const knownTitleSuggestions: Record<string, string> = {
- "nda-clientbravo-2026.pdf": "NDA - Client Bravo",
- "nda-client-bravo-2026.pdf": "NDA - Client Bravo",
- "vendor-agreement-two-signer.pdf": "Vendor agreement - two signer flow",
-};
-
function formatFileSize(sizeInBytes: number) {
const sizeInMegabytes = sizeInBytes / (1024 * 1024);
@@ -63,26 +65,6 @@ function formatFileSize(sizeInBytes: number) {
return `${Math.max(1, Math.round(sizeInBytes / 1024))} KB`;
}
-function makeTitleSuggestion(fileName: string) {
- return fileName
- .replace(/\.pdf$/i, "")
- .replace(/([a-z])([A-Z])/g, "$1 $2")
- .replace(/[_-]+/g, " ")
- .replace(/\s+/g, " ")
- .trim();
-}
-
-function getTitleSuggestion(fileName: string): string {
- const normalizedName = fileName.toLowerCase();
- const knownTitleSuggestion = knownTitleSuggestions[normalizedName];
-
- if (knownTitleSuggestion) {
- return knownTitleSuggestion;
- }
-
- return makeTitleSuggestion(fileName);
-}
-
function isClientVisiblePdf(file: File): boolean {
const normalizedName = file.name.toLowerCase();
@@ -106,6 +88,8 @@ function UploadShellLayout({
previewUrl,
summary,
title,
+ titleError,
+ titleHelper,
}: {
canContinue: boolean;
errorMessage: string | null;
@@ -120,6 +104,8 @@ function UploadShellLayout({
previewUrl: string | null;
summary: UploadSummary | null;
title: string;
+ titleError: string | null;
+ titleHelper: string | null;
}) {
const dropzoneClasses = isBusy
? "border-(--accent) bg-(--accent-softer)"
@@ -150,7 +136,12 @@ function UploadShellLayout({
>
<div className="space-y-6">
<FieldShell
+ disabled={isBusy}
+ error={titleError ?? undefined}
+ helper={titleHelper ?? undefined}
label="Envelope title"
+ maxLength={ENVELOPE_TITLE_MAX_LENGTH}
+ name="envelope-title"
onChange={onTitleChange}
placeholder="e.g., NDA - Client Bravo"
readOnly={false}
@@ -333,6 +324,7 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
const [title, setTitle] = useState("");
const [summary, setSummary] = useState<UploadSummary | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
+ const [serverTitleError, setServerTitleError] = useState<string | null>(null);
const [isCreatingDraft, setIsCreatingDraft] = useState(false);
const [autoFilledTitle, setAutoFilledTitle] = useState<string | null>(null);
const [isDragActive, setIsDragActive] = useState(false);
@@ -426,7 +418,7 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
startThumbnail(file);
- const titleSuggestion = getTitleSuggestion(file.name);
+ const titleSuggestion = suggestEnvelopeTitle(file.name);
setSummary({
file,
@@ -438,6 +430,7 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
if (title.trim().length === 0) {
setTitle(titleSuggestion);
setAutoFilledTitle(titleSuggestion);
+ setServerTitleError(null);
}
}
@@ -464,6 +457,7 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
function handleTitleChange(event: ChangeEvent<HTMLInputElement>) {
const nextTitle = event.target.value;
setTitle(nextTitle);
+ setServerTitleError(null);
if (autoFilledTitle && nextTitle !== autoFilledTitle) {
setAutoFilledTitle(null);
@@ -486,12 +480,20 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
}
async function handleContinue() {
- if (isCreatingDraft || !summary || title.trim().length === 0) {
+ if (isCreatingDraft || !summary) {
+ return;
+ }
+
+ const clientTitleError = validateEnvelopeTitle(title);
+
+ if (clientTitleError) {
+ setServerTitleError(clientTitleError);
return;
}
setIsCreatingDraft(true);
setErrorMessage(null);
+ setServerTitleError(null);
// Taken now, with the file. The file can still be removed and another
// chosen while the draft is being created, and that one's picture must
@@ -521,11 +523,18 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
const payload = await parseResponse<CreateEnvelopeResponse>(response);
if (!payload.data || payload.error) {
- setErrorMessage(
- payload.error ?? "Something went wrong. Please try again.",
- );
+ const failure = classifyEnvelopeCreateFailure({
+ error: payload.error,
+ status: response.status,
+ });
+
+ if (failure.target === "title") {
+ setServerTitleError(failure.message);
+ } else {
+ setErrorMessage(failure.message);
+ }
- if (response.status === 400) {
+ if (failure.clearSelectedFile) {
setSummary(null);
startThumbnail(null);
}
@@ -563,8 +572,15 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
}
}
+ const titleError = getEnvelopeTitleLengthError(title) ?? serverTitleError;
+ const titleHelper =
+ !titleError && title.length >= ENVELOPE_TITLE_MAX_LENGTH
+ ? ENVELOPE_TITLE_LIMIT_REACHED_MESSAGE
+ : null;
const canContinue =
- !isCreatingDraft && summary != null && title.trim().length > 0;
+ !isCreatingDraft &&
+ summary != null &&
+ validateEnvelopeTitle(title) === null;
return (
<div
@@ -607,6 +623,8 @@ export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
previewUrl={previewUrl}
summary={summary}
title={title}
+ titleError={titleError}
+ titleHelper={titleHelper}
/>
</div>
);
diff --git a/src/lib/upload-validation.test.ts b/src/lib/upload-validation.test.ts
new file mode 100644
index 0000000..c0f5be9
--- /dev/null
+++ b/src/lib/upload-validation.test.ts
@@ -0,0 +1,201 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { envelopeTitleSchema } from "./schemas/common.ts";
+import {
+ getPdfImportErrorMessage,
+ type PdfImportFailureCode,
+} from "./services/document-import.ts";
+import {
+ classifyEnvelopeCreateFailure,
+ ENVELOPE_TITLE_MAX_LENGTH,
+ ENVELOPE_TITLE_REQUIRED_MESSAGE,
+ ENVELOPE_TITLE_TOO_LONG_MESSAGE,
+ getEnvelopeTitleLengthError,
+ suggestEnvelopeTitle,
+ validateEnvelopeTitle,
+} from "./upload-validation.ts";
+
+test("envelope title validation enforces the 160-character trimmed limit (issue #210)", () => {
+ const exactLimitTitle = "A".repeat(ENVELOPE_TITLE_MAX_LENGTH);
+ const overLimitTitle = "A".repeat(ENVELOPE_TITLE_MAX_LENGTH + 1);
+
+ assert.equal(getEnvelopeTitleLengthError(""), null);
+ assert.equal(getEnvelopeTitleLengthError(exactLimitTitle), null);
+ assert.equal(getEnvelopeTitleLengthError(` ${exactLimitTitle} `), null);
+ assert.equal(
+ getEnvelopeTitleLengthError(overLimitTitle),
+ ENVELOPE_TITLE_TOO_LONG_MESSAGE,
+ );
+ assert.equal(
+ getEnvelopeTitleLengthError(` ${overLimitTitle} `),
+ ENVELOPE_TITLE_TOO_LONG_MESSAGE,
+ );
+
+ assert.equal(validateEnvelopeTitle(""), ENVELOPE_TITLE_REQUIRED_MESSAGE);
+ assert.equal(validateEnvelopeTitle(" "), ENVELOPE_TITLE_REQUIRED_MESSAGE);
+ assert.equal(validateEnvelopeTitle("NDA"), null);
+ assert.equal(validateEnvelopeTitle(exactLimitTitle), null);
+ assert.equal(validateEnvelopeTitle(` ${exactLimitTitle} `), null);
+ assert.equal(
+ validateEnvelopeTitle(overLimitTitle),
+ ENVELOPE_TITLE_TOO_LONG_MESSAGE,
+ );
+});
+
+test("suggested titles from long PDF filenames stay within 160 well-formed characters", () => {
+ assert.equal(
+ suggestEnvelopeTitle("nda-client-bravo-2026.pdf"),
+ "NDA - Client Bravo",
+ );
+ assert.equal(
+ suggestEnvelopeTitle("master_service-agreement2026.pdf"),
+ "master service agreement2026",
+ );
+
+ const longSuggestion = suggestEnvelopeTitle(`${"a".repeat(185)}.pdf`);
+
+ assert.equal(longSuggestion.length, ENVELOPE_TITLE_MAX_LENGTH);
+ assert.equal(envelopeTitleSchema.safeParse(longSuggestion).success, true);
+
+ // An emoji sitting across the 160-code-unit boundary is dropped whole rather
+ // than split into a lone surrogate.
+ const emojiBoundary = suggestEnvelopeTitle(`${"a".repeat(159)}📄rest.pdf`);
+
+ assert.equal(emojiBoundary, "a".repeat(159));
+ assert.equal(emojiBoundary.isWellFormed(), true);
+ assert.equal(envelopeTitleSchema.safeParse(emojiBoundary).success, true);
+});
+
+test("HTTP 400 title validation errors keep the selected PDF and normalize Zod text", () => {
+ const tooLongParse = envelopeTitleSchema.safeParse(
+ "A".repeat(ENVELOPE_TITLE_MAX_LENGTH + 1),
+ );
+
+ assert.equal(tooLongParse.success, false);
+ assert.deepEqual(
+ classifyEnvelopeCreateFailure({
+ error: tooLongParse.error.issues[0]?.message,
+ status: 400,
+ }),
+ {
+ clearSelectedFile: false,
+ message: ENVELOPE_TITLE_TOO_LONG_MESSAGE,
+ target: "title",
+ },
+ );
+
+ const emptyParse = envelopeTitleSchema.safeParse(" ");
+
+ assert.equal(emptyParse.success, false);
+ assert.deepEqual(
+ classifyEnvelopeCreateFailure({
+ error: emptyParse.error.issues[0]?.message,
+ status: 400,
+ }),
+ {
+ clearSelectedFile: false,
+ message: ENVELOPE_TITLE_REQUIRED_MESSAGE,
+ target: "title",
+ },
+ );
+
+ const missingParse = envelopeTitleSchema.safeParse(null);
+
+ assert.equal(missingParse.success, false);
+ assert.deepEqual(
+ classifyEnvelopeCreateFailure({
+ error: missingParse.error.issues[0]?.message,
+ status: 400,
+ }),
+ {
+ clearSelectedFile: false,
+ message: ENVELOPE_TITLE_REQUIRED_MESSAGE,
+ target: "title",
+ },
+ );
+});
+
+test("HTTP 400/413 PDF defects still clear the invalid selected PDF", () => {
+ const fileDefectCodes: readonly PdfImportFailureCode[] = [
+ "encrypted_pdf",
+ "invalid_type",
+ "too_large",
+ "too_many_pages",
+ "unreadable_pdf",
+ "unsupported_variant",
+ ];
+
+ for (const code of fileDefectCodes) {
+ const message = getPdfImportErrorMessage(code);
+
+ assert.deepEqual(
+ classifyEnvelopeCreateFailure({ error: message, status: 400 }),
+ {
+ clearSelectedFile: true,
+ message,
+ target: "upload",
+ },
+ `expected ${code} to clear the selected file`,
+ );
+ }
+
+ for (const message of [
+ "A PDF file is required.",
+ "The upload could not be read. Choose the PDF again and retry.",
+ "This PDF has no pages. Please upload a valid PDF.",
+ ]) {
+ assert.deepEqual(
+ classifyEnvelopeCreateFailure({ error: message, status: 400 }),
+ {
+ clearSelectedFile: true,
+ message,
+ target: "upload",
+ },
+ );
+ }
+
+ assert.deepEqual(
+ classifyEnvelopeCreateFailure({
+ error: "This file exceeds the 20 MB limit.",
+ status: 413,
+ }),
+ {
+ clearSelectedFile: true,
+ message: "This file exceeds the 20 MB limit.",
+ target: "upload",
+ },
+ );
+});
+
+test("non-file upload, direct-upload, rate-limit, and server errors keep the selected PDF", () => {
+ const nonFileFailures = [
+ { error: getPdfImportErrorMessage("upload_failed"), status: 400 },
+ { error: "Invalid envelope request.", status: 400 },
+ { error: "Direct uploads are not available on this install.", status: 400 },
+ { error: "Invalid upload reference.", status: 400 },
+ {
+ error: "The uploaded file was not found. Please upload it again.",
+ status: 400,
+ },
+ { error: "Too many requests. Try again shortly.", status: 429 },
+ { error: "Unable to create the draft envelope.", status: 500 },
+ ];
+
+ for (const failure of nonFileFailures) {
+ assert.deepEqual(classifyEnvelopeCreateFailure(failure), {
+ clearSelectedFile: false,
+ message: failure.error,
+ target: "upload",
+ });
+ }
+
+ assert.deepEqual(
+ classifyEnvelopeCreateFailure({ error: null, status: 400 }),
+ {
+ clearSelectedFile: false,
+ message: "Something went wrong. Please try again.",
+ target: "upload",
+ },
+ );
+});
diff --git a/src/lib/upload-validation.ts b/src/lib/upload-validation.ts
new file mode 100644
index 0000000..f3c0fe6
--- /dev/null
+++ b/src/lib/upload-validation.ts
@@ -0,0 +1,182 @@
+// Validation and server-error rules for the envelope upload step.
+// Kept separate from upload-shell.tsx so they can be tested without a browser.
+
+import { truncateToWholeCharacters } from "./text-truncate.ts";
+import { MAX_PDF_PAGES } from "./types/domain.ts";
+
+// Matches envelopeTitleSchema in src/lib/schemas/common.ts.
+export const ENVELOPE_TITLE_MAX_LENGTH = 160;
+
+export const ENVELOPE_TITLE_REQUIRED_MESSAGE = "Give the envelope a title.";
+export const ENVELOPE_TITLE_TOO_LONG_MESSAGE = `Envelope title must be ${String(ENVELOPE_TITLE_MAX_LENGTH)} characters or fewer.`;
+export const ENVELOPE_TITLE_LIMIT_REACHED_MESSAGE = `Maximum ${String(ENVELOPE_TITLE_MAX_LENGTH)} characters reached.`;
+
+const DEFAULT_CREATE_ERROR_MESSAGE = "Something went wrong. Please try again.";
+
+const KNOWN_TITLE_SUGGESTIONS: Record<string, string> = {
+ "nda-clientbravo-2026.pdf": "NDA - Client Bravo",
+ "nda-client-bravo-2026.pdf": "NDA - Client Bravo",
+ "vendor-agreement-two-signer.pdf": "Vendor agreement - two signer flow",
+};
+
+// Server 400/413 messages that reject the selected PDF itself rather than the
+// title or the request transport. Keep these aligned with document-import.ts
+// and /api/envelopes without importing Node-only server modules in the browser.
+const KNOWN_FILE_REJECTION_MESSAGES = new Set<string>([
+ "this pdf is password-protected or encrypted. please upload an unlocked pdf.",
+ "only pdf files are supported. please upload a valid pdf.",
+ "this file exceeds the 20 mb limit.",
+ `this pdf has more than ${String(MAX_PDF_PAGES)} pages. split it into smaller documents.`,
+ "we couldn't read this pdf. please upload a valid file.",
+ "this pdf uses an unsupported format. please export it as a standard pdf.",
+ "a pdf file is required.",
+ "the upload could not be read. choose the pdf again and retry.",
+]);
+
+export type EnvelopeCreateFailure = {
+ clearSelectedFile: boolean;
+ message: string;
+ target: "title" | "upload";
+};
+
+/** Returns a length error when the trimmed title exceeds the 160-character limit. */
+export function getEnvelopeTitleLengthError(title: string): string | null {
+ if (title.trim().length > ENVELOPE_TITLE_MAX_LENGTH) {
+ return ENVELOPE_TITLE_TOO_LONG_MESSAGE;
+ }
+
+ return null;
+}
+
+/** Validates an envelope title before submitting a draft upload. */
+export function validateEnvelopeTitle(title: string): string | null {
+ const trimmedLength = title.trim().length;
+
+ if (trimmedLength === 0) {
+ return ENVELOPE_TITLE_REQUIRED_MESSAGE;
+ }
+
+ if (trimmedLength > ENVELOPE_TITLE_MAX_LENGTH) {
+ return ENVELOPE_TITLE_TOO_LONG_MESSAGE;
+ }
+
+ return null;
+}
+
+/** Builds a default envelope title from a PDF filename, capped to 160 chars. */
+export function suggestEnvelopeTitle(fileName: string): string {
+ const normalizedName = fileName.toLowerCase();
+ const knownTitleSuggestion = KNOWN_TITLE_SUGGESTIONS[normalizedName];
+
+ if (knownTitleSuggestion) {
+ return knownTitleSuggestion;
+ }
+
+ const cleaned = fileName
+ .replace(/\.pdf$/i, "")
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .replace(/[_-]+/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ return truncateToWholeCharacters(cleaned, ENVELOPE_TITLE_MAX_LENGTH).trim();
+}
+
+function classifyTitleFailureMessage(rawMessage: string): string | null {
+ const lower = rawMessage.toLowerCase();
+
+ if (
+ lower.includes(`<= ${String(ENVELOPE_TITLE_MAX_LENGTH)}`) ||
+ lower.includes(`<=${String(ENVELOPE_TITLE_MAX_LENGTH)}`) ||
+ lower.includes(`at most ${String(ENVELOPE_TITLE_MAX_LENGTH)}`) ||
+ (lower.includes("title") &&
+ (lower.includes(String(ENVELOPE_TITLE_MAX_LENGTH)) ||
+ lower.includes("too long") ||
+ lower.includes("fewer") ||
+ lower.includes("at most")))
+ ) {
+ return ENVELOPE_TITLE_TOO_LONG_MESSAGE;
+ }
+
+ if (
+ lower.includes(">=1") ||
+ lower.includes(">= 1") ||
+ lower.includes("at least 1 character") ||
+ lower.includes("expected string") ||
+ (lower.includes("title") &&
+ (lower.includes("required") ||
+ lower.includes("empty") ||
+ lower.includes("give the envelope")))
+ ) {
+ return ENVELOPE_TITLE_REQUIRED_MESSAGE;
+ }
+
+ if (lower.includes("title")) {
+ return rawMessage;
+ }
+
+ return null;
+}
+
+function isFileRejectionMessage(rawMessage: string): boolean {
+ const lower = rawMessage.toLowerCase();
+
+ if (KNOWN_FILE_REJECTION_MESSAGES.has(lower)) {
+ return true;
+ }
+
+ // Matches any server PDF defect message (including future import rules) while
+ // keeping non-file errors like "Invalid envelope request.", "Invalid upload
+ // reference.", "Upload failed. Please try again.", or rate/server errors.
+ return (
+ /\bpdf\b/.test(lower) ||
+ lower.includes("20 mb limit") ||
+ lower.includes("file exceeds")
+ );
+}
+
+/**
+ * Classifies a failed POST /api/envelopes response so the upload form only
+ * clears the selected PDF when the server actually rejected the file itself
+ * (issue #210).
+ */
+export function classifyEnvelopeCreateFailure(input: {
+ error: string | null | undefined;
+ status: number;
+}): EnvelopeCreateFailure {
+ const rawMessage = input.error?.trim() ?? "";
+
+ if (input.status === 413) {
+ return {
+ clearSelectedFile: true,
+ message: rawMessage || "This file exceeds the 20 MB limit.",
+ target: "upload",
+ };
+ }
+
+ if (input.status === 400 && rawMessage.length > 0) {
+ const titleMessage = classifyTitleFailureMessage(rawMessage);
+
+ if (titleMessage) {
+ return {
+ clearSelectedFile: false,
+ message: titleMessage,
+ target: "title",
+ };
+ }
+
+ if (isFileRejectionMessage(rawMessage)) {
+ return {
+ clearSelectedFile: true,
+ message: rawMessage,
+ target: "upload",
+ };
+ }
+ }
+
+ return {
+ clearSelectedFile: false,
+ message: rawMessage || DEFAULT_CREATE_ERROR_MESSAGE,
+ target: "upload",
+ };
+}