agentdock-cli 0.4.3 → 0.5.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": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "Migrate, back up, and version your AI coding assistant environment (Claude Code / Codex) — MCP servers, Skills, Agents, Plugins, Hooks, and memory — as a portable, secret-isolated package.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -220,7 +220,7 @@ async function doctorLiveClaude(root) {
220
220
  if (leaks.length) {
221
221
  leakFindings.push({
222
222
  severity: 'error',
223
- message: `在"原文复制"文件中发现 ${leaks.length} 处疑似真实令牌,scan 不会对其打码,迁移会泄露`,
223
+ message: `在"原文复制"文件(skills/agents/memory/hooks/plugins)中发现 ${leaks.length} 处疑似真实令牌;scan 不在扫描期打码,但 \`export --from-scan\` 会自动打码(安全),不会随包泄露`,
224
224
  path: entry.path,
225
225
  });
226
226
  }
@@ -244,7 +244,7 @@ async function doctorLiveClaude(root) {
244
244
  }
245
245
  }
246
246
  }
247
- checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露', '存在明文令牌的"原文复制"文件(skills/agents/memory/hooks/plugins)scan 不会自动打码。请将明文令牌替换为 `{{AGENTDOCK_<AGENT>_<KEY>}}` 占位符并移入 `.env`;若该文件不应随迁移携带,可在 `scan` 后手动剔除。切勿连同真实令牌一起打包分发。'));
247
+ checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露', '免费文本中的明文令牌,`scan` 不在扫描期打码,但 `export --from-scan` 会自动打码(安全),不会随包泄露;若 `doctor --package` 仍报泄露,说明该文件未被正确打码,可手动将明文替换为 `{{AGENTDOCK_<AGENT>_<KEY>}}` 占位符。'));
248
248
  // 4. 运行态隔离
249
249
  const runState = await walkForRunState(claudeDir);
