agentdock-cli 0.7.1 → 1.0.1

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.
@@ -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;
@@ -65,16 +67,20 @@ function findSecretLeaks(text) {
65
67
  continue;
66
68
  }
67
69
  for (const pattern of SECRET_VALUE_PATTERNS) {
68
- const match = pattern.exec(token);
69
- if (match) {
70
- found.add(match[0]);
70
+ if (pattern.test(token)) {
71
+ // 值形态只负责"识别"(大多只匹配前缀,如 sk- / ghp_ / AIza);
72
+ // 打码必须覆盖完整 token,否则前缀替换会残留尾部明文
73
+ // (golden 样本回归用例锁定此行为)。
74
+ found.add(token);
71
75
  break;
72
76
  }
73
77
  }
74
78
  }
75
79
  const bearer = /Bearer\s+([A-Za-z0-9._-]+)/i.exec(line);
76
- if (bearer) {
77
- found.add(`Bearer ${bearer[1]}`);
80
+ // 阈值过滤 `bearer token(s)` 这类文档短语;返回原文匹配(保留大小写),
81
+ // 否则 maskSecretsInText 用构造出的 `Bearer xxx` 去替换小写原文会替换失败。
82
+ if (bearer && bearer[1].length >= 8) {
83
+ found.add(bearer[0]);
78
84
  }
79
85
  }
80
86
  return [...found];
@@ -85,6 +91,31 @@ function maskSecret(value) {
85
91
  }
86
92
  return `${value.slice(0, 4)}****${value.slice(-4)}`;
87
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
+ }
88
119
  /**
89
120
  * Recursively walk a parsed JSON value and collect every leaf that looks like a
90
121
  * secret. `seen` guards against cyclic objects (e.g. shared sub-objects).
@@ -125,38 +156,50 @@ function secretKeyName(agent, jsonPath) {
125
156
  * mutating in place. Mirrors the detection used during `scan` so the placeholder names
126
157
  * match what `renderEnvExample` emitted. Used by the scan→package bridge.
127
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
+ *
128
164
  * When `secretsEnv` is supplied (keyed by the secret placeholder name, e.g.
129
- * `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
130
166
  * the placeholder — this keeps masking and re-injection on the same object so they can
131
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).
132
172
  */
133
- function maskSecretsInPlace(node, basePath, agent, secretsEnv, seen = new WeakSet()) {
173
+ function maskSecretsInPlace(node, basePath, agent, secretsEnv, seen = new WeakSet(), registry = createSecretKeyRegistry()) {
134
174
  if (node === null || typeof node !== 'object') {
135
- return;
175
+ return [];
136
176
  }
137
177
  if (seen.has(node)) {
138
- return;
178
+ return [];
139
179
  }
140
180
  seen.add(node);
181
+ const allocated = [];
141
182
  if (Array.isArray(node)) {
142
183
  node.forEach((item, index) => {
143
- maskSecretsInPlace(item, `${basePath}[${index}]`, agent, secretsEnv, seen);
184
+ allocated.push(...maskSecretsInPlace(item, `${basePath}[${index}]`, agent, secretsEnv, seen, registry));
144
185
  });
145
- return;
186
+ return allocated;
146
187
  }
147
188
  for (const [key, value] of Object.entries(node)) {
148
189
  const childPath = `${basePath}.${key}`;
149
190
  if (typeof value === 'string') {
150
191
  if (isSecretKey(key) || looksLikeSecret(value)) {
151
- const secretName = secretKeyName(agent, childPath);
192
+ const keyName = allocateSecretKey(registry, secretKeyName(agent, childPath), value);
152
193
  node[key] =
153
- 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 });
154
196
  }
155
197
  }
156
198
  else if (typeof value === 'object' && value !== null) {
157
- maskSecretsInPlace(value, childPath, agent, secretsEnv, seen);
199
+ allocated.push(...maskSecretsInPlace(value, childPath, agent, secretsEnv, seen, registry));
158
200
  }
159
201
  }
202
+ return allocated;
160
203
  }
