agentdock-cli 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentdock-cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Diagnose, migrate, and back up your AI coding assistant environment (Claude Code / Codex) — Chinese health reports, MCP servers, Skills, Agents, Plugins, Hooks, and memory, with secret isolation.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -36,6 +36,7 @@
36
36
  "dev": "tsx src/cli.ts",
37
37
  "test": "vitest run",
38
38
  "e2e": "tsx scripts/e2e.ts",
39
+ "e2e:sync": "tsx scripts/e2e-sync.ts",
39
40
  "cli": "tsx src/cli.ts",
40
41
  "prepublishOnly": "npm run build",
41
42
  "release:commits": "node scripts/generate-commit-groups.js"
@@ -9,6 +9,7 @@ const node_path_1 = __importDefault(require("node:path"));
9
9
  const smol_toml_1 = require("smol-toml");
10
10
  const package_json_1 = __importDefault(require("../../package.json"));
11
11
  const sensitive_1 = require("../scanners/sensitive");
12
+ const supply_chain_1 = require("./supply-chain");
12
13
  const package_lock_1 = require("./package-lock");
13
14
  const CATEGORIES = ['mcp', 'skills', 'agents', 'plugins', 'hooks', 'memory', 'settings'];
14
15
  const LEVEL_LABEL = {
@@ -56,69 +57,7 @@ function summarizeAssets(manifest) {
56
57
  }
57
58
  return assets;
58
59
  }
59
- /** 无版本号 → 远端每次拉取/执行的内容都可能变(供应链风险)。 */
60
- function isPinnedSpec(spec) {
61
- if (!spec) {
62
- return false;
63
- }
64
- const at = spec.startsWith('@') ? spec.indexOf('@', 1) : spec.indexOf('@');
65
- return at > 0;
66
- }
67
- function inspectCommandTokens(tokens, file, add) {
68
- const npxIndex = tokens.findIndex((token) => /(^|[\\/])npx(\.cmd|\.exe)?$/i.test(token));
69
- if (npxIndex >= 0) {
70
- const rest = tokens.slice(npxIndex + 1);
71
- if (rest.includes('-y') || rest.includes('--yes')) {
72
- const spec = rest.find((token) => !token.startsWith('-'));
73
- if (spec && !isPinnedSpec(spec)) {
74
- add({
75
- level: 'high',
76
- id: 'unpinned-npx',
77
- message: `MCP 使用 npx -y 拉取未固定版本的远程包并执行:${spec}`,
78
- evidence: `${file} (${spec})`,
79
- });
80
- }
81
- }
82
- }
83
- const uvxIndex = tokens.findIndex((token) => /(^|[\\/])uvx(\.exe)?$/i.test(token));
84
- if (uvxIndex >= 0) {
85
- const spec = tokens.slice(uvxIndex + 1).find((token) => !token.startsWith('-'));
86
- if (spec && !isPinnedSpec(spec)) {
87
- add({
88
- level: 'medium',
89
- id: 'unpinned-uvx',
90
- message: `MCP 使用 uvx 拉取未固定版本的 Python 包并执行:${spec}`,
91
- evidence: `${file} (${spec})`,
92
- });
93
- }
94
- }
95
- }
96
- /** 从 JSON/TOML 结构里挑出 mcpServers / mcp_servers 定义。 */
97
- function collectMcpDefs(value, out) {
98
- if (Array.isArray(value)) {
99
- for (const item of value) {
100
- collectMcpDefs(item, out);
101
- }
102
- return;
103
- }
104
- if (!value || typeof value !== 'object') {
105
- return;
106
- }
107
- const obj = value;
108
- for (const key of ['mcpServers', 'mcp_servers']) {
109
- const servers = obj[key];
110
- if (servers && typeof servers === 'object' && !Array.isArray(servers)) {
111
- for (const def of Object.values(servers)) {
112
- if (def && typeof def === 'object' && !Array.isArray(def)) {
113
- out.push(def);
114
- }
115
- }
116
- }
117
- }
118
- for (const child of Object.values(obj)) {
119
- collectMcpDefs(child, out);
120
- }
121
- }
60
+ /** 从 JSON/TOML 结构里挑出 mcpServers / mcp_servers 定义,再逐个做供应链与权限检查。 */
122
61
  function inspectStructuredFile(file, text, add) {
123
62
  const ext = node_path_1.default.posix.extname(file).toLowerCase();
124
63
  let parsed;
@@ -129,12 +68,9 @@ function inspectStructuredFile(file, text, add) {
129
68
  return;
130
69
  }
131
70
  const defs = [];
132
- collectMcpDefs(parsed, defs);
71
+ (0, supply_chain_1.collectMcpDefs)(parsed, defs);
133
72
  for (const def of defs) {
134
- const command = typeof def.command === 'string' ? def.command : '';
135
- const args = Array.isArray(def.args) ? def.args.filter((arg) => typeof arg === 'string') : [];
136
- const tokens = `${command} ${args.join(' ')}`.trim().split(/\s+/).filter(Boolean);
137
- inspectCommandTokens(tokens, file, add);
73
+ (0, supply_chain_1.inspectMcpDef)(def, file, add);
138
74
  }
139
75
  inspectPermissions(parsed, file, add);
140
76
  }
