| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- import { readFile, stat, mkdir, writeFile } from 'node:fs/promises';
- import { resolve, join } from 'node:path';
- import { randomBytes } from 'node:crypto';
- import { analyzeHar } from '../src/network-capture.js';
- import { probeCapturedRequest } from '../src/network-probe.js';
- const usage = `用法:
- npm run capture:analyze -- data/captures/teams.har
- npm run capture:probe -- data/captures/teams.har <请求编号>
- analyze 只读取本地 HAR,输出隐藏凭证和正文的接口摘要。
- probe 从本地进程请求一个抓包中已确认的只读接口,可关闭 Teams 网页后验证。
- 报告写入 data/captures/reports/;原始 HAR 不修改,令牌不写入报告。
- `;
- try {
- const [mode, input, rawId, ...extra] = process.argv.slice(2);
- if (!mode || mode === '--help' || input === '--help') { console.log(usage); }
- else {
- if (!['analyze', 'probe'].includes(mode) || !input || extra.length || (mode === 'analyze' && rawId !== undefined)
- || (mode === 'probe' && !/^\d+$/.test(rawId || ''))) throw new Error(usage);
- const path = resolve(input), info = await stat(path).catch(() => null);
- if (!info?.isFile()) throw new Error('找不到 HAR 文件,请先导出并检查本地路径。');
- if (info.size > 256 * 1024 * 1024) throw new Error('HAR 超过 256 MiB,请清空网络日志后只抓取一次聊天和日历请求。');
- let har;
- try { har = JSON.parse((await readFile(path, 'utf8')).replace(/^\uFEFF/, '')); }
- catch { throw new Error('文件不是有效的 HAR JSON;请导出包含响应内容的 HAR。'); }
- const result = mode === 'analyze' ? analyzeHar(har) : await probeCapturedRequest(har, Number(rawId));
- const directory = resolve('data/captures/reports');
- await mkdir(directory, { recursive: true });
- const output = join(directory, `${mode}-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomBytes(3).toString('hex')}.json`);
- await writeFile(output, JSON.stringify(result, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
- console.log(JSON.stringify(result, null, 2));
- console.log(`报告已保存:${output}`);
- if (mode === 'probe' && !result.ok) process.exitCode = 2;
- }
- } catch (error) {
- // Analyzer/validation errors are fixed descriptions; never echo an unparsed HAR,
- // a request object, fetch errors, or an exception stack containing credentials.
- console.error(error.message || '抓包处理失败。');
- process.exitCode = 1;
- }
|