Personal Telegram developer console for GitHub
security: cap editor JSON request streams by actual byte count
davoodmehraban89 committed
Oct 24, 2026 at 18:00 UTC
32cea0811506d32432d600b2d87829ba0ec70b0b
1 file changed
+30
src/core/bounded-json.js
new
+30
@@ -0,0 +1,30 @@
1
+export async function readBoundedJson(request, maxBytes) {
2
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError('Invalid request body limit');
3
+ const header = request.headers.get('content-length');
4
+ if (header !== null && (!/^(0|[1-9][0-9]*)$/.test(header) || Number(header) > maxBytes)) {
5
+ throw new RangeError('Editor request body is too large');
6
+ }
7
+ if (!request.body) throw new SyntaxError('Editor request body must be valid JSON');
8
+ const reader = request.body.getReader();
9
+ const chunks = [];
10
+ let total = 0;
11
+ try {
12
+ while (true) {
13
+ const { done, value } = await reader.read();
14
+ if (done) break;
15
+ total += value.byteLength;
16
+ if (total > maxBytes) throw new RangeError('Editor request body is too large');
17
+ chunks.push(value);
18
+ }
19
+ } catch (error) {
20
+ await reader.cancel().catch(() => {});
21
+ throw error;
22
+ } finally {
23
+ reader.releaseLock();
24
+ }
25
+ const bytes = new Uint8Array(total);
26
+ let offset = 0;
27
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
28
+ try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
29
+ catch { throw new SyntaxError('Editor request body must be valid JSON'); }
30
+}