修复请求体按块拼接导致的中文乱码
readBody 原先逐块转成字符串拼接,跨块的多字节汉字被拆坏为替换字符(约72KB中文请求体即可复现), 替换字符还会虚增字节数,使接近上限的合法请求被误判为过大。 改为收集 Buffer、按累计字节数检查上限(仍超限即抛 413「内容过大」),收齐后一次性 UTF-8 解码; 同时去掉每块重新计算整段字节长度的平方级开销。非JSON与空请求体的处理不变。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a965becde3
commit
e68e08b524
2 files changed
+72
-4
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
const test = require('node:test'),
|
||||
assert = require('node:assert/strict'),
|
||||
http = require('node:http');
|
||||
const { readBody } = require('../server/middleware/body');
|
||||
|
||||
// 真实 HTTP:服务端用 readBody 解析后原样回显;客户端按奇数字节分段写出,让多字节汉字落在块边界上。
|
||||
async function echoServer(t) {
|
||||
const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const body = await readBody(req);
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify(body));
|
||||
} catch (e) {
|
||||
res.writeHead(e.status || 500, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify({ error: e.message }));
|
||||
}
|
||||
});
|
||||
await new Promise(r => server.listen(0, '127.0.0.1', r));
|
||||
t.after(() => new Promise(r => server.close(r)));
|
||||
return server.address().port;
|
||||
}
|
||||
function send(port, payload, pieceSize = 1001) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: '127.0.0.1', port, method: 'POST', path: '/' }, res => {
|
||||
const chunks = [];
|
||||
res.on('data', c => chunks.push(c));
|
||||
res.on('end', () =>
|
||||
resolve({ status: res.statusCode, body: JSON.parse(Buffer.concat(chunks).toString('utf8')) }),
|
||||
);
|
||||
});
|
||||
req.on('error', reject);
|
||||
const bytes = Buffer.from(payload);
|
||||
for (let i = 0; i < bytes.length; i += pieceSize) req.write(bytes.subarray(i, i + pieceSize));
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
test('约72KB中文JSON请求体经HTTP分块传输后原样还原', async t => {
|
||||
const port = await echoServer(t);
|
||||
const note = '足金手链金价工费备注,'.repeat(2200);
|
||||
const payload = JSON.stringify({ note, lines: [{ name: '古法金镯子(新款)', note: note.slice(0, 1000) }] });
|
||||
assert.ok(Buffer.byteLength(payload) > 72000 && Buffer.byteLength(payload) < 300000);
|
||||
for (const pieceSize of [1001, 16384, 65537]) {
|
||||
const r = await send(port, payload, pieceSize);
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.note, note);
|
||||
assert.ok(!JSON.stringify(r.body).includes('�'));
|
||||
assert.deepEqual(r.body, JSON.parse(payload));
|
||||
}
|
||||
});
|
||||
|
||||
test('请求体上限、非JSON与空请求体的处理不变', async t => {
|
||||
const port = await echoServer(t);
|
||||
const atLimit = JSON.stringify({ s: '汉'.repeat(99995) });
|
||||
assert.equal(Buffer.byteLength(atLimit), 299993);
|
||||
assert.equal((await send(port, atLimit)).status, 200);
|
||||
const over = JSON.stringify({ s: '汉'.repeat(99998) });
|
||||
assert.equal(Buffer.byteLength(over), 300002);
|
||||
assert.deepEqual(await send(port, over), { status: 413, body: { error: '内容过大' } });
|
||||
assert.deepEqual(await send(port, '{"a":'), { status: 400, body: { error: '请求内容不是有效JSON' } });
|
||||
assert.deepEqual(await send(port, ''), { status: 200, body: {} });
|
||||
});
|
||||
Reference in new issue
Block a user