Skip to content

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

TypeScript

Upload PDFs straight to Vercel Blob from the browser

Claude9eb9cc51e3ad
diff --git a/playwright.config.ts b/playwright.config.ts
index 4d2fe4a..d4c4eca 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -59,7 +59,10 @@ export default defineConfig({
NEXT_TELEMETRY_DISABLED: "1",
// The breach check calls an outside service; the test must not.
PASSWORD_BREACH_CHECK: "off",
- STORAGE_DRIVER: "local",
+ // "local" unless E2E_STORAGE_DRIVER says otherwise. With "blob" and a
+ // BLOB_READ_WRITE_TOKEN in the environment, the same test runs against
+ // a real Vercel Blob store, direct browser upload included.
+ STORAGE_DRIVER: process.env.E2E_STORAGE_DRIVER ?? "local",
STORAGE_LOCAL_DIR: path.join(e2eDataDir, "storage"),
SUPPORT_EMAIL: "[email protected]",
},
diff --git a/src/app/(app)/envelopes/new/page.tsx b/src/app/(app)/envelopes/new/page.tsx
index 7ddbdea..d8bf656 100644
--- a/src/app/(app)/envelopes/new/page.tsx
+++ b/src/app/(app)/envelopes/new/page.tsx
@@ -1,5 +1,18 @@
import { UploadShell } from "@/components/envelopes/upload-shell";
+import { getAuthSession } from "@/lib/auth/server";
+import { supportsDirectUploads } from "@/lib/services/storage";
+import { buildPendingUploadPrefix } from "@/lib/services/storage-keys";
export default async function NewEnvelopePage() {
- return <UploadShell />;
+ // On Vercel Blob the browser sends the PDF straight to storage, into this
+ // user's pending folder. With local storage it goes through the app.
+ const session = supportsDirectUploads() ? await getAuthSession() : null;
+
+ return (
+ <UploadShell
+ directUploadPrefix={
+ session ? buildPendingUploadPrefix(session.user.id) : null
+ }
+ />
+ );
}
diff --git a/src/app/api/envelopes/route.ts b/src/app/api/envelopes/route.ts
index 6f14b2c..4404d23 100644
--- a/src/app/api/envelopes/route.ts
+++ b/src/app/api/envelopes/route.ts
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
+import { z } from "zod";
import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
import {
@@ -14,6 +15,17 @@ import {
} from "@/lib/security/route-controls";
import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
import { DocumentImportError } from "@/lib/services/document-import";
+import {
+ discardPendingUpload,
+ PendingUploadError,
+ readPendingUpload,
+} from "@/lib/services/pending-uploads";
+import {
+ createStorageService,
+ supportsDirectUploads,
+ type StorageService,
+} from "@/lib/services/storage";
+import { isPendingUploadKey } from "@/lib/services/storage-keys";
export async function POST(request: Request) {
const sessionResult = await requireVerifiedSenderSession(request);
@@ -36,37 +48,23 @@ export async function POST(request: Request) {
return rateLimitResponse;
}
- const formData = await request.formData().catch(() => null);
- const parsedTitle = envelopeTitleSchema.safeParse(formData?.get("title"));
- const uploadedFile = formData?.get("file");
-
- if (!parsedTitle.success) {
- const issue = parsedTitle.error.issues[0];
+ const isDirectUpload = (request.headers.get("content-type") ?? "")
+ .toLowerCase()
+ .includes("application/json");
+ const draftRequest = isDirectUpload
+ ? await readDirectUploadRequest(request, session.user.id)
+ : await readFormRequest(request);
- return NextResponse.json(
- { error: issue?.message ?? "Invalid envelope request." },
- { status: 400 },
- );
- }
-
- if (!(uploadedFile instanceof File)) {
- return NextResponse.json(
- { error: "A PDF file is required." },
- { status: 400 },
- );
+ if (draftRequest instanceof Response) {
+ return draftRequest;
}
try {
- const sourcePdfBody = new Uint8Array(await uploadedFile.arrayBuffer());
const result = await createDraftEnvelope(
session.user.id,
{
- sourcePdf: {
- body: sourcePdfBody,
- contentType: uploadedFile.type,
- filename: uploadedFile.name,
- },
- title: parsedTitle.data,
+ sourcePdf: await draftRequest.readSourcePdf(),
+ title: draftRequest.title,
},
{
database: getDb(),
@@ -77,7 +75,10 @@ export async function POST(request: Request) {
status: 201,
});
} catch (error) {
- if (error instanceof DocumentImportError) {
+ if (
+ error instanceof DocumentImportError ||
+ error instanceof PendingUploadError
+ ) {
return NextResponse.json({ error: error.message }, { status: 400 });
}
@@ -93,5 +94,114 @@ export async function POST(request: Request) {
{ error: "Unable to create the draft envelope." },
{ status: 500 },
);
+ } finally {
+ await draftRequest.cleanUp();
}
}
+
+type SourcePdf = {
+ body: Uint8Array;
+ contentType: string;
+ filename: string;
+};
+
+type DraftRequest = {
+ cleanUp: () => Promise<void>;
+ readSourcePdf: () => Promise<SourcePdf>;
+ title: string;
+};
+
+function invalidRequest(message = "Invalid envelope request.") {
+ return NextResponse.json({ error: message }, { status: 400 });
+}
+
+// The PDF arrives in the request itself. Used with local storage; on Vercel
+// a request this size would be refused before it reached the app.
+async function readFormRequest(
+ request: Request,
+): Promise<DraftRequest | Response> {
+ const formData = await request.formData().catch(() => null);
+ const parsedTitle = envelopeTitleSchema.safeParse(formData?.get("title"));
+ const uploadedFile = formData?.get("file");
+
+ if (!parsedTitle.success) {
+ return invalidRequest(parsedTitle.error.issues[0]?.message);
+ }
+
+ if (!(uploadedFile instanceof File)) {
+ return invalidRequest("A PDF file is required.");
+ }
+
+ return {
+ cleanUp: async () => undefined,
+ readSourcePdf: async () => ({
+ body: new Uint8Array(await uploadedFile.arrayBuffer()),
+ contentType: uploadedFile.type,
+ filename: uploadedFile.name,
+ }),
+ title: parsedTitle.data,
+ };
+}
+
+const directUploadRequestSchema = z.object({
+ filename: z.string().trim().min(1).max(255),
+ title: envelopeTitleSchema,
+ uploadKey: z.string().min(1).max(512),
+});
+
+// The browser has already sent the PDF straight to storage and names where
+// it put it. The file is read back and validated like any other upload, and
+// the pending copy is deleted whether or not a draft comes out of it.
+async function readDirectUploadRequest(
+ request: Request,
+ userId: string,
+): Promise<DraftRequest | Response> {
+ if (!supportsDirectUploads()) {
+ return invalidRequest("Direct uploads are not available on this install.");
+ }
+
+ const parsedRequest = directUploadRequestSchema.safeParse(
+ await request.json().catch(() => null),
+ );
+
+ if (!parsedRequest.success) {
+ const issue = parsedRequest.error.issues[0];
+
+ return invalidRequest(
+ issue?.path[0] === "title" ? issue.message : undefined,
+ );
+ }
+
+ const { filename, title, uploadKey } = parsedRequest.data;
+
+ // Checked here as well as on read, so that nothing outside the user's
+ // own pending folder can ever be handed to cleanUp.
+ if (!isPendingUploadKey(uploadKey, userId)) {
+ return invalidRequest("Invalid upload reference.");
+ }
+
+ // Created on first use, inside the caller's error handling.
+ let storageService: StorageService | undefined;
+
+ return {
+ cleanUp: async () => {
+ if (storageService) {
+ await discardPendingUpload({ key: uploadKey, storageService });
+ }
+ },
+ readSourcePdf: async () => {
+ storageService = createStorageService();
+
+ return {
+ body: await readPendingUpload({
+ key: uploadKey,
+ storageService,
+ userId,
+ }),
+ contentType: "application/pdf",
+ filename,
+ };
+ },
+ title,
+ };
+}
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
new file mode 100644
index 0000000..e317c58
--- /dev/null
+++ b/src/app/api/uploads/route.ts
@@ -0,0 +1,72 @@
+import { NextResponse } from "next/server";
+
+import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+import {
+ authorizeDirectUpload,
+ DirectUploadRequestError,
+} from "@/lib/services/direct-upload";
+import { supportsDirectUploads } from "@/lib/services/storage";
+
+// Hands the browser a short-lived signed URL for sending one PDF straight to
+// Vercel Blob. Called by the Blob SDK from the upload page, never by hand.
+export async function POST(request: Request) {
+ const sessionResult = await requireVerifiedSenderSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const rateLimitResponse = applyRateLimit({
+ category: "direct_upload_authorize",
+ key: buildRateLimitKey(["direct-upload", session.user.id]),
+ limit: 30,
+ request,
+ userId: session.user.id,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ if (!supportsDirectUploads()) {
+ return NextResponse.json(
+ { error: "Direct uploads are not available on this install." },
+ { status: 404 },
+ );
+ }
+
+ try {
+ return NextResponse.json(
+ await authorizeDirectUpload({
+ body: await request.json().catch(() => null),
+ request,
+ userId: session.user.id,
+ }),
+ );
+ } catch (error) {
+ if (error instanceof DirectUploadRequestError) {
+ return NextResponse.json({ error: error.message }, { status: 400 });
+ }
+
+ logRouteError(error, {
+ category: "direct_upload_authorize_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while authorizing a direct upload.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "Unable to start the upload." },
+ { status: 500 },
+ );
+ }
+}
diff --git a/src/components/envelopes/upload-shell.tsx b/src/components/envelopes/upload-shell.tsx
index c9540cd..01ac876 100644
--- a/src/components/envelopes/upload-shell.tsx
+++ b/src/components/envelopes/upload-shell.tsx
@@ -239,7 +239,54 @@ function UploadShellLayout({
);
}
-export function UploadShell() {
+// Sends the PDF straight to Vercel Blob with a signed URL from /api/uploads,
+// then tells the app where it is. The Blob SDK is loaded only when used.
+async function createDraftFromDirectUpload(input: {
+ file: File;
+ title: string;
+ uploadPrefix: string;
+}) {
+ const { uploadPresigned } = await import("@vercel/blob/client");
+ const uploadKey = `${input.uploadPrefix}${crypto.randomUUID()}.pdf`;
+
+ await uploadPresigned(uploadKey, input.file, {
+ access: "private",
+ contentType: "application/pdf",
+ handleUploadUrl: "/api/uploads",
+ });
+
+ return fetch("/api/envelopes", {
+ body: JSON.stringify({
+ filename: input.file.name,
+ title: input.title,
+ uploadKey,
+ }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+}
+
+async function createDraftFromForm(input: { file: File; title: string }) {
+ const formData = new FormData();
+
+ formData.append("file", input.file);
+ formData.append("title", input.title);
+
+ return fetch("/api/envelopes", {
+ body: formData,
+ method: "POST",
+ });
+}
+
+type UploadShellProps = {
+ /**
+ * Where this user's browser may upload directly, ending in a slash, or
+ * null when uploads go through the app.
+ */
+ directUploadPrefix?: string | null;
+};
+
+export function UploadShell({ directUploadPrefix = null }: UploadShellProps) {
const router = useRouter();
const [title, setTitle] = useState("");
const [summary, setSummary] = useState<UploadSummary | null>(null);
@@ -267,9 +314,7 @@ export function UploadShell() {
response: Response,
): Promise<{ data: T | null; error: string | null }> {
const payload = (await response.json().catch(() => null)) as
- | { error?: string }
- | T
- | null;
+ { error?: string } | T | null;
if (!response.ok) {
return {
@@ -380,14 +425,13 @@ export function UploadShell() {
return;
}
- const formData = new FormData();
- formData.append("file", summary.file);
- formData.append("title", title.trim());
-
- const response = await fetch("/api/envelopes", {
- body: formData,
- method: "POST",
- });
+ const draftInput = { file: summary.file, title: title.trim() };
+ const response = directUploadPrefix
+ ? await createDraftFromDirectUpload({
+ ...draftInput,
+ uploadPrefix: directUploadPrefix,
+ })
+ : await createDraftFromForm(draftInput);
const payload = await parseResponse<CreateEnvelopeResponse>(response);
if (!payload.data || payload.error) {
diff --git a/src/lib/services/direct-upload.test.ts b/src/lib/services/direct-upload.test.ts
new file mode 100644
index 0000000..a28baeb
--- /dev/null
+++ b/src/lib/services/direct-upload.test.ts
@@ -0,0 +1,117 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ authorizeDirectUpload,
+ DirectUploadRequestError,
+} from "./direct-upload.ts";
+import { MAX_UPLOAD_SIZE_BYTES } from "../types/domain.ts";
+
+const USER_ID = "user_abc123";
+const UPLOAD_KEY = `uploads/${USER_ID}/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.pdf`;
+
+function base64Url(value: string) {
+ return Buffer.from(value).toString("base64url");
+}
+
+// Stands in for Blob's control API, which is not reachable from a test.
+// The delegation token has the shape the SDK reads back when it signs a URL.
+async function issueFakeToken(options: {
+ allowedContentTypes: string[];
+ maximumSizeInBytes: number;
+ operations: string[];
+ pathname: string;
+ validUntil: number;
+}) {
+ return {
+ clientSigningToken: "signing-secret",
+ delegationToken: `${base64Url(
+ JSON.stringify({ ...options, storeId: "store_test" }),
+ )}.signature`,
+ validUntil: options.validUntil,
+ };
+}
+
+function authorize(body: unknown, userId = USER_ID) {
+ return authorizeDirectUpload({
+ body,
+ issueToken: issueFakeToken,
+ request: new Request("https://sign.example.com/api/uploads", {
+ method: "POST",
+ }),
+ userId,
+ });
+}
+
+function generateUrlEvent(pathname: string, multipart = false) {
+ return {
+ payload: { clientPayload: null, multipart, pathname },
+ type: "blob.generate-presigned-url",
+ };
+}
+
+test("a user gets a signed upload URL limited to one PDF in their own folder", async () => {
+ const response = await authorize(generateUrlEvent(UPLOAD_KEY));
+
+ assert.equal(response.type, "blob.generate-presigned-url");
+ assert.ok("presignedUrlPayload" in response);
+ assert.deepEqual(response.presignedUrlPayload.params, {
+ "vercel-blob-add-random-suffix": "false",
+ "vercel-blob-allow-overwrite": "false",
+ "vercel-blob-allowed-content-types": "application/pdf",
+ "vercel-blob-maximum-size-in-bytes": String(MAX_UPLOAD_SIZE_BYTES),
+ "vercel-blob-ttl-days": "1",
+ });
+ assert.ok(response.presignedUrlPayload.signature.length > 0);
+
+ const delegation = JSON.parse(
+ Buffer.from(
+ response.presignedUrlPayload.delegationToken.split(".")[0]!,
+ "base64url",
+ ).toString(),
+ );
+
+ assert.equal(delegation.pathname, UPLOAD_KEY);
+ assert.deepEqual(delegation.operations, ["put"]);
+ assert.deepEqual(delegation.allowedContentTypes, ["application/pdf"]);
+ assert.equal(delegation.maximumSizeInBytes, MAX_UPLOAD_SIZE_BYTES);
+ assert.ok(delegation.validUntil > Date.now());
+ assert.ok(delegation.validUntil <= Date.now() + 10 * 60 * 1000);
+});
+
+test("upload destinations outside the user's own pending folder are refused", async () => {
+ for (const pathname of [
+ "uploads/someone_else/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.pdf",
+ `uploads/${USER_ID}/../someone_else/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.pdf`,
+ `uploads/${USER_ID}/contract.pdf`,
+ `uploads/${USER_ID}/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.exe`,
+ `uploads/${USER_ID}/nested/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.pdf`,
+ `users/${USER_ID}/envelopes/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b/original.pdf`,
+ "",
+ ]) {
+ await assert.rejects(
+ authorize(generateUrlEvent(pathname)),
+ DirectUploadRequestError,
+ pathname,
+ );
+ }
+});
+
+test("multipart uploads and other event types are refused", async () => {
+ await assert.rejects(
+ authorize(generateUrlEvent(UPLOAD_KEY, true)),
+ DirectUploadRequestError,
+ );
+
+ for (const body of [
+ null,
+ "text",
+ {},
+ { type: "blob.upload-completed", payload: { blob: {}, tokenPayload: "" } },
+ { type: "blob.generate-client-token", payload: { pathname: UPLOAD_KEY } },
+ { type: "blob.generate-presigned-url" },
+ { type: "blob.generate-presigned-url", payload: { pathname: 42 } },
+ ]) {
+ await assert.rejects(authorize(body), DirectUploadRequestError);
+ }
+});
diff --git a/src/lib/services/direct-upload.ts b/src/lib/services/direct-upload.ts
new file mode 100644
index 0000000..a7f1e72
--- /dev/null
+++ b/src/lib/services/direct-upload.ts
@@ -0,0 +1,139 @@
+import { issueSignedToken, type IssuedSignedToken } from "@vercel/blob";
+import { handleUploadPresigned } from "@vercel/blob/client";
+
+import { MAX_UPLOAD_SIZE_BYTES } from "../types/domain.ts";
+import { isPendingUploadKey } from "./storage-keys.ts";
+
+// Direct uploads: the browser sends a PDF straight to Vercel Blob instead of
+// through the app, because a request to a Vercel Function is capped at
+// 4.5 MB. The app hands out a signed upload URL that is good for one
+// pathname, PDFs only, up to the upload limit, for a few minutes.
+//
+// This uses signed URLs rather than Blob client tokens because signed URLs
+// work with either kind of Blob credential (the project's OIDC token or a
+// read-write token); client tokens need a read-write token.
+// https://vercel.com/docs/vercel-blob/vercel-signed-urls#presigned-uploads
+
+const UPLOAD_URL_LIFETIME_MS = 10 * 60 * 1000;
+const PDF_CONTENT_TYPES = ["application/pdf"];
+// An upload the app never picks up (a closed tab, a failed request) is
+// deleted by Blob itself after a day. One day is the shortest it offers.
+const PENDING_UPLOAD_TTL_DAYS = 1;
+const GENERATE_URL_EVENT = "blob.generate-presigned-url";
+
+export class DirectUploadRequestError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "DirectUploadRequestError";
+ }
+}
+
+type IssueUploadToken = (options: {
+ allowedContentTypes: string[];
+ maximumSizeInBytes: number;
+ operations: ["put"];
+ pathname: string;
+ validUntil: number;
+}) => Promise<IssuedSignedToken>;
+
+type AuthorizeDirectUploadInput = {
+ body: unknown;
+ /** Replaced in tests, where there is no Blob store to ask. */
+ issueToken?: IssueUploadToken;
+ request: Request;
+ userId: string;
+};
+
+type GenerateUrlEvent = {
+ payload: {
+ clientPayload: string | null;
+ multipart: boolean;
+ pathname: string;
+ };
+ type: typeof GENERATE_URL_EVENT;
+};
+
+function parseGenerateUrlEvent(body: unknown): GenerateUrlEvent {
+ if (
+ typeof body !== "object" ||
+ body === null ||
+ (body as { type?: unknown }).type !== GENERATE_URL_EVENT
+ ) {
+ throw new DirectUploadRequestError("Invalid upload request.");
+ }
+
+ const payload = (body as { payload?: unknown }).payload;
+
+ if (
+ typeof payload !== "object" ||
+ payload === null ||
+ typeof (payload as { pathname?: unknown }).pathname !== "string"
+ ) {
+ throw new DirectUploadRequestError("Invalid upload request.");
+ }
+
+ return {
+ payload: {
+ clientPayload: null,
+ multipart: (payload as { multipart?: unknown }).multipart === true,
+ pathname: (payload as { pathname: string }).pathname,
+ },
+ type: GENERATE_URL_EVENT,
+ };
+}
+
+/**
+ * Answers the Blob SDK's request for somewhere to upload one PDF. Returns
+ * the JSON the SDK in the browser expects. The caller must already have
+ * checked that the request comes from a signed-in, verified user.
+ */
+export async function authorizeDirectUpload({
+ body,
+ issueToken = issueSignedToken,
+ request,
+ userId,
+}: AuthorizeDirectUploadInput) {
+ const event = parseGenerateUrlEvent(body);
+
+ return handleUploadPresigned({
+ body: event,
+ getSignedToken: async (pathname, _clientPayload, multipart) => {
+ if (multipart) {
+ throw new DirectUploadRequestError(
+ "Multipart uploads are not supported.",
+ );
+ }
+
+ if (!isPendingUploadKey(pathname, userId)) {
+ throw new DirectUploadRequestError("Invalid upload destination.");
+ }
+
+ const token = await issueToken({
+ allowedContentTypes: PDF_CONTENT_TYPES,
+ maximumSizeInBytes: MAX_UPLOAD_SIZE_BYTES,
+ operations: ["put"],
+ pathname,
+ validUntil: Date.now() + UPLOAD_URL_LIFETIME_MS,
+ });
+
+ return {
+ token,
+ urlOptions: {
+ addRandomSuffix: false,
+ allowedContentTypes: PDF_CONTENT_TYPES,
+ allowOverwrite: false,
+ maximumSizeInBytes: MAX_UPLOAD_SIZE_BYTES,
+ ttlDays: PENDING_UPLOAD_TTL_DAYS,
+ },
+ };
+ },
+ request,
+ // The SDK insists on a key for checking "upload completed" callbacks
+ // even when none are used. This app asks for no callback (the browser
+ // reports back itself, and the file is validated when it does), and
+ // parseGenerateUrlEvent has already turned away anything that is not a
+ // request for an upload URL, so the key is never used to verify anything.
+ webhookPublicKey:
+ process.env.BLOB_WEBHOOK_PUBLIC_KEY?.trim() || "no-callbacks-used",
+ });
+}
diff --git a/src/lib/services/pending-uploads.test.ts b/src/lib/services/pending-uploads.test.ts
new file mode 100644
index 0000000..9793a76
--- /dev/null
+++ b/src/lib/services/pending-uploads.test.ts
@@ -0,0 +1,174 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { DocumentImportError } from "./document-import.ts";
+import {
+ discardPendingUpload,
+ PendingUploadError,
+ readPendingUpload,
+} from "./pending-uploads.ts";
+import {
+ StorageObjectNotFoundError,
+ type StorageService,
+} from "./storage/types.ts";
+
+const USER_ID = "user_abc123";
+const KEY = `uploads/${USER_ID}/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.pdf`;
+
+function storageWith(
+ overrides: Partial<StorageService>,
+): StorageService & { deleted: string[] } {
+ const deleted: string[] = [];
+
+ return {
+ deleted,
+ async deleteObject(key) {
+ deleted.push(key);
+ },
+ async getObject() {
+ throw new Error("not used");
+ },
+ async getObjectStream(key) {
+ throw new StorageObjectNotFoundError(key);
+ },
+ async headObject() {
+ throw new Error("not used");
+ },
+ async putObject() {
+ throw new Error("not used");
+ },
+ ...overrides,
+ };
+}
+
+function streamOf(...chunks: Uint8Array[]) {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const chunk of chunks) {
+ controller.enqueue(chunk);
+ }
+
+ controller.close();
+ },
+ });
+}
+
+test("a pending upload is read back in full", async () => {
+ const storageService = storageWith({
+ async getObjectStream(key) {
+ return {
+ bucketName: "test",
+ contentLength: 5,
+ key,
+ stream: streamOf(new Uint8Array([1, 2]), new Uint8Array([3, 4, 5])),
+ };
+ },
+ });
+
+ assert.deepEqual(
+ [
+ ...(await readPendingUpload({
+ key: KEY,
+ storageService,
+ userId: USER_ID,
+ })),
+ ],
+ [1, 2, 3, 4, 5],
+ );
+});
+
+test("only the user's own pending uploads can be read", async () => {
+ let reads = 0;
+ const storageService = storageWith({
+ async getObjectStream(key) {
+ reads += 1;
+
+ return { bucketName: "test", key, stream: streamOf() };
+ },
+ });
+
+ for (const key of [
+ "uploads/someone_else/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.pdf",
+ `users/${USER_ID}/envelopes/e1/original.pdf`,
+ `uploads/${USER_ID}/../x/3f0e9a2c-5b7d-4e1f-8a6b-0c9d8e7f6a5b.pdf`,
+ ]) {
+ await assert.rejects(
+ readPendingUpload({ key, storageService, userId: USER_ID }),
+ PendingUploadError,
+ );
+ }
+
+ assert.equal(reads, 0);
+});
+
+test("an oversized upload is refused, whatever size the storage reports", async () => {
+ const declaredTooLarge = storageWith({
+ async getObjectStream(key) {
+ return {
+ bucketName: "test",
+ contentLength: 11,
+ key,
+ stream: streamOf(new Uint8Array(11)),
+ };
+ },
+ });
+ const undeclared = storageWith({
+ async getObjectStream(key) {
+ return {
+ bucketName: "test",
+ // Claims to be small, then keeps sending.
+ contentLength: 4,
+ key,
+ stream: streamOf(new Uint8Array(6), new Uint8Array(6)),
+ };
+ },
+ });
+
+ for (const storageService of [declaredTooLarge, undeclared]) {
+ await assert.rejects(
+ readPendingUpload({
+ key: KEY,
+ maxBytes: 10,
+ storageService,
+ userId: USER_ID,
+ }),
+ (error: unknown) =>
+ error instanceof DocumentImportError && error.code === "too_large",
+ );
+ }
+});
+
+test("a pending upload that is gone asks the user to upload again", async () => {
+ await assert.rejects(
+ readPendingUpload({
+ key: KEY,
+ storageService: storageWith({}),
+ userId: USER_ID,
+ }),
+ PendingUploadError,
+ );
+});
+
+test("discarding deletes the upload and never throws", async () => {
+ const storageService = storageWith({});
+
+ await discardPendingUpload({ key: KEY, storageService });
+ assert.deepEqual(storageService.deleted, [KEY]);
+
+ const originalWarn = console.warn;
+
+ console.warn = () => undefined;
+
+ try {
+ await discardPendingUpload({
+ key: KEY,
+ storageService: storageWith({
+ async deleteObject() {
+ throw new Error("storage is down");
+ },
+ }),
+ });
+ } finally {
+ console.warn = originalWarn;
+ }
+});
diff --git a/src/lib/services/pending-uploads.ts b/src/lib/services/pending-uploads.ts
new file mode 100644
index 0000000..d618c92
--- /dev/null
+++ b/src/lib/services/pending-uploads.ts
@@ -0,0 +1,119 @@
+import { MAX_UPLOAD_SIZE_BYTES } from "../types/domain.ts";
+import { DocumentImportError } from "./document-import.ts";
+import {
+ StorageObjectNotFoundError,
+ type StorageService,
+} from "./storage/types.ts";
+import { isPendingUploadKey } from "./storage-keys.ts";
+
+// A pending upload is a PDF the browser sent straight to storage (see
+// direct-upload.ts). Nothing about it is trusted. The app reads it back
+// with a hard size cap, validates it like any other upload, stores its own
+// copy under the envelope's key, and deletes the pending one.
+
+export class PendingUploadError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "PendingUploadError";
+ }
+}
+
+type PendingUploadInput = {
+ key: string;
+ storageService: StorageService;
+};
+
+async function readStreamWithLimit(
+ stream: ReadableStream<Uint8Array>,
+ maxBytes: number,
+): Promise<Uint8Array> {
+ const reader = stream.getReader();
+ const chunks: Uint8Array[] = [];
+ let totalBytes = 0;
+
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+
+ if (done) {
+ break;
+ }
+
+ totalBytes += value.byteLength;
+
+ if (totalBytes > maxBytes) {
+ throw new DocumentImportError("too_large");
+ }
+
+ chunks.push(value);
+ }
+ } catch (error) {
+ await reader.cancel().catch(() => undefined);
+
+ throw error;
+ }
+
+ const body = new Uint8Array(totalBytes);
+ let offset = 0;
+
+ for (const chunk of chunks) {
+ body.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+
+ return body;
+}
+
+/**
+ * Reads a user's pending upload into memory. Refuses a key that is not in
+ * that user's pending folder, and stops reading at the upload size limit
+ * whatever size the storage reports.
+ */
+export async function readPendingUpload({
+ key,
+ maxBytes = MAX_UPLOAD_SIZE_BYTES,
+ storageService,
+ userId,
+}: PendingUploadInput & {
+ maxBytes?: number;
+ userId: string;
+}): Promise<Uint8Array> {
+ if (!isPendingUploadKey(key, userId)) {
+ throw new PendingUploadError("Invalid upload reference.");
+ }
+
+ try {
+ const object = await storageService.getObjectStream(key);
+
+ if (object.contentLength !== undefined && object.contentLength > maxBytes) {
+ await object.stream.cancel().catch(() => undefined);
+
+ throw new DocumentImportError("too_large");
+ }
+
+ return await readStreamWithLimit(object.stream, maxBytes);
+ } catch (error) {
+ if (error instanceof StorageObjectNotFoundError) {
+ throw new PendingUploadError(
+ "The uploaded file was not found. Please upload it again.",
+ );
+ }
+
+ throw error;
+ }
+}
+
+/**
+ * Deletes a pending upload once it has been dealt with. Never throws: one
+ * that cannot be deleted now is removed by the storage's own expiry.
+ */
+export async function discardPendingUpload({
+ key,
+ storageService,
+}: PendingUploadInput): Promise<void> {
+ try {
+ await storageService.deleteObject(key);
+ } catch (error) {
+ console.warn("Could not delete a pending upload.", error);
+ }
+}
diff --git a/src/lib/services/storage-keys.ts b/src/lib/services/storage-keys.ts
index 5753033..49bfb9e 100644
--- a/src/lib/services/storage-keys.ts
+++ b/src/lib/services/storage-keys.ts
@@ -8,6 +8,10 @@ const RECIPIENT_CERTIFICATE_FILE_NAME = "recipient.pdf";
const LEGACY_INTERNAL_EVIDENCE_FILE_NAME = "internal.json";
const LEGACY_RECIPIENT_EVIDENCE_FILE_NAME = "recipient.json";
+const PENDING_UPLOAD_ROOT_SEGMENT = "uploads";
+const PENDING_UPLOAD_NAME_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.pdf$/;
+
export type CertificateAudience = "internal" | "recipient";
type EnvelopeStorageIdentity = {
@@ -15,6 +19,28 @@ type EnvelopeStorageIdentity = {
userId: string;
};
+/**
+ * Where a user's browser may put a PDF before the app has looked at it.
+ * Ends with a slash; the browser adds "<uuid>.pdf". Nothing under this
+ * prefix is trusted: the app reads the file, validates it, and stores its
+ * own copy under the envelope's key.
+ */
+export function buildPendingUploadPrefix(userId: string): string {
+ return `${PENDING_UPLOAD_ROOT_SEGMENT}/${userId}/`;
+}
+
+/** True only for a pending upload key that belongs to this user. */
+export function isPendingUploadKey(key: string, userId: string): boolean {
+ const prefix = buildPendingUploadPrefix(userId);
+
+ return (
+ userId.length > 0 &&
+ !userId.includes("/") &&
+ key.startsWith(prefix) &&
+ PENDING_UPLOAD_NAME_PATTERN.test(key.slice(prefix.length))
+ );
+}
+
export function buildEnvelopePrefix(input: EnvelopeStorageIdentity): string {
return path.posix.join(
STORAGE_ROOT_SEGMENT,
diff --git a/src/proxy.ts b/src/proxy.ts
index 5dabc36..1a6d607 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -2,6 +2,7 @@ import type { NextRequest } from "next/server";
import { getCookieCache, getSessionCookie } from "better-auth/cookies";
import { NextResponse } from "next/server";
+import { supportsDirectUploads } from "@/lib/services/storage/driver";
import { resolveAuthSecret, resolveAuthUrl } from "@/lib/utils/env";
const DEFAULT_PERMISSIONS_POLICY = [
@@ -27,6 +28,28 @@ function isVercelPreview() {
return process.env.VERCEL === "1" && process.env.VERCEL_ENV === "preview";
}
+// With Vercel Blob the upload page sends the PDF straight to the Blob API,
+// so the browser must be allowed to connect to it. The address is the one
+// the Blob SDK uses, including its override for a stand-in API.
+// https://vercel.com/docs/vercel-blob/vercel-signed-urls#presigned-uploads
+const DEFAULT_BLOB_API_URL = "https://vercel.com/api/blob";
+
+function resolveBlobUploadSource() {
+ try {
+ if (!supportsDirectUploads()) {
+ return false;
+ }
+ } catch {
+ return false;
+ }
+
+ const apiUrl =
+ process.env.NEXT_PUBLIC_VERCEL_BLOB_API_URL?.trim() || DEFAULT_BLOB_API_URL;
+
+ // The trailing slash limits the allowance to this path and below.
+ return `${apiUrl.replace(/\/+$/, "")}/`;
+}
+
function buildContentSecurityPolicy() {
const preview = isVercelPreview();
const directives: Array<[name: string, sources: Array<string | false>]> = [
@@ -58,6 +81,7 @@ function buildContentSecurityPolicy() {
"'self'",
// The field editor reads the just-uploaded PDF back from a blob: URL.
"blob:",
+ resolveBlobUploadSource(),
preview && "https://vercel.live wss://ws-us3.pusher.com",
],
],