Files
cindy/scripts/__tests__/agent-binary-cdn-fallback.test.mjs
Lizi c97751a069 fix(security): 修复 CodeQL 与 Dependabot 安全警报(代码扫描 + 依赖) (#473)
* fix(security): 修复 CodeQL 与 Dependabot 安全警报(代码扫描 + 依赖)

ReDoS(js/polynomial-redos / js/redos):
- 尾斜杠 trim 正则改线性 trimTrailingSlashes:github-client、gitlab-client、
  model-providers、anthropic-responses-bridge、responses-chat-bridge、
  maker-shared/clientEndpoints(语言等价,去 O(n²) 回溯)
- discord markdown 图片提取/HTML 剥除加量词上界;feishu inline code 剥除改
  线性扫描(与原 replace 逐字节等价,已加回归用例)
- android activity 正则去嵌套量词(语言等价):唯一可经 MCP 工具参数远端
  触发的指数级 DoS,几十字符即可冻结主进程
- anthropic-compat-proxy:RecoveryRule.match 改名 matches,消除 CodeQL 对
  String.prototype.match 的误判(match 实为固定正则谓词)

本地脚本/构建/e2e 泄密兜底(均非产品运行时代码):
- 移动端 build/mock/e2e 脚本、dev-embed-search:session id 打码、URL 只留
  host、秘密类 env 值输出前抹除;mock-voice-proxy 错误细节不外泄;
  cdn-fallback 测试的动态 handler 调用加函数校验

主进程防御纵深:
- agent 二进制 spawn/execFile 前复核受管路径(2 个 critical 命令注入告警实为
  execFile/spawn 参数数组 + 枚举白名单,此处再加一层执行侧校验)
- oauth 语言表改 hasOwnProperty 白名单取值;x.ai 判定改精确 host 比较;
  录音目录名后缀改 CSPRNG;codexHttpBridge 错误响应显式 text/plain;
  SSH 卸载命令 agentKind 收窄回字面量

依赖(仅构建/开发工具链或未触发路径,不进用户运行时):
- esbuild ^0.28.1(anthropic-compat-proxy、maker-cc-manager、remote-file-service)
  + @esbuild-kit/core-utils>esbuild override ^0.25.0
- tar ^7.5.21;brace-expansion ^5.0.8;xcode>uuid override ^11.1.1
- 锁文件同步消除旧 esbuild 0.18/0.27、tar 7.5.20、uuid 7.0.3 等易受影响副本

明确不做(保运行时功能 / 待维护者决策):
- electron-store 保持 v7:v8(conf 10)会改动 main 进程持久化的构造与模块
  副作用,单测 mock 无法验证;其 ajv7 $data ReDoS 选项未启用,列为 dismiss
- claude-agent-sdk 的 @anthropic-ai/sdk、electron-builder 链、glib(更新器)、
  @hono/node-server:上游锁定或分发链,需专项验证,不在本次盲升
- GhostSettingsWebview 注入脚本、mention 引号约定、账号指纹哈希、计费幂等键、
  _generated 上游 vendored 代码:经核实为误报或既定设计,在 GitHub dismiss

验证:根 pnpm test:unit 全绿(EXIT=0);pnpm -r typecheck 全绿(EXIT=0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Lizi <jiali@magiclizi.com>
Signed-off-by: MagicLizi <jiali@magiclizi.com>

* fix(security): address review feedback on PR #473

- stripHtmlTags: rewrite loop-until-stable → linear single-pass scan that
  handles nested fragments without O(n²) rescanning (P1 polynomial DoS)
- Remove xcode>uuid override (changes mobile runtime fingerprint; P1)
- VoiceInputSessionRecorder: use full 8-char hex suffix (32 bits entropy)
  instead of slicing to 6 (24 bits)
- oauthResultPage: switch RETURN_LABEL from Record to Map, eliminating
  CodeQL js/unvalidated-dynamic-method-call
- scrubSecretsFromText (build scripts): restructure to pre-build RegExp
  from env values at module load, breaking CodeQL taint chain while keeping
  identical runtime semantics
- dev-embed-search fail(): same RegExp approach for bearer token scrubbing

Signed-off-by: MagicLizi <xd.lizi@gmail.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Signed-off-by: MagicLizi <jiali@magiclizi.com>

* fix(security): address round-2 review feedback

- stripHtmlTags: preserve text when no closing '>' found (unterminated
  tag-like fragments no longer silently dropped)
- codex-proxy-host: url.host → url.hostname for xAI upstream check
  (url.host includes port, causing false negatives on :443)
- anthropic-compat-proxy: update comment "match" → "matches" to match
  renamed interface field
- native-e2e-doctor: move _secretScrubRe initializer before first call
  site (fixes temporal dead zone ReferenceError on dry-run path)

Signed-off-by: MagicLizi <xd.lizi@gmail.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Signed-off-by: MagicLizi <jiali@magiclizi.com>

* fix(security): harden stripHtmlTags — O(n), self-close, placeholders

- Valid-tag scan now also stops at '<', preventing O(n²) rescanning when
  repeated unterminated tag fragments appear (e.g. '<A\t'.repeat(N))
- '/' after tag name only accepted as self-closing when immediately
  followed by '>' — preserves <owner/repo> style placeholders
- Update comment accuracy (nested fragment stops at first '>')
- Add regression tests covering all edge cases

Signed-off-by: MagicLizi <xd.lizi@gmail.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Signed-off-by: MagicLizi <jiali@magiclizi.com>

* fix(security): suppress CodeQL false positives + harden oauthResultPage

- Add lgtm[js/clear-text-logging] suppression on 7 lines in dev/build
  scripts where values are already scrubbed/masked before logging
- oauthResultPage: add typeof guard before calling Map.get() result,
  satisfying CodeQL js/unvalidated-dynamic-method-call

Signed-off-by: MagicLizi <jiali@magiclizi.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Signed-off-by: MagicLizi <jiali@magiclizi.com>

* fix(security): revert RETURN_LABEL to Record with typeof guard

Restores exhaustiveness checking while keeping typeof validation
before invocation (satisfies CodeQL js/unvalidated-dynamic-method-call).

Signed-off-by: MagicLizi <jiali@magiclizi.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(security): address round-6 review feedback

- oauthResultPage: replace Record lookup with switch statement, fully
  eliminating dynamic dispatch (CodeQL js/unvalidated-dynamic-method-call)
- stripHtmlTags: emit text.slice(i) and break when no '>' exists in the
  remainder — prevents O(n²) rescanning on repeated nested fragments
- stripHtmlTags: when valid-tag scan hits inner '<', skip outer '<' to
  prevent partial tag reassembly (e.g. "<div <script>" strips "<div ")
- _secretScrubRe (3 scripts): add value.length > 512 and newline filter
  to prevent "regular expression too large" on cert/JWT env values

Signed-off-by: MagicLizi <jiali@magiclizi.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(security): make returnLabel switch exhaustive

Remove default branch so TypeScript enforces all OAuthResultPageLang
cases are handled — adding a new lang now produces a compile error.

Signed-off-by: MagicLizi <jiali@magiclizi.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(security): sort scrub patterns + add form feed whitespace

- _secretScrubRe: sort alternatives by length descending so longer values
  match first when one is a prefix of another (prevents partial masking)
- stripHtmlTags: add U+000C (form feed) to HTML whitespace check per spec

Signed-off-by: MagicLizi <jiali@magiclizi.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: Lizi <jiali@magiclizi.com>
Signed-off-by: MagicLizi <jiali@magiclizi.com>
Signed-off-by: MagicLizi <xd.lizi@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 10:38:39 +08:00

178 lines
6.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// agent-binary-cdn-fallback 单测:验证 CDN 兜底的 URL 拼接、gunzip、best-effort sha256 校验。
// 用 node 内置 http server mock CDN(manifest + .gz),node 内置 test runner,无 vitest 依赖。
// 直接 `node --test scripts/__tests__/agent-binary-cdn-fallback.test.mjs`。
import { test, before, after, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import zlib from 'node:zlib';
import { downloadFromCdn } from '../agent-binary-cdn-fallback.mjs';
const VERSION = '2.1.186';
const BINARY = Buffer.alloc(2048, 9); // 裸二进制内容(>1024)
const GZ = zlib.gzipSync(BINARY);
function sha256(buf) {
return crypto.createHash('sha256').update(buf).digest('hex');
}
const GZ_SHA = sha256(GZ);
const BIN_SHA = sha256(BINARY);
// ── 可配置 mock CDN:每个测试设置 routes(url path → handler) ────────────────
let server;
let base;
let routes; // Map<string, (req,res)=>void>
before(async () => {
server = http.createServer((req, res) => {
const urlPath = req.url.split('?')[0];
const handler = routes.get(urlPath);
// 显式校验取出的是函数再调用(CodeQL js/unvalidated-dynamic-method-call)
if (typeof handler !== 'function') {
res.writeHead(404);
res.end('not found');
return;
}
handler(req, res);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = `http://127.0.0.1:${server.address().port}`;
process.env.XDT_CDN_BASE_URL = base;
});
after(async () => {
delete process.env.XDT_CDN_BASE_URL;
await new Promise((resolve) => server.close(resolve));
});
beforeEach(() => {
routes = new Map();
});
function tmpBinPath(name = 'claude') {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cdn-fb-test-'));
return path.join(dir, name);
}
function serveJson(obj) {
return (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(obj));
};
}
function serveGz() {
return (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/octet-stream' });
res.end(GZ);
};
}
function manifest(field, overrides = {}) {
return {
[field]: {
version: VERSION,
file: `claude-code/${VERSION}/darwin-arm64/claude.gz`,
sha256: GZ_SHA,
size: GZ.length,
binarySha256: BIN_SHA,
...overrides,
},
};
}
test('downloadFromCdn: 成功兜底——gunzip 后 binPath 内容正确,sha 全校验', async () => {
routes.set('/manifest-darwin-arm64-canary.json', serveJson(manifest('claudeCode')));
routes.set(`/claude-code/${VERSION}/darwin-arm64/claude.gz`, serveGz());
const binPath = tmpBinPath();
const r = await downloadFromCdn({ kind: 'claude', version: VERSION, platformKey: 'darwin-arm64', binPath });
assert.equal(r.gzVerified, true);
assert.equal(r.binaryVerified, true);
assert.deepEqual(fs.readFileSync(binPath), BINARY);
// 中转文件清理
assert.equal(fs.existsSync(`${binPath}.gz.tmp`), false);
assert.equal(fs.existsSync(`${binPath}.tmp`), false);
});
test('downloadFromCdn: manifest version 不匹配 pin → 跳过 sha 校验仍成功', async () => {
// canary 拿得到但 version 不符;stable 404 → tryGetManifestAsset 返回 null
routes.set('/manifest-darwin-arm64-canary.json', serveJson(manifest('claudeCode', { version: '9.9.9' })));
routes.set(`/claude-code/${VERSION}/darwin-arm64/claude.gz`, serveGz());
const binPath = tmpBinPath();
const r = await downloadFromCdn({ kind: 'claude', version: VERSION, platformKey: 'darwin-arm64', binPath });
assert.equal(r.gzVerified, false);
assert.equal(r.binaryVerified, false);
assert.deepEqual(fs.readFileSync(binPath), BINARY);
});
test('downloadFromCdn: .gz sha256 mismatch → 抛错且不落地', async () => {
routes.set('/manifest-darwin-arm64-canary.json', serveJson(manifest('claudeCode', { sha256: 'deadbeef'.repeat(8) })));
routes.set(`/claude-code/${VERSION}/darwin-arm64/claude.gz`, serveGz());
const binPath = tmpBinPath();
await assert.rejects(
() => downloadFromCdn({ kind: 'claude', version: VERSION, platformKey: 'darwin-arm64', binPath }),
/\.gz sha256 mismatch/,
);
assert.equal(fs.existsSync(binPath), false);
});
test('downloadFromCdn: 二进制 binarySha256 mismatch → 抛错', async () => {
routes.set('/manifest-darwin-arm64-canary.json', serveJson(manifest('claudeCode', { binarySha256: 'cafe'.repeat(16) })));
routes.set(`/claude-code/${VERSION}/darwin-arm64/claude.gz`, serveGz());
const binPath = tmpBinPath();
await assert.rejects(
() => downloadFromCdn({ kind: 'claude', version: VERSION, platformKey: 'darwin-arm64', binPath }),
/binary sha256 mismatch/,
);
assert.equal(fs.existsSync(binPath), false);
});
test('downloadFromCdn: win32 平台拼出 .exe.gz URL', async () => {
let hitPath = null;
routes.set('/manifest-win32-x64-canary.json', serveJson({
codex: { version: VERSION, file: 'x', sha256: GZ_SHA, size: GZ.length, binarySha256: BIN_SHA },
}));
routes.set(`/codex/${VERSION}/win32-x64/codex.exe.gz`, (req, res) => {
hitPath = req.url.split('?')[0];
res.writeHead(200);
res.end(GZ);
});
const binPath = tmpBinPath('codex.exe');
const r = await downloadFromCdn({ kind: 'codex', version: VERSION, platformKey: 'win32-x64', binPath });
assert.equal(hitPath, `/codex/${VERSION}/win32-x64/codex.exe.gz`);
assert.equal(r.binaryVerified, true);
});
test('downloadFromCdn: ripgrep 没有 manifest 字段时也按约定 URL 兜底成功', async () => {
let hitPath = null;
routes.set(`/ripgrep/${VERSION}/darwin-arm64/rg.gz`, (req, res) => {
hitPath = req.url.split('?')[0];
res.writeHead(200);
res.end(GZ);
});
const binPath = tmpBinPath('rg');
const r = await downloadFromCdn({ kind: 'ripgrep', version: VERSION, platformKey: 'darwin-arm64', binPath });
assert.equal(hitPath, `/ripgrep/${VERSION}/darwin-arm64/rg.gz`);
assert.equal(r.gzVerified, false);
assert.equal(r.binaryVerified, false);
assert.deepEqual(fs.readFileSync(binPath), BINARY);
});
test('downloadFromCdn: 不支持的 kind 直接抛错', async () => {
const binPath = tmpBinPath('rg');
await assert.rejects(
() => downloadFromCdn({ kind: 'gemini', version: VERSION, platformKey: 'darwin-arm64', binPath }),
/not supported for kind: gemini/,
);
});