capture.js 2.4 KB

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