filedock 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vraj Raval
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,327 @@
1
- # Temporary Holding Version
1
+ # filedock
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/filedock.svg)](https://www.npmjs.com/package/filedock)
4
+ [![license](https://img.shields.io/npm/l/filedock.svg)](./LICENSE)
5
+ [![node](https://img.shields.io/node/v/filedock.svg)](https://nodejs.org)
6
+
7
+ **Fast, safe file uploads for Node.js.** filedock handles `multipart/form-data` requests (the format browsers use for `<input type="file">`). It works as Express middleware with a multer-style API, or as a simple `await upload.parse(req)` on any Node HTTP server.
8
+
9
+ ```js
10
+ app.post('/avatar', upload.single('avatar'), (req, res) => res.json(req.file));
11
+ ```
12
+
13
+ ## Why filedock?
14
+
15
+ | | filedock |
16
+ |---|---|
17
+ | **Safe defaults** | 10 MB per file, 10 files per request and field limits out of the box, so one request can't fill your disk |
18
+ | **File-type rules** | `allowedTypes: ['image/*']` and `allowedExtensions: ['.pdf']` with no custom code |
19
+ | **Automatic cleanup** | If any part of an upload fails, files already saved from that request are deleted |
20
+ | **Client disconnects** | Partial files are removed when the browser cancels or the connection drops |
21
+ | **Secure file names** | Random names by default, and custom names can never escape the upload folder (`../../etc/passwd` is blocked) |
22
+ | **Clear errors** | Each error has a stable `code` and the right HTTP status (413, 415, 400), plus a ready-made JSON error handler |
23
+ | **Required files** | `upload.single('avatar', { required: true })` |
24
+ | **Checksums** | `hash: 'sha256'` gives every file a checksum while it streams |
25
+ | **Promise API** | `await upload.parse(req)` for plain `http` and other frameworks |
26
+ | **TypeScript** | Types included, and `req.file` / `req.files` are typed in Express |
27
+
28
+ Under the hood, filedock uses [busboy](https://github.com/mscdex/busboy), the same well-tested multipart parser that multer uses. Files are streamed and never loaded fully into memory unless you choose memory storage.
29
+
30
+ ---
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npm install filedock
36
+ ```
37
+
38
+ Requires **Node.js 18 or newer**.
39
+
40
+ ---
41
+
42
+ ## Quick start (Express)
43
+
44
+ ```js
45
+ const express = require('express');
46
+ const filedock = require('filedock');
47
+
48
+ const app = express();
49
+ const upload = filedock({ dest: 'uploads/' });
50
+
51
+ // One file in the "avatar" field -> req.file
52
+ app.post('/profile', upload.single('avatar'), (req, res) => {
53
+ res.json({ user: req.body.username, file: req.file });
54
+ });
55
+
56
+ // Turn upload errors into JSON responses
57
+ app.use(filedock.errorHandler());
58
+
59
+ app.listen(3000);
60
+ ```
61
+
62
+ The HTML form:
63
+
64
+ ```html
65
+ <form action="/profile" method="post" enctype="multipart/form-data">
66
+ <input name="username">
67
+ <input type="file" name="avatar">
68
+ <button>Upload</button>
69
+ </form>
70
+ ```
71
+
72
+ `req.file` looks like this:
73
+
74
+ ```js
75
+ {
76
+ fieldname: 'avatar',
77
+ originalname: 'me.png',
78
+ encoding: '7bit',
79
+ mimetype: 'image/png',
80
+ extension: '.png',
81
+ destination: 'uploads/',
82
+ filename: '3f9c2a7e1b0d4c5e8f6a7b8c9d0e1f2a.png',
83
+ path: 'uploads/3f9c2a7e1b0d4c5e8f6a7b8c9d0e1f2a.png',
84
+ size: 48213
85
+ }
86
+ ```
87
+
88
+ ---
89
+
90
+ ## Accepting files
91
+
92
+ | Method | Accepts | Result |
93
+ |---|---|---|
94
+ | `upload.single(name, { required? })` | One file in `name` | `req.file` |
95
+ | `upload.array(name, maxCount, { required? })` | Up to `maxCount` files in `name` | `req.files` (array) |
96
+ | `upload.fields([{ name, maxCount, required }])` | Several named fields | `req.files` = `{ [name]: File[] }` |
97
+ | `upload.any()` | Files in any field | `req.files` (array) |
98
+ | `upload.none()` | Text fields only; any file is rejected | `req.body` |
99
+
100
+ Text fields always end up in `req.body`. A field sent more than once becomes an array.
101
+
102
+ ```js
103
+ app.post('/gallery', upload.array('photos', 10), (req, res) => {
104
+ res.json({ uploaded: req.files.length });
105
+ });
106
+
107
+ app.post('/product', upload.fields([
108
+ { name: 'cover', maxCount: 1, required: true },
109
+ { name: 'gallery', maxCount: 8 },
110
+ ]), (req, res) => {
111
+ const cover = req.files.cover[0];
112
+ const gallery = req.files.gallery;
113
+ res.json({ cover: cover.filename, gallery: gallery.length });
114
+ });
115
+ ```
116
+
117
+ Requests that are not `multipart/form-data` (for example JSON) pass through untouched, so filedock works alongside `express.json()`.
118
+
119
+ ---
120
+
121
+ ## Options
122
+
123
+ ```js
124
+ const upload = filedock({
125
+ dest: 'uploads/', // folder for disk storage
126
+ storage: 'disk', // 'disk' | 'memory' | custom engine
127
+ limits: { fileSize: 5 * 1024 * 1024 }, // override any default limit
128
+ allowedTypes: ['image/*', 'application/pdf'],
129
+ allowedExtensions: ['.png', '.jpg', '.pdf'],
130
+ fileFilter: (req, file) => file.originalname !== 'thumbs.db',
131
+ hash: 'sha256',
132
+ onFile: (req, file) => console.log('saved', file.filename),
133
+ });
134
+ ```
135
+
136
+ | Option | Type | Default | Description |
137
+ |---|---|---|---|
138
+ | `dest` | `string` | OS temp folder | Where disk storage saves files. Created if missing. |
139
+ | `storage` | `'disk'` \| `'memory'` \| engine | `'disk'` | How files are stored (see **Storage**) |
140
+ | `limits` | `object` | see below | Size and count limits |
141
+ | `allowedTypes` | `string[]` | all | Allowed MIME types. Wildcards like `image/*` work. |
142
+ | `allowedExtensions` | `string[]` | all | Allowed extensions, with or without the dot |
143
+ | `fileFilter` | `(req, file) => boolean` | none | Return `false` to skip a file. Throw to reject the request. Can be async. |
144
+ | `hash` | `'sha256'` \| `'sha1'` \| `'md5'` \| `false` | `false` | Adds `file.hash` (hex) |
145
+ | `onFile` | `(req, file) => void` | none | Called after each file is stored. Can be async. |
146
+
147
+ ### Default limits
148
+
149
+ | Limit | Default | Meaning |
150
+ |---|---|---|
151
+ | `fileSize` | 10 MB | Max bytes per file |
152
+ | `files` | 10 | Max files per request |
153
+ | `fields` | 100 | Max text fields per request |
154
+ | `fieldSize` | 1 MB | Max bytes per text field |
155
+ | `fieldNameSize` | 100 | Max bytes per field name |
156
+ | `parts` | 1000 | Max files + fields |
157
+
158
+ Use `Infinity` to remove a limit: `limits: { fileSize: Infinity }`.
159
+
160
+ > **Security note:** `mimetype` and `originalname` come from the client and can be faked. Type filters stop honest mistakes and casual misuse. For strict checks, inspect the file contents after upload (for example with the `file-type` package).
161
+
162
+ ---
163
+
164
+ ## Storage
165
+
166
+ ### Disk (default)
167
+
168
+ ```js
169
+ const upload = filedock({
170
+ storage: filedock.diskStorage({
171
+ // A string, or a function for per-request folders
172
+ destination: (req, file) => `uploads/${req.user.id}`,
173
+ // Optional: choose the saved name (path parts are stripped automatically)
174
+ filename: (req, file) => `${Date.now()}-${filedock.randomFilename(file)}`,
175
+ }),
176
+ });
177
+ ```
178
+
179
+ By default each file gets a random 32-character name that keeps a safe extension, e.g. `3f9c...e1f2a.png`.
180
+
181
+ ### Memory
182
+
183
+ ```js
184
+ const upload = filedock({ storage: 'memory', limits: { fileSize: 2 * 1024 * 1024 } });
185
+
186
+ app.post('/to-s3', upload.single('file'), async (req, res) => {
187
+ await s3.putObject({ Bucket: 'b', Key: req.file.originalname, Body: req.file.buffer });
188
+ res.sendStatus(201);
189
+ });
190
+ ```
191
+
192
+ Memory storage keeps whole files in RAM, so keep `fileSize` small.
193
+
194
+ ### Custom storage engine
195
+
196
+ Any object with `handleFile` and `removeFile` works:
197
+
198
+ ```js
199
+ const myStorage = {
200
+ async handleFile(req, file, stream) {
201
+ const url = await uploadStreamSomewhere(stream, file.originalname);
202
+ return { url }; // merged into the file object
203
+ },
204
+ async removeFile(req, file) {
205
+ await deleteSomewhere(file.url); // called if the request fails later
206
+ },
207
+ };
208
+ const upload = filedock({ storage: myStorage });
209
+ ```
210
+
211
+ ---
212
+
213
+ ## Errors
214
+
215
+ Every upload problem is an `UploadError` with a stable `code`, the related `field`, and a suggested HTTP `status`.
216
+
217
+ | Code | Status | When |
218
+ |---|---|---|
219
+ | `LIMIT_FILE_SIZE` | 413 | A file is larger than `limits.fileSize` |
220
+ | `LIMIT_FILE_COUNT` | 413 | More files than `limits.files` |
221
+ | `LIMIT_FIELD_COUNT` | 413 | More text fields than `limits.fields` |
222
+ | `LIMIT_FIELD_SIZE` | 413 | A text value is longer than `limits.fieldSize` |
223
+ | `LIMIT_FIELD_KEY` | 413 | A field name is longer than `limits.fieldNameSize` |
224
+ | `LIMIT_PART_COUNT` | 413 | More parts than `limits.parts` |
225
+ | `LIMIT_UNEXPECTED_FILE` | 400 | A file arrived in a field you didn't accept, or more than `maxCount` |
226
+ | `MISSING_FILE` | 400 | A `required` file was not sent |
227
+ | `INVALID_FILE_TYPE` | 415 | Blocked by `allowedTypes` or `allowedExtensions` |
228
+ | `INVALID_FIELD_NAME` | 400 | Dangerous field names such as `__proto__` |
229
+ | `MALFORMED_REQUEST` | 400 | The body is not valid multipart data |
230
+ | `REQUEST_ABORTED` | 400 | The client disconnected mid-upload |
231
+ | `STORAGE_ERROR` | 500 | The storage engine failed (e.g. disk full) |
232
+
233
+ ### Quick option: built-in handler
234
+
235
+ ```js
236
+ app.use(filedock.errorHandler());
237
+ // -> 413 { "error": { "code": "LIMIT_FILE_SIZE", "field": "avatar", "message": "File too large: \"avatar\"" } }
238
+ ```
239
+
240
+ ### Custom handling
241
+
242
+ ```js
243
+ app.use((err, req, res, next) => {
244
+ if (err instanceof filedock.UploadError) {
245
+ if (err.code === 'LIMIT_FILE_SIZE') return res.status(413).send('Max 5 MB, please.');
246
+ return res.status(err.status).json({ code: err.code });
247
+ }
248
+ next(err);
249
+ });
250
+ ```
251
+
252
+ Whenever a request fails, every file already stored from that request is removed before the error reaches you.
253
+
254
+ ---
255
+
256
+ ## Without Express: `parse()`
257
+
258
+ ```js
259
+ const http = require('http');
260
+ const filedock = require('filedock');
261
+
262
+ const upload = filedock({ dest: 'uploads/' });
263
+
264
+ http.createServer(async (req, res) => {
265
+ try {
266
+ const { fields, files } = await upload.parse(req);
267
+ res.end(JSON.stringify({ fields, saved: files.map((f) => f.filename) }));
268
+ } catch (err) {
269
+ res.statusCode = err.status || 500;
270
+ res.end(JSON.stringify({ code: err.code }));
271
+ }
272
+ }).listen(3000);
273
+ ```
274
+
275
+ `parse(req, fields?)` accepts the same field list as `upload.fields()`. Without it, files in any field are accepted.
276
+
277
+ ---
278
+
279
+ ## Cleaning up
280
+
281
+ If you move files elsewhere (for example to cloud storage), delete the local copies:
282
+
283
+ ```js
284
+ await upload.cleanup(req.files); // array, or the object from fields()
285
+ ```
286
+
287
+ ---
288
+
289
+ ## Coming from multer?
290
+
291
+ The method names match, so most apps only change the import:
292
+
293
+ ```diff
294
+ - const multer = require('multer');
295
+ - const upload = multer({ dest: 'uploads/' });
296
+ + const filedock = require('filedock');
297
+ + const upload = filedock({ dest: 'uploads/' });
298
+ ```
299
+
300
+ Differences to know about:
301
+
302
+ - filedock has **default limits** (10 MB, 10 files). Raise them with `limits` if you need more.
303
+ - `fileFilter` returns `true` or `false` (or a promise) instead of using a callback.
304
+ - Errors are `UploadError` with a `status`, not `MulterError`.
305
+ - Default file names keep the extension (`abc123.png`), while multer drops it.
306
+
307
+ ---
308
+
309
+ ## Try the demo
310
+
311
+ ```bash
312
+ git clone <your repo> && cd filedock
313
+ npm install
314
+ npm run example # http://localhost:3000
315
+ ```
316
+
317
+ ## Development
318
+
319
+ ```bash
320
+ npm test
321
+ ```
322
+
323
+ The suite (16 tests) starts real HTTP servers and covers uploads, limits, type rules, cleanup after errors, path-traversal attempts, prototype pollution and client disconnects.
324
+
325
+ ## License
326
+
327
+ [MIT](./LICENSE) © Vraj Raval
package/index.d.ts ADDED
@@ -0,0 +1,122 @@
1
+ import type { IncomingMessage, ServerResponse } from 'http';
2
+ import type { Readable } from 'stream';
3
+
4
+ declare namespace filedock {
5
+ interface File {
6
+ /** Form field the file was sent in. */
7
+ fieldname: string;
8
+ /** File name as sent by the client (path parts removed). Do not trust it. */
9
+ originalname: string;
10
+ encoding: string;
11
+ /** MIME type as sent by the client. Do not trust it for security decisions. */
12
+ mimetype: string;
13
+ /** Lower-case extension of originalname, e.g. ".png". */
14
+ extension: string;
15
+ /** Size in bytes. */
16
+ size: number;
17
+ /** Hex checksum, when the `hash` option is set. */
18
+ hash?: string;
19
+ /** Disk storage only. */
20
+ destination?: string;
21
+ filename?: string;
22
+ path?: string;
23
+ /** Memory storage only. */
24
+ buffer?: Buffer;
25
+ [key: string]: unknown;
26
+ }
27
+
28
+ interface StorageEngine {
29
+ handleFile(req: IncomingMessage, file: File, stream: Readable): Promise<Partial<File>>;
30
+ removeFile(req: IncomingMessage | null, file: File): Promise<void>;
31
+ }
32
+
33
+ interface DiskStorageOptions {
34
+ destination?: string | ((req: IncomingMessage, file: File) => string | Promise<string>);
35
+ filename?: (req: IncomingMessage, file: File) => string | Promise<string>;
36
+ }
37
+
38
+ interface Limits {
39
+ /** Max bytes per file. Default 10 MB. */
40
+ fileSize?: number;
41
+ /** Max files per request. Default 10. */
42
+ files?: number;
43
+ /** Max text fields per request. Default 100. */
44
+ fields?: number;
45
+ /** Max bytes per text field value. Default 1 MB. */
46
+ fieldSize?: number;
47
+ /** Max bytes per field name. Default 100. */
48
+ fieldNameSize?: number;
49
+ /** Max parts (files + fields). Default 1000. */
50
+ parts?: number;
51
+ }
52
+
53
+ interface Options {
54
+ storage?: 'disk' | 'memory' | StorageEngine;
55
+ /** Folder for disk storage. Default: the OS temp folder. */
56
+ dest?: string;
57
+ limits?: Limits;
58
+ /** e.g. ['image/*', 'application/pdf'] */
59
+ allowedTypes?: string[];
60
+ /** e.g. ['.png', 'jpg'] */
61
+ allowedExtensions?: string[];
62
+ /** Return false to skip a file; throw to reject the whole request. */
63
+ fileFilter?: (req: IncomingMessage, file: File) => boolean | Promise<boolean>;
64
+ hash?: 'sha256' | 'sha1' | 'md5' | 'sha512' | false;
65
+ onFile?: (req: IncomingMessage, file: File) => void | Promise<void>;
66
+ }
67
+
68
+ interface Field {
69
+ name: string;
70
+ maxCount?: number;
71
+ required?: boolean;
72
+ }
73
+
74
+ type Middleware = (req: any, res: any, next: (err?: any) => void) => void;
75
+
76
+ interface Uploader {
77
+ single(name: string, opts?: { required?: boolean }): Middleware;
78
+ array(name: string, maxCount?: number, opts?: { required?: boolean }): Middleware;
79
+ fields(fields: Field[]): Middleware;
80
+ any(): Middleware;
81
+ none(): Middleware;
82
+ parse(req: IncomingMessage, fields?: Field[]): Promise<{ fields: Record<string, string | string[]>; files: File[] }>;
83
+ cleanup(files: File[] | Record<string, File[]>): Promise<void>;
84
+ }
85
+
86
+ type ErrorCode =
87
+ | 'LIMIT_FILE_SIZE' | 'LIMIT_FILE_COUNT' | 'LIMIT_FIELD_COUNT' | 'LIMIT_FIELD_SIZE'
88
+ | 'LIMIT_FIELD_KEY' | 'LIMIT_PART_COUNT' | 'LIMIT_UNEXPECTED_FILE' | 'MISSING_FILE'
89
+ | 'INVALID_FILE_TYPE' | 'INVALID_FIELD_NAME' | 'MALFORMED_REQUEST' | 'REQUEST_ABORTED'
90
+ | 'STORAGE_ERROR';
91
+
92
+ class UploadError extends Error {
93
+ code: ErrorCode;
94
+ field?: string;
95
+ status: number;
96
+ statusCode: number;
97
+ }
98
+ }
99
+
100
+ declare function filedock(options?: filedock.Options): filedock.Uploader;
101
+
102
+ declare namespace filedock {
103
+ const filedock: (options?: Options) => Uploader;
104
+ function diskStorage(options?: DiskStorageOptions): StorageEngine;
105
+ function memoryStorage(): StorageEngine;
106
+ function errorHandler(): (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: any) => void) => void;
107
+ function randomFilename(file: { originalname: string }): string;
108
+ function safeExtension(name: string): string;
109
+ const ERROR_CODES: ErrorCode[];
110
+ const DEFAULT_LIMITS: Required<Limits>;
111
+ }
112
+
113
+ declare global {
114
+ namespace Express {
115
+ interface Request {
116
+ file?: filedock.File;
117
+ files?: filedock.File[] | Record<string, filedock.File[]>;
118
+ }
119
+ }
120
+ }
121
+
122
+ export = filedock;
package/index.js ADDED
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * filedock: multipart/form-data file uploads for Node.js.
5
+ * Works as Express/Connect middleware (multer-style) or with a promise API on plain `http`.
6
+ */
7
+
8
+ const { processRequest, isMultipart } = require('./lib/process');
9
+ const { diskStorage, memoryStorage, randomFilename, safeExtension } = require('./lib/storage');
10
+ const { UploadError, ERROR_CODES } = require('./lib/errors');
11
+
12
+ const MB = 1024 * 1024;
13
+ const DEFAULT_LIMITS = {
14
+ fileSize: 10 * MB, // per file
15
+ files: 10, // files per request
16
+ fields: 100, // text fields per request
17
+ fieldSize: 1 * MB, // per text field value
18
+ fieldNameSize: 100, // bytes per field name
19
+ parts: 1000, // files + fields
20
+ };
21
+
22
+ function normalizeExtensions(list) {
23
+ if (!list) return null;
24
+ return list.map((e) => (e.startsWith('.') ? e : `.${e}`).toLowerCase());
25
+ }
26
+
27
+ /**
28
+ * Create an uploader.
29
+ * @param {object} [options]
30
+ * @param {'disk'|'memory'|object} [options.storage] 'memory', a diskStorage()/memoryStorage() engine, or a custom one.
31
+ * @param {string} [options.dest] Shortcut for diskStorage({ destination: dest }).
32
+ * @param {object} [options.limits] Override DEFAULT_LIMITS (use Infinity to remove a limit).
33
+ * @param {string[]} [options.allowedTypes] e.g. ['image/*', 'application/pdf']
34
+ * @param {string[]} [options.allowedExtensions] e.g. ['.png', 'jpg']
35
+ * @param {(req, file) => boolean|Promise<boolean>} [options.fileFilter] Return false to skip a file; throw to reject the request.
36
+ * @param {'sha256'|'sha1'|'md5'|false} [options.hash] Compute a checksum of every file.
37
+ * @param {(req, file) => void|Promise<void>} [options.onFile] Called after each file is stored.
38
+ */
39
+ function filedock(options = {}) {
40
+ let storage = options.storage;
41
+ if (storage === 'memory') storage = memoryStorage();
42
+ else if (!storage || storage === 'disk') storage = diskStorage({ destination: options.dest });
43
+ if (typeof storage.handleFile !== 'function' || typeof storage.removeFile !== 'function') {
44
+ throw new TypeError('filedock: storage must have handleFile() and removeFile()');
45
+ }
46
+
47
+ const config = {
48
+ storage,
49
+ limits: Object.assign({}, DEFAULT_LIMITS, options.limits),
50
+ allowedTypes: options.allowedTypes || null,
51
+ allowedExtensions: normalizeExtensions(options.allowedExtensions),
52
+ fileFilter: options.fileFilter || null,
53
+ hash: options.hash || false,
54
+ onFile: options.onFile || null,
55
+ };
56
+
57
+ function fieldsSpec(list) {
58
+ const map = new Map();
59
+ for (const f of list) {
60
+ if (!f || typeof f.name !== 'string') throw new TypeError('filedock: each field needs a "name"');
61
+ map.set(f.name, { maxCount: f.maxCount == null ? Infinity : f.maxCount, required: !!f.required });
62
+ }
63
+ return { mode: 'fields', fields: map };
64
+ }
65
+
66
+ function middleware(spec, assign) {
67
+ return function filedockMiddleware(req, res, next) {
68
+ if (!isMultipart(req)) return next();
69
+ processRequest(req, config, spec).then(({ body, files }) => {
70
+ req.body = body;
71
+ assign(req, files);
72
+ next();
73
+ }, next);
74
+ };
75
+ }
76
+
77
+ return {
78
+ /** Accept one file in `name` -> req.file */
79
+ single(name, opts = {}) {
80
+ return middleware(fieldsSpec([{ name, maxCount: 1, required: opts.required }]), (req, files) => { req.file = files[0]; });
81
+ },
82
+ /** Accept up to `maxCount` files in `name` -> req.files (array) */
83
+ array(name, maxCount, opts = {}) {
84
+ return middleware(fieldsSpec([{ name, maxCount, required: opts.required }]), (req, files) => { req.files = files; });
85
+ },
86
+ /** Accept several named fields -> req.files = { [name]: File[] } */
87
+ fields(list) {
88
+ return middleware(fieldsSpec(list), (req, files) => {
89
+ const grouped = Object.create(null);
90
+ for (const f of list) grouped[f.name] = [];
91
+ for (const file of files) grouped[file.fieldname].push(file);
92
+ req.files = Object.assign({}, grouped);
93
+ });
94
+ },
95
+ /** Accept files in any field -> req.files (array) */
96
+ any() {
97
+ return middleware({ mode: 'any' }, (req, files) => { req.files = files; });
98
+ },
99
+ /** Text fields only; any file is rejected -> req.body */
100
+ none() {
101
+ return middleware({ mode: 'none' }, () => {});
102
+ },
103
+ /**
104
+ * Promise API for plain `http`, Fastify raw requests, etc.
105
+ * @returns {Promise<{ fields: object, files: object[] }>}
106
+ */
107
+ async parse(req, fieldList) {
108
+ if (!isMultipart(req)) throw new UploadError('MALFORMED_REQUEST', undefined, 'Content-Type must be multipart/form-data');
109
+ const spec = fieldList ? fieldsSpec(fieldList) : { mode: 'any' };
110
+ const { body, files } = await processRequest(req, config, spec);
111
+ return { fields: body, files };
112
+ },
113
+ /** Delete stored files, e.g. after you have moved them elsewhere or a later step failed. */
114
+ async cleanup(files) {
115
+ const list = Array.isArray(files) ? files : Object.values(files || {}).flat();
116
+ await Promise.all(list.map((f) => storage.removeFile(null, f).catch(() => {})));
117
+ },
118
+ config,
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Express error handler that turns UploadError into a JSON response.
124
+ * app.use(filedock.errorHandler())
125
+ */
126
+ function errorHandler() {
127
+ return function filedockErrorHandler(err, req, res, next) {
128
+ if (!(err instanceof UploadError)) return next(err);
129
+ res.statusCode = err.status;
130
+ res.setHeader('Content-Type', 'application/json');
131
+ res.end(JSON.stringify({ error: { code: err.code, field: err.field, message: err.message } }));
132
+ };
133
+ }
134
+
135
+ module.exports = filedock;
136
+ module.exports.filedock = filedock;
137
+ module.exports.default = filedock;
138
+ module.exports.diskStorage = diskStorage;
139
+ module.exports.memoryStorage = memoryStorage;
140
+ module.exports.UploadError = UploadError;
141
+ module.exports.ERROR_CODES = ERROR_CODES;
142
+ module.exports.DEFAULT_LIMITS = DEFAULT_LIMITS;
143
+ module.exports.errorHandler = errorHandler;
144
+ module.exports.randomFilename = randomFilename;
145
+ module.exports.safeExtension = safeExtension;
package/lib/errors.js ADDED
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ const MESSAGES = {
4
+ LIMIT_FILE_SIZE: [413, 'File too large'],
5
+ LIMIT_FILE_COUNT: [413, 'Too many files'],
6
+ LIMIT_FIELD_COUNT: [413, 'Too many fields'],
7
+ LIMIT_FIELD_SIZE: [413, 'Field value too long'],
8
+ LIMIT_FIELD_KEY: [413, 'Field name too long'],
9
+ LIMIT_PART_COUNT: [413, 'Too many parts'],
10
+ LIMIT_UNEXPECTED_FILE: [400, 'Unexpected file field'],
11
+ MISSING_FILE: [400, 'Required file is missing'],
12
+ INVALID_FILE_TYPE: [415, 'File type not allowed'],
13
+ INVALID_FIELD_NAME: [400, 'Invalid field name'],
14
+ MALFORMED_REQUEST: [400, 'Malformed multipart request'],
15
+ REQUEST_ABORTED: [400, 'Request aborted by the client'],
16
+ STORAGE_ERROR: [500, 'Could not store the file'],
17
+ };
18
+
19
+ /**
20
+ * Error thrown for every upload problem.
21
+ * `code` is stable and safe to switch on; `status` is a suggested HTTP status.
22
+ */
23
+ class UploadError extends Error {
24
+ constructor(code, field, message) {
25
+ const [status, defaultMessage] = MESSAGES[code] || [500, 'Upload failed'];
26
+ super(message || (field ? `${defaultMessage}: "${field}"` : defaultMessage));
27
+ this.name = 'UploadError';
28
+ this.code = code;
29
+ this.field = field;
30
+ this.status = status;
31
+ this.statusCode = status;
32
+ }
33
+ }
34
+
35
+ module.exports = { UploadError, ERROR_CODES: Object.keys(MESSAGES) };
package/lib/process.js ADDED
@@ -0,0 +1,200 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const { Transform } = require('stream');
6
+ const busboy = require('busboy');
7
+ const { UploadError } = require('./errors');
8
+
9
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
10
+
11
+ function isMultipart(req) {
12
+ const type = (req.headers && req.headers['content-type']) || '';
13
+ return /^multipart\/form-data/i.test(type);
14
+ }
15
+
16
+ function matchesType(mimetype, patterns) {
17
+ const type = String(mimetype || '').toLowerCase();
18
+ return patterns.some((p) => {
19
+ const pat = String(p).toLowerCase();
20
+ if (pat === '*/*' || pat === '*') return true;
21
+ if (pat.endsWith('/*')) return type.startsWith(pat.slice(0, -1));
22
+ return type === pat;
23
+ });
24
+ }
25
+
26
+ function appendField(body, name, value) {
27
+ if (Object.prototype.hasOwnProperty.call(body, name)) {
28
+ const existing = body[name];
29
+ body[name] = Array.isArray(existing) ? existing.concat(value) : [existing, value];
30
+ } else {
31
+ body[name] = value;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Parse one multipart request.
37
+ * @param {import('http').IncomingMessage} req
38
+ * @param {object} config Resolved uploader config.
39
+ * @param {{ mode: 'any'|'none'|'fields', fields?: Map<string, {maxCount:number, required:boolean}> }} spec
40
+ * @returns {Promise<{ body: object, files: object[] }>}
41
+ */
42
+ function processRequest(req, config, spec) {
43
+ return new Promise((resolve, reject) => {
44
+ const body = Object.create(null);
45
+ const files = [];
46
+ const counts = new Map();
47
+ const activeStreams = new Set();
48
+ let pending = 0;
49
+ let finished = false;
50
+ let error = null;
51
+ let settled = false;
52
+ let bb;
53
+
54
+ try {
55
+ bb = busboy({
56
+ headers: req.headers,
57
+ limits: config.limits,
58
+ defParamCharset: 'utf8',
59
+ preservePath: false,
60
+ });
61
+ } catch (e) {
62
+ return reject(new UploadError('MALFORMED_REQUEST', undefined, e.message));
63
+ }
64
+
65
+ function done() {
66
+ if (settled || !finished || pending > 0) return;
67
+ settled = true;
68
+ req.unpipe(bb);
69
+ req.removeListener('close', onClose);
70
+
71
+ if (!error && spec.mode === 'fields') {
72
+ for (const [name, rule] of spec.fields) {
73
+ if (rule.required && !counts.get(name)) { error = new UploadError('MISSING_FILE', name); break; }
74
+ }
75
+ }
76
+ if (error) {
77
+ Promise.all(files.map((f) => config.storage.removeFile(req, f).catch(() => {})))
78
+ .then(() => reject(error));
79
+ } else {
80
+ resolve({ body: Object.assign({}, body), files });
81
+ }
82
+ }
83
+
84
+ function fail(err) {
85
+ if (!error) error = err;
86
+ finished = true;
87
+ req.unpipe(bb);
88
+ req.resume(); // drain the rest of the body so the client can receive the error response
89
+ for (const s of activeStreams) s.destroy(err);
90
+ done();
91
+ }
92
+
93
+ function onClose() {
94
+ if (!req.complete) fail(new UploadError('REQUEST_ABORTED'));
95
+ }
96
+
97
+ bb.on('field', (name, value, info) => {
98
+ if (error) return;
99
+ if (info.nameTruncated) return fail(new UploadError('LIMIT_FIELD_KEY', name));
100
+ if (info.valueTruncated) return fail(new UploadError('LIMIT_FIELD_SIZE', name));
101
+ if (!name || FORBIDDEN_KEYS.has(name)) return fail(new UploadError('INVALID_FIELD_NAME', name));
102
+ appendField(body, name, value);
103
+ });
104
+
105
+ bb.on('file', (fieldname, stream, info) => {
106
+ if (error) return stream.resume();
107
+ // Browsers send an empty part when a file input is left blank: ignore it.
108
+ if (!info.filename) return stream.resume();
109
+
110
+ if (spec.mode === 'none') return stream.resume(), fail(new UploadError('LIMIT_UNEXPECTED_FILE', fieldname));
111
+ const count = (counts.get(fieldname) || 0) + 1;
112
+ if (spec.mode === 'fields') {
113
+ const rule = spec.fields.get(fieldname);
114
+ if (!rule || count > rule.maxCount) return stream.resume(), fail(new UploadError('LIMIT_UNEXPECTED_FILE', fieldname));
115
+ }
116
+
117
+ const file = {
118
+ fieldname,
119
+ originalname: info.filename,
120
+ encoding: info.encoding,
121
+ mimetype: info.mimeType,
122
+ extension: path.extname(info.filename).toLowerCase(),
123
+ };
124
+
125
+ if (config.allowedTypes && !matchesType(file.mimetype, config.allowedTypes)) {
126
+ return stream.resume(), fail(new UploadError('INVALID_FILE_TYPE', fieldname,
127
+ `File type "${file.mimetype}" is not allowed for "${fieldname}"`));
128
+ }
129
+ if (config.allowedExtensions && !config.allowedExtensions.includes(file.extension)) {
130
+ return stream.resume(), fail(new UploadError('INVALID_FILE_TYPE', fieldname,
131
+ `File extension "${file.extension || '(none)'}" is not allowed for "${fieldname}"`));
132
+ }
133
+
134
+ // Reserve the slot now so parallel files in the same field cannot exceed maxCount.
135
+ counts.set(fieldname, count);
136
+ pending++;
137
+ activeStreams.add(stream);
138
+ stream.pause();
139
+
140
+ (async () => {
141
+ if (config.fileFilter) {
142
+ const accept = await config.fileFilter(req, file);
143
+ if (accept === false) {
144
+ counts.set(fieldname, counts.get(fieldname) - 1);
145
+ stream.resume();
146
+ return null;
147
+ }
148
+ }
149
+ if (error) { stream.resume(); return null; }
150
+
151
+ let size = 0;
152
+ const hash = config.hash ? crypto.createHash(config.hash) : null;
153
+ const tap = new Transform({
154
+ transform(chunk, enc, cb) {
155
+ size += chunk.length;
156
+ if (hash) hash.update(chunk);
157
+ cb(null, chunk);
158
+ },
159
+ });
160
+ // Storage engines may do async work (mkdir, naming) before consuming `tap`;
161
+ // keep a listener attached so a failure in that window is never an uncaught error.
162
+ tap.on('error', () => {});
163
+ stream.on('limit', () => fail(new UploadError('LIMIT_FILE_SIZE', fieldname)));
164
+ stream.on('error', (e) => tap.destroy(e));
165
+ stream.pipe(tap);
166
+
167
+ // Track the file before storage finishes so a later failure can clean it up.
168
+ files.push(file);
169
+ let stored;
170
+ try {
171
+ stored = await config.storage.handleFile(req, file, tap);
172
+ } catch (e) {
173
+ if (error) return null;
174
+ throw e instanceof UploadError ? e : Object.assign(new UploadError('STORAGE_ERROR', fieldname), { cause: e });
175
+ }
176
+ Object.assign(file, stored, { size });
177
+ if (hash) file.hash = hash.digest('hex');
178
+ if (config.onFile) await config.onFile(req, file);
179
+ return file;
180
+ })()
181
+ .catch((e) => fail(e instanceof UploadError ? e : Object.assign(new UploadError('STORAGE_ERROR', fieldname, e.message), { cause: e })))
182
+ .finally(() => {
183
+ activeStreams.delete(stream);
184
+ pending--;
185
+ done();
186
+ });
187
+ });
188
+
189
+ bb.on('filesLimit', () => fail(new UploadError('LIMIT_FILE_COUNT')));
190
+ bb.on('fieldsLimit', () => fail(new UploadError('LIMIT_FIELD_COUNT')));
191
+ bb.on('partsLimit', () => fail(new UploadError('LIMIT_PART_COUNT')));
192
+ bb.on('error', (e) => fail(new UploadError('MALFORMED_REQUEST', undefined, e.message)));
193
+ bb.on('close', () => { finished = true; done(); });
194
+
195
+ req.on('close', onClose);
196
+ req.pipe(bb);
197
+ });
198
+ }
199
+
200
+ module.exports = { processRequest, isMultipart, matchesType };
package/lib/storage.js ADDED
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const crypto = require('crypto');
6
+ const { pipeline } = require('stream/promises');
7
+
8
+ /** Lower-case extension of a file name, or '' when it is missing or looks unsafe. */
9
+ function safeExtension(name) {
10
+ const ext = path.extname(name || '').toLowerCase();
11
+ return /^\.[a-z0-9]{1,10}$/.test(ext) ? ext : '';
12
+ }
13
+
14
+ /** Random, collision-resistant file name that keeps a safe extension. */
15
+ function randomFilename(file) {
16
+ return crypto.randomBytes(16).toString('hex') + safeExtension(file.originalname);
17
+ }
18
+
19
+ /**
20
+ * Store files on disk.
21
+ * @param {object} [opts]
22
+ * @param {string | ((req, file) => string | Promise<string>)} [opts.destination] Folder (created if missing).
23
+ * @param {(req, file) => string | Promise<string>} [opts.filename] Name to save as. Path parts are stripped.
24
+ */
25
+ function diskStorage(opts = {}) {
26
+ const destination = opts.destination || require('os').tmpdir();
27
+ const filename = opts.filename || ((req, file) => randomFilename(file));
28
+
29
+ return {
30
+ async handleFile(req, file, stream) {
31
+ const dir = typeof destination === 'function' ? await destination(req, file) : destination;
32
+ if (typeof dir !== 'string' || !dir) throw new Error('diskStorage: destination must resolve to a folder path');
33
+ const rawName = await filename(req, file);
34
+ if (typeof rawName !== 'string' || !rawName) throw new Error('diskStorage: filename must resolve to a non-empty string');
35
+ // Never let a filename escape the destination folder (e.g. "../../etc/passwd").
36
+ const name = path.basename(rawName);
37
+ if (name === '.' || name === '..' || !name) throw new Error('diskStorage: invalid filename');
38
+
39
+ await fs.promises.mkdir(dir, { recursive: true });
40
+ const fullPath = path.join(dir, name);
41
+ try {
42
+ await pipeline(stream, fs.createWriteStream(fullPath, { flags: 'wx' }));
43
+ } catch (err) {
44
+ await fs.promises.unlink(fullPath).catch(() => {});
45
+ throw err;
46
+ }
47
+ return { destination: dir, filename: name, path: fullPath };
48
+ },
49
+ async removeFile(req, file) {
50
+ if (file.path) await fs.promises.unlink(file.path).catch(() => {});
51
+ },
52
+ };
53
+ }
54
+
55
+ /** Keep files in memory as Buffers (file.buffer). Best for small files you forward elsewhere. */
56
+ function memoryStorage() {
57
+ return {
58
+ async handleFile(req, file, stream) {
59
+ const chunks = [];
60
+ for await (const chunk of stream) chunks.push(chunk);
61
+ return { buffer: Buffer.concat(chunks) };
62
+ },
63
+ async removeFile(req, file) {
64
+ delete file.buffer;
65
+ },
66
+ };
67
+ }
68
+
69
+ module.exports = { diskStorage, memoryStorage, randomFilename, safeExtension };
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "filedock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Fast, safe multipart/form-data file uploads for Node.js. Multer-style Express middleware plus a promise API, with safe defaults, type filtering, checksums and automatic cleanup.",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "default": "./index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "index.d.ts",
17
+ "lib"
18
+ ],
19
+ "scripts": {
20
+ "test": "node --test",
21
+ "example": "node examples/server.js",
22
+ "prepublishOnly": "npm test"
23
+ },
24
+ "keywords": [
25
+ "upload",
26
+ "file-upload",
27
+ "multipart",
28
+ "multipart/form-data",
29
+ "form-data",
30
+ "middleware",
31
+ "express",
32
+ "multer",
33
+ "busboy",
34
+ "files",
35
+ "stream"
36
+ ],
37
+ "author": "Vraj Raval",
38
+ "license": "MIT",
39
+ "engines": {
40
+ "node": ">=18"
41
+ },
42
+ "dependencies": {
43
+ "busboy": "^1.6.0"
44
+ },
45
+ "devDependencies": {
46
+ "express": "^5.1.0"
47
+ }
48
+ }