Skip to content
Merged
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
15 changes: 10 additions & 5 deletions .github/workflows/nodejs-old-versions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: Node.js old versions CI

on:
push:
branches: [master]
branches: ['4.x']
pull_request:
branches: [master]
branches: ['4.x']

jobs:
test:
Expand All @@ -19,18 +19,23 @@ jobs:

steps:
- uses: actions/checkout@v6
- name: Use Node.js
- name: Use Node.js for build tools
uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node }}
node-version: '24'
- run: npm install --legacy-peer-deps
- name: Patch vitest imports
run: |
for f in test/*.test.ts; do [ -e "$f" ] || exit 0; sed --version >/dev/null 2>&1 && sed -i "s@'vite-plus/test'@'vitest'@g" "$f" || sed -i '' "s@'vite-plus/test'@'vitest'@g" "$f"; done
sed --version >/dev/null 2>&1 && sed -i "s@'vite-plus'@'vite'@g" vite.config.ts || sed -i '' "s@'vite-plus'@'vite'@g" vite.config.ts
jq 'del(.overrides)' package.json > package.json.tmp && mv package.json.tmp package.json
npm install -D vitest@3 vite@7
- run: npx vitest && npm run build:ts && npm run build:version && npm pack && npx attw --pack
- run: npm run build:ts && npm run build:version && npm pack && npx attw --pack
- name: Use Node.js for compatibility tests
uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node }}
- run: npx vitest run
env:
NODE_OPTIONS: --require ./test/patch-for-node16-18.cjs
- run: npm run test-node16
4 changes: 2 additions & 2 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: CI

on:
push:
branches: [master]
branches: ['4.x']
pull_request:
branches: [master]
branches: ['4.x']
merge_group:

jobs:
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@
"check:fix": "vp check --fix"
},
"dependencies": {
"form-data": "^4.0.5",
"formstream": "^1.5.2",
"form-data": "^4.0.6",
"formstream": "^1.5.3",
"mime-types": "^2.1.35",
"qs": "^6.15.0",
"type-fest": "^4.41.0",
Expand Down
41 changes: 21 additions & 20 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions src/FormData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,18 @@ export class FormData extends _FormData {
// formidable and the browser add a name property
// fs- and request- streams have path property
filename = path.basename(options.filename || value.name || value.path);
} else if (value.readable && value.hasOwnProperty('httpVersion')) {
} else if (value.readable && Object.hasOwn(value, 'httpVersion')) {
// or try http response
filename = path.basename(value.client._httpMessage.path || '');
}

if (filename) {
// https://datatracker.ietf.org/doc/html/rfc6266#section-4.1
// support non-ascii filename
contentDisposition = 'filename="' + filename + '"';
// WHATWG multipart encoding escapes only CR, LF, and double quotes in filenames.
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart-form-data
const escapedFilename = filename.replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22');
contentDisposition = 'filename="' + escapedFilename + '"';
if (NON_ASCII_RE.test(filename)) {
// Preserve legacy filename* support for compatibility, although RFC 7578 forbids it in multipart uploads.
contentDisposition += "; filename*=UTF-8''" + encodeURIComponent(filename);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export function performanceTime(startTime: number, now?: number): number {
}

export function isReadable(stream: any): boolean {
if (typeof Readable.isReadable === 'function') return Readable.isReadable(stream);
if (typeof Readable.isReadable === 'function') return Readable.isReadable(stream) === true;
// patch from node
// https://github.com/nodejs/node/blob/1287530385137dda1d44975063217ccf90759475/lib/internal/streams/utils.js#L119
// simple way https://github.com/sindresorhus/is-stream/blob/main/index.js
Expand Down
33 changes: 33 additions & 0 deletions test/formData.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { strict as assert } from 'node:assert';

import { describe, it } from 'vite-plus/test';

import { WebFormData } from '../src/index.js';

describe('formData.test.ts', () => {
it.each([
['plain.txt', 'filename="plain.txt"'],
['a"b".txt', 'filename="a%22b%22.txt"'],
['a\rb\r.txt', 'filename="a%0Db%0D.txt"'],
['a\nb\n.txt', 'filename="a%0Ab%0A.txt"'],
['a\r\nb.txt', 'filename="a%0D%0Ab.txt"'],
['a%22.txt', 'filename="a%22.txt"'],
["a b';=%.txt", 'filename="a b\';=%.txt"'],
['中文.txt', 'filename="中文.txt"; filename*=UTF-8\'\'%E4%B8%AD%E6%96%87.txt'],
['中"\r\n.txt', 'filename="中%22%0D%0A.txt"; filename*=UTF-8\'\'%E4%B8%AD%22%0D%0A.txt'],
])('should safely serialize filename %j', (filename, disposition) => {
const form = new WebFormData();
form.append('file', Buffer.from('data'), { filename, contentType: 'text/plain' });
assert.equal(
form.getBuffer().toString(),
`--${form.getBoundary()}\r\nContent-Disposition: form-data; name="file"; ${disposition}\r\n` +
`Content-Type: text/plain\r\n\r\ndata\r\n--${form.getBoundary()}--\r\n`,
);
});

it('should escape a custom filepath after normalization', () => {
const form = new WebFormData();
form.append('file', Buffer.from('data'), { filepath: 'folder/a"\r\n.txt' });
assert.ok(form.getBuffer().toString().includes('filename="folder/a%22%0D%0A.txt"\r\n'));
});
});
41 changes: 41 additions & 0 deletions test/options.files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,4 +322,45 @@ describe('options.files.test.ts', () => {
assert.equal(response.data.form.hello, 'hello world,😄😓');
assert.equal(response.data.form.foo, 'bar');
});
it.each(['buffer', 'readable', 'stream path'])('should prevent filename header injection from %s', async (source) => {
const filename = 'evil.txt"\r\nX-Injected: smuggled\r\nContent-Disposition: form-data; name="ghost';
const escaped = 'evil.txt%22%0D%0AX-Injected: smuggled%0D%0AContent-Disposition: form-data; name=%22ghost';
const field = source === 'stream path' ? 'file' : escaped;
const makeFiles = () => {
if (source === 'stream path') {
return Object.assign(Readable.from([Buffer.from('data')]), { path: filename });
}
return {
[filename]: source === 'buffer' ? Buffer.from('data') : Readable.from([Buffer.from('data')]),
};
};

const raw = await urllib.request(`${_url}raw`, { files: makeFiles(), dataType: 'text' });
assert.equal(raw.status, 200);
assert.ok(raw.data.includes(`Content-Disposition: form-data; name="${field}"; filename="${escaped}"\r\n`));
assert.doesNotMatch(raw.data, /\r\nX-Injected:/);
assert.equal(raw.data.match(/\r\nContent-Disposition:/g)?.length, 1);

const parsed = await urllib.request(`${_url}multipart`, {
files: makeFiles(),
data: { role: 'user' },
dataType: 'json',
});
assert.equal(parsed.status, 200);
assert.deepEqual(Object.keys(parsed.data.files), [field]);
assert.equal(parsed.data.files[field].filename, escaped);
assert.equal(parsed.data.files[field].size, 4);
assert.deepEqual(parsed.data.form, { role: 'user' });
});

it('should escape normal multipart field names', async () => {
const response = await urllib.request(`${_url}raw`, {
files: Buffer.from('data'),
data: { 'field"\r\nX-Injected: value': 'unchanged\r\nvalue' },
dataType: 'text',
});
assert.ok(response.data.includes('name="field%22%0D%0AX-Injected: value"\r\n'));
assert.ok(response.data.includes('\r\n\r\nunchanged\r\nvalue\r\n'));
assert.doesNotMatch(response.data, /\r\nX-Injected:/);
});
});
12 changes: 9 additions & 3 deletions test/options.timeout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,15 @@ describe('options.timeout.test.ts', () => {
// console.error(err);
assert.equal(err.name, 'HttpClientRequestTimeoutError');
assert.equal(err.message, 'Request timeout for 10 ms');
assert.equal(err.cause.name, 'InformationalError');
assert.equal(err.cause.message, 'HTTP/2: "stream timeout after 10"');
assert.equal(err.cause.code, 'UND_ERR_INFO');
// Newer Undici 7 releases use HeadersTimeoutError for HTTP/2 headers timeouts.
if (err.cause.name === 'HeadersTimeoutError') {
assert.equal(err.cause.message, 'HTTP/2: "headers timeout after 10"');
assert.equal(err.cause.code, 'UND_ERR_HEADERS_TIMEOUT');
} else {
assert.equal(err.cause.name, 'InformationalError');
assert.equal(err.cause.message, 'HTTP/2: "stream timeout after 10"');
assert.equal(err.cause.code, 'UND_ERR_INFO');
}

assert.equal(err.res.status, -1);
assert(err.res.rt > 10, `actual ${err.res.rt}`);
Expand Down
15 changes: 14 additions & 1 deletion test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
import { strict as assert } from 'node:assert';
import { Readable } from 'node:stream';

import { describe, it } from 'vite-plus/test';

import { globalId } from '../src/utils.js';
import { globalId, isReadable } from '../src/utils.js';

describe('utils.test.ts', () => {
describe('isReadable()', () => {
it('should return a boolean for streams and non-stream values', () => {
const stream = Readable.from(['hello']);
assert.equal(isReadable(stream), true);
stream.destroy();
assert.equal(isReadable(stream), false);
for (const value of [null, undefined, {}, 'hello', Buffer.from('hello')]) {
assert.equal(isReadable(value), false);
}
});
});

describe('globalId()', () => {
it('should auto increase', () => {
assert(globalId('unittest') === 1);
Expand Down
Loading