fix(panel): align bridge export body limits and cap Excel cell text

- Raise BRIDGE_MAX_EXPORT_BODY_BYTES to 12 MiB so 8 MiB Base64-encoded exports and verified __exportFileAction /api/settings fallbacks are not rejected with 413.
- Cap xlsxBuilder inline string cells at Excel's 32,767 UTF-16 code unit limit without splitting surrogate pairs and replace lone surrogates.
This commit is contained in:
fish
2026-11-24 16:13:42 +09:00
parent a5f9068f89
commit 0b700d1f9f
6 changed files with 165 additions and 16 deletions
+26 -6
View File
@@ -6161,7 +6161,7 @@ return { triggerBlobDownload, triggerTextFileDownload, buildExportableSettingsJs
})(); })();
// --- src/core/xlsxBuilder.js --- // --- src/core/xlsxBuilder.js ---
const { uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { const { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => {
/** /**
* @fileoverview 零外部依赖原生 Excel (`.xlsx` / ECMA-376 OOXML) 多工作表构建器 (`xlsxBuilder.js`)。 * @fileoverview 零外部依赖原生 Excel (`.xlsx` / ECMA-376 OOXML) 多工作表构建器 (`xlsxBuilder.js`)。
* 内置标准 IEEE 802.3 CRC-32 及 ZIP STORE 封装,支持: * 内置标准 IEEE 802.3 CRC-32 及 ZIP STORE 封装,支持:
@@ -6172,7 +6172,10 @@ const { uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => {
* - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。 * - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。
*/ */
const MAX_EXCEL_CELL_CHARS = 32767;
const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g; const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g;
const LONE_SURROGATE_RE =
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
const INVALID_SHEET_NAME_RE = /[\\/?*[\]:]/g; const INVALID_SHEET_NAME_RE = /[\\/?*[\]:]/g;
// --- 样式索引常量(对应下方 STYLES_XML 中的 cellXfs 顺序) --- // --- 样式索引常量(对应下方 STYLES_XML 中的 cellXfs 顺序) ---
@@ -6368,9 +6371,24 @@ function buildZipStoreArchive(entries) {
return archive; return archive;
} }
function escapeXmlText(val) { function sanitizeExcelCellText(val) {
return String(val ?? '') const clean = String(val ?? '')
.replace(INVALID_XML_CTRL_RE, '') .replace(INVALID_XML_CTRL_RE, '')
.replace(LONE_SURROGATE_RE, '\uFFFD');
if (clean.length <= MAX_EXCEL_CELL_CHARS) {
return clean;
}
// 桌面版 Excel 单格文本硬上限为 32,767 UTF-16 码元;预留 1 位给省略号并避免劈断代理对
let cut = MAX_EXCEL_CELL_CHARS - 1;
const prevCode = clean.charCodeAt(cut - 1);
if (prevCode >= 0xd800 && prevCode <= 0xdbff) {
cut -= 1;
}
return `${clean.slice(0, cut)}…`;
}
function escapeXmlText(val) {
return sanitizeExcelCellText(val)
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
.replace(/>/g, '&gt;') .replace(/>/g, '&gt;')
@@ -6390,10 +6408,12 @@ function columnIndexToLetter(index) {
} }
/** /**
* 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。 * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽;
* 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。
*/ */
function measureExcelVisualWidth(str) { function measureExcelVisualWidth(str) {
const s = String(str ?? '').replace(/\r?\n/g, ' '); const raw = String(str ?? '');
const s = (raw.length > 128 ? raw.slice(0, 128) : raw).replace(/\r?\n/g, ' ');
let w = 0; let w = 0;
for (let i = 0; i < s.length; i += 1) { for (let i = 0; i < s.length; i += 1) {
const code = s.charCodeAt(i); const code = s.charCodeAt(i);
@@ -6805,7 +6825,7 @@ function buildXlsxWorkbookBytes(sheets) {
return buildZipStoreArchive(archiveEntries); return buildZipStoreArchive(archiveEntries);
} }
return { uint8ArrayToBase64, buildXlsxWorkbookBytes }; return { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes };
})(); })();
// --- src/core/reportExporter.js --- // --- src/core/reportExporter.js ---
+33 -3
View File
@@ -71,7 +71,8 @@ const overlayMethods = Object.fromEntries(
); );
const BRIDGE_MAX_BODY_BYTES = 64 * 1024; const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
const BRIDGE_MAX_EXPORT_BODY_BYTES = 8 * 1024 * 1024; // 8 MiB 原始导出文件经 Base64 (4/3x) 编码和 JSON 封装后约 10.7 MiB,预留 12 MiB 请求体上限
const BRIDGE_MAX_EXPORT_BODY_BYTES = 12 * 1024 * 1024;
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS); const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
/** /**
@@ -1343,17 +1344,34 @@ export function createWindowBridgeController(options) {
return; return;
} }
const maxBodyBytes = let maxBodyBytes =
parsedUrl.pathname === '/api/export-file' parsedUrl.pathname === '/api/export-file'
? BRIDGE_MAX_EXPORT_BODY_BYTES ? BRIDGE_MAX_EXPORT_BODY_BYTES
: BRIDGE_MAX_BODY_BYTES; : BRIDGE_MAX_BODY_BYTES;
const chunks = []; const chunks = [];
let totalBytes = 0; let totalBytes = 0;
let aborted = false; let aborted = false;
let checkedSettingsExportPrefix = false;
req.on('data', (chunk) => { req.on('data', (chunk) => {
totalBytes += chunk.length; const nextTotal = totalBytes + chunk.length;
if (
nextTotal > maxBodyBytes &&
!checkedSettingsExportPrefix &&
parsedUrl.pathname === '/api/settings' &&
nextTotal <= BRIDGE_MAX_EXPORT_BODY_BYTES
) {
checkedSettingsExportPrefix = true;
const sampleParts = chunks.length > 0 ? [...chunks, chunk] : [chunk];
const headBuf = Buffer.concat(sampleParts, Math.min(nextTotal, 512));
const headStr = headBuf.toString('utf8').trimStart();
if (/^\{\s*"__exportFileAction"\s*:\s*"(?:save|reveal)"/.test(headStr)) {
maxBodyBytes = BRIDGE_MAX_EXPORT_BODY_BYTES;
}
}
totalBytes = nextTotal;
if (totalBytes > maxBodyBytes) { if (totalBytes > maxBodyBytes) {
aborted = true; aborted = true;
chunks.length = 0;
res.writeHead(413, { 'Content-Type': 'application/json' }); res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload too large' })); res.end(JSON.stringify({ error: 'Payload too large' }));
req.destroy(); req.destroy();
@@ -1372,6 +1390,18 @@ export function createWindowBridgeController(options) {
res.end(JSON.stringify({ error: 'Invalid JSON body' })); res.end(JSON.stringify({ error: 'Invalid JSON body' }));
return; return;
} }
if (
totalBytes > BRIDGE_MAX_BODY_BYTES &&
parsedUrl.pathname === '/api/settings' &&
(!bodyObj ||
typeof bodyObj !== 'object' ||
Array.isArray(bodyObj) ||
typeof bodyObj.__exportFileAction !== 'string')
) {
res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload too large' }));
return;
}
Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'POST', bodyObj, normalizedReqEndpoint)) Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'POST', bodyObj, normalizedReqEndpoint))
.then((out) => { .then((out) => {
const hdrs = { const hdrs = {
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title> <title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795501504789"> <link rel="stylesheet" href="/styles.css?v=1795504410473">
<script src="/preload.js"></script> <script src="/preload.js"></script>
</head> </head>
<body> <body>
<div id="app-root"></div> <div id="app-root"></div>
<script src="/app.js?v=1795501504789"></script> <script src="/app.js?v=1795504410473"></script>
</body> </body>
</html> </html>
+24 -4
View File
@@ -8,7 +8,10 @@
* - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。 * - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。
*/ */
export const MAX_EXCEL_CELL_CHARS = 32767;
const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g; const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g;
const LONE_SURROGATE_RE =
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
const INVALID_SHEET_NAME_RE = /[\\/?*[\]:]/g; const INVALID_SHEET_NAME_RE = /[\\/?*[\]:]/g;
// --- 样式索引常量(对应下方 STYLES_XML 中的 cellXfs 顺序) --- // --- 样式索引常量(对应下方 STYLES_XML 中的 cellXfs 顺序) ---
@@ -204,9 +207,24 @@ function buildZipStoreArchive(entries) {
return archive; return archive;
} }
function escapeXmlText(val) { function sanitizeExcelCellText(val) {
return String(val ?? '') const clean = String(val ?? '')
.replace(INVALID_XML_CTRL_RE, '') .replace(INVALID_XML_CTRL_RE, '')
.replace(LONE_SURROGATE_RE, '\uFFFD');
if (clean.length <= MAX_EXCEL_CELL_CHARS) {
return clean;
}
// 桌面版 Excel 单格文本硬上限为 32,767 UTF-16 码元;预留 1 位给省略号并避免劈断代理对
let cut = MAX_EXCEL_CELL_CHARS - 1;
const prevCode = clean.charCodeAt(cut - 1);
if (prevCode >= 0xd800 && prevCode <= 0xdbff) {
cut -= 1;
}
return `${clean.slice(0, cut)}…`;
}
function escapeXmlText(val) {
return sanitizeExcelCellText(val)
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
.replace(/>/g, '&gt;') .replace(/>/g, '&gt;')
@@ -226,10 +244,12 @@ function columnIndexToLetter(index) {
} }
/** /**
* 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。 * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽;
* 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。
*/ */
function measureExcelVisualWidth(str) { function measureExcelVisualWidth(str) {
const s = String(str ?? '').replace(/\r?\n/g, ' '); const raw = String(str ?? '');
const s = (raw.length > 128 ? raw.slice(0, 128) : raw).replace(/\r?\n/g, ' ');
let w = 0; let w = 0;
for (let i = 0; i < s.length; i += 1) { for (let i = 0; i < s.length; i += 1) {
const code = s.charCodeAt(i); const code = s.charCodeAt(i);
@@ -1641,3 +1641,35 @@ test('i18n static t(...) key completeness guard, scopeAll formatters, and locali
globalThis.window = prevWin; globalThis.window = prevWin;
} }
}); });
test('xlsxBuilder enforces 32,767 UTF-16 cell limit without splitting surrogate pairs or emitting lone surrogates', async () => {
const { buildXlsxWorkbookBytes, MAX_EXCEL_CELL_CHARS } = await import('../src/core/xlsxBuilder.js');
assert.equal(MAX_EXCEL_CELL_CHARS, 32767);
// Place an emoji ('😀' = \uD83D\uDE00, 2 UTF-16 code units) straddling index 32765..32766
const boundaryEmojiText = `${'A'.repeat(32765)}😀${'B'.repeat(500)}`;
const loneSurrogateText = `ok\uD800mid\uDC00end`;
const bytes = buildXlsxWorkbookBytes([
{
name: 'OverflowGuard',
columns: [{ header: 'TextCol', type: 'text' }],
rows: [[boundaryEmojiText], [loneSurrogateText]],
},
]);
const rawArchiveStr = Buffer.from(bytes).toString('utf8');
const cellMatches = [...rawArchiveStr.matchAll(/<c r="A[23]"[^>]*><is><t[^>]*>([\s\S]*?)<\/t><\/is><\/c>/g)];
assert.equal(cellMatches.length, 2);
const cellA2 = cellMatches[0][1];
assert.ok(
cellA2.length <= MAX_EXCEL_CELL_CHARS,
`Expected <= 32767 UTF-16 code units, got ${cellA2.length}`
);
assert.equal(cellA2.length, 32766, 'Backs off by 1 code unit before emoji high surrogate + ellipsis');
assert.ok(cellA2.endsWith('…'));
assert.equal(/[\uD800-\uDFFF]/.test(cellA2), false, 'No split surrogate code unit remains');
const cellA3 = cellMatches[1][1];
assert.equal(cellA3, 'ok\uFFFDmid\uFFFDend');
});
+48 -1
View File
@@ -345,7 +345,8 @@ test('Loopback HTTP bridge enforces Origin, Private Network CORS, token auth, an
assert.equal(postBody.echoData.enableWindowOverlay, false); assert.equal(postBody.echoData.enableWindowOverlay, false);
assert.equal(receivedCalls.length, 3); assert.equal(receivedCalls.length, 3);
// 6. Oversized POST body -> 413 // 6. Oversized POST body -> 413 for regular /api/settings (including spoofed nested strings),
// while legitimate __exportFileAction fallback (>64 KiB) and 8 MiB Base64 /api/export-file (~10.7 MiB JSON) succeed
const hugePayload = JSON.stringify({ pad: 'x'.repeat(70 * 1024) }); const hugePayload = JSON.stringify({ pad: 'x'.repeat(70 * 1024) });
const hugeRes = await fetch(`http://127.0.0.1:${port}/api/settings`, { const hugeRes = await fetch(`http://127.0.0.1:${port}/api/settings`, {
method: 'POST', method: 'POST',
@@ -357,6 +358,52 @@ test('Loopback HTTP bridge enforces Origin, Private Network CORS, token auth, an
body: hugePayload, body: hugePayload,
}).catch(() => ({ status: 413 })); }).catch(() => ({ status: 413 }));
assert.equal(hugeRes.status, 413); assert.equal(hugeRes.status, 413);
const spoofedSettingsPayload = JSON.stringify({
note: '{"__exportFileAction":"save"}',
pad: 'y'.repeat(70 * 1024),
});
const spoofedRes = await fetch(`http://127.0.0.1:${port}/api/settings`, {
method: 'POST',
headers: {
Origin: validOrigin,
'Content-Type': 'application/json',
'X-Usage-Monitor-Token': token,
},
body: spoofedSettingsPayload,
}).catch(() => ({ status: 413 }));
assert.equal(spoofedRes.status, 413);
const fallbackExportRes = await fetch(`http://127.0.0.1:${port}/api/settings`, {
method: 'POST',
headers: {
Origin: validOrigin,
'Content-Type': 'application/json',
'X-Usage-Monitor-Token': token,
},
body: JSON.stringify({
__exportFileAction: 'save',
payload: { filename: 'fallback.xlsx', encoding: 'base64', content: 'A'.repeat(200 * 1024) },
}),
});
assert.equal(fallbackExportRes.status, 200);
// 8 MiB binary encoded as Base64 (~10.67 MiB) fits within 12 MiB BRIDGE_MAX_EXPORT_BODY_BYTES
const eightMibBase64 = Buffer.alloc(8 * 1024 * 1024, 0x50).toString('base64');
const maxExportRes = await fetch(`http://127.0.0.1:${port}/api/export-file`, {
method: 'POST',
headers: {
Origin: validOrigin,
'Content-Type': 'application/json',
'X-Usage-Monitor-Token': token,
},
body: JSON.stringify({
filename: 'max-8mib.xlsx',
encoding: 'base64',
content: eightMibBase64,
}),
});
assert.equal(maxExportRes.status, 200);
} finally { } finally {
await controller.stop(); await controller.stop();
} }