-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(co-busboy): port co-busboy from JavaScript to TypeScript #5757
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
fengmk2
wants to merge
3
commits into
next
Choose a base branch
from
port-co-busboy
base: next
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| node_modules | ||
| .tshy* | ||
| coverage | ||
| dist |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| # Changelog | ||
|
|
||
| ## 4.0.0-beta.36 | ||
|
|
||
| **Initial TypeScript Release** | ||
|
|
||
| This is a TypeScript port of [co-busboy](https://github.com/cojs/busboy) with the following improvements: | ||
|
|
||
| - Full TypeScript support with comprehensive type definitions | ||
| - Modern async/await API (no generator dependencies) | ||
| - Replaced `chan` library with native Promise-based queue implementation | ||
| - ESM module format | ||
| - Compatible with Node.js >= 22.18.0 | ||
|
|
||
| ### Features | ||
|
|
||
| - Parse multipart/form-data with async/await | ||
| - Support for both Node.js native requests and Koa context objects | ||
| - Auto-decompression of gzip/deflate compressed requests | ||
| - Field auto-collection with `autoFields` option | ||
| - Validation hooks: `checkField` and `checkFile` | ||
| - Limit enforcement (413 errors for parts/files/fields limits) | ||
|
|
||
| ### Breaking Changes from co-busboy 2.x | ||
|
|
||
| - Requires Node.js >= 22.18.0 | ||
| - ESM only (no CommonJS support) | ||
| - Generator/yield syntax is no longer supported (use async/await) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| MIT License | ||
|
|
||
| Copyright (c) 2017-present Alibaba Group Holding Limited and other contributors. | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| # @eggjs/co-busboy | ||
|
|
||
| Multipart form data handling with async/await support for Egg.js and Koa. | ||
|
|
||
| A TypeScript port of [co-busboy](https://github.com/cojs/busboy), providing a promise-based wrapper around [busboy](https://github.com/mscdex/busboy) for parsing multipart/form-data. | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| npm install @eggjs/co-busboy | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| ```typescript | ||
| import { parse } from '@eggjs/co-busboy'; | ||
|
|
||
| // In a Koa middleware | ||
| app.use(async (ctx) => { | ||
| const parts = parse(ctx, { autoFields: true }); | ||
| let part; | ||
|
|
||
| while ((part = await parts())) { | ||
| if (Array.isArray(part)) { | ||
| // It's a field: [name, value, nameTruncated, valueTruncated] | ||
| console.log('Field:', part[0], '=', part[1]); | ||
| } else { | ||
| // It's a file stream with additional properties | ||
| console.log('File:', part.filename, part.mimeType); | ||
| // Consume the stream | ||
| part.pipe(fs.createWriteStream(`./uploads/${part.filename}`)); | ||
| } | ||
| } | ||
|
|
||
| // Access auto-collected fields (when autoFields: true) | ||
| console.log(parts.field); // { fieldName: value } | ||
| console.log(parts.fields); // [[name, value, nameTrunc, valTrunc], ...] | ||
| }); | ||
| ``` | ||
|
|
||
| ## API | ||
|
|
||
| ### `parse(request, options?)` | ||
|
|
||
| Parse multipart form data from a request. | ||
|
|
||
| #### Parameters | ||
|
|
||
| - `request` - Node.js IncomingMessage or Koa context | ||
| - `options` - Optional configuration object | ||
|
|
||
| #### Options | ||
|
|
||
| All standard [busboy options](https://github.com/mscdex/busboy#api) are supported, plus: | ||
|
|
||
| - `autoFields` (boolean, default: `false`) - When true, automatically collects all form fields. Fields will be available via `parts.field` (object lookup) and `parts.fields` (array lookup). Only file streams will be returned in the iteration. | ||
|
|
||
| - `checkField` (function) - Hook to validate form fields. Return an Error to reject the field. | ||
|
|
||
| ```typescript | ||
| checkField: (name, value, fieldnameTruncated, valueTruncated) => { | ||
| if (name === '_csrf' && !isValidToken(value)) { | ||
| return new Error('Invalid CSRF token'); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| - `checkFile` (function) - Hook to validate file uploads. Return an Error to reject the file. | ||
| ```typescript | ||
| checkFile: (fieldname, stream, filename, encoding, mimetype) => { | ||
| if (!filename.endsWith('.jpg')) { | ||
| const err = new Error('Only JPG files allowed'); | ||
| err.status = 400; | ||
| return err; | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| #### Return Value | ||
|
|
||
| Returns a `Parts` function that yields parts when called: | ||
|
|
||
| ```typescript | ||
| interface Parts { | ||
| (): Promise<Part | null>; | ||
| field: Record<string, string | string[]>; | ||
| fields: FieldTuple[]; | ||
| } | ||
| ``` | ||
|
|
||
| - Call `parts()` repeatedly to get each part | ||
| - Returns `null` when parsing is complete | ||
| - When `autoFields` is true, fields are collected in `parts.field` and `parts.fields` | ||
|
|
||
| #### Part Types | ||
|
|
||
| **Field** - An array with 4 elements: | ||
|
|
||
| ```typescript | ||
| type FieldTuple = [ | ||
| string, // name | ||
| string, // value | ||
| boolean, // fieldnameTruncated | ||
| boolean // valueTruncated | ||
| ]; | ||
| ``` | ||
|
|
||
| **File** - A Readable stream with additional properties: | ||
|
|
||
| ```typescript | ||
| interface FileStream extends Readable { | ||
| fieldname: string; | ||
| filename: string; | ||
| encoding: string; | ||
| transferEncoding: string; | ||
| mime: string; | ||
| mimeType: string; | ||
| } | ||
| ``` | ||
|
|
||
| ## Error Handling | ||
|
|
||
| Limit errors include status and code properties: | ||
|
|
||
| ```typescript | ||
| try { | ||
| while ((part = await parts())) { | ||
| // process part | ||
| } | ||
| } catch (err) { | ||
| console.log(err.status); // 413 | ||
| console.log(err.code); // 'Request_files_limit', 'Request_fields_limit', or 'Request_parts_limit' | ||
| } | ||
| ``` | ||
|
|
||
| ## Compression Support | ||
|
|
||
| Gzip and deflate compressed requests are automatically decompressed via the `inflation` library. | ||
|
|
||
| ## License | ||
|
|
||
| [MIT](LICENSE) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| { | ||
| "name": "@eggjs/co-busboy", | ||
| "version": "4.0.0-beta.36", | ||
| "description": "co-busboy for egg - multipart form data handling with async/await support", | ||
| "keywords": [ | ||
| "busboy", | ||
| "egg", | ||
| "form-data", | ||
| "koa", | ||
| "multipart", | ||
| "upload" | ||
| ], | ||
| "homepage": "https://github.com/eggjs/egg/tree/next/packages/co-busboy", | ||
| "license": "MIT", | ||
| "author": "eggjs", | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/eggjs/egg.git", | ||
| "directory": "packages/co-busboy" | ||
| }, | ||
| "files": [ | ||
| "dist" | ||
| ], | ||
| "type": "module", | ||
| "main": "./dist/index.js", | ||
| "module": "./dist/index.js", | ||
| "types": "./dist/index.d.ts", | ||
| "exports": { | ||
| ".": "./src/index.ts", | ||
| "./package.json": "./package.json" | ||
| }, | ||
| "publishConfig": { | ||
| "access": "public", | ||
| "exports": { | ||
| ".": "./dist/index.js", | ||
| "./package.json": "./package.json" | ||
| } | ||
| }, | ||
| "scripts": { | ||
| "typecheck": "tsgo --noEmit" | ||
| }, | ||
| "dependencies": { | ||
| "black-hole-stream": "catalog:", | ||
| "busboy": "catalog:", | ||
| "inflation": "catalog:" | ||
| }, | ||
| "devDependencies": { | ||
| "@eggjs/tsconfig": "workspace:*", | ||
| "@types/busboy": "catalog:", | ||
| "formstream": "catalog:", | ||
| "typescript": "catalog:" | ||
| }, | ||
| "engines": { | ||
| "node": ">=22.18.0" | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In the usage example, the code writes uploaded files directly to
./uploads/${part.filename}, which uses the attacker-controlledfilenamevalue to construct a filesystem path. An attacker can supply values like../../../../etc/passwdasfilenameto perform path traversal and overwrite or create arbitrary files outside the intended upload directory. To avoid this, normalize and strictly validate or replace the original filename before using it in a filesystem path, and join it to a fixed upload directory in a way that prevents escaping that directory.