Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,13 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Run tests
run: pnpm run ci --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
- name: Run tests with coverage
if: ${{ matrix.os != 'windows-latest' }}
run: pnpm run test:cov --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}

- name: Run tests without coverage
if: ${{ matrix.os == 'windows-latest' }}
run: pnpm run test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}

- name: Run example tests
if: ${{ matrix.node != '20' && matrix.os != 'windows-latest' }}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"fmt": "oxfmt",
"typecheck": "pnpm clean && pnpm -r run typecheck",
"fmtcheck": "oxfmt --check .",
"pretest": "pnpm run clean && pnpm -r run pretest",
"pretest": "pnpm run clean && pnpm -r --parallel run pretest",
"test": "vitest run --bail 1 --retry 2 --testTimeout 20000 --hookTimeout 20000",
"test:cov": "pnpm run test --coverage",
"preci": "pnpm -r --parallel run pretest",
Expand Down
4 changes: 4 additions & 0 deletions packages/co-busboy/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
.tshy*
coverage
dist
28 changes: 28 additions & 0 deletions packages/co-busboy/CHANGELOG.md
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)
21 changes: 21 additions & 0 deletions packages/co-busboy/LICENSE
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.
142 changes: 142 additions & 0 deletions packages/co-busboy/README.md
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}`));
Copy link

Copilot AI Dec 30, 2025

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-controlled filename value to construct a filesystem path. An attacker can supply values like ../../../../etc/passwd as filename to 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.

Copilot uses AI. Check for mistakes.
}
}

// 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)
56 changes: 56 additions & 0 deletions packages/co-busboy/package.json
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"
}
}
Loading
Loading