From 0b700d1f9f3c3b3cd17e7616061fd48cfa75d829 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 16:13:42 +0900 Subject: [PATCH] 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. --- sidecars/panel/app.js | 32 +++++++++--- sidecars/panel/backend/window-bridge.mjs | 36 ++++++++++++-- sidecars/panel/index.html | 4 +- sidecars/panel/src/core/xlsxBuilder.js | 28 +++++++++-- .../test/cross-module-regressions.test.mjs | 32 ++++++++++++ sidecars/panel/test/window-bridge.test.mjs | 49 ++++++++++++++++++- 6 files changed, 165 insertions(+), 16 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index c51f470..c06b8f3 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -6161,7 +6161,7 @@ return { triggerBlobDownload, triggerTextFileDownload, buildExportableSettingsJs })(); // --- src/core/xlsxBuilder.js --- -const { uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { +const { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { /** * @fileoverview 零外部依赖原生 Excel (`.xlsx` / ECMA-376 OOXML) 多工作表构建器 (`xlsxBuilder.js`)。 * 内置标准 IEEE 802.3 CRC-32 及 ZIP STORE 封装,支持: @@ -6172,7 +6172,10 @@ const { uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { * - 全部字符串采用 `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 LONE_SURROGATE_RE = + /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?= 0xd800 && prevCode <= 0xdbff) { + cut -= 1; + } + return `${clean.slice(0, cut)}…`; +} + +function escapeXmlText(val) { + return sanitizeExcelCellText(val) .replace(/&/g, '&') .replace(//g, '>') @@ -6390,10 +6408,12 @@ function columnIndexToLetter(index) { } /** - * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。 + * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽; + * 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。 */ 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; for (let i = 0; i < s.length; i += 1) { const code = s.charCodeAt(i); @@ -6805,7 +6825,7 @@ function buildXlsxWorkbookBytes(sheets) { return buildZipStoreArchive(archiveEntries); } -return { uint8ArrayToBase64, buildXlsxWorkbookBytes }; +return { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes }; })(); // --- src/core/reportExporter.js --- diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index bf96b6c..211fd8d 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -71,7 +71,8 @@ const overlayMethods = Object.fromEntries( ); 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); /** @@ -1343,17 +1344,34 @@ export function createWindowBridgeController(options) { return; } - const maxBodyBytes = + let maxBodyBytes = parsedUrl.pathname === '/api/export-file' ? BRIDGE_MAX_EXPORT_BODY_BYTES : BRIDGE_MAX_BODY_BYTES; const chunks = []; let totalBytes = 0; let aborted = false; + let checkedSettingsExportPrefix = false; 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) { aborted = true; + chunks.length = 0; res.writeHead(413, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Payload too large' })); req.destroy(); @@ -1372,6 +1390,18 @@ export function createWindowBridgeController(options) { res.end(JSON.stringify({ error: 'Invalid JSON body' })); 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)) .then((out) => { const hdrs = { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 7c9ed05..2cff9c0 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/core/xlsxBuilder.js b/sidecars/panel/src/core/xlsxBuilder.js index b9890f3..e1e1a30 100644 --- a/sidecars/panel/src/core/xlsxBuilder.js +++ b/sidecars/panel/src/core/xlsxBuilder.js @@ -8,7 +8,10 @@ * - 全部字符串采用 `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 LONE_SURROGATE_RE = + /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?= 0xd800 && prevCode <= 0xdbff) { + cut -= 1; + } + return `${clean.slice(0, cut)}…`; +} + +function escapeXmlText(val) { + return sanitizeExcelCellText(val) .replace(/&/g, '&') .replace(//g, '>') @@ -226,10 +244,12 @@ function columnIndexToLetter(index) { } /** - * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。 + * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽; + * 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。 */ 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; for (let i = 0; i < s.length; i += 1) { const code = s.charCodeAt(i); diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 611360b..87ed9ec 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1641,3 +1641,35 @@ test('i18n static t(...) key completeness guard, scopeAll formatters, and locali 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(/]*>]*>([\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'); +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index e91da06..452bc8a 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -345,7 +345,8 @@ test('Loopback HTTP bridge enforces Origin, Private Network CORS, token auth, an assert.equal(postBody.echoData.enableWindowOverlay, false); 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 hugeRes = await fetch(`http://127.0.0.1:${port}/api/settings`, { method: 'POST', @@ -357,6 +358,52 @@ test('Loopback HTTP bridge enforces Origin, Private Network CORS, token auth, an body: hugePayload, }).catch(() => ({ 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 { await controller.stop(); }