161
204
  /**
162
205
  * Stable short hash so the same token maps to the same placeholder key across
@@ -6,12 +6,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.toJsonError = toJsonError;
7
7
  exports.toJsonLine = toJsonLine;
8
8
  const package_json_1 = __importDefault(require("../../package.json"));
9
+ const format_versions_1 = require("../constants/format-versions");
9
10
  function toJsonError(code, message) {
10
11
  return { code, message };
11
12
  }
12
13
  function toJsonLine(command, success, data, errors) {
13
14
  const report = {
14
- schemaVersion: 1,
15
+ schemaVersion: format_versions_1.JSON_SCHEMA_VERSION,
15
16
  generatedAt: new Date().toISOString(),
16
17
  toolVersion: package_json_1.default.version,
17
18
  command,
@@ -15,6 +15,7 @@ exports.copyDirectorySafe = copyDirectorySafe;
15
15
  exports.pathExists = pathExists;
16
16
  exports.readJsonFile = readJsonFile;
17
17
  exports.writeJsonFile = writeJsonFile;
18
+ exports.writeBinaryFile = writeBinaryFile;
18
19
  const promises_1 = __importDefault(require("node:fs/promises"));
19
20
  const node_path_1 = __importDefault(require("node:path"));
20
21
  const picomatch_1 = __importDefault(require("picomatch"));
@@ -86,6 +87,20 @@ async function writeTextFile(targetPath, content) {
86
87
  await promises_1.default.writeFile(tmpPath, content, 'utf8');
87
88
  await promises_1.default.rename(tmpPath, targetPath);
88
89
  }
90
+ /**
91
+ * Resolve a symlink target. Broken, cyclic or permission-denied links return
92
+ * null so one bad link cannot abort a whole copy.
93
+ */
94
+ async function resolveSymlinkTarget(sourcePath) {
95
+ try {
96
+ const resolvedPath = await promises_1.default.realpath(sourcePath);
97
+ const stat = await promises_1.default.stat(resolvedPath);
98
+ return { resolvedPath, stat };
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
89
104
  async function walkDirectoryWithSymlinkPolicy(currentPath, relativeBase, followSymlinks, visitedRealDirectories = new Set()) {
90
105
  const entries = await promises_1.default.readdir(currentPath, { withFileTypes: true });
91
106
  const files = [];
@@ -106,8 +121,11 @@ async function walkDirectoryWithSymlinkPolicy(currentPath, relativeBase, followS
106
121
  if (!followSymlinks) {
107
122
  continue;
108
123
  }
109
- const resolvedPath = await promises_1.default.realpath(sourcePath);
110
- const stat = await promises_1.default.stat(resolvedPath);
124
+ const resolved = await resolveSymlinkTarget(sourcePath);
125
+ if (!resolved) {
126
+ continue;
127
+ }
128
+ const { resolvedPath, stat } = resolved;
111
129
  if (stat.isDirectory()) {
112
130
  if (visitedRealDirectories.has(resolvedPath)) {
113
131
  continue;
@@ -160,3 +178,10 @@ async function writeJsonFile(targetPath, data) {
160
178
  await promises_1.default.writeFile(tmpPath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
161
179
  await promises_1.default.rename(tmpPath, targetPath);
162
180
  }
181
+ /** 二进制版原子写:tmp + rename。 */
182
+ async function writeBinaryFile(targetPath, data, mode) {
183
+ await ensureDirectory(node_path_1.default.dirname(targetPath));
184
+ const tmpPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`;
185
+ await promises_1.default.writeFile(tmpPath, data, mode === undefined ? {} : { mode });
186
+ await promises_1.default.rename(tmpPath, targetPath);
187
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createZip = createZip;
7
+ exports.readZip = readZip;
8
+ const node_zlib_1 = __importDefault(require("node:zlib"));
9
+ /**
10
+ * 极简 zip 读写(无第三方依赖)。
11
+ * 写入固定使用 store(不压缩),读取支持 store(0) 与 deflate(8)。
12
+ * 仅面向 AgentDock 同步 bundle(文本/小文件),不支持 zip64、加密与分卷。
13
+ */
14
+ const EOCD_SIG = 0x06054b50;
15
+ const CENTRAL_SIG = 0x02014b50;
16
+ const LOCAL_SIG = 0x04034b50;
17
+ // 1980-01-01 00:00:00,保证同内容产物字节一致
18
+ const DOS_TIME = 0;
19
+ const DOS_DATE = 0x0021;
20
+ const CRC_TABLE = (() => {
21
+ const table = new Uint32Array(256);
22
+ for (let n = 0; n < 256; n += 1) {
23
+ let c = n;
24
+ for (let k = 0; k < 8; k += 1) {
25
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
26
+ }
27
+ table[n] = c >>> 0;
28
+ }
29
+ return table;
30
+ })();
31
+ function crc32(buf) {
32
+ let crc = 0xffffffff;
33
+ for (const byte of buf) {
34
+ crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
35
+ }
36
+ return (crc ^ 0xffffffff) >>> 0;
37
+ }
38
+ /** 把若干文件打成 zip;key 为 posix 相对路径。 */
39
+ function createZip(entries) {
40
+ if (entries.size > 0xffff) {
41
+ throw new Error('ZIP_TOO_MANY_FILES: 超出 zip 单卷上限');
42
+ }
43
+ const locals = [];
44
+ const centrals = [];
45
+ let offset = 0;
46
+ for (const [name, data] of entries) {
47
+ const nameBuf = Buffer.from(name, 'utf8');
48
+ const crc = crc32(data);
49
+ const local = Buffer.alloc(30);
50
+ local.writeUInt32LE(LOCAL_SIG, 0);
51
+ local.writeUInt16LE(20, 4); // version needed
52
+ local.writeUInt16LE(0, 6); // flags
53
+ local.writeUInt16LE(0, 8); // method: store
54
+ local.writeUInt16LE(DOS_TIME, 10);
55
+ local.writeUInt16LE(DOS_DATE, 12);
56
+ local.writeUInt32LE(crc, 14);
57
+ local.writeUInt32LE(data.length, 18);
58
+ local.writeUInt32LE(data.length, 22);
59
+ local.writeUInt16LE(nameBuf.length, 26);
60
+ local.writeUInt16LE(0, 28); // extra len
61
+ locals.push(local, nameBuf, data);
62
+ const central = Buffer.alloc(46);
63
+ central.writeUInt32LE(CENTRAL_SIG, 0);
64
+ central.writeUInt16LE(20, 4); // version made by
65
+ central.writeUInt16LE(20, 6); // version needed
66
+ central.writeUInt16LE(0, 8);
67
+ central.writeUInt16LE(0, 10); // method
68
+ central.writeUInt16LE(DOS_TIME, 12);
69
+ central.writeUInt16LE(DOS_DATE, 14);
70
+ central.writeUInt32LE(crc, 16);
71
+ central.writeUInt32LE(data.length, 20);
72
+ central.writeUInt32LE(data.length, 24);
73
+ central.writeUInt16LE(nameBuf.length, 28);
74
+ // extra/comment/disk/intAttr/extAttr 均为 0
75
+ central.writeUInt32LE(offset, 42);
76
+ centrals.push(central, nameBuf);
77
+ offset += 30 + nameBuf.length + data.length;
78
+ }
79
+ const centralStart = offset;
80
+ const centralBuf = Buffer.concat(centrals);
81
+ const eocd = Buffer.alloc(22);
82
+ eocd.writeUInt32LE(EOCD_SIG, 0);
83
+ eocd.writeUInt16LE(entries.size, 8);
84
+ eocd.writeUInt16LE(entries.size, 10);
85
+ eocd.writeUInt32LE(centralBuf.length, 12);
86
+ eocd.writeUInt32LE(centralStart, 16);
87
+ return Buffer.concat([...locals, centralBuf, eocd]);
88
+ }
89
+ /** 读取 zip 为 文件映射(posix 相对路径 → 内容),目录项自动跳过。 */
90
+ function readZip(buffer) {
91
+ // EOCD 至少 22 字节,注释最长 65535
92
+ const scanStart = Math.max(0, buffer.length - 22 - 65535);
93
+ let eocd = -1;
94
+ for (let i = buffer.length - 22; i >= scanStart; i -= 1) {
95
+ if (buffer.readUInt32LE(i) === EOCD_SIG) {
96
+ eocd = i;
97
+ break;
98
+ }
99
+ }
100
+ if (eocd < 0) {
101
+ throw new Error('ZIP_INVALID: 未找到 zip 结尾记录(文件损坏或不是 zip)');
102
+ }
103
+ const total = buffer.readUInt16LE(eocd + 10);
104
+ const cdOffset = buffer.readUInt32LE(eocd + 16);
105
+ const out = new Map();
106
+ let cursor = cdOffset;
107
+ for (let index = 0; index < total; index += 1) {
108
+ if (buffer.readUInt32LE(cursor) !== CENTRAL_SIG) {
109
+ throw new Error('ZIP_INVALID: 中央目录损坏');
110
+ }
111
+ const method = buffer.readUInt16LE(cursor + 10);
112
+ const compressedSize = buffer.readUInt32LE(cursor + 20);
113
+ const nameLen = buffer.readUInt16LE(cursor + 28);
114
+ const extraLen = buffer.readUInt16LE(cursor + 30);
115
+ const commentLen = buffer.readUInt16LE(cursor + 32);
116
+ const localOffset = buffer.readUInt32LE(cursor + 42);
117
+ const name = buffer.subarray(cursor + 46, cursor + 46 + nameLen).toString('utf8');
118
+ if (!name.endsWith('/')) {
119
+ if (buffer.readUInt32LE(localOffset) !== LOCAL_SIG) {
120
+ throw new Error(`ZIP_INVALID: ${name} 的本地文件头损坏`);
121
+ }
122
+ const localNameLen = buffer.readUInt16LE(localOffset + 26);
123
+ const localExtraLen = buffer.readUInt16LE(localOffset + 28);
124
+ const dataStart = localOffset + 30 + localNameLen + localExtraLen;
125
+ const raw = buffer.subarray(dataStart, dataStart + compressedSize);
126
+ if (method === 0) {
127
+ out.set(name, Buffer.from(raw));
128
+ }
129
+ else if (method === 8) {
130
+ out.set(name, node_zlib_1.default.inflateRawSync(raw));
131
+ }
132
+ else {
133
+ throw new Error(`ZIP_UNSUPPORTED: ${name} 使用了不支持的压缩方式 ${method}`);
134
+ }
135
+ }
136
+ cursor += 46 + nameLen + extraLen + commentLen;
137
+ }
138
+ return out;
139
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentdock-cli",
3
- "version": "0.7.1",
3
+ "version": "1.0.1",
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",
@@ -35,6 +35,7 @@
35
35
  "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node -e \"require('fs').copyFileSync('package.json','dist/package.json')\"",
36
36
  "dev": "tsx src/cli.ts",
37
37
  "test": "vitest run",
38
+ "e2e": "tsx scripts/e2e.ts",
38
39
  "cli": "tsx src/cli.ts",
39
40
  "prepublishOnly": "npm run build",
40
41
  "release:commits": "node scripts/generate-commit-groups.js"