Skip to content

Commit 9aeb45b

Browse files
authored
Merge commit from fork
1 parent b0af6bb commit 9aeb45b

2 files changed

Lines changed: 28 additions & 14 deletions

File tree

‎src/middleware/body-limit/index.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,24 @@ describe('Body Limit Middleware', () => {
8181
expect(await res.text()).toBe('abc')
8282
})
8383

84+
it('should pass a body sent in many tiny chunks', async () => {
85+
const app = new Hono()
86+
app.use('*', bodyLimit({ maxSize: 10000 }))
87+
app.post('/', async (c) => c.text(String((await c.req.text()).length)))
88+
const stream = new ReadableStream({
89+
start(controller) {
90+
for (let i = 0; i < 10000; i++) {
91+
controller.enqueue(new Uint8Array([120]))
92+
}
93+
controller.close()
94+
},
95+
})
96+
const res = await app.request('/', buildRequestInit({ body: stream }))
97+
98+
expect(res.status).toBe(200)
99+
expect(await res.text()).toBe('10000')
100+
})
101+
84102
it('should return 413 response', async () => {
85103
const readSpy = vi.fn().mockImplementation(() => {
86104
return {

‎src/middleware/body-limit/index.ts‎

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -78,33 +78,29 @@ export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => {
7878
// and Content-Length is ignored. Read the body up-front so the size check
7979
// is final before the handler runs, regardless of how (or whether) the
8080
// handler reads the body.
81+
// One growing buffer: keeping every chunk lets a body sent in tiny chunks exhaust memory
8182
let size = 0
82-
const chunks: Uint8Array[] = []
83+
let buffer = new Uint8Array(0)
8384
const rawReader = c.req.raw.body.getReader()
8485
for (;;) {
8586
const { done, value } = await rawReader.read()
8687
if (done) {
8788
break
8889
}
90+
const offset = size
8991
size += value.length
9092
if (size > maxSize) {
9193
return onError(c)
9294
}
93-
chunks.push(value)
95+
if (size > buffer.length) {
96+
const grown = new Uint8Array(Math.min(maxSize, Math.max(size, buffer.length * 2)))
97+
grown.set(buffer.subarray(0, offset))
98+
buffer = grown
99+
}
100+
buffer.set(value, offset)
94101
}
95102

96-
const requestInit: RequestInit & { duplex: 'half' } = {
97-
body: new ReadableStream({
98-
start(controller) {
99-
for (const chunk of chunks) {
100-
controller.enqueue(chunk)
101-
}
102-
controller.close()
103-
},
104-
}),
105-
duplex: 'half',
106-
}
107-
c.req.raw = new Request(c.req.raw, requestInit as RequestInit)
103+
c.req.raw = new Request(c.req.raw, { body: buffer.subarray(0, size) })
108104

109105
return next()
110106
}

0 commit comments

Comments
 (0)