agentdock-cli 1.0.1 → 1.2.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/README.md +47 -2
- package/dist/package.json +2 -1
- package/dist/src/cli.js +42 -1
- package/dist/src/commands/diff.js +71 -0
- package/dist/src/commands/doctor.js +1 -0
- package/dist/src/commands/history.js +107 -0
- package/dist/src/commands/recover.js +180 -0
- package/dist/src/commands/restore.js +103 -0
- package/dist/src/commands/snapshot.js +154 -0
- package/dist/src/constants/command-error-codes.js +4 -0
- package/dist/src/core/attest.js +5 -92
- package/dist/src/core/doctor.js +281 -0
- package/dist/src/core/report-html.js +72 -0
- package/dist/src/core/snapshot-diff.js +122 -0
- package/dist/src/core/snapshot.js +535 -0
- package/dist/src/core/supply-chain.js +114 -0
- package/dist/src/i18n/index.js +96 -4
- package/package.json +2 -1
|
@@ -0,0 +1,535 @@
|
|
|
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.SNAPSHOT_BUNDLE_DIR = void 0;
|
|
7
|
+
exports.configFilesFor = configFilesFor;
|
|
8
|
+
exports.snapshotsDir = snapshotsDir;
|
|
9
|
+
exports.hashBuffer = hashBuffer;
|
|
10
|
+
exports.redactConfigText = redactConfigText;
|
|
11
|
+
exports.createSnapshot = createSnapshot;
|
|
12
|
+
exports.listSnapshots = listSnapshots;
|
|
13
|
+
exports.latestSnapshot = latestSnapshot;
|
|
14
|
+
exports.loadSnapshot = loadSnapshot;
|
|
15
|
+
exports.readSnapshotContents = readSnapshotContents;
|
|
16
|
+
exports.readLiveConfig = readLiveConfig;
|
|
17
|
+
exports.findUnchangedSnapshot = findUnchangedSnapshot;
|
|
18
|
+
exports.exportSnapshot = exportSnapshot;
|
|
19
|
+
exports.importSnapshots = importSnapshots;
|
|
20
|
+
exports.planRestore = planRestore;
|
|
21
|
+
exports.applyRestore = applyRestore;
|
|
22
|
+
exports.prepareUndo = prepareUndo;
|
|
23
|
+
exports.applyUndo = applyUndo;
|
|
24
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
25
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
26
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
27
|
+
const package_json_1 = __importDefault(require("../../package.json"));
|
|
28
|
+
const snapshot_diff_1 = require("./snapshot-diff");
|
|
29
|
+
const fs_1 = require("../utils/fs");
|
|
30
|
+
/**
|
|
31
|
+
* 配置快照(v1.2)。
|
|
32
|
+
* 只采集关键配置文件(不复制 skills / memory 全量),默认明文保存,
|
|
33
|
+
* `--redact` 时对疑似令牌值打码。所有写入都限制在 `<root>/.agentdock` 内。
|
|
34
|
+
*/
|
|
35
|
+
/** 每个 agent 需要纳入快照的配置文件(相对用户主目录)。 */
|
|
36
|
+
const CONFIG_FILES = {
|
|
37
|
+
claude: ['.claude.json', '.claude/settings.json', '.claude/settings.local.json'],
|
|
38
|
+
codex: ['.codex/config.toml'],
|
|
39
|
+
};
|
|
40
|
+
const SECRET_KEY_PATTERN = /(token|secret|passw|api[_-]?key|auth|credential|cookie)/i;
|
|
41
|
+
const REDACTED = '***REDACTED***';
|
|
42
|
+
/** 只保留最近这么多个快照的索引条目,避免 index.json 无限增长。 */
|
|
43
|
+
const MAX_INDEX_ENTRIES = 200;
|
|
44
|
+
function configFilesFor(agent) {
|
|
45
|
+
if (agent === 'claude')
|
|
46
|
+
return [...CONFIG_FILES.claude];
|
|
47
|
+
if (agent === 'codex')
|
|
48
|
+
return [...CONFIG_FILES.codex];
|
|
49
|
+
return [...CONFIG_FILES.claude, ...CONFIG_FILES.codex];
|
|
50
|
+
}
|
|
51
|
+
function snapshotsDir(root) {
|
|
52
|
+
return node_path_1.default.join(root, '.agentdock', 'snapshots');
|
|
53
|
+
}
|
|
54
|
+
function indexPath(root) {
|
|
55
|
+
return node_path_1.default.join(snapshotsDir(root), 'index.json');
|
|
56
|
+
}
|
|
57
|
+
function restoreRecordPath(root) {
|
|
58
|
+
return node_path_1.default.join(root, '.agentdock', 'last-restore.json');
|
|
59
|
+
}
|
|
60
|
+
function hashBuffer(data) {
|
|
61
|
+
return node_crypto_1.default.createHash('sha256').update(data).digest('hex');
|
|
62
|
+
}
|
|
63
|
+
function fileKind(relPath) {
|
|
64
|
+
if (relPath.endsWith('.json'))
|
|
65
|
+
return 'json';
|
|
66
|
+
if (relPath.endsWith('.toml'))
|
|
67
|
+
return 'toml';
|
|
68
|
+
return 'text';
|
|
69
|
+
}
|
|
70
|
+
function redactTextByLine(text) {
|
|
71
|
+
return text
|
|
72
|
+
.split(/\r?\n/)
|
|
73
|
+
.map((line) => {
|
|
74
|
+
const match = /^(\s*[A-Za-z0-9_.-]*(?:token|secret|passw|api[_-]?key|auth|credential)[A-Za-z0-9_.-]*\s*=\s*).*/i.exec(line);
|
|
75
|
+
return match ? `${match[1]}"${REDACTED}"` : line;
|
|
76
|
+
})
|
|
77
|
+
.join('\n');
|
|
78
|
+
}
|
|
79
|
+
function redactJsonValue(value) {
|
|
80
|
+
if (Array.isArray(value)) {
|
|
81
|
+
return value.map(redactJsonValue);
|
|
82
|
+
}
|
|
83
|
+
if (value && typeof value === 'object') {
|
|
84
|
+
const out = {};
|
|
85
|
+
for (const [key, value2] of Object.entries(value)) {
|
|
86
|
+
out[key] = SECRET_KEY_PATTERN.test(key) ? REDACTED : redactJsonValue(value2);
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
/** 对单个配置文件内容做脱敏;解析失败时退回按行正则。 */
|
|
93
|
+
function redactConfigText(relPath, text) {
|
|
94
|
+
if (fileKind(relPath) === 'json') {
|
|
95
|
+
try {
|
|
96
|
+
return `${JSON.stringify(redactJsonValue(JSON.parse(text)), null, 2)}\n`;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return redactTextByLine(text);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return redactTextByLine(text);
|
|
103
|
+
}
|
|
104
|
+
function computeCounts(files) {
|
|
105
|
+
let topLevelKeys = 0;
|
|
106
|
+
let envKeys = 0;
|
|
107
|
+
let mcpCount = 0;
|
|
108
|
+
for (const [relPath, buffer] of files) {
|
|
109
|
+
const parsed = (0, snapshot_diff_1.parseConfigObject)(relPath, buffer.toString('utf8'));
|
|
110
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const obj = parsed;
|
|
114
|
+
topLevelKeys += Object.keys(obj).length;
|
|
115
|
+
if (relPath.endsWith('settings.json') || relPath.endsWith('settings.local.json')) {
|
|
116
|
+
const env = obj.env;
|
|
117
|
+
if (env && typeof env === 'object' && !Array.isArray(env)) {
|
|
118
|
+
envKeys += Object.keys(env).length;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const mcp = obj.mcpServers ?? obj.mcp_servers;
|
|
122
|
+
if (mcp && typeof mcp === 'object' && !Array.isArray(mcp)) {
|
|
123
|
+
mcpCount += Object.keys(mcp).length;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { topLevelKeys, envKeys, mcpCount };
|
|
127
|
+
}
|
|
128
|
+
function newSnapshotId(now = new Date()) {
|
|
129
|
+
return now.toISOString().replace(/[:.]/g, '-');
|
|
130
|
+
}
|
|
131
|
+
async function readIndex(root) {
|
|
132
|
+
try {
|
|
133
|
+
const parsed = await (0, fs_1.readJsonFile)(indexPath(root));
|
|
134
|
+
if (Array.isArray(parsed)) {
|
|
135
|
+
return parsed;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// 索引缺失或损坏时按目录重建
|
|
140
|
+
}
|
|
141
|
+
return rebuildIndex(root);
|
|
142
|
+
}
|
|
143
|
+
async function rebuildIndex(root) {
|
|
144
|
+
const dir = snapshotsDir(root);
|
|
145
|
+
if (!(await (0, fs_1.pathExists)(dir))) {
|
|
146
|
+
return [];
|
|
147
|
+
}
|
|
148
|
+
const entries = [];
|
|
149
|
+
const names = await promises_1.default.readdir(dir);
|
|
150
|
+
for (const name of names) {
|
|
151
|
+
if (name === 'index.json') {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const meta = await (0, fs_1.readJsonFile)(node_path_1.default.join(dir, name, 'snapshot.json'));
|
|
156
|
+
entries.push({
|
|
157
|
+
id: meta.id,
|
|
158
|
+
createdAt: meta.createdAt,
|
|
159
|
+
agent: meta.agent,
|
|
160
|
+
files: meta.files.length,
|
|
161
|
+
redacted: meta.redacted,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
// 不是快照目录,跳过
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return entries.sort((a, b) => b.id.localeCompare(a.id));
|
|
169
|
+
}
|
|
170
|
+
async function writeIndex(root, entries) {
|
|
171
|
+
// 快照 id 以 ISO 时间戳开头,按 id 倒序即时间倒序;同毫秒时 `-1` 后缀排在更前。
|
|
172
|
+
const sorted = [...entries].sort((a, b) => b.id.localeCompare(a.id));
|
|
173
|
+
await (0, fs_1.writeJsonFile)(indexPath(root), sorted.slice(0, MAX_INDEX_ENTRIES));
|
|
174
|
+
}
|
|
175
|
+
/** 采集当前配置并写入快照,返回快照元数据。 */
|
|
176
|
+
async function createSnapshot(options) {
|
|
177
|
+
const files = new Map();
|
|
178
|
+
for (const relPath of configFilesFor(options.agent)) {
|
|
179
|
+
const abs = (0, fs_1.safeResolveWithin)(options.root, relPath);
|
|
180
|
+
if (!(await (0, fs_1.pathExists)(abs))) {
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const raw = await promises_1.default.readFile(abs);
|
|
184
|
+
const content = options.redact
|
|
185
|
+
? Buffer.from(redactConfigText(relPath, raw.toString('utf8')), 'utf8')
|
|
186
|
+
: raw;
|
|
187
|
+
files.set(relPath, content);
|
|
188
|
+
}
|
|
189
|
+
if (files.size === 0) {
|
|
190
|
+
throw new Error(`SNAPSHOT_EMPTY: 在 ${options.root} 下未找到可快照的配置文件`);
|
|
191
|
+
}
|
|
192
|
+
const createdAt = new Date();
|
|
193
|
+
const baseId = newSnapshotId(createdAt);
|
|
194
|
+
let id = baseId;
|
|
195
|
+
let dir = node_path_1.default.join(snapshotsDir(options.root), id);
|
|
196
|
+
let suffix = 0;
|
|
197
|
+
while (await (0, fs_1.pathExists)(dir)) {
|
|
198
|
+
suffix += 1;
|
|
199
|
+
id = `${baseId}-${suffix}`;
|
|
200
|
+
dir = node_path_1.default.join(snapshotsDir(options.root), id);
|
|
201
|
+
}
|
|
202
|
+
await (0, fs_1.ensureDirectory)(node_path_1.default.join(dir, 'files'));
|
|
203
|
+
const entries = [];
|
|
204
|
+
for (const [relPath, content] of files) {
|
|
205
|
+
const target = (0, fs_1.safeResolveWithin)(node_path_1.default.join(dir, 'files'), relPath, 'snapshot file');
|
|
206
|
+
await (0, fs_1.ensureDirectory)(node_path_1.default.dirname(target));
|
|
207
|
+
await (0, fs_1.writeBinaryFile)(target, content, 0o600);
|
|
208
|
+
entries.push({
|
|
209
|
+
relPath,
|
|
210
|
+
sha256: hashBuffer(content),
|
|
211
|
+
size: content.length,
|
|
212
|
+
kind: fileKind(relPath),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const meta = {
|
|
216
|
+
id,
|
|
217
|
+
createdAt: createdAt.toISOString(),
|
|
218
|
+
agent: options.agent,
|
|
219
|
+
root: options.root,
|
|
220
|
+
toolVersion: package_json_1.default.version,
|
|
221
|
+
redacted: options.redact,
|
|
222
|
+
files: entries,
|
|
223
|
+
counts: computeCounts(files),
|
|
224
|
+
};
|
|
225
|
+
const metaPath = node_path_1.default.join(dir, 'snapshot.json');
|
|
226
|
+
await (0, fs_1.writeJsonFile)(metaPath, meta);
|
|
227
|
+
await chmodQuiet(metaPath, 0o600);
|
|
228
|
+
const index = await readIndex(options.root);
|
|
229
|
+
await writeIndex(options.root, [
|
|
230
|
+
{ id: meta.id, createdAt: meta.createdAt, agent: meta.agent, files: meta.files.length, redacted: meta.redacted },
|
|
231
|
+
...index.filter((item) => item.id !== meta.id),
|
|
232
|
+
]);
|
|
233
|
+
return meta;
|
|
234
|
+
}
|
|
235
|
+
async function chmodQuiet(target, mode) {
|
|
236
|
+
try {
|
|
237
|
+
await promises_1.default.chmod(target, mode);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// Windows 上权限位语义有限,忽略
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
async function listSnapshots(root) {
|
|
244
|
+
return readIndex(root);
|
|
245
|
+
}
|
|
246
|
+
/** 最近一次快照;agent 指定时匹配该 agent 或 `all` 采集的快照。 */
|
|
247
|
+
async function latestSnapshot(root, agent) {
|
|
248
|
+
const index = await readIndex(root);
|
|
249
|
+
const matches = agent
|
|
250
|
+
? index.filter((item) => item.agent === agent || item.agent === 'all')
|
|
251
|
+
: index;
|
|
252
|
+
if (matches.length === 0) {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
const newest = [...matches].sort((a, b) => b.id.localeCompare(a.id))[0];
|
|
256
|
+
return loadSnapshot(root, newest.id);
|
|
257
|
+
}
|
|
258
|
+
/** 解析快照 id:支持完整 id、唯一前缀、快照目录路径与 `latest`。 */
|
|
259
|
+
async function loadSnapshot(root, idOrPath) {
|
|
260
|
+
const dir = await resolveSnapshotDir(root, idOrPath);
|
|
261
|
+
try {
|
|
262
|
+
const meta = await (0, fs_1.readJsonFile)(node_path_1.default.join(dir, 'snapshot.json'));
|
|
263
|
+
return { meta, dir };
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: 无法读取快照 ${idOrPath}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
async function resolveSnapshotDir(root, idOrPath) {
|
|
270
|
+
const looksLikePath = idOrPath.includes('/') || idOrPath.includes('\\') || node_path_1.default.isAbsolute(idOrPath);
|
|
271
|
+
if (looksLikePath) {
|
|
272
|
+
const resolved = node_path_1.default.resolve(idOrPath);
|
|
273
|
+
if (await (0, fs_1.pathExists)(resolved)) {
|
|
274
|
+
return resolved;
|
|
275
|
+
}
|
|
276
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: ${idOrPath}`);
|
|
277
|
+
}
|
|
278
|
+
const base = snapshotsDir(root);
|
|
279
|
+
if (idOrPath === 'latest') {
|
|
280
|
+
const latest = await latestSnapshot(root);
|
|
281
|
+
if (!latest) {
|
|
282
|
+
throw new Error('SNAPSHOT_NOT_FOUND: 尚无任何快照');
|
|
283
|
+
}
|
|
284
|
+
return latest.dir;
|
|
285
|
+
}
|
|
286
|
+
const direct = node_path_1.default.join(base, idOrPath);
|
|
287
|
+
if (await (0, fs_1.pathExists)(node_path_1.default.join(direct, 'snapshot.json'))) {
|
|
288
|
+
return direct;
|
|
289
|
+
}
|
|
290
|
+
if (await (0, fs_1.pathExists)(base)) {
|
|
291
|
+
const names = (await promises_1.default.readdir(base)).filter((name) => name !== 'index.json' && name.startsWith(idOrPath));
|
|
292
|
+
if (names.length === 1) {
|
|
293
|
+
return node_path_1.default.join(base, names[0]);
|
|
294
|
+
}
|
|
295
|
+
if (names.length > 1) {
|
|
296
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: 前缀 ${idOrPath} 匹配到多个快照,请提供完整 id`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: ${idOrPath}`);
|
|
300
|
+
}
|
|
301
|
+
/** 读取快照中保存的配置内容(relPath → 原始字节)。 */
|
|
302
|
+
async function readSnapshotContents(snapshot) {
|
|
303
|
+
const contents = new Map();
|
|
304
|
+
for (const file of snapshot.meta.files) {
|
|
305
|
+
const source = (0, fs_1.safeResolveWithin)(node_path_1.default.join(snapshot.dir, 'files'), file.relPath, 'snapshot file');
|
|
306
|
+
try {
|
|
307
|
+
contents.set(file.relPath, await promises_1.default.readFile(source));
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
// 快照内容缺失时跳过,由调用方按"文件不存在"处理
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return contents;
|
|
314
|
+
}
|
|
315
|
+
/** 读取本机当前的关键配置文件。 */
|
|
316
|
+
async function readLiveConfig(root, agent) {
|
|
317
|
+
const contents = new Map();
|
|
318
|
+
for (const relPath of configFilesFor(agent)) {
|
|
319
|
+
const abs = (0, fs_1.safeResolveWithin)(root, relPath);
|
|
320
|
+
try {
|
|
321
|
+
contents.set(relPath, await promises_1.default.readFile(abs));
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
// 文件不存在
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return contents;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* 当前配置与最近快照完全一致时返回该快照元数据,否则返回 null。
|
|
331
|
+
* 用于 `snapshot --if-changed`:定时任务里没变化就不重复落盘。
|
|
332
|
+
*/
|
|
333
|
+
async function findUnchangedSnapshot(root, agent) {
|
|
334
|
+
const latest = await latestSnapshot(root, agent);
|
|
335
|
+
// agent 范围不同(如已有 all 快照、本次只采 claude)时视为有变化,避免漏采
|
|
336
|
+
if (!latest || latest.meta.agent !== agent) {
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const stored = await readSnapshotContents(latest);
|
|
340
|
+
const live = await readLiveConfig(root, agent);
|
|
341
|
+
if (stored.size !== live.size) {
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
for (const [relPath, current] of live) {
|
|
345
|
+
const before = stored.get(relPath);
|
|
346
|
+
if (!before) {
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
// 快照若已脱敏,比对前同样对当前内容脱敏,避免每次都判定为变化
|
|
350
|
+
const comparable = latest.meta.redacted
|
|
351
|
+
? Buffer.from(redactConfigText(relPath, current.toString('utf8')), 'utf8')
|
|
352
|
+
: current;
|
|
353
|
+
if (hashBuffer(before) !== hashBuffer(comparable)) {
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return latest.meta;
|
|
358
|
+
}
|
|
359
|
+
// ===== 快照分享(push / pull) =====
|
|
360
|
+
/** 分享目录名:目标目录下按 `<target>/.agentdock-snapshots/<id>/` 存放快照。 */
|
|
361
|
+
exports.SNAPSHOT_BUNDLE_DIR = '.agentdock-snapshots';
|
|
362
|
+
/**
|
|
363
|
+
* 把一份快照复制到目标目录(如 Git 工作副本)。
|
|
364
|
+
* 明文快照含真实密钥,默认拒绝导出,必须先 `snapshot --redact` 或显式 `--force`。
|
|
365
|
+
*/
|
|
366
|
+
async function exportSnapshot(root, targetDir, id, force) {
|
|
367
|
+
const list = await listSnapshots(root);
|
|
368
|
+
const chosenId = id ?? list[0]?.id;
|
|
369
|
+
if (!chosenId) {
|
|
370
|
+
throw new Error('SNAPSHOT_NOT_FOUND: 还没有可导出的快照');
|
|
371
|
+
}
|
|
372
|
+
const loaded = await loadSnapshot(root, chosenId);
|
|
373
|
+
if (!loaded.meta.redacted && !force) {
|
|
374
|
+
throw new Error('SNAPSHOT_NOT_REDACTED: 快照含明文敏感值,分享前请用 `agentdock snapshot --redact` 重新采集,或加 --force 强制导出');
|
|
375
|
+
}
|
|
376
|
+
const dest = node_path_1.default.join(targetDir, exports.SNAPSHOT_BUNDLE_DIR, loaded.meta.id);
|
|
377
|
+
if (await (0, fs_1.pathExists)(dest)) {
|
|
378
|
+
if (!force) {
|
|
379
|
+
throw new Error(`SNAPSHOT_EXISTS: 目标已存在:${dest}(加 --force 覆盖)`);
|
|
380
|
+
}
|
|
381
|
+
await promises_1.default.rm(dest, { recursive: true, force: true });
|
|
382
|
+
}
|
|
383
|
+
await (0, fs_1.copyDirectorySafe)(loaded.dir, dest);
|
|
384
|
+
return { id: loaded.meta.id, dest, redacted: loaded.meta.redacted };
|
|
385
|
+
}
|
|
386
|
+
async function findSnapshotDirs(base) {
|
|
387
|
+
if (await (0, fs_1.pathExists)(node_path_1.default.join(base, 'snapshot.json'))) {
|
|
388
|
+
return [base];
|
|
389
|
+
}
|
|
390
|
+
let names;
|
|
391
|
+
try {
|
|
392
|
+
names = await promises_1.default.readdir(base);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return [];
|
|
396
|
+
}
|
|
397
|
+
const dirs = [];
|
|
398
|
+
for (const name of names) {
|
|
399
|
+
const candidate = node_path_1.default.join(base, name);
|
|
400
|
+
if (await (0, fs_1.pathExists)(node_path_1.default.join(candidate, 'snapshot.json'))) {
|
|
401
|
+
dirs.push(candidate);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return dirs;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* 从目标目录导入快照:支持直接指向某份快照目录,或指向包含
|
|
408
|
+
* `.agentdock-snapshots/<id>/` 的目录(如 Git 工作副本)。
|
|
409
|
+
*/
|
|
410
|
+
async function importSnapshots(root, sourceDir, force) {
|
|
411
|
+
const dirs = new Set([
|
|
412
|
+
...(await findSnapshotDirs(sourceDir)),
|
|
413
|
+
...(await findSnapshotDirs(node_path_1.default.join(sourceDir, exports.SNAPSHOT_BUNDLE_DIR))),
|
|
414
|
+
]);
|
|
415
|
+
if (dirs.size === 0) {
|
|
416
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: 在 ${sourceDir} 下未找到快照`);
|
|
417
|
+
}
|
|
418
|
+
const imported = [];
|
|
419
|
+
const skipped = [];
|
|
420
|
+
await (0, fs_1.ensureDirectory)(snapshotsDir(root));
|
|
421
|
+
for (const dir of dirs) {
|
|
422
|
+
let meta;
|
|
423
|
+
try {
|
|
424
|
+
meta = await (0, fs_1.readJsonFile)(node_path_1.default.join(dir, 'snapshot.json'));
|
|
425
|
+
}
|
|
426
|
+
catch {
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
// id 会被拼进本地路径,只接受安全字符,避免路径穿越
|
|
430
|
+
if (!meta.id || !/^[0-9A-Za-z._-]+$/.test(meta.id)) {
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
const dest = node_path_1.default.join(snapshotsDir(root), meta.id);
|
|
434
|
+
if (await (0, fs_1.pathExists)(dest)) {
|
|
435
|
+
if (!force) {
|
|
436
|
+
skipped.push(meta.id);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
await promises_1.default.rm(dest, { recursive: true, force: true });
|
|
440
|
+
}
|
|
441
|
+
await (0, fs_1.copyDirectorySafe)(dir, dest);
|
|
442
|
+
imported.push(meta.id);
|
|
443
|
+
}
|
|
444
|
+
await writeIndex(root, await rebuildIndex(root));
|
|
445
|
+
return { imported, skipped };
|
|
446
|
+
}
|
|
447
|
+
/** 生成恢复计划(不写盘)。 */
|
|
448
|
+
async function planRestore(root, snapshot) {
|
|
449
|
+
const contents = await readSnapshotContents(snapshot);
|
|
450
|
+
const entries = [];
|
|
451
|
+
for (const [relPath, content] of contents) {
|
|
452
|
+
const target = (0, fs_1.safeResolveWithin)(root, relPath);
|
|
453
|
+
let action = 'create';
|
|
454
|
+
if (await (0, fs_1.pathExists)(target)) {
|
|
455
|
+
try {
|
|
456
|
+
const current = await promises_1.default.readFile(target);
|
|
457
|
+
action = hashBuffer(current) === hashBuffer(content) ? 'skip' : 'overwrite';
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
action = 'overwrite';
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
entries.push({ relPath, target, action });
|
|
464
|
+
}
|
|
465
|
+
return entries;
|
|
466
|
+
}
|
|
467
|
+
/** 执行恢复;调用前必须已确认 apply。写前自动生成一份 before-restore 快照。 */
|
|
468
|
+
async function applyRestore(root, snapshot, entries) {
|
|
469
|
+
const actionable = entries.filter((entry) => entry.action !== 'skip');
|
|
470
|
+
if (actionable.length === 0) {
|
|
471
|
+
return {
|
|
472
|
+
snapshotId: snapshot.meta.id,
|
|
473
|
+
applied: true,
|
|
474
|
+
entries,
|
|
475
|
+
undo: false,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
const backup = await createSnapshot({ root, agent: snapshot.meta.agent, redact: snapshot.meta.redacted });
|
|
479
|
+
const sourceRoot = node_path_1.default.join(snapshot.dir, 'files');
|
|
480
|
+
for (const entry of entries) {
|
|
481
|
+
if (entry.action === 'skip') {
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
const source = (0, fs_1.safeResolveWithin)(sourceRoot, entry.relPath, 'snapshot file');
|
|
485
|
+
await (0, fs_1.copyFileSafe)(source, entry.target);
|
|
486
|
+
await chmodQuiet(entry.target, 0o600);
|
|
487
|
+
}
|
|
488
|
+
const record = {
|
|
489
|
+
snapshotId: snapshot.meta.id,
|
|
490
|
+
backupSnapshotId: backup.id,
|
|
491
|
+
restoredAt: new Date().toISOString(),
|
|
492
|
+
};
|
|
493
|
+
await (0, fs_1.writeJsonFile)(restoreRecordPath(root), record);
|
|
494
|
+
return {
|
|
495
|
+
snapshotId: snapshot.meta.id,
|
|
496
|
+
applied: true,
|
|
497
|
+
entries,
|
|
498
|
+
backupSnapshotId: backup.id,
|
|
499
|
+
undo: false,
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
/** 恢复最近一次恢复前快照所需的上下文。 */
|
|
503
|
+
async function readRestoreRecord(root) {
|
|
504
|
+
try {
|
|
505
|
+
return await (0, fs_1.readJsonFile)(restoreRecordPath(root));
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
throw new Error('RESTORE_NO_UNDO: 没有可撤销的恢复记录(或已完成撤销)');
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/** 撤销最近一次恢复:把写前快照重新写回。 */
|
|
512
|
+
async function prepareUndo(root) {
|
|
513
|
+
const record = await readRestoreRecord(root);
|
|
514
|
+
const snapshot = await loadSnapshot(root, record.backupSnapshotId);
|
|
515
|
+
const entries = await planRestore(root, snapshot);
|
|
516
|
+
return { snapshot, entries };
|
|
517
|
+
}
|
|
518
|
+
async function applyUndo(root, snapshot, entries) {
|
|
519
|
+
const sourceRoot = node_path_1.default.join(snapshot.dir, 'files');
|
|
520
|
+
for (const entry of entries) {
|
|
521
|
+
if (entry.action === 'skip') {
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
const source = (0, fs_1.safeResolveWithin)(sourceRoot, entry.relPath, 'snapshot file');
|
|
525
|
+
await (0, fs_1.copyFileSafe)(source, entry.target);
|
|
526
|
+
await chmodQuiet(entry.target, 0o600);
|
|
527
|
+
}
|
|
528
|
+
await promises_1.default.rm(restoreRecordPath(root), { force: true });
|
|
529
|
+
return {
|
|
530
|
+
snapshotId: snapshot.meta.id,
|
|
531
|
+
applied: true,
|
|
532
|
+
entries,
|
|
533
|
+
undo: true,
|
|
534
|
+
};
|
|
535
|
+
}
|
|
@@ -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
|
+
}
|