250
250
  const runStateFindings = runState.map((p) => ({
@@ -332,7 +332,7 @@ async function doctorLiveCodex(root) {
332
332
  if (leaks.length) {
333
333
  leakFindings.push({
334
334
  severity: 'error',
335
- message: `在"原文复制"文件中发现 ${leaks.length} 处疑似真实令牌,scan 不会对其打码,迁移会泄露`,
335
+ message: `在"原文复制"文件(skills/agents/memory/hooks/plugins)中发现 ${leaks.length} 处疑似真实令牌;scan 不在扫描期打码,但 \`export --from-scan\` 会自动打码(安全),不会随包泄露`,
336
336
  path: entry.path,
337
337
  });
338
338
  }
@@ -354,7 +354,7 @@ async function doctorLiveCodex(root) {
354
354
  // ignore
355
355
  }
356
356
  }
357
- checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露', '存在明文令牌的"原文复制"文件(skills/agents/memory/hooks/plugins)scan 不会自动打码。请将明文令牌替换为 `{{AGENTDOCK_<AGENT>_<KEY>}}` 占位符并移入 `.env`;若该文件不应随迁移携带,可在 `scan` 后手动剔除。切勿连同真实令牌一起打包分发。'));
357
+ checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露', '免费文本中的明文令牌,`scan` 不在扫描期打码,但 `export --from-scan` 会自动打码(安全),不会随包泄露;若 `doctor --package` 仍报泄露,说明该文件未被正确打码,可手动将明文替换为 `{{AGENTDOCK_<AGENT>_<KEY>}}` 占位符。'));
358
358
  // 4. 运行态隔离
359
359
  const runState = await walkForRunState(codexDir);
360
360
  const runStateFindings = runState.map((p) => ({
@@ -53,6 +53,39 @@ async function isIdenticalDirectory(targetPath, sourcePath) {
53
53
  }
54
54
  return true;
55
55
  }
56
+ /**
57
+ * Recursively merge `source` into `target`. Objects merge key-by-key
58
+ * (source wins on name conflict); arrays / primitives are replaced by source.
59
+ * Used so a merged `.claude.json` keeps the target's other top-level
60
+ * keys and its existing mcpServers while the package's servers win.
61
+ */
62
+ function deepMerge(target, source) {
63
+ if (typeof source !== 'object' || source === null || Array.isArray(source)) {
64
+ return source;
65
+ }
66
+ if (typeof target !== 'object' || target === null || Array.isArray(target)) {
67
+ return source;
68
+ }
69
+ const out = { ...target };
70
+ for (const [key, value] of Object.entries(source)) {
71
+ out[key] = deepMerge(target[key], value);
72
+ }
73
+ return out;
74
+ }
75
+ async function mergeJsonFile(from, to) {
76
+ const source = JSON.parse(await promises_1.default.readFile(from, 'utf8'));
77
+ let target = {};
78
+ if (await (0, fs_1.pathExists)(to)) {
79
+ try {
80
+ target = JSON.parse(await promises_1.default.readFile(to, 'utf8'));
81
+ }
82
+ catch {
83
+ target = {};
84
+ }
85
+ }
86
+ const merged = deepMerge(target, source);
87
+ await (0, fs_1.writeJsonFile)(to, merged);
88
+ }
56
89
  async function installPackage(packagePath, explicitTargetPath, overwrite = false) {
57
90
  const packageRoot = node_path_1.default.resolve(packagePath);
58
91
  const manifestSnapshotPath = node_path_1.default.join(packageRoot, 'manifest.resolved.json');
@@ -75,6 +108,7 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
75
108
  from: (0, fs_1.safeResolveWithin)(packageRoot, source.from, 'source.from'),
76
109
  to: (0, fs_1.safeResolveWithin)(targetRoot, source.to, 'source.to'),
77
110
  kind: source.kind,
111
+ merge: source.merge ?? false,
78
112
  })),
79
113
  ...installPlan.templates.map((template) => ({
80
114
  from: (0, fs_1.safeResolveWithin)(packageRoot, template.from, 'template.from'),
@@ -89,6 +123,10 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
89
123
  try {
90
124
  const conflicts = [];
91
125
  for (const entry of entries) {
126
+ // Merge entries blend into the existing target; they never conflict.
127
+ if (entry.merge) {
128
+ continue;
129
+ }
92
130
  if (!(await (0, fs_1.pathExists)(entry.to))) {
93
131
  continue;
94
132
  }
@@ -110,6 +148,12 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
110
148
  throw new Error(`Install conflict detected:\n${conflicts.join('\n')}`);
111
149
  }
112
150
  for (const entry of entries) {
151
+ if (entry.merge) {
152
+ // Deep-merge JSON into the existing target (preserving other
153
+ // top-level keys / other mcpServers). Never clobbers it.
154
+ await mergeJsonFile(entry.from, entry.to);
155
+ continue;
156
+ }
113
157
  if (entry.kind === 'directory') {
114
158
  await (0, fs_1.copyDirectorySafe)(entry.from, entry.to);
115
159
  }
@@ -95,7 +95,45 @@ async function exportFromScan(options) {
95
95
  const payloadSourcesRoot = node_path_1.default.join(outputPath, 'payload', 'sources');
96
96
  await (0, fs_1.ensureDirectory)(payloadSourcesRoot);
97
97
  const sources = [];
98
+ const freeTextSecrets = [];
98
99
  const toFrom = (diskRel) => `payload/sources/${diskRel}`;
100
+ /**
101
+ * Walk a copied directory and mask (or re-inject, when `env` is set)
102
+ * leaked secret tokens in every text file. Skips files with no leak and
103
+ * no placeholder so binaries / clean files are never rewritten.
104
+ */
105
+ async function processDirectoryTexts(dir, agent) {
106
+ let entries;
107
+ try {
108
+ entries = await promises_1.default.readdir(dir, { withFileTypes: true });
109
+ }
110
+ catch {
111
+ return;
112
+ }
113
+ for (const entry of entries) {
114
+ const full = node_path_1.default.join(dir, entry.name);
115
+ if (entry.isDirectory()) {
116
+ await processDirectoryTexts(full, agent);
117
+ continue;
118
+ }
119
+ let content;
120
+ try {
121
+ content = await promises_1.default.readFile(full, 'utf8');
122
+ }
123
+ catch {
124
+ continue; // unreadable / binary — leave untouched
125
+ }
126
+ const hasLeak = (0, sensitive_1.findSecretLeaks)(content).length > 0;
127
+ const hasPlaceholder = env ? /\{\{AGENTDOCK_[A-Z0-9_]+\}\}/.test(content) : false;
128
+ if (!hasLeak && !hasPlaceholder) {
129
+ continue;
130
+ }
131
+ const out = env
132
+ ? (0, sensitive_1.injectSecretsInText)((0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets), env)
133
+ : (0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets);
134
+ await (0, fs_1.writeTextFile)(full, out);
135
+ }
136
+ }
99
137
  for (const [agentName, domain] of Object.entries(manifest.agents)) {
100
138
  if (!domain) {
101
139
  continue;
@@ -125,7 +163,11 @@ async function exportFromScan(options) {
125
163
  const diskRel = '.agentdock-mcp.json';
126
164
  const content = JSON.stringify(merged, null, 2);
127
165
  await (0, fs_1.writeTextFile)(node_path_1.default.join(payloadSourcesRoot, diskRel), content);
128
- sources.push({ id: `${agent}-mcp-merged`, kind: 'file', from: toFrom(diskRel), to: '.claude.json' });
166
+ // `merge: true` → installer deep-merges this JSON into the target's
167
+ // existing file (preserving other top-level keys / other mcpServers)
168
+ // instead of overwriting it. Makes `install` safe on a machine
169
+ // that already has a `.claude.json`.
170
+ sources.push({ id: `${agent}-mcp-merged`, kind: 'file', from: toFrom(diskRel), to: '.claude.json', merge: true });
129
171
  }
130
172
  // --- Everything else ---
131
173
  for (const entry of iterEntries(domain)) {
@@ -140,8 +182,10 @@ async function exportFromScan(options) {
140
182
  const kind = stat.isDirectory() ? 'directory' : 'file';
141
183
  const targetDisk = node_path_1.default.join(payloadSourcesRoot, rel);
142
184
  if (kind === 'directory') {
143
- // verbatim recursive copy (skill dirs); re-injection skipped for directories in v0.3
185
+ // recursive copy (skill dirs), then mask/inject any leaked
186
+ // tokens inside the copied text files (prevents plaintext riding into the package)
144
187
  await (0, fs_1.copyDirectorySafe)(entry.path, targetDisk);
188
+ await processDirectoryTexts(targetDisk, agent);
145
189
  }
146
190
  else if (entry.kind === 'settings') {
147
191
  if (node_path_1.default.extname(entry.path) === '.toml') {
@@ -175,11 +219,28 @@ async function exportFromScan(options) {
175
219
  }
176
220
  else {
177
221
  // skill .md / agent .md / plugin json / hook script / memory md:
178
- // copied verbatim. In v0.2 `scan` isolates secrets only from settings
179
- // + mcpServers, so masking free text or plugin registries here would
180
- // risk false-positive corruption. Re-injection is handled at the
181
- // object level for JSON secrets above.
182
- await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
222
+ // mask (or re-inject when `env` is set) any leaked secret tokens
223
+ // so plaintext never rides into the package. Clean files (no leak,
224
+ // no placeholder) are copied verbatim.
225
+ let content;
226
+ try {
227
+ content = await promises_1.default.readFile(entry.path, 'utf8');
228
+ }
229
+ catch {
230
+ await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
231
+ continue;
232
+ }
233
+ const hasLeak = (0, sensitive_1.findSecretLeaks)(content).length > 0;
234
+ const hasPlaceholder = env ? /\{\{AGENTDOCK_[A-Z0-9_]+\}\}/.test(content) : false;
235
+ if (!hasLeak && !hasPlaceholder) {
236
+ await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
237
+ }
238
+ else {
239
+ const out = env
240
+ ? (0, sensitive_1.injectSecretsInText)((0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets), env)
241
+ : (0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets);
242
+ await (0, fs_1.writeTextFile)(targetDisk, out);
243
+ }
183
244
  }
184
245
  sources.push({ id: entry.id, kind, from: toFrom(rel), to: rel });
185
246
  }
@@ -192,7 +253,23 @@ async function exportFromScan(options) {
192
253
  const snapshotPath = node_path_1.default.join(outputPath, 'manifest.resolved.json');
193
254
  const installPlanPath = node_path_1.default.join(outputPath, 'meta', 'install-plan.json');
194
255
  const packageMetadataPath = node_path_1.default.join(outputPath, 'package.json');
195
- await (0, fs_1.writeJsonFile)(snapshotPath, manifest);
256
+ const envExamplePath = node_path_1.default.join(outputPath, '.env.example');
257
+ // Free-text secrets discovered during export are folded into the resolved
258
+ // manifest + the package's own `.env.example` so `--env` re-injection
259
+ // and `doctor --package` stay consistent end-to-end.
260
+ const augmentedSecrets = [
261
+ ...manifest.secrets,
262
+ ...freeTextSecrets.map((secret) => ({
263
+ key: secret.key,
264
+ source: secret.source,
265
+ sample: secret.sample,
266
+ })),
267
+ ];
268
+ const resolvedManifest = {
269
+ ...manifest,
270
+ secrets: augmentedSecrets,
271
+ };
272
+ await (0, fs_1.writeJsonFile)(snapshotPath, resolvedManifest);
196
273
  await (0, fs_1.writeJsonFile)(installPlanPath, installPlan);
197
274
  await (0, fs_1.writeJsonFile)(packageMetadataPath, {
198
275
  name: 'agentdock-scan-package',
@@ -200,6 +277,7 @@ async function exportFromScan(options) {
200
277
  project: manifest.project.name,
201
278
  manifestVersion: 3,
202
279
  });
280
+ await (0, fs_1.writeTextFile)(envExamplePath, (0, sensitive_1.renderEnvExample)(augmentedSecrets));
203
281
  return { outputPath, snapshotPath, installPlanPath };
204
282
  }
205
283
  finally {
@@ -16,6 +16,8 @@ exports.maskSecret = maskSecret;
16
16
  exports.collectSecrets = collectSecrets;
17
17
  exports.secretKeyName = secretKeyName;
18
18
  exports.maskSecretsInPlace = maskSecretsInPlace;
19
+ exports.maskSecretsInText = maskSecretsInText;
20
+ exports.injectSecretsInText = injectSecretsInText;
19
21
  exports.renderEnvExample = renderEnvExample;
20
22
  const SECRET_KEY_PATTERN = /(token|api[_-]?key|secret|password|passwd|auth|private[_-]?key|credential|access[_-]?key)/i;
21
23
  const SECRET_VALUE_PATTERNS = [
@@ -156,6 +158,53 @@ function maskSecretsInPlace(node, basePath, agent, secretsEnv, seen = new WeakSe
156
158
  }
157
159
  }
158
160
  }
161
+ /**
162
+ * Stable short hash so the same token maps to the same placeholder key across
163
+ * files (keeps `.env.example` / re-injection deduped and deterministic).
164
+ */
165
+ function stableHash(input) {
166
+ let h = 0x811c9dc5;
167
+ for (let i = 0; i < input.length; i++) {
168
+ h ^= input.charCodeAt(i);
169
+ h = Math.imul(h, 0x01000193);
170
+ }
171
+ return (h >>> 0).toString(36).toUpperCase().padStart(7, '0').slice(0, 7);
172
+ }
173
+ /**
174
+ * Mask every secret token found in free text (skills/agents/memory/hooks `.md`,
175
+ * etc.) with a stable `{{AGENTDOCK_<AGENT>_FREETEXT_<HASH>}}` placeholder,
176
+ * and record each as a secret so `.env.example` + `--env` re-injection stay
177
+ * consistent. Replaces the previous verbatim copy that let real tokens ride
178
+ * into the package. Detection uses the same value patterns as `looksLikeSecret`
179
+ * / `findSecretLeaks`.
180
+ */
181
+ function maskSecretsInText(text, agent, accumulator) {
182
+ const tokens = [...new Set(findSecretLeaks(text))];
183
+ if (tokens.length === 0) {
184
+ return text;
185
+ }
186
+ // Longest tokens first so a prefix token can't swallow a longer one.
187
+ tokens.sort((a, b) => b.length - a.length);
188
+ let out = text;
189
+ for (const token of tokens) {
190
+ const key = `AGENTDOCK_${agent.toUpperCase()}_FREETEXT_${stableHash(token)}`;
191
+ const placeholder = `{{${key}}}`;
192
+ if (out.includes(placeholder)) {
193
+ continue;
194
+ }
195
+ out = out.split(token).join(placeholder);
196
+ accumulator.push({ key, sample: maskSecret(token), source: 'freetext' });
197
+ }
198
+ return out;
199
+ }
200
+ /**
201
+ * Re-inject real values into free text for an `--env` export. Placeholders use
202
+ * the same `{{AGENTDOCK_*_FREETEXT_*}}` names emitted by `maskSecretsInText`,
203
+ * keyed by the env file's `AGENTDOCK_*` keys.
204
+ */
205
+ function injectSecretsInText(text, secretsEnv) {
206
+ return text.replace(/\{\{(AGENTDOCK_[A-Z0-9_]+)\}\}/g, (match, key) => secretsEnv[key] !== undefined ? secretsEnv[key] : match);
207
+ }
159
208
  /**
160
209
  * Render a `.env.example` from isolated secrets. Only placeholder keys are
161
210
  * written — never the real values, which stay on the source machine.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentdock-cli",
3
- "version": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "Migrate, back up, and version your AI coding assistant environment (Claude Code / Codex) — MCP servers, Skills, Agents, Plugins, Hooks, and memory — as a portable, secret-isolated package.",
5
5
  "keywords": [
6
6
  "claude-code",