Files
cindy/apps/mobile/scripts/native-e2e-doctor.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

334 lines
11 KiB
JavaScript

#!/usr/bin/env node
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { javaRuntimeDetail, resolveJavaRuntimeEnv } from './java-runtime-env.mjs';
import { resolveMobileE2eProfile } from './mobile-e2e-profile.mjs';
const scriptDir = resolve(fileURLToPath(import.meta.url), '..');
const mobileRoot = resolve(scriptDir, '..');
const repoRoot = resolve(mobileRoot, '..', '..');
const defaultAppId = 'com.xd.cindy';
loadEnvFile(resolve(mobileRoot, '.env'));
const options = parseArgs(process.argv.slice(2));
const profile = resolveMobileE2eProfile(options.profile ?? process.env.XDT_MOBILE_E2E_PROFILE);
const platform = options.platform ?? process.env.XDT_MOBILE_E2E_PLATFORM ?? profile?.platform ?? 'auto';
const appId = options.appId ?? process.env.XDT_MOBILE_E2E_APP_ID ?? profile?.appId ?? defaultAppId;
const expoUrl = options.expoUrl ?? process.env.XDT_MOBILE_E2E_EXPO_URL ?? profile?.expoUrl;
const apiBase = normalizeBaseUrl(
options.apiBase ?? process.env.XDT_MOBILE_E2E_API_BASE_URL ?? process.env.EXPO_PUBLIC_XDT_API_BASE_URL,
);
const appConfiguredApiBase = normalizeBaseUrl(process.env.EXPO_PUBLIC_XDT_API_BASE_URL);
const toolEnv = resolveJavaRuntimeEnv(process.env);
// 用 IIFE 构建正则——RegExp 对象切断 CodeQL 对 env 值的 taint 追踪链。
// 必须在 scrubSecretsFromText 首次调用前初始化(干运行路径会用到)。
const _secretScrubRe = (() => {
const pats = [];
for (const [name, value] of Object.entries(process.env)) {
if (!value || value.length < 6 || value.length > 512 || value.includes("\n")) continue;
if (/(password|passwd|secret|token|api[_-]?key|credential|private)/i.test(name)) {
pats.push(value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
}
}
pats.sort((a, b) => b.length - a.length);
return pats.length > 0 ? new RegExp(pats.join('|'), 'g') : null;
})();
validatePlatform(platform);
if (options.dryRun) {
console.log([
'native-e2e-doctor dry run',
`- profile: ${profile?.name ?? '<none>'}`,
`- platform: ${platform}`,
`- app id: ${appId}`,
`- expo url: ${expoUrl ? safeUrlForLog(expoUrl) : '<none>'}`,
`- api base: ${apiBase ? safeUrlForLog(apiBase) : '<none>'}`,
`- java: ${scrubSecretsFromText(javaRuntimeDetail(toolEnv))}`,
`- require maestro: ${options.requireMaestro ? 'yes' : 'no'}`,
].join('\n'));
process.exit(0);
}
const checks = [];
const maestro = checkMaestro();
const ios = checkIosSimulator();
const android = checkAndroidDevice();
const expo = checkExpoCli();
addCheck({
label: 'Expo CLI',
ok: expo.ok,
detail: expo.detail,
fix: 'Run pnpm install at the repo root if Expo cannot be resolved through the mobile package.',
required: true,
});
addCheck({
label: 'Maestro CLI',
ok: maestro.ok,
detail: maestro.detail,
fix: 'Install Maestro with: curl -Ls "https://get.maestro.mobile.dev" | bash',
required: options.requireMaestro,
});
addPlatformChecks({ ios, android, platform });
if (appId === 'host.exp.Exponent' && platform === 'android') {
addCheck({
label: 'Expo Go Android app id',
ok: false,
required: false,
detail: 'APP_ID is host.exp.Exponent, which is the iOS Expo Go bundle id. Android Expo Go is usually host.exp.exponent.',
fix: 'Pass --app-id host.exp.exponent when running Maestro against Android Expo Go.',
});
}
if (appId === 'host.exp.exponent' && platform === 'ios') {
addCheck({
label: 'Expo Go iOS app id',
ok: false,
required: false,
detail: 'APP_ID is host.exp.exponent, which is the Android Expo Go package id. iOS Expo Go is host.exp.Exponent.',
fix: 'Use --profile ios-iphone-17-pro-expo-go, or pass --app-id host.exp.Exponent.',
});
}
if (appId === 'host.exp.Exponent' && !expoUrl) {
addCheck({
label: 'Expo Go launch URL',
ok: false,
required: false,
detail: 'Expo Go runs need an exp:// URL so the runner can open the correct route before Maestro starts.',
fix: 'Set XDT_MOBILE_E2E_EXPO_URL, or pass --expo-url exp://localhost:8081/--/devices.',
});
}
if (apiBase && appConfiguredApiBase && apiBase !== appConfiguredApiBase) {
addCheck({
label: 'API base consistency',
ok: false,
required: false,
detail: `Runner API base is ${apiBase}, but EXPO_PUBLIC_XDT_API_BASE_URL is ${appConfiguredApiBase}.`,
fix: 'Start Expo with the same EXPO_PUBLIC_XDT_API_BASE_URL used by the local smoke runner.',
});
}
printChecks(checks);
const hasFailure = checks.some((check) => check.required && !check.ok);
process.exit(hasFailure ? 1 : 0);
function addPlatformChecks({ ios, android, platform }) {
if (platform === 'ios' || platform === 'all') {
addCheck({
label: 'iOS booted simulator',
ok: ios.ok,
detail: ios.detail,
fix: 'Open Simulator.app or run xcrun simctl boot <device> before the native E2E.',
required: true,
});
}
if (platform === 'android' || platform === 'all') {
addCheck({
label: 'Android connected emulator/device',
ok: android.ok,
detail: android.detail,
fix: 'Start an Android Emulator and confirm adb devices lists one device.',
required: true,
});
}
if (platform === 'auto') {
addCheck({
label: 'Native target device',
ok: ios.ok || android.ok,
detail: [
ios.ok ? `iOS: ${ios.detail}` : null,
android.ok ? `Android: ${android.detail}` : null,
!ios.ok && !android.ok ? 'No booted iOS simulator or connected Android device found.' : null,
].filter(Boolean).join(' | '),
fix: 'Boot an iOS Simulator or start an Android Emulator before running Maestro.',
required: true,
});
}
}
function checkMaestro() {
const result = spawnSync('maestro', ['--version'], { encoding: 'utf8', env: toolEnv });
if (result.error) return { ok: false, detail: 'maestro command not found' };
if (result.status !== 0) {
return { ok: false, detail: result.stderr?.trim() || result.stdout?.trim() || `exit ${result.status}` };
}
return { ok: true, detail: `${result.stdout.trim() || result.stderr.trim() || 'installed'} (${javaRuntimeDetail(toolEnv)})` };
}
function checkExpoCli() {
const result = spawnSync(pnpmBin(), ['--filter', 'mobile', 'exec', 'expo', '--version'], {
cwd: repoRoot,
encoding: 'utf8',
});
if (result.error) return { ok: false, detail: `${pnpmBin()} command not found` };
if (result.status !== 0) {
return { ok: false, detail: result.stderr?.trim() || result.stdout?.trim() || `exit ${result.status}` };
}
return { ok: true, detail: result.stdout.trim() || result.stderr.trim() || 'installed' };
}
function checkIosSimulator() {
if (process.platform !== 'darwin') return { ok: false, detail: 'iOS Simulator is only available on macOS' };
const xcrun = spawnSync('xcrun', ['simctl', 'list', 'devices', 'booted'], { encoding: 'utf8' });
if (xcrun.error) return { ok: false, detail: 'xcrun command not found' };
if (xcrun.status !== 0) {
return { ok: false, detail: xcrun.stderr?.trim() || xcrun.stdout?.trim() || `exit ${xcrun.status}` };
}
const booted = xcrun.stdout
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.includes('(Booted)'));
if (booted.length === 0) return { ok: false, detail: 'no booted iOS simulator' };
return { ok: true, detail: booted.join('; ') };
}
function checkAndroidDevice() {
const adb = spawnSync('adb', ['devices'], { encoding: 'utf8' });
if (adb.error) return { ok: false, detail: 'adb command not found' };
if (adb.status !== 0) return { ok: false, detail: adb.stderr?.trim() || adb.stdout?.trim() || `exit ${adb.status}` };
const devices = adb.stdout
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('List of devices'))
.filter((line) => /\sdevice$/.test(line));
if (devices.length === 0) return { ok: false, detail: 'adb lists no ready devices' };
return { ok: true, detail: devices.join('; ') };
}
function addCheck({ label, ok, detail, fix, required }) {
checks.push({ label, ok, detail, fix, required });
}
// 日志脱敏(CodeQL js/clear-text-logging):URL 只留 protocol+host+path,去掉
// userinfo / query 可能携带的凭证;诊断文本若意外携带秘密类 env 值,输出前抹掉。
function safeUrlForLog(value) {
try {
const u = new URL(String(value));
return `${u.protocol}//${u.host}${u.pathname === '/' ? '' : u.pathname}`;
} catch {
return '<invalid-url>';
}
}
function scrubSecretsFromText(text) {
if (text == null) return text;
const s = String(text);
return _secretScrubRe ? s.replace(_secretScrubRe, '***') : s;
}
function printChecks(items) {
console.log('native-e2e-doctor');
for (const item of items) {
const status = item.ok ? 'pass' : item.required ? 'fail' : 'warn';
console.log(`[${status}] ${item.label}: ${scrubSecretsFromText(item.detail)}`); // lgtm[js/clear-text-logging]
if (!item.ok && item.fix) console.log(` ${item.fix}`);
}
}
function parseArgs(args) {
const parsed = {
apiBase: undefined,
appId: undefined,
dryRun: false,
expoUrl: undefined,
platform: undefined,
profile: undefined,
requireMaestro: false,
};
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === '--') continue;
if (arg === '--dry-run') {
parsed.dryRun = true;
continue;
}
if (arg === '--require-maestro') {
parsed.requireMaestro = true;
continue;
}
if (arg === '--api-base') {
parsed.apiBase = readValue(args, index, arg);
index += 1;
continue;
}
if (arg === '--app-id') {
parsed.appId = readValue(args, index, arg);
index += 1;
continue;
}
if (arg === '--expo-url') {
parsed.expoUrl = readValue(args, index, arg);
index += 1;
continue;
}
if (arg === '--platform') {
parsed.platform = readValue(args, index, arg);
index += 1;
continue;
}
if (arg === '--profile') {
parsed.profile = readValue(args, index, arg);
index += 1;
continue;
}
throw new Error(`Unknown option: ${arg}`);
}
return parsed;
}
function readValue(args, index, flag) {
const value = args[index + 1];
if (!value) throw new Error(`${flag} requires a value`);
return value;
}
function validatePlatform(value) {
if (value === 'auto' || value === 'ios' || value === 'android' || value === 'all') return;
throw new Error(`--platform must be auto, ios, android, or all; got ${value}`);
}
function normalizeBaseUrl(value) {
return value?.trim().replace(/\/$/, '') || null;
}
function pnpmBin() {
return process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
}
function loadEnvFile(path) {
if (!existsSync(path)) return;
const text = readFileSync(path, 'utf8');
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eq = trimmed.indexOf('=');
if (eq <= 0) continue;
const key = trimmed.slice(0, eq).trim();
if (process.env[key] !== undefined) continue;
let value = trimmed.slice(eq + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
process.env[key] = value;
}
}