Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let local disk uploads take PDFs up to the 20 MB limit
Claude328ef77e2ad9
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex dbad64e..018556f 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -4,7 +4,7 @@ import pg from "pg";import { e2eDatabaseUrl, e2eSetupToken } from "../playwright.config";import { extractLink, extractLinks, waitForEmail } from "./support/outbox";import { totpCode } from "./support/totp";-import { writeSamplePdf } from "./support/sample-pdf";+import { writeLargePdf, writeSamplePdf } from "./support/sample-pdf";const PASSWORD = "correct horse battery staple 42";// The ampersand is on purpose: the name goes into HTML emails and page titles.@@ -1487,6 +1487,65 @@ test("a signer who declines is told the decline was recorded, not that the link});});+test("with local disk storage a PDF just under 20 MB uploads, and a larger request is refused", async ({+ page,+}, testInfo) => {+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });+ let adminEmail = "";++ await database.connect();++ try {+ const admin = await database.query<{ email: string }>(+ `select email from public."user" where role = 'admin' limit 1`,+ );++ adminEmail = admin.rows[0]?.email ?? "";+ } finally {+ await database.end();+ }++ expect(adminEmail).not.toBe("");++ await page.goto("/login");+ await page.getByLabel("Email").fill(adminEmail);+ await page.getByLabel("Password").fill(PASSWORD);+ await page.getByRole("button", { name: "Log in" }).click();+ await expect(page).toHaveURL(/\/dashboard$/);++ await test.step("a 19 MB PDF, over Next.js's 10 MB default, makes a draft", async () => {+ const pdfPath = await writeLargePdf(+ testInfo.outputPath("large.pdf"),+ 19 * 1024 * 1024,+ );++ await page.goto("/envelopes/new");+ await page.getByLabel("Envelope title").fill("Large agreement");+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);+ await page.getByRole("button", { name: "Next ->" }).click();+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);+ });++ await test.step("a request over the limit gets the size message", async () => {+ const response = await page.request.post("/api/envelopes", {+ headers: { origin: new URL(page.url()).origin },+ multipart: {+ file: {+ buffer: Buffer.alloc(22 * 1024 * 1024),+ mimeType: "application/pdf",+ name: "too-large.pdf",+ },+ title: "Too large",+ },+ });++ expect(response.status()).toBe(413);+ expect(await response.json()).toEqual({+ error: "This file exceeds the 20 MB limit.",+ });+ });+});+test("two-step sign-in: an administrator sets it up and requires it of everyone", async ({browser,page,diff --git a/e2e/support/sample-pdf.ts b/e2e/support/sample-pdf.tsindex 91d272a..60c5efc 100644--- a/e2e/support/sample-pdf.ts+++ b/e2e/support/sample-pdf.ts@@ -1,6 +1,7 @@+import { randomBytes } from "node:crypto";import { writeFile } from "node:fs/promises";-import { PDFDocument, StandardFonts } from "pdf-lib";+import { PDFDocument, PDFName, PDFString, StandardFonts } from "pdf-lib";/** Writes a small two-page PDF and returns its path. */export async function writeSamplePdf(filePath: string): Promise<string> {@@ -28,3 +29,43 @@ export async function writeSamplePdf(filePath: string): Promise<string> {return filePath;}++/**+ * Writes a one-page PDF padded to about `sizeBytes` with an attached file of+ * random bytes, which cannot be compressed, and returns its path.+ */+export async function writeLargePdf(+ filePath: string,+ sizeBytes: number,+): Promise<string> {+ const document = await PDFDocument.create();+ const font = await document.embedFont(StandardFonts.Helvetica);+ const page = document.addPage([612, 792]);++ page.drawText("Large sample agreement", { font, size: 18, x: 72, y: 700 });++ const padding = document.context.register(+ document.context.stream(randomBytes(sizeBytes), { Type: "EmbeddedFile" }),+ );+ const name = PDFString.of("padding.bin");++ document.catalog.set(+ PDFName.of("Names"),+ document.context.obj({+ EmbeddedFiles: {+ Names: [+ name,+ document.context.obj({+ EF: { F: padding },+ F: name,+ Type: "Filespec",+ }),+ ],+ },+ }),+ );++ await writeFile(filePath, await document.save());++ return filePath;+}diff --git a/next.config.ts b/next.config.tsindex 5ba5f17..9720c77 100644--- a/next.config.ts+++ b/next.config.ts@@ -2,6 +2,8 @@ import { readFileSync } from "node:fs";import type { NextConfig } from "next";+import { MAX_REQUEST_BODY_BYTES } from "./src/lib/types/domain.ts";+// The version this deployment runs, compared with the latest release by// "Check for updates" in Settings (src/lib/software-update.ts).const { version } = JSON.parse(readFileSync("./package.json", "utf8")) as {@@ -18,6 +20,14 @@ const nextConfig: NextConfig = {NEXT_PUBLIC_BOTID:process.env.VERCEL === "1" && process.env.BOTID === "1" ? "1" : "",},+ experimental: {+ // Every request passes through the Proxy (src/proxy.ts), and Next.js+ // keeps only the first 10 MB of a body that does. With local disk+ // storage the PDF is sent in the request itself, so the limit has to+ // fit a PDF at the 20 MB upload limit and the rest of the form.+ // https://nextjs.org/docs/app/api-reference/config/next-config-js/proxyClientMaxBodySize+ proxyClientMaxBodySize: MAX_REQUEST_BODY_BYTES,+ },images: {unoptimized: true,},diff --git a/src/app/api/envelopes/route.ts b/src/app/api/envelopes/route.tsindex 07aadc6..6b7e543 100644--- a/src/app/api/envelopes/route.ts+++ b/src/app/api/envelopes/route.ts@@ -26,6 +26,7 @@ import {type StorageService,} from "@/lib/services/storage";import { isPendingUploadKey } from "@/lib/services/storage-keys";+import { MAX_REQUEST_BODY_BYTES } from "@/lib/types/domain";export async function POST(request: Request) {const sessionResult = await requireVerifiedSenderSession(request);@@ -120,9 +121,27 @@ function invalidRequest(message = "Invalid envelope request.") {async function readFormRequest(request: Request,): Promise<DraftRequest | Response> {+ // A body over the limit is cut short before it gets here, so it could+ // only fail to parse. Say why instead.+ const declaredLength = Number(request.headers.get("content-length"));++ if (declaredLength > MAX_REQUEST_BODY_BYTES) {+ return NextResponse.json(+ { error: "This file exceeds the 20 MB limit." },+ { status: 413 },+ );+ }+const formData = await request.formData().catch(() => null);- const parsedTitle = envelopeTitleSchema.safeParse(formData?.get("title"));- const uploadedFile = formData?.get("file");++ if (!formData) {+ return invalidRequest(+ "The upload could not be read. Choose the PDF again and retry.",+ );+ }++ const parsedTitle = envelopeTitleSchema.safeParse(formData.get("title"));+ const uploadedFile = formData.get("file");if (!parsedTitle.success) {return invalidRequest(parsedTitle.error.issues[0]?.message);diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.tsindex 51c2771..be652d9 100644--- a/src/lib/types/domain.ts+++ b/src/lib/types/domain.ts@@ -2,6 +2,13 @@ export const MAX_SIGNERS_PER_ENVELOPE = 10;/** People who get a copy of the finished document without signing. */export const MAX_COPY_RECIPIENTS_PER_ENVELOPE = 10;export const MAX_UPLOAD_SIZE_BYTES = 20 * 1024 * 1024;+/**+ * The largest request body the app reads in full: a PDF at the upload limit+ * plus room for the rest of the multipart form (the title and the part+ * headers). Next.js cuts every body that passes through the Proxy at this+ * size (next.config.ts), so it must stay above MAX_UPLOAD_SIZE_BYTES.+ */+export const MAX_REQUEST_BODY_BYTES = MAX_UPLOAD_SIZE_BYTES + 1024 * 1024;export const SIGNING_LINK_TTL_SECONDS = 7 * 24 * 60 * 60;export const RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS = 7 * 24 * 60 * 60;export const MANUAL_NUDGE_COOLDOWN_SECONDS = 24 * 60 * 60;