diff --git a/.github/workflows/nodejs-old-versions.yml b/.github/workflows/nodejs-old-versions.yml index 58c90150..01c4194a 100644 --- a/.github/workflows/nodejs-old-versions.yml +++ b/.github/workflows/nodejs-old-versions.yml @@ -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: @@ -19,10 +19,10 @@ 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: | @@ -30,7 +30,12 @@ jobs: 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 diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 6ad3d8b1..080e443a 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -2,9 +2,9 @@ name: CI on: push: - branches: [master] + branches: ['4.x'] pull_request: - branches: [master] + branches: ['4.x'] merge_group: jobs: diff --git a/package.json b/package.json index 9a76c0e0..dfad0003 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 61a8b117..6cf74e4a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,11 +13,11 @@ importers: .: dependencies: form-data: - specifier: ^4.0.5 - version: 4.0.5 + specifier: ^4.0.6 + version: 4.0.6 formstream: - specifier: ^1.5.2 - version: 1.5.2 + specifier: ^1.5.3 + version: 1.5.3 mime-types: specifier: ^2.1.35 version: 2.1.35 @@ -652,6 +652,7 @@ packages: '@ungap/structured-clone@1.3.0': resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} + deprecated: Potential CWE-502 - Update to 1.3.1 or higher '@vitest/coverage-v8@4.1.2': resolution: {integrity: sha512-sPK//PHO+kAkScb8XITeB1bf7fsk85Km7+rt4eeuRR3VS1/crD47cmV5wicisJmjNdfeokTZwjMk4Mj2d58Mgg==} @@ -1086,12 +1087,12 @@ packages: resolution: {integrity: sha512-yeXZaNbCBGaT9giTpLPBdtedzjwhlJBUoL/R4BVQU5mn0TQXOHwVIl1Q2DMuBIdNno4ktA1abZ7dQFVxD6uHxw==} engines: {node: '>=16'} - form-data@4.0.5: - resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==} + form-data@4.0.6: + resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} engines: {node: '>= 6'} - formstream@1.5.2: - resolution: {integrity: sha512-NASf0lgxC1AyKNXQIrXTEYkiX99LhCEXTkiGObXAkpBui86a4u8FjH1o2bGb3PpqI3kafC+yw4zWeK6l6VHTgg==} + formstream@1.5.3: + resolution: {integrity: sha512-dho1DOEYWII8HXtnUg3EKm9vcMxaOgF469psDkq9SIcb0KHtl16fQX5toylxnomL1K5pCJDaVrx/LIXtapEluQ==} fs-constants@1.0.0: resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} @@ -1170,8 +1171,8 @@ packages: resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} engines: {node: '>= 0.4'} - hasown@2.0.2: - resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} engines: {node: '>= 0.4'} highlight.js@10.7.3: @@ -2661,7 +2662,7 @@ snapshots: has-property-descriptors: 1.0.2 has-proto: 1.2.0 has-symbols: 1.1.0 - hasown: 2.0.2 + hasown: 2.0.4 internal-slot: 1.1.0 is-array-buffer: 3.0.5 is-callable: 1.2.7 @@ -2709,7 +2710,7 @@ snapshots: es-errors: 1.3.0 get-intrinsic: 1.3.0 has-tostringtag: 1.0.2 - hasown: 2.0.2 + hasown: 2.0.4 es-to-primitive@1.3.0: dependencies: @@ -2739,15 +2740,15 @@ snapshots: dependencies: signal-exit: 4.1.0 - form-data@4.0.5: + form-data@4.0.6: dependencies: asynckit: 0.4.0 combined-stream: 1.0.8 es-set-tostringtag: 2.1.0 - hasown: 2.0.2 + hasown: 2.0.4 mime-types: 2.1.35 - formstream@1.5.2: + formstream@1.5.3: dependencies: destroy: 1.2.0 mime: 2.6.0 @@ -2767,7 +2768,7 @@ snapshots: call-bound: 1.0.4 define-properties: 1.2.1 functions-have-names: 1.2.3 - hasown: 2.0.2 + hasown: 2.0.4 is-callable: 1.2.7 functions-have-names@1.2.3: {} @@ -2786,7 +2787,7 @@ snapshots: get-proto: 1.0.1 gopd: 1.2.0 has-symbols: 1.1.0 - hasown: 2.0.2 + hasown: 2.0.4 math-intrinsics: 1.1.0 get-proto@1.0.1: @@ -2833,7 +2834,7 @@ snapshots: dependencies: has-symbols: 1.1.0 - hasown@2.0.2: + hasown@2.0.4: dependencies: function-bind: 1.1.2 @@ -2852,7 +2853,7 @@ snapshots: internal-slot@1.1.0: dependencies: es-errors: 1.3.0 - hasown: 2.0.2 + hasown: 2.0.4 side-channel: 1.1.0 is-array-buffer@3.0.5: @@ -2919,7 +2920,7 @@ snapshots: call-bound: 1.0.4 gopd: 1.2.0 has-tostringtag: 1.0.2 - hasown: 2.0.2 + hasown: 2.0.4 is-set@2.0.3: {} diff --git a/src/FormData.ts b/src/FormData.ts index d67d6844..556b4e70 100644 --- a/src/FormData.ts +++ b/src/FormData.ts @@ -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); } } diff --git a/src/utils.ts b/src/utils.ts index a8eb477d..5e568199 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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 diff --git a/test/formData.test.ts b/test/formData.test.ts new file mode 100644 index 00000000..d647c339 --- /dev/null +++ b/test/formData.test.ts @@ -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')); + }); +}); diff --git a/test/options.files.test.ts b/test/options.files.test.ts index 240bba6f..39d3e440 100644 --- a/test/options.files.test.ts +++ b/test/options.files.test.ts @@ -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:/); + }); }); diff --git a/test/options.timeout.test.ts b/test/options.timeout.test.ts index 4cefec6c..8d459bd3 100644 --- a/test/options.timeout.test.ts +++ b/test/options.timeout.test.ts @@ -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}`); diff --git a/test/utils.test.ts b/test/utils.test.ts index 08a0f59e..f3762c48 100644 --- a/test/utils.test.ts +++ b/test/utils.test.ts @@ -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);