import type { Readable } from 'node:stream' import fastifyMultipart from '@fastify/multipart' import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify' import type { UploadAuthenticator } from '../authenticator.js' import { isExplicitOnlyContentType } from '../contentTypes.js' import { deleteFile } from '../deleteFile.js' import { checkContentType, DETECTABLE_CONTENT_TYPES, } from '../detectContentType.js' import type { ContentTypeRejection } from '../detectContentType.js' import { UploadError } from '../errors.js' import { generateStorageKey, trimTrailingSlashes } from '../keys.js' import { assertOwnership, assertTokenAllowsFile, createPendingUpload, } from '../pending.js' import { serializeUpload } from '../serialize.js' import { SERVE_ROUTE_PATH, SERVE_TOKEN_PARAM, verifyServeToken, } from '../serveToken.js' import { resolveTarget } from '../targets.js' import type { ContentDisposition, StorageTargets, UploadDatabase, UploadRecord, } from '../types.js' import { UPLOAD_TOKEN_HEADER, verifyUploadToken } from '../uploadToken.js' import type { UploadTokenPayload } from '../uploadToken.js' import { handleS3Webhook } from '../webhooks/s3.js' import type { FetchCertificate } from '../webhooks/sns.js' const FIVE_HUNDRED_MB = 500 * 1024 * 1024 /** Bytes allowed for multipart boundaries, headers, and form fields. */ const MULTIPART_ENVELOPE_ALLOWANCE = 64 * 1024 /** * MIME types a browser executes or renders as a document when served * inline from this origin. They are served as attachments, even when the * signed URL asked for inline, because the stored MIME type is * client-asserted and an inline document from the app's origin is stored * cross-site scripting. The plugin's `inlineTypes` option exempts specific * types. */ const ACTIVE_CONTENT_TYPES = new Set([ 'text/html', 'application/xhtml+xml', 'image/svg+xml', 'text/xml', 'application/xml', 'text/javascript', 'application/javascript', 'application/ecmascript', 'text/ecmascript', 'application/pdf', ]) export interface UploadPluginOptions { /** * Secret upload tokens and serve URLs are signed with. Usually * `process.env.UPLOAD_TOKEN_SECRET`; the plugin throws a configuration * error when it's missing. */ tokenSecret: string | undefined /** The app's storage targets. */ targets: StorageTargets db: UploadDatabase /** Route prefix. Defaults to `/upload`. */ prefix?: string /** * Hard outer ceiling on upload request size. Defaults to 500 MB. The * effective bound per request comes from the token (`maxFiles` times * `maxFileSize` plus a multipart envelope allowance), so this only needs * to sit above the largest profile's aggregate. */ bodyLimit?: number /** * Resolves the requesting user. When configured, the upload routes reject * unauthenticated requests and tokens issued to someone else. Build it * with `createUploadAuthenticator()`. Without it the token itself is the * only identity on the route, so configure it in any app with auth. */ authenticate?: UploadAuthenticator /** * Enables `POST {prefix}/webhook/s3` for S3 event notifications delivered * through SNS. `topicArn` is the only topic accepted. */ s3Webhook?: { topicArn: string fetchCertificate?: FetchCertificate fetch?: typeof fetch } /** `Cache-Control` for served files. Defaults to `private, max-age=3600`. */ serveCacheControl?: string /** * Active-content MIME types the serve route may send inline when the * signed URL asks for `inline`, e.g. `['application/pdf']` to preview PDFs * in the browser. Every other active type is always served as an * attachment. Only list types you're comfortable rendering from the app's * origin, keeping in mind that the stored MIME type is client-asserted. */ inlineTypes?: string[] /** * Checks each file's type by what its bytes are, using * `acceptedContentType()`, instead of trusting the type the client * claimed. On `POST {prefix}/fs`, a file the detector recognises is * accepted when its detected type is in the profile's `allowedMimeTypes`; * one it doesn't recognise is accepted on its claimed type, through a * wildcard too, except that a claimed type the detector would have * recognised is refused, and a type that can carry script (SVG, HTML, * JavaScript, XML) must be listed exactly. Files are stored under the * canonical spelling of the accepted type (`image/jpeg` for a claimed * `image/jpg`). The S3 webhook checks objects' bytes against their * declared type the same way `confirmUpload` does. * * Defaults to `true`. `false` checks the claimed type only. */ verifyContentType?: boolean } function sendError(reply: FastifyReply, e: unknown) { if (e instanceof UploadError) { return reply .code(e.statusCode) .send({ error: { code: e.code, message: e.message } }) } throw e } function headerValue(req: FastifyRequest, name: string): string | undefined { const value = req.headers[name] return Array.isArray(value) ? value[0] : value } function normalizeMimeType(mimeType: string): string { return mimeType.split(';')[0].trim().toLowerCase() } /** * The type a file is stored with under `verifyContentType`: what its bytes * are, when the token allows that. Throws `MIME_TYPE_NOT_ALLOWED` otherwise, * saying why. */ function verifiedContentType( payload: UploadTokenPayload, data: Uint8Array, claimedType: string, filename: string, ): string { const result = checkContentType(data, payload.allowedMimeTypes, claimedType) if ('contentType' in result) { return result.contentType } throw new UploadError( 'MIME_TYPE_NOT_ALLOWED', describeRejection(result.rejected, filename, payload.profile), ) } /** * Explains a refused file in terms a developer can act on. The case that * needs it most is a file sent as one type whose bytes are another, like an * iPhone photo sent as `image/heic` that is an `image/heic-sequence`. */ function describeRejection( { detected, claimed }: ContentTypeRejection, filename: string, profile: string, ): string { const file = filename ? `File '${filename}'` : 'File' const notAllowed = (type: string) => isExplicitOnlyContentType(type) ? `which upload profile '${profile}' only accepts when its ` + 'allowedMimeTypes lists it by name' : `which is not in the allowedMimeTypes of upload profile '${profile}'` if (detected) { // Only a type the bytes prove is worth suggesting adding const fix = `Add '${detected}' to accept it.` if (claimed && claimed !== detected) { return ( `${file} was sent as '${claimed}', but its content is ` + `'${detected}', ${notAllowed(detected)}. ${fix}` ) } return `${file} is '${detected}', ${notAllowed(detected)}. ${fix}` } if (!claimed) { return ( `${file} was sent without a type, and its content isn't a type that ` + 'could be recognised.' ) } if (DETECTABLE_CONTENT_TYPES.has(claimed)) { return ( `${file} was sent as '${claimed}', but its content isn't ` + `'${claimed}' or any other type that could be recognised.` ) } return `${file} was sent as '${claimed}', ${notAllowed(claimed)}.` } function contentDispositionHeader( disposition: ContentDisposition, filename: string, ) { // ASCII fallback plus RFC 5987 encoded form for everything else const ascii = filename.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_') const encoded = encodeURIComponent(filename) return `${disposition}; filename="${ascii}"; filename*=UTF-8''${encoded}` } /** * Registers the upload routes on a Fastify server. Register it on the * `server` returned by `createServer()` in `api/src/server.ts`: * * - `POST {prefix}/fs` accepts multipart uploads for object-storage targets * - `GET {prefix}/serve?token=...` serves files behind signed URLs * - `POST {prefix}/webhook/s3` receives S3 event notifications (opt-in) * - `GET {prefix}/health` answers liveness checks */ export async function cedarUploadsPlugin( fastify: FastifyInstance, options: UploadPluginOptions, ): Promise { const { tokenSecret, targets, db, prefix = '/upload', bodyLimit = FIVE_HUNDRED_MB, authenticate, s3Webhook, serveCacheControl = 'private, max-age=3600', inlineTypes = [], verifyContentType = true, } = options const allowedInlineTypes = new Set(inlineTypes.map(normalizeMimeType)) if (!tokenSecret) { throw new UploadError( 'CONFIGURATION', 'cedarUploadsPlugin needs a `tokenSecret`. Set UPLOAD_TOKEN_SECRET in ' + '.env (generate one with `yarn cedar generate secret`).', ) } const base = trimTrailingSlashes(prefix) await fastify.register(fastifyMultipart, { throwFileSizeLimit: true, limits: { fileSize: bodyLimit }, }) const verifyRequestToken = async ( req: FastifyRequest, ): Promise => { const payload = verifyUploadToken(headerValue(req, UPLOAD_TOKEN_HEADER), { secret: tokenSecret, }) if (authenticate) { const user = await authenticate(req) // With an authenticator configured, an unauthenticated request cannot // spend a user-bound token; `assertOwnership` throws for a null actor assertOwnership( { userId: payload.sub, organizationId: payload.organizationId ?? null, }, user, 'this upload token', ) } return payload } fastify.post(`${base}/fs`, { bodyLimit }, async (req, reply) => { // Files stored by this request so far. A later part failing validation // rolls them all back: a partial batch would leave completed rows the // client never learns about and the cleanup job never claims. const stored: { target: string; upload: UploadRecord }[] = [] try { const payload = await verifyRequestToken(req) const target = resolveTarget(targets, payload.target) if (target.providerType === 'db') { throw new UploadError( 'NOT_SUPPORTED', `Upload profile '${payload.profile}' stores files inline in the ` + 'database. Send them as base64 through GraphQL instead.', ) } const requestBound = payload.maxFiles * payload.maxFileSize + MULTIPART_ENVELOPE_ALLOWANCE const contentLength = Number(headerValue(req, 'content-length')) if (Number.isFinite(contentLength) && contentLength > requestBound) { throw new UploadError( 'FILE_TOO_LARGE', `Request body of ${contentLength} bytes exceeds what upload ` + `profile '${payload.profile}' allows.`, ) } if (!req.isMultipart()) { throw new UploadError( 'NOT_SUPPORTED', 'Upload requests must be multipart/form-data.', ) } for await (const part of req.parts({ limits: { fileSize: payload.maxFileSize, files: payload.maxFiles }, })) { if (part.type !== 'file') { continue } // With `verifyContentType` the claimed type is not checked here: the // bytes decide once they are read, and browsers often claim // `application/octet-stream` for formats they don't know, like HEIC if (!verifyContentType) { assertTokenAllowsFile(payload, { contentType: part.mimetype, size: 0n, }) } let data: Buffer try { data = await part.toBuffer() } catch (e) { if ( typeof e === 'object' && e !== null && 'code' in e && e.code === 'FST_REQ_FILE_TOO_LARGE' ) { throw new UploadError( 'FILE_TOO_LARGE', `File '${part.filename}' exceeds the ${payload.maxFileSize} ` + `byte limit for upload profile '${payload.profile}'.`, ) } throw e } const size = BigInt(data.byteLength) const mimeType = verifyContentType ? verifiedContentType(payload, data, part.mimetype, part.filename) : part.mimetype assertTokenAllowsFile(payload, { contentType: mimeType, size }) const storageKey = generateStorageKey(mimeType) // Row first: a crash between the row and the write leaves a pending // row the cleanup job can find, whereas bytes-first would leave an // object on disk that nothing references const upload = await createPendingUpload({ db, payload, filename: part.filename, mimeType, size, storageKey, }) stored.push({ target: payload.target, upload }) await target.write(storageKey, data, { contentType: mimeType }) const { count } = await db.upload.updateMany({ where: { id: upload.id, status: 'pending' }, data: { status: 'completed' }, }) if (count !== 1) { throw new UploadError( 'NOT_PENDING', `Upload ${upload.id} was settled before its bytes were written.`, ) } } if (stored.length === 0) { throw new UploadError('NOT_SUPPORTED', 'No file was included.') } return reply.code(201).send({ uploads: stored.map(({ upload }) => serializeUpload({ ...upload, status: 'completed' }), ), }) } catch (e) { for (const { target, upload } of stored) { await deleteFile(resolveTarget(targets, target), { db, upload, }).catch(() => undefined) } return sendError(reply, e) } }) fastify.get<{ Querystring: Record }>( `${base}${SERVE_ROUTE_PATH}`, async (req, reply) => { try { const { target: targetName, key, disposition: requested, } = verifyServeToken(req.query[SERVE_TOKEN_PARAM], { secret: tokenSecret, }) const target = resolveTarget(targets, targetName) const upload = await db.upload.findFirst({ where: { target: targetName, storageKey: key, status: 'completed' }, omit: { data: true }, }) if (!upload) { throw new UploadError('NOT_FOUND', 'File not found.') } const etag = `"${upload.id}-${upload.updatedAt.getTime()}"` if (headerValue(req, 'if-none-match') === etag) { return reply.code(304).send() } let body: Readable | Buffer try { body = target.readStream ? await target.readStream(key) : await target.read(key) } catch (e) { throw new UploadError('NOT_FOUND', 'File not found.', e) } const mimeType = normalizeMimeType(upload.mimeType) const disposition: ContentDisposition = ACTIVE_CONTENT_TYPES.has(mimeType) && !allowedInlineTypes.has(mimeType) ? 'attachment' : requested return reply .code(200) .header('Content-Type', upload.mimeType) .header('Content-Length', upload.size.toString()) .header( 'Content-Disposition', contentDispositionHeader(disposition, upload.filename), ) .header('X-Content-Type-Options', 'nosniff') .header('Cache-Control', serveCacheControl) .header('ETag', etag) .send(body) } catch (e) { return sendError(reply, e) } }, ) if (s3Webhook) { // SNS posts JSON with a text/plain content type fastify.addContentTypeParser( ['text/plain', 'application/json'], { parseAs: 'string' }, (_req, body, done) => done(null, body), ) fastify.post<{ Body: string }>(`${base}/webhook/s3`, async (req, reply) => { try { const body = typeof req.body === 'string' ? req.body : JSON.stringify(req.body) const result = await handleS3Webhook(body, { db, targets, topicArn: s3Webhook.topicArn, fetchCertificate: s3Webhook.fetchCertificate, fetch: s3Webhook.fetch, verifyContentType, }) return reply.code(200).send(result) } catch (e) { return sendError(reply, e) } }) } // Liveness only: target names and provider types are configuration, and // this route is unauthenticated fastify.get(`${base}/health`, async () => ({ ok: true })) }