agentdock-cli 0.7.1 → 1.0.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 +118 -11
- package/dist/package.json +2 -1
- package/dist/src/cli.js +88 -0
- package/dist/src/commands/attest.js +60 -0
- package/dist/src/commands/install.js +3 -0
- package/dist/src/commands/keygen.js +48 -0
- package/dist/src/commands/pack.js +78 -0
- package/dist/src/commands/sign.js +62 -0
- package/dist/src/commands/sync.js +170 -0
- package/dist/src/commands/verify.js +80 -0
- package/dist/src/constants/command-error-codes.js +11 -0
- package/dist/src/constants/format-versions.js +17 -0
- package/dist/src/core/attest.js +440 -0
- package/dist/src/core/exporter.js +2 -0
- package/dist/src/core/installer.js +59 -12
- package/dist/src/core/pack.js +46 -0
- package/dist/src/core/package-lock.js +230 -0
- package/dist/src/core/package-sign.js +27 -0
- package/dist/src/core/scan-export.js +2 -0
- package/dist/src/core/signature.js +111 -0
- package/dist/src/core/sync-env.js +81 -0
- package/dist/src/core/sync.js +471 -0
- package/dist/src/i18n/index.js +74 -2
- package/dist/src/scanners/sensitive.js +9 -5
- package/dist/src/utils/command-json.js +2 -1
- package/dist/src/utils/fs.js +27 -2
- package/dist/src/utils/zip.js +139 -0
- package/package.json +2 -1
|
@@ -0,0 +1,440 @@
|
|
|
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.attestPackage = attestPackage;
|
|
7
|
+
exports.renderAttestMarkdown = renderAttestMarkdown;
|
|
8
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
+
const smol_toml_1 = require("smol-toml");
|
|
10
|
+
const package_json_1 = __importDefault(require("../../package.json"));
|
|
11
|
+
const sensitive_1 = require("../scanners/sensitive");
|
|
12
|
+
const package_lock_1 = require("./package-lock");
|
|
13
|
+
const CATEGORIES = ['mcp', 'skills', 'agents', 'plugins', 'hooks', 'memory', 'settings'];
|
|
14
|
+
const LEVEL_LABEL = {
|
|
15
|
+
high: '高',
|
|
16
|
+
medium: '中',
|
|
17
|
+
low: '低',
|
|
18
|
+
};
|
|
19
|
+
const LEVEL_ORDER = { high: 0, medium: 1, low: 2 };
|
|
20
|
+
function createRiskCollector() {
|
|
21
|
+
const seen = new Map();
|
|
22
|
+
return {
|
|
23
|
+
add(risk) {
|
|
24
|
+
const key = `${risk.id}\0${risk.evidence ?? ''}`;
|
|
25
|
+
if (!seen.has(key)) {
|
|
26
|
+
seen.set(key, risk);
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
list() {
|
|
30
|
+
return [...seen.values()].sort((a, b) => LEVEL_ORDER[a.level] - LEVEL_ORDER[b.level]);
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** 文本文件判定:含 NUL 字节视为二进制,返回 null。 */
|
|
35
|
+
function decodeText(data) {
|
|
36
|
+
if (data.length === 0) {
|
|
37
|
+
return '';
|
|
38
|
+
}
|
|
39
|
+
const sample = data.subarray(0, Math.min(data.length, 8000));
|
|
40
|
+
return sample.includes(0) ? null : data.toString('utf8');
|
|
41
|
+
}
|
|
42
|
+
function summarizeAssets(manifest) {
|
|
43
|
+
const assets = [];
|
|
44
|
+
for (const [agent, domain] of Object.entries(manifest.agents ?? {})) {
|
|
45
|
+
if (!domain) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const counts = {};
|
|
49
|
+
let total = 0;
|
|
50
|
+
for (const category of CATEGORIES) {
|
|
51
|
+
const count = domain[category].length;
|
|
52
|
+
counts[category] = count;
|
|
53
|
+
total += count;
|
|
54
|
+
}
|
|
55
|
+
assets.push({ agent, counts, total });
|
|
56
|
+
}
|
|
57
|
+
return assets;
|
|
58
|
+
}
|
|
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
|
+
}
|
|
122
|
+
function inspectStructuredFile(file, text, add) {
|
|
123
|
+
const ext = node_path_1.default.posix.extname(file).toLowerCase();
|
|
124
|
+
let parsed;
|
|
125
|
+
try {
|
|
126
|
+
parsed = ext === '.toml' ? (0, smol_toml_1.parse)(text) : JSON.parse(text);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const defs = [];
|
|
132
|
+
collectMcpDefs(parsed, defs);
|
|
133
|
+
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);
|
|
138
|
+
}
|
|
139
|
+
inspectPermissions(parsed, file, add);
|
|
140
|
+
}
|
|
141
|
+
function inspectPermissionNode(node, file, add) {
|
|
142
|
+
if (node.defaultMode === 'bypassPermissions') {
|
|
143
|
+
add({
|
|
144
|
+
level: 'high',
|
|
145
|
+
id: 'skip-permissions',
|
|
146
|
+
message: '权限默认模式为 bypassPermissions(跳过所有确认),安装后命令可无提示执行',
|
|
147
|
+
evidence: file,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
const allow = node.allow;
|
|
151
|
+
if (Array.isArray(allow) && allow.some((item) => item === 'Bash' || item === 'Bash(*)')) {
|
|
152
|
+
add({
|
|
153
|
+
level: 'medium',
|
|
154
|
+
id: 'broad-permissions',
|
|
155
|
+
message: '权限允许项包含 `Bash` / `Bash(*)`(任意 shell 命令),建议收窄到具体命令',
|
|
156
|
+
evidence: file,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** 只对结构化配置判权限;文档里提到这些词不算风险。 */
|
|
161
|
+
function inspectPermissions(value, file, add) {
|
|
162
|
+
if (Array.isArray(value)) {
|
|
163
|
+
for (const item of value) {
|
|
164
|
+
inspectPermissions(item, file, add);
|
|
165
|
+
}
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (!value || typeof value !== 'object') {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const obj = value;
|
|
172
|
+
if (obj.dangerouslySkipPermissions === true) {
|
|
173
|
+
add({
|
|
174
|
+
level: 'high',
|
|
175
|
+
id: 'skip-permissions',
|
|
176
|
+
message: '配置启用了 dangerouslySkipPermissions(跳过所有确认),安装后命令可无提示执行',
|
|
177
|
+
evidence: file,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
if (obj.permissions && typeof obj.permissions === 'object' && !Array.isArray(obj.permissions)) {
|
|
181
|
+
inspectPermissionNode(obj.permissions, file, add);
|
|
182
|
+
}
|
|
183
|
+
for (const child of Object.values(obj)) {
|
|
184
|
+
inspectPermissions(child, file, add);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
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
|
+
/**
|
|
211
|
+
* 对一个安装包(目录或 .zip)生成审计清单:
|
|
212
|
+
* 资产清单 + 密钥处理方式 + 供应链风险 +(有 lock 时)完整性校验。
|
|
213
|
+
*/
|
|
214
|
+
async function attestPackage(targetPath) {
|
|
215
|
+
const resolved = node_path_1.default.resolve(targetPath);
|
|
216
|
+
const contents = await (0, package_lock_1.readPackageContents)(resolved);
|
|
217
|
+
const manifestBuf = contents.files.get('manifest.resolved.json');
|
|
218
|
+
if (!manifestBuf) {
|
|
219
|
+
throw new Error(`ATTEST_PACKAGE_INVALID: ${resolved} 缺少 manifest.resolved.json,不是可审计的安装包`);
|
|
220
|
+
}
|
|
221
|
+
let manifest;
|
|
222
|
+
try {
|
|
223
|
+
manifest = JSON.parse(manifestBuf.toString('utf8'));
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
throw new Error(`ATTEST_PACKAGE_INVALID: manifest.resolved.json 不是合法 JSON(${error.message})`);
|
|
227
|
+
}
|
|
228
|
+
const assets = summarizeAssets(manifest);
|
|
229
|
+
const collector = createRiskCollector();
|
|
230
|
+
const placeholders = new Set();
|
|
231
|
+
const placeholderPattern = /\{\{(AGENTDOCK_[A-Z0-9_]+)\}\}/g;
|
|
232
|
+
const leaks = [];
|
|
233
|
+
const textNpxFiles = new Set();
|
|
234
|
+
let textNpxHits = 0;
|
|
235
|
+
for (const [rel, data] of contents.files) {
|
|
236
|
+
if (!rel.startsWith('payload/')) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const text = decodeText(data);
|
|
240
|
+
if (text === null) {
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
for (const match of text.matchAll(placeholderPattern)) {
|
|
244
|
+
placeholders.add(match[1]);
|
|
245
|
+
}
|
|
246
|
+
const found = (0, sensitive_1.findSecretLeaks)(text);
|
|
247
|
+
if (found.length > 0) {
|
|
248
|
+
leaks.push({ file: rel, count: found.length });
|
|
249
|
+
}
|
|
250
|
+
inspectStructuredFile(rel, text, (risk) => collector.add(risk));
|
|
251
|
+
const textSpecs = collectTextNpxSpecs(text);
|
|
252
|
+
if (textSpecs.length > 0) {
|
|
253
|
+
textNpxHits += textSpecs.length;
|
|
254
|
+
textNpxFiles.add(rel);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (textNpxHits > 0) {
|
|
258
|
+
const files = [...textNpxFiles];
|
|
259
|
+
const sample = files.slice(0, 3).join(', ');
|
|
260
|
+
collector.add({
|
|
261
|
+
level: 'medium',
|
|
262
|
+
id: 'unpinned-npx-text',
|
|
263
|
+
message: `${files.length} 个技能/脚本文本中出现 ${textNpxHits} 处 \`npx -y\` 未固定版本命令(多为文档示例;若会被执行请固定版本)`,
|
|
264
|
+
evidence: files.length > 3 ? `${sample} 等 ${files.length} 个文件` : sample,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
for (const asset of assets) {
|
|
268
|
+
const hooks = asset.counts.hooks ?? 0;
|
|
269
|
+
if (hooks > 0) {
|
|
270
|
+
collector.add({
|
|
271
|
+
level: 'medium',
|
|
272
|
+
id: 'hooks',
|
|
273
|
+
message: `${asset.agent} 包含 ${hooks} 个 hook 定义,安装后会执行本地命令,请逐条审阅`,
|
|
274
|
+
evidence: asset.agent,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const lockPresent = contents.files.has(package_lock_1.PACKAGE_LOCK_FILENAME);
|
|
279
|
+
let integrity = {
|
|
280
|
+
lockPresent,
|
|
281
|
+
verified: false,
|
|
282
|
+
missing: 0,
|
|
283
|
+
modified: 0,
|
|
284
|
+
extra: 0,
|
|
285
|
+
signaturePresent: false,
|
|
286
|
+
signatureValid: false,
|
|
287
|
+
};
|
|
288
|
+
if (lockPresent) {
|
|
289
|
+
try {
|
|
290
|
+
const verify = await (0, package_lock_1.verifyPackage)(resolved, false);
|
|
291
|
+
integrity = {
|
|
292
|
+
lockPresent: true,
|
|
293
|
+
verified: verify.ok,
|
|
294
|
+
missing: verify.missing.length,
|
|
295
|
+
modified: verify.modified.length,
|
|
296
|
+
extra: verify.extra.length,
|
|
297
|
+
signaturePresent: verify.signature.present,
|
|
298
|
+
signatureValid: verify.signature.valid,
|
|
299
|
+
};
|
|
300
|
+
if (verify.signature.present && !verify.signature.valid) {
|
|
301
|
+
collector.add({
|
|
302
|
+
level: 'high',
|
|
303
|
+
id: 'signature-invalid',
|
|
304
|
+
message: '包签名校验失败(签名与 lock 不匹配,或使用了非预期的签名文件)',
|
|
305
|
+
evidence: verify.signature.error,
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
else if (!verify.ok) {
|
|
309
|
+
collector.add({
|
|
310
|
+
level: 'high',
|
|
311
|
+
id: 'integrity-mismatch',
|
|
312
|
+
message: '包内容与 agentdock.lock.json 不一致(缺失或哈希不符)',
|
|
313
|
+
evidence: `missing=${verify.missing.length}, modified=${verify.modified.length}, lockCorrupt=${verify.lockCorrupt}`,
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
integrity = {
|
|
319
|
+
lockPresent: true,
|
|
320
|
+
verified: false,
|
|
321
|
+
missing: 0,
|
|
322
|
+
modified: 0,
|
|
323
|
+
extra: 0,
|
|
324
|
+
signaturePresent: false,
|
|
325
|
+
signatureValid: false,
|
|
326
|
+
error: error.message,
|
|
327
|
+
};
|
|
328
|
+
collector.add({
|
|
329
|
+
level: 'high',
|
|
330
|
+
id: 'integrity-invalid',
|
|
331
|
+
message: 'agentdock.lock.json 无法解析或不完整',
|
|
332
|
+
evidence: error.message,
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const risks = collector.list();
|
|
337
|
+
const summary = {
|
|
338
|
+
high: risks.filter((risk) => risk.level === 'high').length,
|
|
339
|
+
medium: risks.filter((risk) => risk.level === 'medium').length,
|
|
340
|
+
low: risks.filter((risk) => risk.level === 'low').length,
|
|
341
|
+
};
|
|
342
|
+
if (leaks.length > 0) {
|
|
343
|
+
const sample = leaks.slice(0, 3).map((leak) => `${leak.file}(${leak.count})`).join(', ');
|
|
344
|
+
// 放在 risks 之后重新汇总,保证 summary 与列表一致。
|
|
345
|
+
risks.unshift({
|
|
346
|
+
level: 'high',
|
|
347
|
+
id: 'package-leak',
|
|
348
|
+
message: `包内发现 ${leaks.length} 个文件含疑似真实令牌(应在交付前修复)`,
|
|
349
|
+
evidence: sample,
|
|
350
|
+
});
|
|
351
|
+
summary.high += 1;
|
|
352
|
+
}
|
|
353
|
+
return {
|
|
354
|
+
packagePath: resolved,
|
|
355
|
+
manifestVersion: typeof manifest.version === 'number' ? manifest.version : null,
|
|
356
|
+
assets,
|
|
357
|
+
secrets: {
|
|
358
|
+
placeholders: placeholders.size,
|
|
359
|
+
envExample: contents.files.has('.env.example'),
|
|
360
|
+
leaks,
|
|
361
|
+
},
|
|
362
|
+
integrity,
|
|
363
|
+
risks,
|
|
364
|
+
summary,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
function escapeCell(value) {
|
|
368
|
+
return value.replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
|
|
369
|
+
}
|
|
370
|
+
/** 中文 Markdown 审计清单(面向安全 / 合规验收)。 */
|
|
371
|
+
function renderAttestMarkdown(result) {
|
|
372
|
+
const lines = [];
|
|
373
|
+
lines.push('# AgentDock 交付审计清单', '');
|
|
374
|
+
lines.push(`- 交付包:${result.packagePath}`);
|
|
375
|
+
lines.push(`- 生成时间:${new Date().toISOString()}`);
|
|
376
|
+
lines.push(`- 工具版本:agentdock v${package_json_1.default.version}`);
|
|
377
|
+
lines.push(`- manifest 版本:${result.manifestVersion ?? '未知'}`);
|
|
378
|
+
lines.push('');
|
|
379
|
+
lines.push('## 1. 资产清单', '');
|
|
380
|
+
lines.push('| 助手 | MCP | Skill | Agent | Plugin | Hook | Memory | Settings | 合计 |');
|
|
381
|
+
lines.push('| --- | --- | --- | --- | --- | --- | --- | --- | --- |');
|
|
382
|
+
for (const asset of result.assets) {
|
|
383
|
+
const cells = CATEGORIES.map((category) => String(asset.counts[category] ?? 0));
|
|
384
|
+
lines.push(`| ${asset.agent} | ${cells.join(' | ')} | ${asset.total} |`);
|
|
385
|
+
}
|
|
386
|
+
if (result.assets.length === 0) {
|
|
387
|
+
lines.push('| (无资产) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |');
|
|
388
|
+
}
|
|
389
|
+
lines.push('');
|
|
390
|
+
lines.push('## 2. 密钥处理', '');
|
|
391
|
+
lines.push(`- 占位符:${result.secrets.placeholders} 个 \`{{AGENTDOCK_*}}\`(真实值不随包交付,需在目标机 .env 填值)`);
|
|
392
|
+
lines.push(`- \`.env.example\`:${result.secrets.envExample ? '已生成' : '未生成'}`);
|
|
393
|
+
if (result.secrets.leaks.length === 0) {
|
|
394
|
+
lines.push('- 包内疑似真实令牌:0 处');
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
lines.push(`- 包内疑似真实令牌:${result.secrets.leaks.length} 个文件!`);
|
|
398
|
+
for (const leak of result.secrets.leaks.slice(0, 10)) {
|
|
399
|
+
lines.push(` - \`${leak.file}\`:${leak.count} 处`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
lines.push('');
|
|
403
|
+
lines.push('## 3. 完整性', '');
|
|
404
|
+
if (!result.integrity.lockPresent) {
|
|
405
|
+
lines.push('- 未提供 `agentdock.lock.json`(无法校验包内容,建议用 `agentdock pack` 生成)');
|
|
406
|
+
}
|
|
407
|
+
else if (result.integrity.verified) {
|
|
408
|
+
lines.push('- `agentdock.lock.json`:校验通过');
|
|
409
|
+
lines.push(`- 多余文件:${result.integrity.extra} 个(仅提示,不参与哈希)`);
|
|
410
|
+
}
|
|
411
|
+
else {
|
|
412
|
+
lines.push('- `agentdock.lock.json`:校验失败');
|
|
413
|
+
lines.push(`- 缺失 ${result.integrity.missing} 个 / 哈希不符 ${result.integrity.modified} 个`);
|
|
414
|
+
if (result.integrity.error) {
|
|
415
|
+
lines.push(`- 错误:${result.integrity.error}`);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
if (result.integrity.signaturePresent) {
|
|
419
|
+
lines.push(`- 签名:${result.integrity.signatureValid ? '校验通过' : '校验失败'}`);
|
|
420
|
+
}
|
|
421
|
+
lines.push('');
|
|
422
|
+
lines.push('## 4. 供应链风险', '');
|
|
423
|
+
if (result.risks.length === 0) {
|
|
424
|
+
lines.push('未发现已知风险项(未固定版本的远程执行、hook shell、过宽权限)。');
|
|
425
|
+
}
|
|
426
|
+
else {
|
|
427
|
+
lines.push('| 级别 | 项目 | 说明 | 证据 |');
|
|
428
|
+
lines.push('| --- | --- | --- | --- |');
|
|
429
|
+
for (const risk of result.risks) {
|
|
430
|
+
lines.push(`| ${LEVEL_LABEL[risk.level]} | ${risk.id} | ${escapeCell(risk.message)} | ${escapeCell(risk.evidence ?? '')} |`);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
lines.push('');
|
|
434
|
+
lines.push('## 5. 结论', '');
|
|
435
|
+
lines.push(`- 高风险 ${result.summary.high} 项 / 中风险 ${result.summary.medium} 项 / 低风险 ${result.summary.low} 项`);
|
|
436
|
+
lines.push(result.summary.high > 0
|
|
437
|
+
? '- 结论:**存在高风险项**,建议修复后再交付(可加 `--strict` 让 CI 直接失败)。'
|
|
438
|
+
: '- 结论:未发现高风险项。');
|
|
439
|
+
return `${lines.join('\n')}\n`;
|
|
440
|
+
}
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.exportManifest = exportManifest;
|
|
7
7
|
const node_path_1 = __importDefault(require("node:path"));
|
|
8
|
+
const format_versions_1 = require("../constants/format-versions");
|
|
8
9
|
const template_renderer_1 = require("./template-renderer");
|
|
9
10
|
const source_destination_1 = require("./source-destination");
|
|
10
11
|
const fs_1 = require("../utils/fs");
|
|
@@ -70,6 +71,7 @@ async function exportManifest(manifest, manifestDirectory) {
|
|
|
70
71
|
await (0, fs_1.writeJsonFile)(packageMetadataPath, {
|
|
71
72
|
name: 'agentdock-package',
|
|
72
73
|
version: '1.0.0',
|
|
74
|
+
formatVersion: format_versions_1.PACKAGE_FORMAT_VERSION,
|
|
73
75
|
project: manifest.project.name,
|
|
74
76
|
manifestVersion: manifest.version,
|
|
75
77
|
});
|
|
@@ -8,6 +8,7 @@ exports.installPackage = installPackage;
|
|
|
8
8
|
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
9
9
|
const node_path_1 = __importDefault(require("node:path"));
|
|
10
10
|
const smol_toml_1 = require("smol-toml");
|
|
11
|
+
const format_versions_1 = require("../constants/format-versions");
|
|
11
12
|
const fs_1 = require("../utils/fs");
|
|
12
13
|
/** Parse a data file by its extension (TOML or JSON). */
|
|
13
14
|
function parseByExt(filePath, content) {
|
|
@@ -95,7 +96,8 @@ function mergeOnlyKeys(target, source, keys) {
|
|
|
95
96
|
* When `mergeKeys` is given, only those top-level keys are merged (the rest
|
|
96
97
|
* of the target is preserved). On a *fresh* target (file absent) the whole
|
|
97
98
|
* payload is restored regardless, so a first install still carries the full
|
|
98
|
-
* configuration.
|
|
99
|
+
* configuration. An existing target that fails to parse is rejected earlier
|
|
100
|
+
* by `planInstall` (as a conflict) — it is never replaced wholesale.
|
|
99
101
|
*/
|
|
100
102
|
async function mergeDataFile(from, to, mergeKeys) {
|
|
101
103
|
let source = {};
|
|
@@ -115,13 +117,9 @@ async function mergeDataFile(from, to, mergeKeys) {
|
|
|
115
117
|
}
|
|
116
118
|
return;
|
|
117
119
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
122
|
-
catch {
|
|
123
|
-
target = {};
|
|
124
|
-
}
|
|
120
|
+
// planInstall 已确保可合并目标要么不存在、要么可解析;此处解析失败说明目标刚被外部改动,
|
|
121
|
+
// 直接失败而不是用包内容整体替换用户文件。
|
|
122
|
+
const target = parseByExt(to, await promises_1.default.readFile(to, 'utf8'));
|
|
125
123
|
const merged = mergeKeys && mergeKeys.length > 0
|
|
126
124
|
? mergeOnlyKeys(target, source, mergeKeys)
|
|
127
125
|
: deepMerge(target, source);
|
|
@@ -132,6 +130,31 @@ async function mergeDataFile(from, to, mergeKeys) {
|
|
|
132
130
|
await (0, fs_1.writeJsonFile)(to, merged);
|
|
133
131
|
}
|
|
134
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* 校验包元数据里的 `formatVersion`:
|
|
135
|
+
* - 没有 `package.json`、没有该字段或无法解析 → 视为 1(兼容 v0.9 及更早的旧包);
|
|
136
|
+
* - 高于当前支持版本 → 抛出稳定错误 `PACKAGE_FORMAT_UNSUPPORTED`,而不是在后续步骤里崩掉。
|
|
137
|
+
*/
|
|
138
|
+
async function assertSupportedPackageFormat(packageRoot) {
|
|
139
|
+
let raw;
|
|
140
|
+
try {
|
|
141
|
+
raw = await promises_1.default.readFile(node_path_1.default.join(packageRoot, 'package.json'), 'utf8');
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
let parsed;
|
|
147
|
+
try {
|
|
148
|
+
parsed = JSON.parse(raw);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const formatVersion = typeof parsed.formatVersion === 'number' ? parsed.formatVersion : 1;
|
|
154
|
+
if (formatVersion > format_versions_1.PACKAGE_FORMAT_VERSION) {
|
|
155
|
+
throw new Error(`PACKAGE_FORMAT_UNSUPPORTED: 包格式版本 ${formatVersion} 高于当前支持的 ${format_versions_1.PACKAGE_FORMAT_VERSION},请升级 agentdock-cli 后再安装`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
135
158
|
/**
|
|
136
159
|
* Produce a read-only preview of what `install` would do for a package
|
|
137
160
|
* against a target path — without writing anything. Boundary checks
|
|
@@ -142,6 +165,7 @@ async function planInstall(packagePath, explicitTargetPath, overwrite = false) {
|
|
|
142
165
|
const packageRoot = node_path_1.default.resolve(packagePath);
|
|
143
166
|
const manifestSnapshotPath = node_path_1.default.join(packageRoot, 'manifest.resolved.json');
|
|
144
167
|
const installPlanPath = node_path_1.default.join(packageRoot, 'meta', 'install-plan.json');
|
|
168
|
+
await assertSupportedPackageFormat(packageRoot);
|
|
145
169
|
if (!(await (0, fs_1.pathExists)(manifestSnapshotPath))) {
|
|
146
170
|
throw new Error(`Missing package manifest snapshot: ${manifestSnapshotPath}`);
|
|
147
171
|
}
|
|
@@ -178,8 +202,15 @@ async function planInstall(packagePath, explicitTargetPath, overwrite = false) {
|
|
|
178
202
|
let action;
|
|
179
203
|
let note;
|
|
180
204
|
if (entry.merge) {
|
|
181
|
-
|
|
182
|
-
|
|
205
|
+
// 目标存在但解析失败(损坏 JSON/TOML)→ 冲突而非合并:绝不用包内容整体替换用户文件。
|
|
206
|
+
if (exists && !(await isParseableDataFile(entry.to))) {
|
|
207
|
+
action = 'conflict';
|
|
208
|
+
note = 'merge: target file is unparseable (corrupt JSON/TOML), fix it manually before installing';
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
action = 'merge';
|
|
212
|
+
note = exists ? await describeMerge(entry.from, entry.to, entry.mergeKeys) : 'merge: target missing (will create)';
|
|
213
|
+
}
|
|
183
214
|
}
|
|
184
215
|
else if (!exists) {
|
|
185
216
|
action = 'create';
|
|
@@ -198,6 +229,16 @@ async function planInstall(packagePath, explicitTargetPath, overwrite = false) {
|
|
|
198
229
|
const conflicts = entries.filter((entry) => entry.action === 'conflict');
|
|
199
230
|
return { targetPath: targetRoot, entries, conflicts };
|
|
200
231
|
}
|
|
232
|
+
/** Whether an existing data file (JSON/TOML by extension) parses cleanly. */
|
|
233
|
+
async function isParseableDataFile(filePath) {
|
|
234
|
+
try {
|
|
235
|
+
parseByExt(filePath, await promises_1.default.readFile(filePath, 'utf8'));
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
201
242
|
/** Human-readable summary of what a merge entry would add to the target file. */
|
|
202
243
|
async function describeMerge(sourcePath, targetPath, mergeKeys) {
|
|
203
244
|
try {
|
|
@@ -236,7 +277,9 @@ async function describeMerge(sourcePath, targetPath, mergeKeys) {
|
|
|
236
277
|
return 'merge: deep-merge into existing';
|
|
237
278
|
}
|
|
238
279
|
}
|
|
239
|
-
async function installPackage(packagePath, explicitTargetPath, overwrite = false, dryRun = false
|
|
280
|
+
async function installPackage(packagePath, explicitTargetPath, overwrite = false, dryRun = false,
|
|
281
|
+
/** 'fail':有冲突即报错(install 默认);'skip':冲突项跳过并保留在 plan 中(sync pull 用)。 */
|
|
282
|
+
conflictPolicy = 'fail') {
|
|
240
283
|
const plan = await planInstall(packagePath, explicitTargetPath, overwrite);
|
|
241
284
|
// Dry-run: validate + preview only, never touch the target.
|
|
242
285
|
if (dryRun) {
|
|
@@ -247,7 +290,7 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
|
|
|
247
290
|
const lockPath = node_path_1.default.join(plan.targetPath, '.agentdock.lock');
|
|
248
291
|
const lockHandle = await (0, fs_1.acquireLock)(lockPath);
|
|
249
292
|
try {
|
|
250
|
-
if (plan.conflicts.length > 0) {
|
|
293
|
+
if (conflictPolicy === 'fail' && plan.conflicts.length > 0) {
|
|
251
294
|
throw new Error(`Install conflict detected:\n${plan.conflicts.map((entry) => entry.to).join('\n')}`);
|
|
252
295
|
}
|
|
253
296
|
for (const entry of plan.entries) {
|
|
@@ -255,6 +298,10 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
|
|
|
255
298
|
if (entry.action === 'skip') {
|
|
256
299
|
continue;
|
|
257
300
|
}
|
|
301
|
+
// sync pull 默认策略:冲突项不覆盖、不报错,显式留在结果里。
|
|
302
|
+
if (entry.action === 'conflict') {
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
258
305
|
if (entry.action === 'merge') {
|
|
259
306
|
// Deep-merge the payload into the existing target (preserving other
|
|
260
307
|
// top-level keys / other mcpServers or mcp_servers). Never clobbers it.
|
|
@@ -0,0 +1,46 @@
|
|
|
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.packFromScan = packFromScan;
|
|
7
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
8
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
+
const scan_export_1 = require("./scan-export");
|
|
10
|
+
const package_lock_1 = require("./package-lock");
|
|
11
|
+
const zip_1 = require("../utils/zip");
|
|
12
|
+
const fs_1 = require("../utils/fs");
|
|
13
|
+
/**
|
|
14
|
+
* `pack` = `export --from-scan` + `agentdock.lock.json`(逐文件 SHA-256 + 聚合哈希)
|
|
15
|
+
* + 可选 `.zip`。包目录本身仍是 `install` / `sync` 直接可用的格式。
|
|
16
|
+
*/
|
|
17
|
+
async function packFromScan(options) {
|
|
18
|
+
const manifestPath = node_path_1.default.resolve(options.scanManifestPath);
|
|
19
|
+
const manifestSha256 = (0, package_lock_1.sha256Buffer)(await promises_1.default.readFile(manifestPath));
|
|
20
|
+
const exported = await (0, scan_export_1.exportFromScan)({
|
|
21
|
+
scanManifestPath: manifestPath,
|
|
22
|
+
out: options.out,
|
|
23
|
+
env: options.env,
|
|
24
|
+
overwrite: options.overwrite,
|
|
25
|
+
});
|
|
26
|
+
const { lock, lockPath } = await (0, package_lock_1.writePackageLock)(exported.outputPath, {
|
|
27
|
+
manifestPath,
|
|
28
|
+
manifestSha256,
|
|
29
|
+
});
|
|
30
|
+
let zipPath;
|
|
31
|
+
let zipEntryCount;
|
|
32
|
+
if (options.zip) {
|
|
33
|
+
const trimmed = exported.outputPath.replace(/[\\/]+$/, '');
|
|
34
|
+
zipPath = `${trimmed}.zip`;
|
|
35
|
+
const contents = await (0, package_lock_1.readPackageContents)(trimmed);
|
|
36
|
+
await (0, fs_1.writeBinaryFile)(zipPath, (0, zip_1.createZip)(contents.files));
|
|
37
|
+
zipEntryCount = contents.files.size;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
outputPath: exported.outputPath,
|
|
41
|
+
lockPath,
|
|
42
|
+
zipPath,
|
|
43
|
+
fileCount: lock.files.length,
|
|
44
|
+
zipEntryCount,
|
|
45
|
+
};
|
|
46
|
+
}
|