@@ -184,29 +120,6 @@ function inspectPermissions(value, file, add) {
184
120
  inspectPermissions(child, file, add);
185
121
  }
186
122
  }
187
- /**
188
- * 自由文本(skill / memory / 脚本)里的 `npx -y` 多为文档示例。
189
- * 逐文件收集后汇总成一条中风险,避免把文档示例误报成高风险。
190
- */
191
- function collectTextNpxSpecs(text) {
192
- const specs = [];
193
- for (const line of text.split(/\r?\n/)) {
194
- const tokens = line.split(/[\s"'`,;:(){}[\]<>]+/).filter(Boolean);
195
- const index = tokens.findIndex((token) => /(^|[\\/])npx(\.cmd|\.exe)?$/i.test(token));
196
- if (index < 0) {
197
- continue;
198
- }
199
- const rest = tokens.slice(index + 1);
200
- if (!rest.includes('-y') && !rest.includes('--yes')) {
201
- continue;
202
- }
203
- const spec = rest.find((token) => !token.startsWith('-'));
204
- if (spec && !isPinnedSpec(spec)) {
205
- specs.push(spec);
206
- }
207
- }
208
- return specs;
209
- }
210
123
  /**
211
124
  * 对一个安装包(目录或 .zip)生成审计清单:
212
125
  * 资产清单 + 密钥处理方式 + 供应链风险 +(有 lock 时)完整性校验。
@@ -248,7 +161,7 @@ async function attestPackage(targetPath) {
248
161
  leaks.push({ file: rel, count: found.length });
249
162
  }
250
163
  inspectStructuredFile(rel, text, (risk) => collector.add(risk));
251
- const textSpecs = collectTextNpxSpecs(text);
164
+ const textSpecs = (0, supply_chain_1.collectTextNpxSpecs)(text);
252
165
  if (textSpecs.length > 0) {
253
166
  textNpxHits += textSpecs.length;
254
167
  textNpxFiles.add(rel);
@@ -12,9 +12,30 @@ const yaml_1 = __importDefault(require("yaml"));
12
12
  const claude_scanner_1 = require("../scanners/claude-scanner");
13
13
  const codex_scanner_1 = require("../scanners/codex-scanner");
14
14
  const sensitive_1 = require("../scanners/sensitive");
15
+ const supply_chain_1 = require("./supply-chain");
15
16
  const smol_toml_1 = require("smol-toml");
16
17
  const fs_1 = require("../utils/fs");
17
18
  // ===== helpers =====
19
+ const SUPPLY_CHAIN_REMEDIATION = '为 npx / uvx 指定固定版本(如 `npx -y <包名>@1.2.3`、`uvx <包名>==1.2.3`),避免远端代码在每次安装时任意变化;内网/离线环境可改为本地可执行文件或私有镜像。';
20
+ /** 把供应链风险映射为 doctor 警告级 finding(体检只提醒,不判失败)。 */
21
+ function supplyRiskFinding(risk) {
22
+ return { severity: 'warn', message: risk.message, path: risk.evidence };
23
+ }
24
+ /**
25
+ * 供应链风险检查:未固定版本的 npx -y / uvx 远程拉取(doctor live 复用
26
+ * attest 的共享检测;风险统一为 warn 级,`unpinned-npx` 在 attest 中才是 high)。
27
+ */
28
+ function supplyChainCheck(findings) {
29
+ return makeCheck('supply-chain', '供应链风险', findings, '未发现未固定版本的 npx -y / uvx 远程拉取命令', SUPPLY_CHAIN_REMEDIATION);
30
+ }
31
+ /** 从 JSON/TOML 结构化配置里收集未固定版本的 npx / uvx 拉取。 */
32
+ function supplyFindingsFromStructured(file, parsed, findings) {
33
+ const defs = [];
34
+ (0, supply_chain_1.collectMcpDefs)(parsed, defs);
35
+ for (const def of defs) {
36
+ (0, supply_chain_1.inspectMcpDef)(def, file, (risk) => findings.push(supplyRiskFinding(risk)));
37
+ }
38
+ }
18
39
  async function fileExists(targetPath) {
19
40
  try {
20
41
  await promises_1.default.access(targetPath);
@@ -253,6 +274,43 @@ async function doctorLiveClaude(root) {
253
274
  path: p,
254
275
  }));
255
276
  checks.push(makeCheck('run-state', '运行态隔离', runStateFindings, '运行态文件被排除在导出之外'));
277
+ // 5. 供应链风险:未固定版本的 npx -y / uvx 远程拉取
278
+ const supplyFindings = [];
279
+ for (const file of [node_path_1.default.join(claudeDir, 'settings.json'), node_path_1.default.join(root, '.claude.json')]) {
280
+ if (!(await fileExists(file))) {
281
+ continue;
282
+ }
283
+ try {
284
+ supplyFindingsFromStructured(file, JSON.parse(await promises_1.default.readFile(file, 'utf8')), supplyFindings);
285
+ }
286
+ catch {
287
+ // 解析失败已在 config-valid 检查中报告
288
+ }
289
+ }
290
+ // hooks 脚本里的 npx -y 多为文档示例,逐条收集后汇总成一条警告
291
+ const textNpxFiles = new Set();
292
+ let textNpxHits = 0;
293
+ for (const entry of domain.hooks) {
294
+ try {
295
+ const specs = (0, supply_chain_1.collectTextNpxSpecs)(await promises_1.default.readFile(entry.path, 'utf8'));
296
+ if (specs.length > 0) {
297
+ textNpxHits += specs.length;
298
+ textNpxFiles.add(entry.path);
299
+ }
300
+ }
301
+ catch {
302
+ // 不可读脚本跳过
303
+ }
304
+ }
305
+ if (textNpxHits > 0) {
306
+ const files = [...textNpxFiles];
307
+ supplyFindings.push({
308
+ severity: 'warn',
309
+ message: `${files.length} 个 hook 脚本中出现 ${textNpxHits} 处 \`npx -y\` 未固定版本命令(若会被执行请固定版本)`,
310
+ path: files.join(', '),
311
+ });
312
+ }
313
+ checks.push(supplyChainCheck(supplyFindings));
256
314
  return checks;
257
315
  }
258
316
  async function doctorLiveCodex(root) {
@@ -363,6 +421,17 @@ async function doctorLiveCodex(root) {
363
421
  path: p,
364
422
  }));
