import { afterAll, beforeAll, describe, it } from 'bun:test'; import { expect } from 'chai'; import { createServer, Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { gzipSync } from 'node:zlib'; import { BodyParser, parseBytes } from './body-parser'; import { BodyOptions } from './body-protocol'; import { HttpError } from '../error/http-error'; /** A server that parses each request with the options in the x-options header and answers with what it got. */ let server: Server; let url: string; beforeAll(async () => { server = createServer(async (req, res) => { const options: BodyOptions = JSON.parse(String(req.headers['x-options'] || '{}')); try { await new BodyParser(options).parse(req); const body = (req as any).body; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ type: Buffer.isBuffer(body) ? 'buffer' : typeof body, body: Buffer.isBuffer(body) ? body.toString('hex') : body })); } catch (error) { res.statusCode = error instanceof HttpError ? error.statusCode : 500; res.end(String((error as Error).message)); } }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; }); afterAll(() => server.close()); async function post(body: BodyInit | undefined, headers: Record = {}, options: BodyOptions = {}) { const res = await fetch(url, { method: body === undefined ? 'GET' : 'POST', body, headers: { ...headers, 'x-options': JSON.stringify(options) } }); const text = await res.text(); return { status: res.status, ...(res.status === 200 ? JSON.parse(text) : { message: text }) }; } describe('BodyParser', () => { it('parses JSON', async () => { expect(await post('{"a":[1,2]}', { 'content-type': 'application/json' })).to.deep.equal({ status: 200, type: 'object', body: { a: [1, 2] } }); expect(await post('', { 'content-type': 'application/json; charset=utf-8' })).to.deep.include({ status: 200, body: {} }); }); it('refuses malformed and, when strict, non-object JSON', async () => { expect((await post('{a', { 'content-type': 'application/json' })).status).to.equal(400); expect((await post('"text"', { 'content-type': 'application/json' })).status).to.equal(400); expect(await post('"text"', { 'content-type': 'application/json' }, { strict: false })).to.deep.include({ status: 200, body: 'text' }); }); it('parses text, raw and forms', async () => { expect(await post('héllo', { 'content-type': 'text/plain' })).to.deep.include({ type: 'string', body: 'héllo' }); expect(await post(new Uint8Array([0xe9]), { 'content-type': 'text/plain; charset=latin1' })).to.deep.include({ body: 'é' }); expect(await post(new Uint8Array([1, 2, 255]), { 'content-type': 'application/octet-stream' })).to.deep.include({ type: 'buffer', body: '0102ff' }); expect(await post('a[b]=1&c=x+y', { 'content-type': 'application/x-www-form-urlencoded' })).to.deep.include({ body: { a: { b: '1' }, c: 'x y' } }); }); it('gives {} to requests without a body or of another type', async () => { expect(await post(undefined)).to.deep.include({ status: 200, body: {} }); expect(await post('', { 'content-type': 'application/xml' })).to.deep.include({ status: 200, body: {} }); }); it('decompresses gzip unless inflate is off', async () => { const body = new Uint8Array(gzipSync('{"zipped":true}')); expect(await post(body, { 'content-type': 'application/json', 'content-encoding': 'gzip' })).to.deep.include({ body: { zipped: true } }); expect((await post(body, { 'content-type': 'application/json', 'content-encoding': 'gzip' }, { inflate: false })).status).to.equal(415); expect((await post(body, { 'content-type': 'application/json', 'content-encoding': 'compress' })).status).to.equal(415); expect((await post('not gzip', { 'content-type': 'application/json', 'content-encoding': 'gzip' })).status).to.equal(400); }); it('refuses bodies over the limit, also after decompression', async () => { expect((await post('x'.repeat(2048), { 'content-type': 'text/plain' }, { limit: '1kb' })).status).to.equal(413); expect((await post(new Uint8Array(gzipSync('x'.repeat(4096))), { 'content-type': 'text/plain', 'content-encoding': 'gzip' }, { limit: '1kb' })).status).to.equal(413); expect(await post('x'.repeat(1024), { 'content-type': 'text/plain' }, { limit: '1kb' })).to.deep.include({ status: 200 }); }); it('refuses unsupported charsets and too many form parameters', async () => { expect((await post('{}', { 'content-type': 'application/json; charset=latin1' })).status).to.equal(415); expect((await post('a=1', { 'content-type': 'application/x-www-form-urlencoded; charset=latin1' })).status).to.equal(415); expect((await post('a=1&b=2&c=3', { 'content-type': 'application/x-www-form-urlencoded' }, { parameterLimit: 2 })).status).to.equal(413); }); it('reads sizes', () => { expect(parseBytes('100kb')).to.equal(102400); expect(parseBytes('5mb')).to.equal(5 * 1024 * 1024); expect(parseBytes('1.5KB')).to.equal(1536); expect(parseBytes(10)).to.equal(10); expect(() => parseBytes('lots')).to.throw(TypeError); }); it('leaves a body that was already read', async () => { const request = { _body: true, body: 'kept', headers: { 'content-length': '3', 'content-type': 'text/plain' } }; await new BodyParser().parse(request); expect(request.body).to.equal('kept'); }); });