来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
180 lines
6.6 KiB
TypeScript
180 lines
6.6 KiB
TypeScript
// @vitest-environment jsdom
|
||
/**
|
||
* CSV 公式注入(CSV / Formula Injection)回归网。
|
||
*
|
||
* 背景:`escapeCsvCell` 只做 CSV **语法**转义(引号/逗号/换行),不做**内容语义**防护,
|
||
* 于是 `=1+1` / `=cmd|'/C calc'!A0` / `@SUM(A1)` 等单元格被原样写出,Excel/WPS 打开
|
||
* 会按公式解释(公式注入)。分拣单另有自写 CSV,它给每个单元格都加了引号 —— 但引号
|
||
* 只解决 CSV 语法,**防不住公式**,故同样要过守卫。
|
||
*
|
||
* ⚠️ 本测试钉住两条硬约束(2026-09-24 开发者要求):
|
||
* ① 守卫**不得影响业务流程**:纯数字(`-5.00` / `+3.5` / `-1e5`)输出字节必须不变;
|
||
* ② 守卫**不得导致 CSV 无法导出**:任何入参都必须能产出文本、不得抛错。
|
||
*/
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
import { describe, expect, it } from 'vitest';
|
||
import { downloadCsv, guardCsvFormulaInjection } from './excelImportExport';
|
||
|
||
/** 抓真实 Blob:走与页面完全相同的 downloadCsv 代码路径 */
|
||
function renderCsvBlob(headers: string[], rows: (string | number | null | undefined)[][]): Blob {
|
||
let captured: Blob | null = null;
|
||
const origCreate = URL.createObjectURL;
|
||
const origRevoke = URL.revokeObjectURL;
|
||
(URL as any).createObjectURL = (b: Blob) => {
|
||
captured = b;
|
||
return 'blob:probe';
|
||
};
|
||
(URL as any).revokeObjectURL = () => {};
|
||
try {
|
||
downloadCsv('probe.csv', headers, rows);
|
||
} finally {
|
||
(URL as any).createObjectURL = origCreate;
|
||
(URL as any).revokeObjectURL = origRevoke;
|
||
}
|
||
expect(captured, 'downloadCsv 未产出 Blob(导出被阻断)').toBeTruthy();
|
||
return captured as unknown as Blob;
|
||
}
|
||
|
||
/** 注意:Blob.text() 按规范走 UTF-8 decode,会剥掉 BOM;BOM 用字节断言单独验 */
|
||
async function renderCsv(headers: string[], rows: (string | number | null | undefined)[][]): Promise<string> {
|
||
return await renderCsvBlob(headers, rows).text();
|
||
}
|
||
|
||
/** 去掉 BOM 后按 RFC4180 子集解析成二维数组(含引号内逗号/换行) */
|
||
function parseCsv(text: string): string[][] {
|
||
const s = text.replace(/^\uFEFF/, '');
|
||
const rows: string[][] = [];
|
||
let row: string[] = [];
|
||
let cell = '';
|
||
let quoted = false;
|
||
for (let i = 0; i < s.length; i += 1) {
|
||
const c = s[i];
|
||
if (quoted) {
|
||
if (c === '"') {
|
||
if (s[i + 1] === '"') {
|
||
cell += '"';
|
||
i += 1;
|
||
} else quoted = false;
|
||
} else cell += c;
|
||
continue;
|
||
}
|
||
if (c === '"') {
|
||
quoted = true;
|
||
} else if (c === ',') {
|
||
row.push(cell);
|
||
cell = '';
|
||
} else if (c === '\r' && s[i + 1] === '\n') {
|
||
row.push(cell);
|
||
rows.push(row);
|
||
row = [];
|
||
cell = '';
|
||
i += 1;
|
||
} else if (c === '\n') {
|
||
row.push(cell);
|
||
rows.push(row);
|
||
row = [];
|
||
cell = '';
|
||
} else cell += c;
|
||
}
|
||
if (cell !== '' || row.length) {
|
||
row.push(cell);
|
||
rows.push(row);
|
||
}
|
||
return rows;
|
||
}
|
||
|
||
const FORMULA_START = /^[=+\-@\t\r]/;
|
||
|
||
describe('CSV 公式注入:写出的单元格不得以公式字符开头', () => {
|
||
it('= + - @ TAB CR 开头的非数字值全部被中和', async () => {
|
||
const headers = ['a', 'b', 'c', 'd', 'e', 'f'];
|
||
const text = await renderCsv(headers, [
|
||
['=1+1', "=cmd|'/C calc'!A0", '@SUM(A1)', '+1+1', '-1+1', '\t=1+1'],
|
||
]);
|
||
const [head, data] = parseCsv(text);
|
||
expect(head).toEqual(headers);
|
||
expect(data).toHaveLength(6);
|
||
for (const cell of data) {
|
||
expect(FORMULA_START.test(cell), `单元格仍以公式字符开头:${JSON.stringify(cell)}`).toBe(false);
|
||
expect(cell.startsWith("'")).toBe(true);
|
||
}
|
||
});
|
||
|
||
it('真实业务字段里的注入内容(备注/地址/名称)同样被中和', async () => {
|
||
const text = await renderCsv(['备注', '配送地址', '客户'], [
|
||
["=HYPERLINK(\"http://evil/\",\"点我\")", '@恶意地址', '=1+1'],
|
||
]);
|
||
for (const cell of parseCsv(text)[1]) {
|
||
expect(FORMULA_START.test(cell)).toBe(false);
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('硬约束①:不得影响业务流程 —— 纯数字与普通文本输出字节不变', () => {
|
||
it('带符号数字/科学计数保持原样(财务数字列零影响)', async () => {
|
||
const headers = ['负数', '正数', '科学计数', '长小数'];
|
||
const text = await renderCsv(headers, [['-5.00', '+3.5', '-1e5', '1234.56']]);
|
||
// 逐字节比对:应恰好是原值,未被加前缀、未被加引号
|
||
expect(text).toBe(`${headers.join(',')}\r\n-5.00,+3.5,-1e5,1234.56`);
|
||
});
|
||
|
||
it('UTF-8 BOM 保留(Windows Excel 中文不乱码)', async () => {
|
||
const buf = new Uint8Array(await renderCsvBlob(['a'], [['1']]).arrayBuffer());
|
||
expect([buf[0], buf[1], buf[2]]).toEqual([0xef, 0xbb, 0xbf]);
|
||
});
|
||
|
||
it('普通文本与既有 CSV 语法转义保持不变', async () => {
|
||
const text = await renderCsv(['a', 'b', 'c', 'd'], [['正常文本', '带,逗号', '带"引号', '带\n换行']]);
|
||
expect(text).toBe('a,b,c,d\r\n正常文本,"带,逗号","带""引号","带\n换行"');
|
||
});
|
||
|
||
it('守卫对纯数字是幂等的(不重复加前缀)', () => {
|
||
expect(guardCsvFormulaInjection('-5.00')).toBe('-5.00');
|
||
expect(guardCsvFormulaInjection('+3.5')).toBe('+3.5');
|
||
expect(guardCsvFormulaInjection('正常文本')).toBe('正常文本');
|
||
expect(guardCsvFormulaInjection("'=1+1")).toBe("'=1+1"); // 已带前缀的不再叠加
|
||
});
|
||
});
|
||
|
||
describe('硬约束②:不得导致 CSV 无法导出', () => {
|
||
it('异常/极端入参一律可导出,且不抛错', async () => {
|
||
const weird: unknown[] = [
|
||
null,
|
||
undefined,
|
||
NaN,
|
||
Infinity,
|
||
-Infinity,
|
||
0,
|
||
{},
|
||
[],
|
||
'x'.repeat(5000),
|
||
'-'.repeat(5000),
|
||
'='.repeat(5000),
|
||
'\t',
|
||
'\r',
|
||
'=😀表情',
|
||
'\uD800 lone surrogate',
|
||
];
|
||
// 若守卫抛错,这里会直接失败(即"导出被阻断")
|
||
const text = await renderCsv(['c'], [weird as never[]]);
|
||
expect(parseCsv(text)[1]).toHaveLength(weird.length);
|
||
});
|
||
|
||
it('空表(只有表头)也能导出', async () => {
|
||
const text = await renderCsv(['a', 'b'], []);
|
||
expect(text).toBe('a,b');
|
||
});
|
||
});
|
||
|
||
describe('分拣单自写 CSV 必须复用同一个守卫', () => {
|
||
it('源码里调用了 guardCsvFormulaInjection(否则引号包一层仍会中招)', () => {
|
||
const src = readFileSync(
|
||
path.join(__dirname, '../pages/picking/PickingManagement.tsx'),
|
||
'utf8'
|
||
);
|
||
expect(src).toContain("guardCsvFormulaInjection } from '../../utils/excelImportExport'");
|
||
expect(src).toContain('guardCsvFormulaInjection(String(cell))');
|
||
});
|
||
});
|