修复请求体按块拼接导致的中文乱码

readBody 原先逐块转成字符串拼接,跨块的多字节汉字被拆坏为替换字符(约72KB中文请求体即可复现),
替换字符还会虚增字节数,使接近上限的合法请求被误判为过大。
改为收集 Buffer、按累计字节数检查上限(仍超限即抛 413「内容过大」),收齐后一次性 UTF-8 解码;
同时去掉每块重新计算整段字节长度的平方级开销。非JSON与空请求体的处理不变。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 12:45:27 -08:00
1 parent a965becde3
commit e68e08b524
2 files changed
+72 -4

No files matched your search

+9 -4
View File
@@ -1,12 +1,17 @@
'use strict';
const { fail } = require('../../ledger');
// 保持原样(含按块拼接字符串的已知问题),修正留到下一阶段。
const LIMIT = 300000;
// 按字节累计、超限即拒绝;收齐后一次性按 UTF-8 解码,避免多字节字符被块边界截断。
async function readBody(req) {
let raw = '';
const chunks = [];
let size = 0;
for await (const chunk of req) {
raw += chunk;
if (Buffer.byteLength(raw) > 300000) fail('内容过大', 413);
const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
size += buffer.length;
if (size > LIMIT) fail('内容过大', 413);
chunks.push(buffer);
}
const raw = Buffer.concat(chunks, size).toString('utf8');
try {
return JSON.parse(raw || '{}');
} catch {