@molecule/api-uploads
Core interface · storage · API (Node) · v1.4.1 · Apache-2.0
File uploads and storage
npm install @molecule/api-uploadsHow it works
@molecule/api-uploads is the storage core interface on the API (Node) side: the API your app calls, with no vendor inside.
Choose the implementation by bonding one of its 4 providers: @molecule/api-uploads-encrypted, @molecule/api-uploads-filesystem, @molecule/api-uploads-mirror, @molecule/api-uploads-s3.
import { getProvider, getUploads, receiveUploads, sendUpload } from '@molecule/api-uploads'
// a bond called setProvider() at startup; the default, `@molecule/api-uploads-filesystem`, stores
// files under FILE_UPLOAD_PATH (./uploads), a folder that ignores itself in git: no .gitignore entry
router.post(
'/files',
requireAuth, // refuse anonymous requests before anything is stored
receiveUploads({
field: 'file',
maxFileBytes: 5 * 1024 * 1024, // optional; 10 MiB when left out
types: ['image/png', 'image/jpeg', 'application/pdf', 'text/plain'],
}), // refuses: 415 not multipart or another type, 413 too large or too many, 400 no file or another field
async (req, res) => {
const [file] = getUploads(req, 'file') // fully stored; refusals never reach here
await saveFileRow({ id: file.id, userId: getUserId(res), name: file.filename }) // own it
res.status(201).json({ id: file.id }) // a throw or a 4xx/5xx answer removes the stored file
},
)
router.get('/files/:id', async (req, res) => {
const row = await getFileRow(req.params.id)
if (!row || row.userId !== getUserId(res)) return res.status(404).end() // ownership → no IDOR
const stream = await getProvider().getFile?.(row.id) // null for any id no stored file has, `../x` too
if (!stream) return res.status(404).end()
await sendUpload(res, stream, { filename: row.name }) // a download; { inline: true, type } shows an image
})
// Try it with the server running (curl builds the multipart body; add your auth header). A .txt
// file goes up as text/plain, which `types` allows:
// echo hi > /tmp/a.txt
// id=$(curl -fsS -F file=@/tmp/a.txt localhost:$PORT/files | node -pe 'JSON.parse(fs.readFileSync(0)).id')
// curl -fsS localhost:$PORT/files/$id → hiProviders (4): @molecule/api-uploads-encrypted, @molecule/api-uploads-filesystem, @molecule/api-uploads-mirror, @molecule/api-uploads-s3
Works with: @molecule/api-bond, @molecule/api-i18n, @molecule/api-middleware-body-parser
Live demos
Running apps built with Molecule that install this package — open the app or study the template.
Reference
Uploads core interface for molecule.dev.
Defines the standard interface for upload providers, receiveUploads: the route
middleware that receives a request's files into the bonded provider, and sendUpload, which
serves a stored file back as a download the browser does not open (never stream.pipe(res)).
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { getProvider, getUploads, receiveUploads, sendUpload } from '@molecule/api-uploads'
// a bond called setProvider() at startup; the default, `@molecule/api-uploads-filesystem`, stores
// files under FILE_UPLOAD_PATH (./uploads), a folder that ignores itself in git: no .gitignore entry
router.post(
'/files',
requireAuth, // refuse anonymous requests before anything is stored
receiveUploads({
field: 'file',
maxFileBytes: 5 * 1024 * 1024, // optional; 10 MiB when left out
types: ['image/png', 'image/jpeg', 'application/pdf', 'text/plain'],
}), // refuses: 415 not multipart or another type, 413 too large or too many, 400 no file or another field
async (req, res) => {
const [file] = getUploads(req, 'file') // fully stored; refusals never reach here
await saveFileRow({ id: file.id, userId: getUserId(res), name: file.filename }) // own it
res.status(201).json({ id: file.id }) // a throw or a 4xx/5xx answer removes the stored file
},
)
router.get('/files/:id', async (req, res) => {
const row = await getFileRow(req.params.id)
if (!row || row.userId !== getUserId(res)) return res.status(404).end() // ownership → no IDOR
const stream = await getProvider().getFile?.(row.id) // null for any id no stored file has, `../x` too
if (!stream) return res.status(404).end()
await sendUpload(res, stream, { filename: row.name }) // a download; { inline: true, type } shows an image
})
// Try it with the server running (curl builds the multipart body; add your auth header). A .txt
// file goes up as text/plain, which `types` allows:
// echo hi > /tmp/a.txt
// id=$(curl -fsS -F file=@/tmp/a.txt localhost:$PORT/files | node -pe 'JSON.parse(fs.readFileSync(0)).id')
// curl -fsS localhost:$PORT/files/$id → hi
Type
core
Installation
npm install @molecule/api-uploads @molecule/api-bond @molecule/api-i18n @molecule/api-middleware-body-parser
API
Interfaces
ReceiveUploadsOptions
What an upload route accepts. Anything outside it is refused before the handler runs, with a
translated { error, errorKey } body. The multipart parsing comes from the body parser bond
(@molecule/api-middleware-body-parser-express on Express), which mlcl add installs and
wires with the upload provider: a route needs only this package.
interface ReceiveUploadsOptions {
/** The form field the files are sent in. A file in any other field is refused with 400. */
field: string
/** The largest file accepted, in bytes (default 10 MiB). A larger one is refused with 413. */
maxFileBytes?: number
/** The most files accepted in `field` (default 1). More are refused with 413. */
maxFiles?: number
/**
* The MIME types accepted, as the client declares them (`'image/png'`, or `'image/*'` for a
* whole family). Another type is refused with 415. Omit it to accept any type but those a
* browser runs (see `allowActiveTypes`).
*/
types?: readonly string[]
/**
* Store files of the types a browser runs when it opens them (HTML, SVG, JavaScript and every
* XML type). Without it they are refused with 415 `uploads.error.fileTypeBlocked`, on every
* provider, whatever `types` says. Set it only on a route whose files are served back through
* `sendUpload()`, as downloads the browser does not open. Never set it on a route that shows its
* files to users (an avatar, a gallery image): there the file would run on the app's origin.
*/
allowActiveTypes?: boolean
/** When false, a request with no file passes with none; by default it is refused with 400. */
required?: boolean
/** The most text fields accepted (default 20); they become `req.body`, as strings. */
maxFields?: number
/** The largest text field, in bytes (default 64 KiB). A larger one is refused with 413. */
maxFieldBytes?: number
}
UploadResponse
The response sendUpload writes: an Express response, or Node's own ServerResponse.
interface UploadResponse extends NodeJS.WritableStream {
/** Sets a response header. */
setHeader(name: string, value: string | number): unknown
}
SendUploadOptions
How sendUpload serves a file.
interface SendUploadOptions {
/**
* The name the browser saves the file under: the stored `filename`. Only its first 200
* characters are sent, and a character that cannot be encoded is replaced.
*/
filename?: string
/**
* Show the file in the browser (an image in an `<img>`, a video, plain text) rather than
* download it. Honoured only for a type in `INLINE_UPLOAD_TYPES` or an `audio/*` or
* `video/*` type; any other file is still a download.
*/
inline?: boolean
/** The stored type (`file.mimetype`). Sent only for an inline file; a download is always `application/octet-stream`. */
type?: string
/** The file's size in bytes, sent as `Content-Length`. */
size?: number
}
UploadedFile
Properties describing an uploading/uploaded file.
interface UploadedFile {
/**
* The unique file identifier.
*/
id: string
/**
* The file's fieldname from the form.
* `getUploads(req, fieldname)` returns the files sent in it.
*/
fieldname: string
/**
* The original filename - e.g., `some-image.jpg`.
*/
filename: string
/**
* The file's encoding - e.g., `binary`.
*/
encoding: string
/**
* The file's mimetype - e.g., `image/jpeg`.
*/
mimetype: string
/**
* The file's size in bytes.
*/
size: number
/**
* The source stream (available during upload).
*/
stream?: NodeJS.ReadableStream
/**
* A promise that resolves when the upload completes.
*/
uploadPromise?: Promise<void>
/**
* Whether the upload has completed.
*/
uploaded: boolean
/**
* The URL/location of the uploaded file (if available).
*/
location?: string
}
FileInfo
Information about a file being uploaded.
This interface is provider-agnostic. Implementations using busboy or other multipart parsers should adapt to this interface.
interface FileInfo {
/**
* The original filename - e.g., `some-image.jpg`. `undefined` when the client sent none (busboy
* types it `string | undefined`: a part counts as a file by its `application/octet-stream`
* type alone), so a multipart parser's info is passed as it is.
*/
filename: string | undefined
/**
* The file's encoding - e.g., `7bit`, `binary`.
*/
encoding: string
/**
* The file's MIME type - e.g., `image/jpeg`.
*/
mimeType: string
/**
* Store the file even when its type is one a browser runs (`BLOCKED_UPLOAD_TYPES`).
* `receiveUploads` sets it for a route created with `allowActiveTypes: true`; every provider
* refuses such a file without it.
*/
allowActiveTypes?: boolean
}
UploadProvider
Upload provider interface.
All upload providers must implement this interface.
interface UploadProvider {
/**
* Uploads a file from a stream.
*/
upload: UploadHandler
/**
* Aborts an in-progress upload.
*/
abortUpload: AbortHandler
/**
* Deletes a file.
*/
deleteFile: DeleteHandler
/**
* Gets a file stream for reading: `null` when no stored file has that id (see
* `GetFileHandler`). It carries the bytes only; keep the name and type from
* `getUploads(req)` if the route serves them back.
*/
getFile?: GetFileHandler
/**
* Proves the storage backend is reachable/writable with one cheap operation
* (an S3 `HeadBucket`, a filesystem writability check), and REJECTS when it
* is not. Optional providers (encrypted, mirror) delegate to the provider
* they wrap and need not implement it.
*/
ping?(): Promise<void>
/**
* Releases any client/connection the provider holds (e.g. an SDK client).
*/
close?(): Promise<void>
}
Types
UploadHandler
Callback invoked by the multipart parser for each incoming file. Implementations
pipe the stream to a storage backend and return an UploadedFile descriptor.
type UploadHandler = (
fieldname: string,
stream: NodeJS.ReadableStream,
info: FileInfo,
onError: (error: Error) => void,
) => UploadedFile
fieldname— The form field name the file was submitted under.stream— The readable stream of file data.info— Metadata about the file (filename, encoding, MIME type).onError— Callback to invoke if a stream error occurs during upload.
AbortHandler
Callback invoked to abort an in-progress upload and clean up any partially written data in the storage backend.
type AbortHandler = (file: UploadedFile) => void | Promise<void>
DeleteHandler
Callback invoked to permanently delete an uploaded file from storage.
type DeleteHandler = (id: string) => Promise<void>
GetFileHandler
Callback invoked to retrieve a readable stream for an uploaded file. Resolves null when no
stored file has that id, whatever the id (a client's ../x included), so a route answers 404.
Rejects only when the storage itself fails; an Express 5 route passes that to its error handler.
type GetFileHandler = (id: string) => Promise<NodeJS.ReadableStream | null>
Classes
UploadAbortedError
Thrown by conforming upload providers to reject a file's uploadPromise when
abortUpload() is called on it — signals a deliberate cancellation, distinguishable
from both a successful upload and a real transport/storage failure.
class UploadAbortedError extends Error {
constructor() {
super(
t('uploads.error.aborted', undefined, {
defaultValue: 'Upload was aborted.',
}),
)
this.name = 'UploadAbortedError'
}
}
UploadRefusedError
What a provider passes to upload()'s onError to refuse a file, rather than to report that
storing it failed. receiveUploads() answers it as the client's error, with status and
{ error, errorKey } as JSON, the way it answers a file that is too large; any other error is
the server's, a 500.
class UploadRefusedError extends Error {
/** The HTTP status the refusal is answered with (4xx). */
readonly status: number
/** The translation key of the message. */
readonly errorKey: string
/** The values the message interpolates. */
readonly values?: Record<string, string | number>
/**
* A refusal, its message translated now.
*
* @param errorKey - The translation key of the message.
* @param values - The values it interpolates.
* @param defaultValue - The English message, `{{name}}` for each value.
* @param status - The HTTP status (default 415, a type the server will not store).
*/
constructor(
errorKey: string,
values: Record<string, string | number> | undefined,
defaultValue: string,
status = 415,
) {
super(t(errorKey, values, { defaultValue }))
this.name = 'UploadRefusedError'
this.status = status
this.errorKey = errorKey
this.values = values
}
}
Functions
baseUploadType(mimeType)
A declared type as BLOCKED_UPLOAD_TYPES lists it: without parameters, in lower case.
function baseUploadType(mimeType: string): string
mimeType— The type as declared (Text/HTML; charset=utf-8).
Returns: The bare type (text/html).
isBlockedUploadType(mimeType)
Whether a declared type is one a browser runs when it opens the file, by rule rather than by name:
a type in BLOCKED_UPLOAD_TYPES, any +xml type, or any type whose subtype names a script
(text/jscript, application/ecmascript). Browsers decide by these rules, so a list of names
always lagged behind. Parameters and case do not matter.
function isBlockedUploadType(mimeType: string): boolean
mimeType— The type as declared (Application/Atom+XML; charset=utf-8).
Returns: True when no provider stores the type unless the route allows it.
blockedTypeRefusal(info)
What a provider's upload() calls before it stores a file: the refusal for a type a browser runs
(isBlockedUploadType, also when declared with a charset or in capitals), or null when the
type may be stored or the route allows it (info.allowActiveTypes).
function blockedTypeRefusal(
info: Pick<FileInfo, 'mimeType' | 'allowActiveTypes'>,
): UploadRefusedError | null
info— The file's info, asupload()received it.
Returns: The error to pass to onError, or null when the file may be stored.
setProvider(provider)
Registers an upload provider as the active singleton. Called by bond packages during application startup.
function setProvider(provider: UploadProvider): void
provider— The upload provider implementation to bond.
getProvider()
Retrieves the bonded upload provider, throwing if none is configured.
function getProvider(): UploadProvider
Returns: The bonded upload provider.
hasProvider()
Checks whether an upload provider is currently bonded.
function hasProvider(): boolean
Returns: true if an upload provider is bonded.
receiveUploads(options)
Middleware that receives a route's uploaded files into the bonded upload provider.
It refuses, before the handler runs and with a translated { error, errorKey } body: a body
that is not multipart/form-data (415), a file over maxFileBytes or more than maxFiles
files (413), a type outside types or one a browser runs (415; see allowActiveTypes), a file
in another field or no file (400). When it
refuses, when storage fails, or when the client disconnects, every file it stored for the
request is removed. The handler runs once every file is fully stored: read them with
getUploads, and the text fields from req.body (as strings).
It keeps owning the files after the handler starts. When the route then answers with a status
of 400 or more, they are removed too; a 2xx or 3xx answer keeps them, and so does a client that
goes away before the answer (the handler may already have saved what points at the file). A handler that fails need not clean up itself, though it can with
discardUploads (before it answers, or when it answers 2xx with the failure in the body).
Put it after the route's authentication check, so an anonymous request is refused before
anything is stored. Calling it only records the options: the parser is built on the first
request, so a router module can be imported (by a test, before the bonds are wired) without a
body parser bond. It throws, when the router loads, for types that name a type a browser
runs without allowActiveTypes: true. Serve the files back with sendUpload().
function receiveUploads(options: ReceiveUploadsOptions): Middleware
options— The form field, and optionally the size cap (default 10 MiB), the accepted types and counts.
Returns: The route's middleware.
getUploads(req, field)
The files receiveUploads stored for this request: the ones still in storage, so none
after discardUploads removed them.
function getUploads(req: unknown, field?: string): UploadedFile[]
req— The request.field— The form field, or every field when omitted.
Returns: The stored files, in arrival order; empty when none were sent.
discardUploads(req)
Removes the files receiveUploads stored for this request. Call it when the handler fails
after the upload and will not answer with an error status: a handler that reports the failure in
a 2xx body. One that throws, or answers 400 or more, needs no call: the parser removes the files
itself when it sees that answer.
Each file removed is forgotten, so getUploads(req) no longer lists it and nothing removes it
twice. A file that cannot be removed is logged and stays listed, for the parser to try again.
function discardUploads(req: unknown): Promise<void>
req— The request.
isInlineUploadType(type)
Whether sendUpload shows a file of this type in the browser when asked to.
function isInlineUploadType(type: string): boolean
type— The stored type.
Returns: True for INLINE_UPLOAD_TYPES and audio/* or video/* types.
sendUpload(res, stream, options)
Sends a stored file (the stream getProvider().getFile(id) resolves) as the response. By default
it is a download the browser never opens: application/octet-stream, Content-Disposition: attachment, X-Content-Type-Options: nosniff and a sandboxing Content-Security-Policy, so an
HTML or SVG file, or one whose declared type lied, cannot run on the app's origin. A route that
pipes the stream itself (stream.pipe(res)) sends no type, and the browser guesses one.
It never fails on a file's name, whatever the client once sent: a name of any length or encoding is sent in the header cut to 200 characters.
Pass { inline: true, type: file.mimetype } to show an image, audio, video or plain text file in
the page instead.
function sendUpload(
res: UploadResponse,
stream: NodeJS.ReadableStream,
options?: SendUploadOptions,
): Promise<void>
res— The response.stream— The stored file.options— The file's name, and whether to show it inline.
Returns: Resolves when the file is sent; rejects when reading it fails, after closing the response.
Constants
BLOCKED_UPLOAD_TYPES
The declared types a browser runs when it opens the file (HTML, SVG, JavaScript, XML), named
outright. Every provider refuses to store them unless the route was created with
receiveUploads({ allowActiveTypes: true }). The declared type is the client's claim, so this is
the second layer: the first is serving every file with sendUpload.
This is not the whole rule: a browser also runs every other +xml type (application/atom+xml)
and every script type (text/jscript). To ask whether a type is one a browser runs, call
isBlockedUploadType; never test membership here.
const BLOCKED_UPLOAD_TYPES: ReadonlySet<string>
INLINE_UPLOAD_TYPES
The types sendUpload shows in the browser when asked to: none of them can run code there.
const INLINE_UPLOAD_TYPES: ReadonlySet<string>
Available Providers
| Provider | Package |
|---|---|
| Encrypted (wraps another store) | @molecule/api-uploads-encrypted |
| Local Filesystem | @molecule/api-uploads-filesystem |
| Mirrored (several stores) | @molecule/api-uploads-mirror |
| AWS S3 / S3-compatible | @molecule/api-uploads-s3 |
Injection Notes
Requirements
Peer dependencies:
@molecule/api-bond^1.0.1@molecule/api-i18n^1.0.1@molecule/api-middleware-body-parser^1.2.0
Runtime Dependencies
@molecule/api-bond@molecule/api-i18n@molecule/api-middleware-body-parser
A weak upload integration leaks files or trusts the client. receiveUploads does the
request side: it refuses wrong types, oversized files, extra files and non-multipart bodies
before the handler runs, removes partial files when a request fails or the client disconnects,
and removes the stored files when the route then fails. The handler still owns the rest:
- Own every file. Persist the returned
UploadedFileid with the uploader'suser_id, and on read/delete load the row and 404 if it isn't the caller's — an unscopedgetFile(id)is an IDOR (anyone enumerates everyone's files). - Put the auth check before
receiveUploads, so an anonymous request is refused before anything is stored. - Serve a stored file with
sendUpload, notstream.pipe(res), which sends no type and lets the browser guess one: a file whose declared type lied would run on the app's origin.sendUploadsendsapplication/octet-streamas an attachment withnosniff;{ inline: true, type: file.mimetype }shows an image, audio, video or plain text file. - The declared type is the client's claim.
typesrefuses what the client declares, and every provider refuses the types a browser runs (HTML, SVG, JavaScript, every XML type) with 415. A route that stores any file, served back only throughsendUpload, passesallowActiveTypes: true; a route that shows its files to users (an avatar) never does. When the content matters (an image you render), check the stored bytes too. - A failed route keeps nothing. When the handler throws, or answers with a status of 400 or
more,
receiveUploadsremoves the files it stored. A client that goes away before the answer removes nothing: the handler may already have saved what points at the file. CalldiscardUploads(req)only when the handler fails yet answers 2xx (the failure in the body), so the stored files do not stay with nothing pointing at them. - Use
receiveUploadsrather than a multipart parser of your own. The bundled provider bonds cap a file's size only through the parser's'limit'event on the stream ('Stream limit reached.'ononError); a plain stream is never size-limited. - Private by default. Do NOT put user uploads on a public, guessable path; serve them through an authenticated route (or a short-lived signed URL). Public buckets leak files.
- Persist the id, never the provider URL. Store
file.id(or a serve URL you build from it, e.g./api/files/<id>) — NEVER the rawfile.location. A bucket URL 403s the moment storage is private (the default here), so a renderedlocationworks only on the local filesystem bond and breaks on S3; and only the id lets a later route serve, delete, or REPLACE the object. Persistinglocationstrands the file — uncleanable. - Free the blob on delete AND replace. Deleting the owning row must also call
deleteFile(id)— a row-only delete orphans the object in storage forever. On REPLACE (a new upload overwriting a stored id)deleteFilethe OLD id too, or every change leaks the previous blob. Both are best-effort (log, don't fail the request) and run AFTER the row write so a storage hiccup never leaves a row pointing at a gone object. - Never build a storage key from the raw client filename — sanitize/generate the key server-side (path traversal / overwrite).
- Stream to storage (the API takes a
NodeJS.ReadableStream); never buffer a whole upload in memory. - Aborting an upload is neither a success nor a failure.
abortUpload()rejects the file'suploadPromisewithUploadAbortedError— it never resolvesuploadPromiseand never invokes theupload()call'sonErrorfor the abort itself — and what was written of the file is removed. This holds across every bundled provider, so swapping providers never changes what a consumer observes on abort. SeeUploadAbortedErrorfor the full contract.
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:
- Uploading a valid file through the UI shows progress/confirmation and the file appears in the user's file list.
- The uploaded content is retrievable: opening/downloading it returns the same content (an uploaded image actually renders).
- A disallowed file type is rejected with a visible error and does NOT appear in the list.
- An over-the-cap file is rejected cleanly (visible error, no partial phantom entry).
- Ownership is enforced: a second signed-in user cannot retrieve the first user's file by its id/URL (404 — not the file).
- Deleting a file removes it from the list, and it stays gone (and unretrievable) after a full reload.
Translations
Translation strings are provided by @molecule/api-locales-uploads.