Skip to content

Commit f3ddede

Browse files
update: limit content-length to 10mb on api
This commit fixes the issue #149, by limiting the content-length. If it exceeds the value (10mb), will be rejected with code 413. Signed-off-by: toddynnn <86982643+ToddyTheNoobDud@users.noreply.github.com>
1 parent 3dff357 commit f3ddede

File tree

1 file changed

+53
-4
lines changed

1 file changed

+53
-4
lines changed

src/api/index.js

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,59 @@ async function requestHandler(nodelink, req, res) {
236236
}
237237
}
238238

239+
const MAX_BODY_SIZE = 10 * 1024 * 1024
240+
239241
let body = ''
240242
if (req.method !== 'GET') {
243+
const contentLength = parseInt(req.headers['content-length'])
244+
if (!isNaN(contentLength) && contentLength > MAX_BODY_SIZE) {
245+
logger(
246+
'warn',
247+
'Server',
248+
`Request rejected: Content-Length ${contentLength} exceeds limit of ${MAX_BODY_SIZE}`
249+
)
250+
sendErrorResponse(
251+
req,
252+
res,
253+
413,
254+
'Payload Too Large',
255+
'Request body is too large.',
256+
parsedUrl.pathname,
257+
trace
258+
)
259+
req.destroy()
260+
return
261+
}
262+
241263
await new Promise((resolve) => {
242-
req.on('data', (chunk) => {
264+
let receivedSize = 0
265+
266+
const onData = (chunk) => {
267+
receivedSize += chunk.length
268+
if (receivedSize > MAX_BODY_SIZE) {
269+
logger(
270+
'warn',
271+
'Server',
272+
`Request rejected: Body size exceeded limit of ${MAX_BODY_SIZE}`
273+
)
274+
req.removeListener('data', onData)
275+
req.removeListener('end', onEnd)
276+
sendErrorResponse(
277+
req,
278+
res,
279+
413,
280+
'Payload Too Large',
281+
'Request body is too large.',
282+
parsedUrl.pathname,
283+
trace
284+
)
285+
req.destroy()
286+
return
287+
}
243288
body += chunk.toString()
244-
})
245-
req.on('end', () => {
289+
}
290+
291+
const onEnd = () => {
246292
try {
247293
if (
248294
req.headers['content-type']?.includes('application/json') &&
@@ -268,7 +314,10 @@ async function requestHandler(nodelink, req, res) {
268314
return
269315
}
270316
resolve()
271-
})
317+
}
318+
319+
req.on('data', onData)
320+
req.on('end', onEnd)
272321
})
273322
}
274323
req.body = body

0 commit comments

Comments
 (0)