Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add a local storage driver and stream downloads through the app
Claudeac77893f315a
diff --git a/src/app/api/download/[token]/route.ts b/src/app/api/download/[token]/route.tsindex 85cdbb2..af0f4c5 100644--- a/src/app/api/download/[token]/route.ts+++ b/src/app/api/download/[token]/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server";import { getDb } from "@/lib/db/connection";+import { createDownloadResponse } from "@/lib/download-response";import {DownloadAccessError,getPublicEnvelopeDownloadForToken,@@ -11,10 +12,6 @@ import {buildRateLimitKey,} from "@/lib/security/route-controls";import { getClientIpAddress } from "@/lib/security/request";-import { buildContentDisposition } from "@/lib/services/storage";-import { createStorageService } from "@/lib/services/storage";--const PRESIGNED_DOWNLOAD_TTL_SECONDS = 5 * 60;// Public download route for recipient email links only.// Sender downloads must go through the authenticated /api/envelopes/[id]/download route.@@ -57,33 +54,7 @@ export async function GET(database: getDb(),});- if ("body" in download) {- const responseBody = download.body.slice().buffer as ArrayBuffer;-- return new Response(responseBody, {- headers: {- "cache-control": "private, no-store",- "content-disposition": buildContentDisposition(download.fileName),- "content-length": String(download.contentLength),- "content-type": download.contentType,- },- status: 200,- });- }-- const presignedDownload =- await createStorageService().createPresignedDownloadUrl({- expiresInSeconds: PRESIGNED_DOWNLOAD_TTL_SECONDS,- fileName: download.fileName,- key: download.key,- });-- return NextResponse.redirect(new URL(presignedDownload.url, request.url), {- headers: {- "cache-control": "private, no-store",- },- status: 302,- });+ return await createDownloadResponse(download);} catch (error) {if (error instanceof DownloadAccessError) {return new NextResponse(error.message, {diff --git a/src/app/api/envelopes/[id]/download/route.ts b/src/app/api/envelopes/[id]/download/route.tsindex 256244b..5a52b6a 100644--- a/src/app/api/envelopes/[id]/download/route.ts+++ b/src/app/api/envelopes/[id]/download/route.ts@@ -3,6 +3,7 @@ import { ZodError } from "zod";import { requireVerifiedSenderSession } from "@/lib/auth/route-session";import { getDb } from "@/lib/db/connection";+import { createDownloadResponse } from "@/lib/download-response";import {DownloadAccessError,getSenderEnvelopeDownload,@@ -10,10 +11,6 @@ import {import { downloadRequestSchema } from "@/lib/schemas/envelope";import { logRouteError } from "@/lib/security/logging";import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";-import { buildContentDisposition } from "@/lib/services/storage";-import { createStorageService } from "@/lib/services/storage";--const PRESIGNED_DOWNLOAD_TTL_SECONDS = 5 * 60;type EnvelopeDownloadRouteContext = {params: Promise<{@@ -53,36 +50,7 @@ export async function GET(},);- if (!("body" in download)) {- const presignedDownload =- await createStorageService().createPresignedDownloadUrl({- expiresInSeconds: PRESIGNED_DOWNLOAD_TTL_SECONDS,- fileName: download.fileName,- key: download.key,- });-- return NextResponse.redirect(- new URL(presignedDownload.url, request.url),- {- headers: {- "cache-control": "private, no-store",- },- status: 302,- },- );- }-- const responseBody = download.body.slice().buffer as ArrayBuffer;-- return new Response(responseBody, {- headers: {- "cache-control": "private, no-store",- "content-disposition": buildContentDisposition(download.fileName),- "content-length": String(download.contentLength),- "content-type": download.contentType,- },- status: 200,- });+ return await createDownloadResponse(download);} catch (error) {if (error instanceof ZodError) {const issue = error.issues[0];diff --git a/src/lib/download-response.ts b/src/lib/download-response.tsnew file mode 100644index 0000000..6b7a3fb--- /dev/null+++ b/src/lib/download-response.ts@@ -0,0 +1,58 @@+import {+ DownloadAccessError,+ type EnvelopeDownloadResult,+} from "./downloads.ts";+import {+ buildContentDisposition,+ createStorageService,+ StorageObjectNotFoundError,+ type StorageService,+} from "./services/storage.ts";++type CreateDownloadResponseOptions = {+ storageService?: StorageService;+};++/**+ * Turns a resolved download into an HTTP response. Stored files are streamed+ * straight from storage so the function never buffers a whole PDF, which keeps+ * large files clear of serverless response-size limits.+ */+export async function createDownloadResponse(+ download: EnvelopeDownloadResult,+ { storageService }: CreateDownloadResponseOptions = {},+): Promise<Response> {+ const headers = new Headers({+ "cache-control": "private, no-store",+ "content-disposition": buildContentDisposition(download.fileName),+ "content-type": download.contentType,+ "x-content-type-options": "nosniff",+ });++ if ("body" in download) {+ headers.set("content-length", String(download.contentLength));++ return new Response(download.body.slice().buffer as ArrayBuffer, {+ headers,+ status: 200,+ });+ }++ try {+ const object = await (+ storageService ?? createStorageService()+ ).getObjectStream(download.key);++ if (typeof object.contentLength === "number") {+ headers.set("content-length", String(object.contentLength));+ }++ return new Response(object.stream, { headers, status: 200 });+ } catch (error) {+ if (error instanceof StorageObjectNotFoundError) {+ throw new DownloadAccessError("This file is no longer available.", 404);+ }++ throw error;+ }+}diff --git a/src/lib/services/storage.ts b/src/lib/services/storage.tsindex c803664..2105ee0 100644--- a/src/lib/services/storage.ts+++ b/src/lib/services/storage.ts@@ -1,52 +1,26 @@-import {- DeleteObjectCommand,- GetObjectCommand,- HeadObjectCommand,- PutObjectCommand,- S3Client,-} from "@aws-sdk/client-s3";-import { getSignedUrl } from "@aws-sdk/s3-request-presigner";+import type { S3Client } from "@aws-sdk/client-s3";-import { getEnv, type EnvSource } from "../utils/env.ts";-import { assertServiceConfig } from "./service-config.ts";+import { type EnvSource } from "../utils/env.ts";+import { createLocalStorageService } from "./storage/local.ts";+import { createR2StorageService } from "./storage/r2.ts";+import { type StorageService } from "./storage/types.ts";-const STORAGE_ENV_KEYS = [- "R2_ACCOUNT_ID",- "R2_ACCESS_KEY_ID",- "R2_BUCKET_NAME",- "R2_SECRET_ACCESS_KEY",-] as const;+export {+ StorageObjectNotFoundError,+ type StorageObject,+ type StorageObjectHead,+ type StorageObjectRef,+ type StorageObjectStream,+ type StorageService,+} from "./storage/types.ts";++export type StorageDriver = "local" | "r2";type CreateStorageServiceOptions = {env?: EnvSource;s3Client?: S3Client;};-export type StorageObjectRef = {- bucketName: string;- key: string;-};--export type PresignedStorageUrl = StorageObjectRef & {- expiresAt: number;- method: "GET" | "PUT";- url: string;-};--export type StorageObject = StorageObjectRef & {- body: Uint8Array;- contentLength?: number;- contentType?: string;- etag?: string;-};--export type StorageObjectHead = StorageObjectRef & {- contentLength?: number;- contentType?: string;- etag?: string;- exists: boolean;-};-export function buildContentDisposition(fileName: string,dispositionType: "attachment" | "inline" = "attachment",@@ -57,190 +31,32 @@ export function buildContentDisposition(return `${dispositionType}; filename="${fallbackName}"; filename*=UTF-8''${encodedName}`;}-async function readS3Body(body: unknown): Promise<Uint8Array> {- if (- !body ||- typeof body !== "object" ||- !("transformToByteArray" in body) ||- typeof body.transformToByteArray !== "function"- ) {- return new Uint8Array();- }+export function resolveStorageDriver(+ env: EnvSource = process.env,+): StorageDriver {+ const configuredDriver = env.STORAGE_DRIVER?.trim().toLowerCase();- return (- body as {- transformToByteArray: () => Promise<Uint8Array>;- }- ).transformToByteArray();-}--function normalizeStorageKey(key: string): string {- const normalizedKey = key.trim().replaceAll("\\", "/").replace(/^\/+/, "");-- if (normalizedKey.length === 0) {- throw new Error("Storage key is required.");+ if (!configuredDriver) {+ return "r2";}- const segments = normalizedKey.split("/");-- if (- segments.some(- (segment) => segment.length === 0 || segment === "." || segment === "..",- )- ) {- throw new Error("Storage key is invalid.");+ if (configuredDriver === "local" || configuredDriver === "r2") {+ return configuredDriver;}- return normalizedKey;-}--export interface StorageService {- createPresignedDownloadUrl(input: {- expiresInSeconds: number;- fileName?: string;- key: string;- }): Promise<PresignedStorageUrl>;- deleteObject(key: string): Promise<void>;- getObject(key: string): Promise<StorageObject>;- headObject(key: string): Promise<StorageObjectHead>;- putObject(input: {- body: Uint8Array;- contentType: string;- key: string;- }): Promise<StorageObjectRef>;+ throw new Error(+ `Unknown STORAGE_DRIVER "${configuredDriver}". Use "local" or "r2".`,+ );}export function createStorageService({env = process.env,s3Client,}: CreateStorageServiceOptions = {}): StorageService {- assertServiceConfig("storage", STORAGE_ENV_KEYS, env);-- const storageEnv = getEnv(env).storage;- const config = {- accessKeyId: storageEnv.accessKeyId!,- bucketName: storageEnv.bucketName!,- endpoint: `https://${storageEnv.accountId!}.r2.cloudflarestorage.com`,- region: "auto" as const,- secretAccessKey: storageEnv.secretAccessKey!,- };- const client =- s3Client ??- new S3Client({- credentials: {- accessKeyId: config.accessKeyId,- secretAccessKey: config.secretAccessKey,- },- endpoint: config.endpoint,- region: config.region,- });-- return {- async createPresignedDownloadUrl(input) {- const key = normalizeStorageKey(input.key);- const url = await getSignedUrl(- client,- new GetObjectCommand({- Bucket: config.bucketName,- Key: key,- ResponseContentDisposition: input.fileName- ? buildContentDisposition(input.fileName)- : undefined,- }),- {- expiresIn: input.expiresInSeconds,- },- );-- return {- bucketName: config.bucketName,- expiresAt: Math.floor(Date.now() / 1000) + input.expiresInSeconds,- key,- method: "GET",- url,- };- },- async deleteObject(key) {- const normalizedKey = normalizeStorageKey(key);-- await client.send(- new DeleteObjectCommand({- Bucket: config.bucketName,- Key: normalizedKey,- }),- );- },- async getObject(key) {- const normalizedKey = normalizeStorageKey(key);- const response = await client.send(- new GetObjectCommand({- Bucket: config.bucketName,- Key: normalizedKey,- }),- );- const body = await readS3Body(response.Body);-- return {- body,- bucketName: config.bucketName,- contentLength: response.ContentLength,- contentType: response.ContentType,- etag: response.ETag?.replaceAll('"', ""),- key: normalizedKey,- };- },- async headObject(key) {- const normalizedKey = normalizeStorageKey(key);-- try {- const response = await client.send(- new HeadObjectCommand({- Bucket: config.bucketName,- Key: normalizedKey,- }),- );-- return {- bucketName: config.bucketName,- contentLength: response.ContentLength,- contentType: response.ContentType,- etag: response.ETag?.replaceAll('"', ""),- exists: true,- key: normalizedKey,- };- } catch (error) {- if (- error instanceof Error &&- "name" in error &&- (error.name === "NotFound" || error.name === "NoSuchKey")- ) {- return {- bucketName: config.bucketName,- exists: false,- key: normalizedKey,- };- }-- throw error;- }- },- async putObject(input) {- const key = normalizeStorageKey(input.key);-- await client.send(- new PutObjectCommand({- Body: input.body,- Bucket: config.bucketName,- ContentLength: input.body.length,- ContentType: input.contentType,- Key: key,- }),- );-- return {- bucketName: config.bucketName,- key,- };- },- };+ switch (resolveStorageDriver(env)) {+ case "local":+ return createLocalStorageService({ env });+ case "r2":+ return createR2StorageService({ env, s3Client });+ }}diff --git a/src/lib/services/storage/local.ts b/src/lib/services/storage/local.tsnew file mode 100644index 0000000..eeb8d19--- /dev/null+++ b/src/lib/services/storage/local.ts@@ -0,0 +1,180 @@+import { createReadStream } from "node:fs";+import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";+import path from "node:path";+import { Readable } from "node:stream";++import { type EnvSource } from "../../utils/env.ts";+import {+ normalizeStorageKey,+ StorageObjectNotFoundError,+ type StorageService,+} from "./types.ts";++// Filesystem storage for local development, the end-to-end test, and+// self-hosted installs that run on a machine with a persistent disk.+// It cannot work on Vercel, where the filesystem is read-only and ephemeral.++const LOCAL_BUCKET_NAME = "local";+const DEFAULT_LOCAL_STORAGE_DIR = ".data/storage";+const METADATA_SUFFIX = ".meta.json";++type CreateLocalStorageServiceOptions = {+ env?: EnvSource;+ rootDir?: string;+};++type LocalObjectMetadata = {+ contentType?: string;+};++function isMissingFileError(error: unknown): boolean {+ return (+ error instanceof Error &&+ "code" in error &&+ (error as NodeJS.ErrnoException).code === "ENOENT"+ );+}++export function createLocalStorageService({+ env = process.env,+ rootDir,+}: CreateLocalStorageServiceOptions = {}): StorageService {+ if (env.VERCEL === "1") {+ throw new Error(+ "STORAGE_DRIVER=local cannot be used on Vercel. Connect a Vercel Blob store instead.",+ );+ }++ const resolvedRootDir = path.resolve(+ rootDir ?? env.STORAGE_LOCAL_DIR?.trim() ?? DEFAULT_LOCAL_STORAGE_DIR,+ );++ function resolveObjectPath(key: string) {+ const normalizedKey = normalizeStorageKey(key);+ const objectPath = path.join(resolvedRootDir, ...normalizedKey.split("/"));++ return { normalizedKey, objectPath };+ }++ async function readMetadata(+ objectPath: string,+ ): Promise<LocalObjectMetadata> {+ try {+ return JSON.parse(+ await readFile(`${objectPath}${METADATA_SUFFIX}`, "utf8"),+ ) as LocalObjectMetadata;+ } catch {+ return {};+ }+ }++ async function statObject(objectPath: string) {+ try {+ const stats = await stat(objectPath);++ return stats.isFile() ? stats : null;+ } catch (error) {+ if (isMissingFileError(error)) {+ return null;+ }++ throw error;+ }+ }++ return {+ async deleteObject(key) {+ const { objectPath } = resolveObjectPath(key);++ await Promise.all([+ rm(objectPath, { force: true }),+ rm(`${objectPath}${METADATA_SUFFIX}`, { force: true }),+ ]);+ },+ async getObject(key) {+ const { normalizedKey, objectPath } = resolveObjectPath(key);++ try {+ const [body, metadata] = await Promise.all([+ readFile(objectPath),+ readMetadata(objectPath),+ ]);++ return {+ body: new Uint8Array(body),+ bucketName: LOCAL_BUCKET_NAME,+ contentLength: body.length,+ contentType: metadata.contentType,+ key: normalizedKey,+ };+ } catch (error) {+ if (isMissingFileError(error)) {+ throw new StorageObjectNotFoundError(normalizedKey);+ }++ throw error;+ }+ },+ async getObjectStream(key) {+ const { normalizedKey, objectPath } = resolveObjectPath(key);+ const stats = await statObject(objectPath);++ if (!stats) {+ throw new StorageObjectNotFoundError(normalizedKey);+ }++ const metadata = await readMetadata(objectPath);++ return {+ bucketName: LOCAL_BUCKET_NAME,+ contentLength: stats.size,+ contentType: metadata.contentType,+ key: normalizedKey,+ stream: Readable.toWeb(+ createReadStream(objectPath),+ ) as ReadableStream<Uint8Array>,+ };+ },+ async headObject(key) {+ const { normalizedKey, objectPath } = resolveObjectPath(key);+ const stats = await statObject(objectPath);++ if (!stats) {+ return {+ bucketName: LOCAL_BUCKET_NAME,+ exists: false,+ key: normalizedKey,+ };+ }++ const metadata = await readMetadata(objectPath);++ return {+ bucketName: LOCAL_BUCKET_NAME,+ contentLength: stats.size,+ contentType: metadata.contentType,+ exists: true,+ key: normalizedKey,+ };+ },+ async putObject(input) {+ const { normalizedKey, objectPath } = resolveObjectPath(input.key);++ await mkdir(path.dirname(objectPath), { recursive: true });+ await Promise.all([+ writeFile(objectPath, input.body),+ writeFile(+ `${objectPath}${METADATA_SUFFIX}`,+ JSON.stringify({+ contentType: input.contentType,+ } satisfies LocalObjectMetadata),+ ),+ ]);++ return {+ bucketName: LOCAL_BUCKET_NAME,+ key: normalizedKey,+ };+ },+ };+}diff --git a/src/lib/services/storage/r2.ts b/src/lib/services/storage/r2.tsnew file mode 100644index 0000000..3232254--- /dev/null+++ b/src/lib/services/storage/r2.ts@@ -0,0 +1,189 @@+import {+ DeleteObjectCommand,+ GetObjectCommand,+ HeadObjectCommand,+ PutObjectCommand,+ S3Client,+} from "@aws-sdk/client-s3";++import { getEnv, type EnvSource } from "../../utils/env.ts";+import { assertServiceConfig } from "../service-config.ts";+import {+ normalizeStorageKey,+ StorageObjectNotFoundError,+ type StorageService,+} from "./types.ts";++const STORAGE_ENV_KEYS = [+ "R2_ACCOUNT_ID",+ "R2_ACCESS_KEY_ID",+ "R2_BUCKET_NAME",+ "R2_SECRET_ACCESS_KEY",+] as const;++type CreateR2StorageServiceOptions = {+ env?: EnvSource;+ s3Client?: S3Client;+};++function isNotFoundError(error: unknown): boolean {+ return (+ error instanceof Error &&+ (error.name === "NotFound" || error.name === "NoSuchKey")+ );+}++async function readS3Body(body: unknown): Promise<Uint8Array> {+ if (+ !body ||+ typeof body !== "object" ||+ !("transformToByteArray" in body) ||+ typeof body.transformToByteArray !== "function"+ ) {+ return new Uint8Array();+ }++ return (+ body as {+ transformToByteArray: () => Promise<Uint8Array>;+ }+ ).transformToByteArray();+}++export function createR2StorageService({+ env = process.env,+ s3Client,+}: CreateR2StorageServiceOptions = {}): StorageService {+ assertServiceConfig("storage", STORAGE_ENV_KEYS, env);++ const storageEnv = getEnv(env).storage;+ const config = {+ accessKeyId: storageEnv.accessKeyId!,+ bucketName: storageEnv.bucketName!,+ endpoint: `https://${storageEnv.accountId!}.r2.cloudflarestorage.com`,+ region: "auto" as const,+ secretAccessKey: storageEnv.secretAccessKey!,+ };+ const client =+ s3Client ??+ new S3Client({+ credentials: {+ accessKeyId: config.accessKeyId,+ secretAccessKey: config.secretAccessKey,+ },+ endpoint: config.endpoint,+ region: config.region,+ });++ return {+ async deleteObject(key) {+ const normalizedKey = normalizeStorageKey(key);++ await client.send(+ new DeleteObjectCommand({+ Bucket: config.bucketName,+ Key: normalizedKey,+ }),+ );+ },+ async getObject(key) {+ const normalizedKey = normalizeStorageKey(key);+ const response = await client.send(+ new GetObjectCommand({+ Bucket: config.bucketName,+ Key: normalizedKey,+ }),+ );+ const body = await readS3Body(response.Body);++ return {+ body,+ bucketName: config.bucketName,+ contentLength: response.ContentLength,+ contentType: response.ContentType,+ etag: response.ETag?.replaceAll('"', ""),+ key: normalizedKey,+ };+ },+ async getObjectStream(key) {+ const normalizedKey = normalizeStorageKey(key);++ try {+ const response = await client.send(+ new GetObjectCommand({+ Bucket: config.bucketName,+ Key: normalizedKey,+ }),+ );++ if (!response.Body) {+ throw new StorageObjectNotFoundError(normalizedKey);+ }++ return {+ bucketName: config.bucketName,+ contentLength: response.ContentLength,+ contentType: response.ContentType,+ key: normalizedKey,+ stream:+ response.Body.transformToWebStream() as ReadableStream<Uint8Array>,+ };+ } catch (error) {+ if (isNotFoundError(error)) {+ throw new StorageObjectNotFoundError(normalizedKey);+ }++ throw error;+ }+ },+ async headObject(key) {+ const normalizedKey = normalizeStorageKey(key);++ try {+ const response = await client.send(+ new HeadObjectCommand({+ Bucket: config.bucketName,+ Key: normalizedKey,+ }),+ );++ return {+ bucketName: config.bucketName,+ contentLength: response.ContentLength,+ contentType: response.ContentType,+ etag: response.ETag?.replaceAll('"', ""),+ exists: true,+ key: normalizedKey,+ };+ } catch (error) {+ if (isNotFoundError(error)) {+ return {+ bucketName: config.bucketName,+ exists: false,+ key: normalizedKey,+ };+ }++ throw error;+ }+ },+ async putObject(input) {+ const key = normalizeStorageKey(input.key);++ await client.send(+ new PutObjectCommand({+ Body: input.body,+ Bucket: config.bucketName,+ ContentLength: input.body.length,+ ContentType: input.contentType,+ Key: key,+ }),+ );++ return {+ bucketName: config.bucketName,+ key,+ };+ },+ };+}diff --git a/src/lib/services/storage/types.ts b/src/lib/services/storage/types.tsnew file mode 100644index 0000000..2945794--- /dev/null+++ b/src/lib/services/storage/types.ts@@ -0,0 +1,65 @@+export type StorageObjectRef = {+ bucketName: string;+ key: string;+};++export type StorageObject = StorageObjectRef & {+ body: Uint8Array;+ contentLength?: number;+ contentType?: string;+ etag?: string;+};++export type StorageObjectStream = StorageObjectRef & {+ contentLength?: number;+ contentType?: string;+ stream: ReadableStream<Uint8Array>;+};++export type StorageObjectHead = StorageObjectRef & {+ contentLength?: number;+ contentType?: string;+ etag?: string;+ exists: boolean;+};++export class StorageObjectNotFoundError extends Error {+ constructor(key: string) {+ super(`Storage object not found: ${key}`);+ this.name = "StorageObjectNotFoundError";+ }+}++export interface StorageService {+ deleteObject(key: string): Promise<void>;+ /** Reads the whole object into memory. Use for processing, not for downloads. */+ getObject(key: string): Promise<StorageObject>;+ /** Streams the object. Use for responses so large files are never buffered. */+ getObjectStream(key: string): Promise<StorageObjectStream>;+ headObject(key: string): Promise<StorageObjectHead>;+ putObject(input: {+ body: Uint8Array;+ contentType: string;+ key: string;+ }): Promise<StorageObjectRef>;+}++export function normalizeStorageKey(key: string): string {+ const normalizedKey = key.trim().replaceAll("\\", "/").replace(/^\/+/, "");++ if (normalizedKey.length === 0) {+ throw new Error("Storage key is required.");+ }++ const segments = normalizedKey.split("/");++ if (+ segments.some(+ (segment) => segment.length === 0 || segment === "." || segment === "..",+ )+ ) {+ throw new Error("Storage key is invalid.");+ }++ return normalizedKey;+}