365
423
  checks.push(makeCheck('run-state', '运行态隔离', runStateFindings, '运行态文件被排除在导出之外'));
424
+ // 5. 供应链风险:未固定版本的 npx -y / uvx 远程拉取
425
+ const supplyFindings = [];
426
+ if (await fileExists(configPath)) {
427
+ try {
428
+ supplyFindingsFromStructured(configPath, (0, smol_toml_1.parse)(await promises_1.default.readFile(configPath, 'utf8')), supplyFindings);
429
+ }
430
+ catch {
431
+ // 解析失败已在 config-valid 检查中报告
432
+ }
433
+ }
434
+ checks.push(supplyChainCheck(supplyFindings));
366
435
  return checks;
367
436
  }
368
437
  async function doctorLive(options) {
@@ -123,6 +123,62 @@ function renderShareCard(report) {
123
123
  <p class="share-card-note">仅含评分与数量,不含路径、变量名与配置内容。由 AgentDock 生成。</p>
124
124
  </section>`;
125
125
  }
126
+ function renderNextSteps(report) {
127
+ // 按体检模式给出可复制的下一步命令:live → 先 scan 再打包;scan → 打包;
128
+ // package → 审计 + 安装。全部本地执行,不联网、不上传。
129
+ const steps = [];
130
+ if (report.mode === 'package') {
131
+ steps.push({
132
+ title: '审计安装包',
133
+ detail: '检查完整性、签名与供应链风险,确认无泄露后再安装。',
134
+ command: `agentdock verify ${'<包目录>'} --strict`,
135
+ }, {
136
+ title: '安装到目标机',
137
+ detail: '按 .env.example 填好真实值后安装;冲突项默认跳过。',
138
+ command: `agentdock install ${'<包目录>'} ${'<目标目录>'}`,
139
+ });
140
+ }
141
+ else if (report.mode === 'scan') {
142
+ steps.push({
143
+ title: '生成可分发安装包',
144
+ detail: '令牌自动打码为占位符,真实值留在本机 .env。',
145
+ command: `agentdock pack --from-scan ${'<扫描目录>/agentdock.scan.yml'} --out ${'<包目录>'} --zip`,
146
+ }, {
147
+ title: '审计安装包',
148
+ detail: '确认没有明文令牌、完整性校验通过。',
149
+ command: `agentdock doctor --package ${'<包目录>'}`,
150
+ });
151
+ }
152
+ else {
153
+ steps.push({
154
+ title: '扫描当前环境',
155
+ detail: '生成迁移清单,并隔离配置中的密钥。',
156
+ command: 'agentdock scan --agent all --out ./agentdock-scan',
157
+ }, {
158
+ title: '打包并打码',
159
+ detail: '把 scan 产物打成安装包,令牌替换为占位符。',
160
+ command: `agentdock pack --from-scan ./agentdock-scan/agentdock.scan.yml --out ./agentdock-package --zip`,
161
+ }, {
162
+ title: '在目标机还原',
163
+ detail: '先填 .env,再安装;可加 --dry-run 预览。',
164
+ command: `agentdock install ./agentdock-package ${'<目标目录>'}`,
165
+ });
166
+ }
167
+ const items = steps
168
+ .map((step, index) => `
169
+ <li class="step">
170
+ <div class="step-head"><span class="step-index">${index + 1}</span><span class="step-title">${escapeHtml(step.title)}</span></div>
171
+ <p class="step-detail">${escapeHtml(step.detail)}</p>
172
+ <code class="step-command">${escapeHtml(step.command)}</code>
173
+ </li>`)
174
+ .join('');
175
+ return `
176
+ <section class="card">
177
+ <h2>下一步</h2>
178
+ <ol class="steps">${items}</ol>
179
+ <p class="muted">所有命令均在本机执行,不联网、不上传配置。完整用法见 <code>agentdock --help</code>。</p>
180
+ </section>`;
181
+ }
126
182
  const STYLES = `
127
183
  :root {
128
184
  color-scheme: light;
@@ -243,6 +299,20 @@ const STYLES = `
243
299
  .share-stat-label { font-size: 12px; color: var(--muted); }
244
300
  .share-card-note { margin: 18px 0 0; font-size: 12px; color: var(--muted); }
245
301
  .muted { color: var(--muted); font-size: 14px; }
302
+ .steps { margin: 0; padding: 0; list-style: none; display: grid; gap: 12px; }
303
+ .step { border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px; background: #fafbff; }
304
+ .step-head { display: flex; align-items: center; gap: 10px; }
305
+ .step-index {
306
+ width: 22px; height: 22px; border-radius: 999px; background: var(--accent); color: #fff;
307
+ display: inline-flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700;
308
+ }
309
+ .step-title { font-weight: 600; font-size: 14px; }
310
+ .step-detail { margin: 6px 0 8px; color: var(--muted); font-size: 13px; }
311
+ .step-command {
312
+ display: block; background: #101828; color: #e6e9f0; border-radius: 8px;
313
+ padding: 9px 12px; font-size: 12px; word-break: break-all;
314
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
315
+ }
246
316
  @media (max-width: 640px) {
247
317
  .hero { grid-template-columns: 1fr; justify-items: center; text-align: center; }
248
318
  .stat-line { justify-content: center; }
@@ -303,6 +373,8 @@ function renderReportHtml(report) {
303
373
  ${renderRemediation(report)}
304
374
  </section>
305
375
 
376
+ ${renderNextSteps(report)}
377
+
306
378
  ${renderShareCard(report)}
307
379
  </div>
308
380
  </body>
@@ -97,6 +97,16 @@ async function exportFromScan(options) {
97
97
  await (0, fs_1.ensureDirectory)(payloadSourcesRoot);
98
98
  const sources = [];
99
99
  const freeTextSecrets = [];
100
+ // 一次导出共享同一占位符键分配表:同名 leaf 键同值共享、异值 _2/_3 消歧。
101
+ const secretKeyRegistry = (0, sensitive_1.createSecretKeyRegistry)();
102
+ const structuredSecrets = new Map();
103
+ const recordAllocated = (items) => {
104
+ for (const item of items) {
105
+ if (!structuredSecrets.has(item.key)) {
106
+ structuredSecrets.set(item.key, item);
107
+ }
108
+ }
109
+ };
100
110
  const toFrom = (diskRel) => `payload/sources/${diskRel}`;
101
111
  /**
102
112
  * Walk a copied directory and mask (or re-inject, when `env` is set)
@@ -158,7 +168,7 @@ async function exportFromScan(options) {
158
168
  continue;
159
169
  }
160
170
  const cloned = JSON.parse(JSON.stringify(def));
161
- (0, sensitive_1.maskSecretsInPlace)(cloned, `${claudeJsonPath}#mcpServers.${name}`, agent, env);
171
+ recordAllocated((0, sensitive_1.maskSecretsInPlace)(cloned, `${claudeJsonPath}#mcpServers.${name}`, agent, env, undefined, secretKeyRegistry));
162
172
  merged.mcpServers[name] = cloned;
163
173
  }
164
174
  const diskRel = '.agentdock-mcp.json';
@@ -195,7 +205,7 @@ async function exportFromScan(options) {
195
205
  // lands back as a valid .codex/config.toml.
196
206
  try {
197
207
  const parsed = (0, smol_toml_1.parse)(await promises_1.default.readFile(entry.path, 'utf8'));
198
- (0, sensitive_1.maskSecretsInPlace)(parsed, entry.path, agent, env);
208
+ recordAllocated((0, sensitive_1.maskSecretsInPlace)(parsed, entry.path, agent, env, undefined, secretKeyRegistry));
199
209
  await (0, fs_1.writeTextFile)(targetDisk, (0, smol_toml_1.stringify)(parsed));
200
210
  }
201
211
  catch (parseErr) {
@@ -209,7 +219,7 @@ async function exportFromScan(options) {
209
219
  else {
210
220
  try {
211
221
  const obj = JSON.parse(await promises_1.default.readFile(entry.path, 'utf8'));
212
- (0, sensitive_1.maskSecretsInPlace)(obj, entry.path, agent, env);
222
+ recordAllocated((0, sensitive_1.maskSecretsInPlace)(obj, entry.path, agent, env, undefined, secretKeyRegistry));
213
223
  await (0, fs_1.writeTextFile)(targetDisk, JSON.stringify(obj, null, 2));
214
224
  }
215
225
  catch (parseErr) {
@@ -266,8 +276,16 @@ async function exportFromScan(options) {
266
276
  // Free-text secrets discovered during export are folded into the resolved
267
277
  // manifest + the package's own `.env.example` so `--env` re-injection
268
278
  // and `doctor --package` stay consistent end-to-end.
279
+ //
280
+ // Structured keys come from the export-side allocation table (source of
281
+ // truth for the actual `{{...}}` placeholders written into the payload),
282
+ // which disambiguates same-name leaf keys across MCP servers / settings.
269
283
  const augmentedSecrets = [
270
- ...manifest.secrets,
284
+ ...[...structuredSecrets.values()].map((item) => ({
285
+ key: item.key,
286
+ source: item.source,
287
+ sample: item.sample,
288
+ })),
271
289
  ...freeTextSecrets.map((secret) => ({
272
290
  key: secret.key,
273
291
  source: secret.source,
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ /**
3
+ * 供应链风险共享检测(attest / doctor / report 复用)。
4
+ *
5
+ * 覆盖面:未固定版本的 `npx -y` / `uvx` 远程包拉取执行——远端内容可随时变化,
6
+ * 安装即执行,是 AI 助手配置里最常见的供应链攻击面。
7
+ * 自由文本(skills/agents/memory/hooks 脚本)中的 `npx -y` 多为文档示例,
8
+ * 由 `collectTextNpxSpecs` 逐行收集后由调用方汇总成一条中风险,避免误报成高风险。
9
+ *
10
+ * 权限类风险(bypassPermissions / 过宽 Bash / hook 定义)只在 attest 的包审计
11
+ * 中启用,不在 doctor 的 live 体检里重复报警。
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.isPinnedSpec = isPinnedSpec;
15
+ exports.collectMcpDefs = collectMcpDefs;
16
+ exports.inspectCommandTokens = inspectCommandTokens;
17
+ exports.inspectMcpDef = inspectMcpDef;
18
+ exports.collectTextNpxSpecs = collectTextNpxSpecs;
19
+ /** 无版本号 → 远端每次拉取/执行的内容都可能变(供应链风险)。 */
20
+ function isPinnedSpec(spec) {
21
+ if (!spec) {
22
+ return false;
23
+ }
24
+ const at = spec.startsWith('@') ? spec.indexOf('@', 1) : spec.indexOf('@');
25
+ return at > 0;
26
+ }
27
+ /** 从 JSON/TOML 结构里挑出 mcpServers / mcp_servers 定义。 */
28
+ function collectMcpDefs(value, out) {
29
+ if (Array.isArray(value)) {
30
+ for (const item of value) {
31
+ collectMcpDefs(item, out);
32
+ }
33
+ return;
34
+ }
35
+ if (!value || typeof value !== 'object') {
36
+ return;
37
+ }
38
+ const obj = value;
39
+ for (const key of ['mcpServers', 'mcp_servers']) {
40
+ const servers = obj[key];
41
+ if (servers && typeof servers === 'object' && !Array.isArray(servers)) {
42
+ for (const def of Object.values(servers)) {
43
+ if (def && typeof def === 'object' && !Array.isArray(def)) {
44
+ out.push(def);
45
+ }
46
+ }
47
+ }
48
+ }
49
+ for (const child of Object.values(obj)) {
50
+ collectMcpDefs(child, out);
51
+ }
52
+ }
53
+ /**
54
+ * 检查一条命令行(command + args 拆成的 tokens)里的 npx / uvx 是否未固定版本。
55
+ */
56
+ function inspectCommandTokens(tokens, file, add) {
57
+ const npxIndex = tokens.findIndex((token) => /(^|[\\/])npx(\.cmd|\.exe)?$/i.test(token));
58
+ if (npxIndex >= 0) {
59
+ const rest = tokens.slice(npxIndex + 1);
60
+ if (rest.includes('-y') || rest.includes('--yes')) {
61
+ const spec = rest.find((token) => !token.startsWith('-'));
62
+ if (spec && !isPinnedSpec(spec)) {
63
+ add({
64
+ level: 'high',
65
+ id: 'unpinned-npx',
66
+ message: `MCP 使用 npx -y 拉取未固定版本的远程包并执行:${spec}`,
67
+ evidence: `${file} (${spec})`,
68
+ });
69
+ }
70
+ }
71
+ }
72
+ const uvxIndex = tokens.findIndex((token) => /(^|[\\/])uvx(\.exe)?$/i.test(token));
73
+ if (uvxIndex >= 0) {
74
+ const spec = tokens.slice(uvxIndex + 1).find((token) => !token.startsWith('-'));
75
+ if (spec && !isPinnedSpec(spec)) {
76
+ add({
77
+ level: 'medium',
78
+ id: 'unpinned-uvx',
79
+ message: `MCP 使用 uvx 拉取未固定版本的 Python 包并执行:${spec}`,
80
+ evidence: `${file} (${spec})`,
81
+ });
82
+ }
83
+ }
84
+ }
85
+ /** 从解析后的 JSON/TOML 定义中提取 command + args 并做供应链检查。 */
86
+ function inspectMcpDef(def, file, add) {
87
+ const command = typeof def.command === 'string' ? def.command : '';
88
+ const args = Array.isArray(def.args) ? def.args.filter((arg) => typeof arg === 'string') : [];
89
+ const tokens = `${command} ${args.join(' ')}`.trim().split(/\s+/).filter(Boolean);
90
+ inspectCommandTokens(tokens, file, add);
91
+ }
92
+ /**
93
+ * 自由文本(skill / memory / 脚本)里的 `npx -y` 多为文档示例。
94
+ * 逐行收集未固定版本的 spec,由调用方汇总,避免把文档示例误报成高风险。
95
+ */
96
+ function collectTextNpxSpecs(text) {
97
+ const specs = [];
98
+ for (const line of text.split(/\r?\n/)) {
99
+ const tokens = line.split(/[\s"'`,;:(){}[\]<>]+/).filter(Boolean);
100
+ const index = tokens.findIndex((token) => /(^|[\\/])npx(\.cmd|\.exe)?$/i.test(token));
101
+ if (index < 0) {
102
+ continue;
103
+ }
104
+ const rest = tokens.slice(index + 1);
105
+ if (!rest.includes('-y') && !rest.includes('--yes')) {
106
+ continue;
107
+ }
108
+ const spec = rest.find((token) => !token.startsWith('-'));
109
+ if (spec && !isPinnedSpec(spec)) {
110
+ specs.push(spec);
111
+ }
112
+ }
113
+ return specs;
114
+ }
@@ -13,6 +13,8 @@ exports.isSecretKey = isSecretKey;
13
13
  exports.looksLikeSecret = looksLikeSecret;
14
14
  exports.findSecretLeaks = findSecretLeaks;
15
15
  exports.maskSecret = maskSecret;
16
+ exports.createSecretKeyRegistry = createSecretKeyRegistry;
17
+ exports.allocateSecretKey = allocateSecretKey;
16
18
  exports.collectSecrets = collectSecrets;
17
19
  exports.secretKeyName = secretKeyName;
18
20
  exports.maskSecretsInPlace = maskSecretsInPlace;
@@ -89,6 +91,31 @@ function maskSecret(value) {
89
91
  }
90
92
  return `${value.slice(0, 4)}****${value.slice(-4)}`;
91
93
  }
94
+ function createSecretKeyRegistry() {
95
+ return { assigned: new Map() };
96
+ }
97
+ /** 为 `value` 分配一个以 `baseName` 为前缀的唯一占位符键(确定性:值相同必得同名)。 */
98
+ function allocateSecretKey(registry, baseName, value) {
99
+ const existing = registry.assigned.get(baseName);
100
+ if (existing === undefined) {
101
+ registry.assigned.set(baseName, value);
102
+ return baseName;
103
+ }
104
+ if (existing === value) {
105
+ return baseName;
106
+ }
107
+ for (let n = 2;; n++) {
108
+ const candidate = `${baseName}_${n}`;
109
+ const held = registry.assigned.get(candidate);
110
+ if (held === undefined) {
111
+ registry.assigned.set(candidate, value);
112
+ return candidate;
113
+ }
114
+ if (held === value) {
115
+ return candidate;
116
+ }
117
+ }
118
+ }
92
119
  /**
93
120
  * Recursively walk a parsed JSON value and collect every leaf that looks like a
94
121
  * secret. `seen` guards against cyclic objects (e.g. shared sub-objects).
@@ -129,38 +156,50 @@ function secretKeyName(agent, jsonPath) {
129
156
  * mutating in place. Mirrors the detection used during `scan` so the placeholder names
130
157
  * match what `renderEnvExample` emitted. Used by the scan→package bridge.
131
158
  *
159
+ * Returns the placeholder keys actually allocated by this call, so the caller can
160
+ * rebuild the package's `.env.example` / resolved manifest from real assignments
161
+ * (scan-time key names may collide across MCP servers; the export-side registry is
162
+ * the source of truth).
163
+ *
132
164
  * When `secretsEnv` is supplied (keyed by the secret placeholder name, e.g.
133
- * `AGENTDOCK_CLUDE_GITHUB_TOKEN`), the real value is written back directly instead of
165
+ * `AGENTDOCK_CLAUDE_GITHUB_TOKEN`), the real value is written back directly instead of
134
166
  * the placeholder — this keeps masking and re-injection on the same object so they can
135
167
  * never desync (no fragile string placeholder matching).
168
+ *
169
+ * `registry` lets consecutive calls (per MCP server / per settings file) share one
170
+ * allocation table; omitted, each call gets a private table (still disambiguating
171
+ * conflicts within the same file).
136
172
  */
137
- function maskSecretsInPlace(node, basePath, agent, secretsEnv, seen = new WeakSet()) {
173
+ function maskSecretsInPlace(node, basePath, agent, secretsEnv, seen = new WeakSet(), registry = createSecretKeyRegistry()) {
138
174
  if (node === null || typeof node !== 'object') {
139
- return;
175
+ return [];
140
176
  }
141
177
  if (seen.has(node)) {
142
- return;
178
+ return [];
143
179
  }
144
180
  seen.add(node);
181
+ const allocated = [];
145
182
  if (Array.isArray(node)) {
146
183
  node.forEach((item, index) => {
147
- maskSecretsInPlace(item, `${basePath}[${index}]`, agent, secretsEnv, seen);
184
+ allocated.push(...maskSecretsInPlace(item, `${basePath}[${index}]`, agent, secretsEnv, seen, registry));
148
185
  });
149
- return;
186
+ return allocated;
150
187
  }
151
188
  for (const [key, value] of Object.entries(node)) {
152
189
  const childPath = `${basePath}.${key}`;
153
190
  if (typeof value === 'string') {
154
191
  if (isSecretKey(key) || looksLikeSecret(value)) {
155
- const secretName = secretKeyName(agent, childPath);
192
+ const keyName = allocateSecretKey(registry, secretKeyName(agent, childPath), value);
156
193
  node[key] =
157
- secretsEnv && secretsEnv[secretName] !== undefined ? secretsEnv[secretName] : `{{${secretName}}}`;
194
+ secretsEnv && secretsEnv[keyName] !== undefined ? secretsEnv[keyName] : `{{${keyName}}}`;
195
+ allocated.push({ key: keyName, sample: maskSecret(value), source: childPath });
158
196
  }
159
197
  }
160
198
  else if (typeof value === 'object' && value !== null) {
161
- maskSecretsInPlace(value, childPath, agent, secretsEnv, seen);
199
+ allocated.push(...maskSecretsInPlace(value, childPath, agent, secretsEnv, seen, registry));
162
200
  }
163
201
  }
202
+ return allocated;
164
203
  }
165
204
  /**
166
205
  * Stable short hash so the same token maps to the same placeholder key across
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentdock-cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Diagnose, migrate, and back up your AI coding assistant environment (Claude Code / Codex) — Chinese health reports, MCP servers, Skills, Agents, Plugins, Hooks, and memory, with secret isolation.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -36,6 +36,7 @@
36
36
  "dev": "tsx src/cli.ts",
37
37
  "test": "vitest run",
38
38
  "e2e": "tsx scripts/e2e.ts",
39
+ "e2e:sync": "tsx scripts/e2e-sync.ts",
39
40
  "cli": "tsx src/cli.ts",
40
41
  "prepublishOnly": "npm run build",
41
42
  "release:commits": "node scripts/generate-commit-groups.js"