Skip to content
Myr

body.test.ts

This file

Path

src/utils/body.test.ts

496 lines 路 14.5 KiB 路 TypeScript

Last changed by

Merge commit from forkTaku Amanobefore adoption531e9c5

History of this file

Take it

1import { parseBody } from './body'2import type { BodyData } from './body'34type RecursiveRecord<K extends string, T> = {5  [key in K]: T | RecursiveRecord<K, T>6}78describe('Parse Body Util', () => {9  const FORM_URL = 'https://localhost/form'10  const SEARCH_URL = 'https://localhost/search'1112  const createRequest = (13    url: string,14    method: 'POST',15    body: BodyInit,16    headers?: { [key: string]: string }17  ) => {18    return new Request(url, {19      method,20      body,21      headers,22    })23  }2425  const createNestedKey = (depth: number) =>26    Array(depth + 1)27      .fill('a')28      .join('.')2930  it('should parse `multipart/form-data`', async () => {31    const data = new FormData()32    data.append('message', 'hello')3334    const req = createRequest(FORM_URL, 'POST', data)3536    expect(await parseBody(req)).toEqual({ message: 'hello' })37  })3839  it('should parse `x-www-form-urlencoded`', async () => {40    const searchParams = new URLSearchParams()41    searchParams.append('message', 'hello')4243    const req = createRequest(SEARCH_URL, 'POST', searchParams, {44      'Content-Type': 'application/x-www-form-urlencoded',45    })4647    expect(await parseBody(req)).toEqual({ message: 'hello' })48  })4950  it('should parse mixed-case `x-www-form-urlencoded`', async () => {51    const searchParams = new URLSearchParams()52    searchParams.append('message', 'hello')5354    const req = createRequest(SEARCH_URL, 'POST', searchParams, {55      'Content-Type': 'Application/X-WWW-Form-Urlencoded',56    })5758    expect(await parseBody(req)).toEqual({ message: 'hello' })59  })6061  it('should parse mixed-case `multipart/form-data`', async () => {62    const data = new FormData()63    data.append('message', 'hello')6465    const source = createRequest(FORM_URL, 'POST', data)66    const contentType = source.headers67      .get('Content-Type')!68      .replace('multipart/form-data', 'Multipart/Form-Data')69    const req = createRequest(FORM_URL, 'POST', await source.arrayBuffer(), {70      'Content-Type': contentType,71    })7273    expect(await parseBody(req)).toEqual({ message: 'hello' })74  })7576  it('should not parse multiple values in default', async () => {77    const data = new FormData()78    data.append('file', 'bbb')79    data.append('message', 'hello')8081    const req = createRequest(FORM_URL, 'POST', data)8283    expect(await parseBody(req)).toEqual({84      file: 'bbb',85      message: 'hello',86    })87  })8889  it('should not update file object properties', async () => {90    const file = new File(['foo'], 'file1', {91      type: 'application/octet-stream',92    })93    const data = new FormData()94    data.append('file', file)95    data.append('file.hoo', 'hoo')9697    const req = createRequest(FORM_URL, 'POST', data)9899    const parsedData = await parseBody(req, { dot: true })100    expect(parsedData.file).not.instanceOf(File)101    expect(parsedData).toEqual({102      file: {103        hoo: 'hoo',104      },105    })106  })107108  it('should override value if `all` option is false', async () => {109    const data = new FormData()110    data.append('file', 'aaa')111    data.append('file', 'bbb')112    data.append('message', 'hello')113114    const req = createRequest(FORM_URL, 'POST', data)115116    expect(await parseBody(req)).toEqual({117      file: 'bbb',118      message: 'hello',119    })120  })121122  it('should parse multiple values if `all` option is true', async () => {123    const data = new FormData()124    data.append('file', 'aaa')125    data.append('file', 'bbb')126    data.append('message', 'hello')127128    const req = createRequest(FORM_URL, 'POST', data)129130    expect(await parseBody(req, { all: true })).toEqual({131      file: ['aaa', 'bbb'],132      message: 'hello',133    })134  })135136  it('should not parse nested values in default', async () => {137    const data = new FormData()138    data.append('obj.key1', 'value1')139    data.append('obj.key2', 'value2')140141    const req = createRequest(FORM_URL, 'POST', data)142143    expect(await parseBody(req, { dot: false })).toEqual({144      'obj.key1': 'value1',145      'obj.key2': 'value2',146    })147  })148149  it('should not parse nested values in default for non-nested keys', async () => {150    const data = new FormData()151    data.append('key1', 'value1')152    data.append('key2', 'value2')153154    const req = createRequest(FORM_URL, 'POST', data)155156    expect(await parseBody(req, { dot: false })).toEqual({157      key1: 'value1',158      key2: 'value2',159    })160  })161162  it('should handle nested values and non-nested values together with dot option true', async () => {163    const data = new FormData()164    data.append('obj.key1', 'value1')165    data.append('obj.key2', 'value2')166    data.append('key3', 'value3')167168    const req = createRequest(FORM_URL, 'POST', data)169170    expect(await parseBody(req, { dot: true })).toEqual({171      obj: { key1: 'value1', key2: 'value2' },172      key3: 'value3',173    })174  })175176  it('should handle deeply nested objects with dot option true', async () => {177    const data = new FormData()178    data.append('a.b.c.d', 'value')179180    const req = createRequest(FORM_URL, 'POST', data)181182    expect(await parseBody(req, { dot: true })).toEqual({183      a: { b: { c: { d: 'value' } } },184    })185  })186187  it('should allow 32 nesting levels by default', async () => {188    const data = new FormData()189    data.append(createNestedKey(32), 'value')190191    const req = createRequest(FORM_URL, 'POST', data)192    let nested: unknown = await parseBody(req, { dot: true })193194    for (let i = 0; i <= 32; i++) {195      nested = (nested as Record<string, unknown>).a196    }197    expect(nested).toBe('value')198  })199200  it('should reject dot notation deeper than the default limit', async () => {201    const data = new FormData()202    data.append(createNestedKey(33), 'value')203204    const req = createRequest(FORM_URL, 'POST', data)205206    await expect(parseBody(req, { dot: true })).rejects.toThrow('Nesting limit exceeded')207  })208209  it('should reject deeply nested keys without splitting every segment', async () => {210    const req = createRequest(SEARCH_URL, 'POST', `${'.'.repeat(65_530)}=value`, {211      'Content-Type': 'application/x-www-form-urlencoded',212    })213214    await expect(parseBody(req, { dot: true })).rejects.toThrow('Nesting limit exceeded')215  })216217  it('should reject too many nested objects across multiple fields', async () => {218    const searchParams = new URLSearchParams()219    for (let i = 0; i <= 10_000; i++) {220      searchParams.append(`field${i}.value`, 'value')221    }222223    const req = createRequest(SEARCH_URL, 'POST', searchParams, {224      'Content-Type': 'application/x-www-form-urlencoded',225    })226227    await expect(parseBody(req, { dot: true })).rejects.toThrow('Nesting limit exceeded')228  })229230  it('should skip keys starting with __proto__. to prevent prototype pollution', async () => {231    const data = new FormData()232    data.append('__proto__.polluted', 'malicious')233234    const req = createRequest(FORM_URL, 'POST', data)235236    expect(await parseBody(req, { dot: true })).toEqual({})237  })238239  it('should skip keys containing nested __proto__. to prevent prototype pollution', async () => {240    const data = new FormData()241    data.append('a.__proto__.polluted', 'malicious')242243    const req = createRequest(FORM_URL, 'POST', data)244245    expect(await parseBody(req, { dot: true })).toEqual({})246  })247248  it('should not pollute Object.prototype via __proto__ keys', async () => {249    const data = new FormData()250    data.append('__proto__.injected', 'yes')251    data.append('a.__proto__.injected', 'yes')252253    const req = createRequest(FORM_URL, 'POST', data)254255    await parseBody(req, { dot: true })256257    expect(({} as Record<string, unknown>).injected).toBeUndefined()258  })259260  it('should parse key ending with __proto__ as a normal value', async () => {261    const data = new FormData()262    data.append('a.__proto__', 'value')263264    const req = createRequest(FORM_URL, 'POST', data)265266    const result = await parseBody(req, { dot: true })267    expect(result).toHaveProperty('a')268    expect(269      Object.getOwnPropertyDescriptor(270        (result as Record<string, Record<string, string>>).a,271        '__proto__'272      )?.value273    ).toBe('value')274  })275276  it('should parse key containing __proto__ as a substring normally', async () => {277    const data = new FormData()278    data.append('data__proto__key.value', 'test')279280    const req = createRequest(FORM_URL, 'POST', data)281282    expect(await parseBody(req, { dot: true })).toEqual({283      data__proto__key: { value: 'test' },284    })285  })286287  it('should parse nested values if `dot` option is true', async () => {288    const data = new FormData()289    data.append('obj.key1', 'value1')290    data.append('obj.key2', 'value2')291292    const req = createRequest(FORM_URL, 'POST', data)293294    expect(await parseBody(req, { dot: true })).toEqual({295      obj: { key1: 'value1', key2: 'value2' },296    })297  })298299  it('should parse data if both `all` and `dot` are set', async () => {300    const data = new FormData()301    data.append('obj.sub.foo', 'value1')302    data.append('obj.sub.foo', 'value2')303    data.append('key', 'value3')304305    const req = createRequest(FORM_URL, 'POST', data)306307    expect(await parseBody(req, { dot: true, all: true })).toEqual({308      obj: { sub: { foo: ['value1', 'value2'] } },309      key: 'value3',310    })311  })312313  it('should parse nested values if values are `File`', async () => {314    const file1 = new File(['foo'], 'file1', {315      type: 'application/octet-stream',316    })317    const file2 = new File(['bar'], 'file2', {318      type: 'application/octet-stream',319    })320    const data = new FormData()321    data.append('file.file1', file1)322    data.append('file.file2', file2)323324    const req = createRequest(FORM_URL, 'POST', data)325326    const result = await parseBody(req, { all: true, dot: true })327    expect(result).toMatchObject({328      file: {329        file1: { name: 'file1', type: 'application/octet-stream' },330        file2: { name: 'file2', type: 'application/octet-stream' },331      },332    })333  })334335  it('should parse multiple values if values are `File`', async () => {336    const file1 = new File(['foo'], 'file1', {337      type: 'application/octet-stream',338    })339    const file2 = new File(['bar'], 'file2', {340      type: 'application/octet-stream',341    })342    const data = new FormData()343    data.append('file', file1)344    data.append('file', file2)345346    const req = createRequest(FORM_URL, 'POST', data)347348    const result = await parseBody(req, { all: true })349    expect(result).toMatchObject({350      file: [351        { name: 'file1', type: 'application/octet-stream' },352        { name: 'file2', type: 'application/octet-stream' },353      ],354    })355  })356357  it('should parse multiple values if key ends with `[]`', async () => {358    const data = new FormData()359    data.append('file[]', 'aaa')360    data.append('file[]', 'bbb')361    data.append('message', 'hello')362363    const req = createRequest(FORM_URL, 'POST', data)364365    expect(await parseBody(req, { all: true })).toEqual({366      'file[]': ['aaa', 'bbb'],367      message: 'hello',368    })369  })370371  it('should parse single value as array if the key has `[]`', async () => {372    const data = new FormData()373    data.append('foo[]', 'bar')374    const req = createRequest(FORM_URL, 'POST', data)375376    expect(await parseBody(req, { all: true })).toEqual({377      'foo[]': ['bar'],378    })379  })380381  it('should return blank object if body is JSON', async () => {382    const payload = { message: 'hello hono' }383384    const req = createRequest('http://localhost/json', 'POST', JSON.stringify(payload), {385      'Content-Type': 'application/json',386    })387388    expect(await parseBody(req)).toEqual({})389  })390391  describe('Return type', () => {392    let req: Request393    beforeEach(() => {394      req = createRequest(FORM_URL, 'POST', new FormData())395    })396397    it('without options', async () => {398      expectTypeOf((await parseBody(req))['key']).toEqualTypeOf<string | File>()399    })400401    it('{all: true}', async () => {402      expectTypeOf((await parseBody(req, { all: true }))['key']).toEqualTypeOf<403        string | File | (string | File)[]404      >()405    })406407    it('{all: boolean}', async () => {408      expectTypeOf((await parseBody(req, { all: !!Math.random() }))['key']).toEqualTypeOf<409        string | File | (string | File)[]410      >()411    })412413    it('{dot: true}', async () => {414      expectTypeOf((await parseBody(req, { dot: true }))['key']).toEqualTypeOf<415        string | File | RecursiveRecord<string, string | File>416      >()417    })418419    it('{dot: boolean}', async () => {420      expectTypeOf((await parseBody(req, { dot: !!Math.random() }))['key']).toEqualTypeOf<421        string | File | RecursiveRecord<string, string | File>422      >()423    })424425    it('{all: true, dot: true}', async () => {426      expectTypeOf((await parseBody(req, { all: true, dot: true }))['key']).toEqualTypeOf<427        | string428        | File429        | (string | File)[]430        | RecursiveRecord<string, string | File | (string | File)[]>431      >()432    })433434    it('{all: boolean, dot: boolean}', async () => {435      expectTypeOf(436        (await parseBody(req, { all: !!Math.random(), dot: !!Math.random() }))['key']437      ).toEqualTypeOf<438        | string439        | File440        | (string | File)[]441        | RecursiveRecord<string, string | File | (string | File)[]>442      >()443    })444445    it('specify return type explicitly', async () => {446      expectTypeOf(447        await parseBody<{ key1: string; key2: string }>(req, {448          all: !!Math.random(),449          dot: !!Math.random(),450        })451      ).toEqualTypeOf<{ key1: string; key2: string }>()452    })453  })454})455456describe('BodyData', () => {457  it('without options', async () => {458    expectTypeOf(({} as BodyData)['key']).toEqualTypeOf<string | File>()459  })460461  it('{all: true}', async () => {462    expectTypeOf(({} as BodyData<{ all: true }>)['key']).toEqualTypeOf<463      string | File | (string | File)[]464    >()465  })466467  it('{all: boolean}', async () => {468    expectTypeOf(({} as BodyData<{ all: boolean }>)['key']).toEqualTypeOf<469      string | File | (string | File)[]470    >()471  })472473  it('{dot: true}', async () => {474    expectTypeOf(({} as BodyData<{ dot: true }>)['key']).toEqualTypeOf<475      string | File | RecursiveRecord<string, string | File>476    >()477  })478479  it('{dot: boolean}', async () => {480    expectTypeOf(({} as BodyData<{ dot: boolean }>)['key']).toEqualTypeOf<481      string | File | RecursiveRecord<string, string | File>482    >()483  })484485  it('{all: true, dot: true}', async () => {486    expectTypeOf(({} as BodyData<{ all: true; dot: true }>)['key']).toEqualTypeOf<487      string | File | (string | File)[] | RecursiveRecord<string, string | File | (string | File)[]>488    >()489  })490491  it('{all: boolean, dot: boolean}', async () => {492    expectTypeOf(({} as BodyData<{ all: boolean; dot: boolean }>)['key']).toEqualTypeOf<493      string | File | (string | File)[] | RecursiveRecord<string, string | File | (string | File)[]>494    >()495  })496})