-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathcli.ts
More file actions
452 lines (410 loc) · 14.1 KB
/
cli.ts
File metadata and controls
452 lines (410 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#!/usr/bin/env node
import { execSync } from "child_process";
import { Command } from "commander";
import { existsSync, readFileSync, statSync } from "fs";
import { basename, dirname, join, resolve } from "path";
import { fileURLToPath } from "url";
import {
applyExternalSignature,
MAX_SIG_BLOCK_SIZE,
prepareForExternalSigning,
signMcpbFile,
unsignMcpbFile,
verifyMcpbFile,
} from "../node/sign.js";
import { cleanMcpb, validateManifest } from "../node/validate.js";
import { initExtension } from "./init.js";
import { packExtension } from "./pack.js";
import { unpackExtension } from "./unpack.js";
// ES modules equivalent of __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Get version from package.json
const packageJsonPath = join(__dirname, "..", "..", "package.json");
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
const version = packageJson.version;
/**
* Create a self-signed certificate for signing MCPB extensions
*/
function createSelfSignedCertificate(certPath: string, keyPath: string): void {
const subject = "/CN=MCPB Self-Signed Certificate/O=MCPB Extensions/C=US";
try {
// Generate a self-signed certificate valid for 10 years, no password
execSync(
`openssl req -x509 -newkey rsa:4096 -keyout "${keyPath}" -out "${certPath}" -days 3650 -nodes -subj "${subject}"`,
{ stdio: "pipe" },
);
} catch (error) {
throw new Error(`Failed to create self-signed certificate: ${error}`);
}
}
// Create the CLI program
const program = new Command();
program
.name("mcpb")
.description("Tools for building MCP Bundles")
.version(version);
// Init command
program
.command("init [directory]")
.description("Create a new MCPB extension manifest")
.option("-y, --yes", "Accept all defaults (non-interactive mode)")
.option(
"--manifest-version <version>",
"Manifest version to use in the generated manifest",
)
.action(
(
directory?: string,
options?: { yes?: boolean; manifestVersion?: string },
) => {
void (async () => {
try {
const success = await initExtension(
directory,
options?.yes,
options?.manifestVersion,
);
process.exit(success ? 0 : 1);
} catch (error) {
console.error(
`ERROR: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
})();
},
);
// Validate command
program
.command("validate <manifest>")
.description("Validate an MCPB manifest file")
.action((manifestPath: string) => {
const success = validateManifest(manifestPath);
process.exit(success ? 0 : 1);
});
// Clean command
program
.command("clean <mcpb>")
.description(
"Cleans an MCPB file, validates the manifest, and minimizes bundle size",
)
.action(async (mcpbFile: string) => {
await cleanMcpb(mcpbFile);
});
// Pack command
program
.command("pack [directory] [output]")
.description("Pack a directory into an MCPB extension")
.action((directory: string = process.cwd(), output?: string) => {
void (async () => {
try {
const success = await packExtension({
extensionPath: directory,
outputPath: output,
});
process.exit(success ? 0 : 1);
} catch (error) {
console.error(
`ERROR: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
})();
});
// Unpack command
program
.command("unpack <mcpb-file> [output]")
.description("Unpack an MCPB extension file")
.action((mcpbFile: string, output?: string) => {
void (async () => {
try {
const success = await unpackExtension({
mcpbPath: mcpbFile,
outputDir: output,
});
process.exit(success ? 0 : 1);
} catch (error) {
console.error(
`ERROR: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
})();
});
// Sign command
program
.command("sign <mcpb-file>")
.description("Sign an MCPB extension file")
.option(
"-c, --cert <path>",
"Path to certificate file (PEM format)",
"cert.pem",
)
.option(
"-k, --key <path>",
"Path to private key file (PEM format)",
"key.pem",
)
.option(
"-i, --intermediate <paths...>",
"Paths to intermediate certificate files",
)
.option("--self-signed", "Create a self-signed certificate if none exists")
.action(
(
mcpbFile: string,
options: {
cert: string;
key: string;
intermediate?: string[];
selfSigned?: boolean;
},
) => {
void (async () => {
try {
const mcpbPath = resolve(mcpbFile);
if (!existsSync(mcpbPath)) {
console.error(`ERROR: MCPB file not found: ${mcpbFile}`);
process.exit(1);
}
let certPath = options.cert;
let keyPath = options.key;
// Create self-signed certificate if requested
if (options.selfSigned) {
const mcpbDir = resolve(__dirname, "..");
certPath = join(mcpbDir, "self-signed-cert.pem");
keyPath = join(mcpbDir, "self-signed-key.pem");
if (!existsSync(certPath) || !existsSync(keyPath)) {
console.log("Creating self-signed certificate...");
createSelfSignedCertificate(certPath, keyPath);
console.log("Self-signed certificate created");
} else {
console.log("Using existing self-signed certificate");
}
} else {
// Check for manual certificate paths
if (!existsSync(certPath)) {
console.error(`ERROR: Certificate file not found: ${certPath}`);
console.log(
"Tip: Use --self-signed to create a self-signed certificate",
);
process.exit(1);
}
if (!existsSync(keyPath)) {
console.error(`ERROR: Private key file not found: ${keyPath}`);
process.exit(1);
}
}
console.log(`Signing ${basename(mcpbPath)}...`);
signMcpbFile(mcpbPath, certPath, keyPath, options.intermediate);
console.log(`Successfully signed ${basename(mcpbPath)}`);
// Display certificate info
const signatureInfo = await verifyMcpbFile(mcpbPath);
if (
signatureInfo.status === "signed" ||
signatureInfo.status === "self-signed"
) {
console.log(`Signed by: ${signatureInfo.publisher}`);
console.log(`Issuer: ${signatureInfo.issuer}`);
if (signatureInfo.status === "self-signed") {
console.log(`Warning: Certificate is self-signed`);
}
}
} catch (error) {
console.log(
`ERROR: Signing failed: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
})();
},
);
// Verify command
program
.command("verify <mcpb-file>")
.description("Verify the signature of an MCPB extension file")
.action((mcpbFile: string) => {
void (async () => {
try {
const mcpbPath = resolve(mcpbFile);
if (!existsSync(mcpbPath)) {
console.error(`ERROR: MCPB file not found: ${mcpbFile}`);
process.exit(1);
}
console.log(`Verifying ${basename(mcpbPath)}...`);
const result = await verifyMcpbFile(mcpbPath);
if (result.status === "signed") {
console.log(`Signature is valid`);
console.log(`Signed by: ${result.publisher}`);
console.log(`Issuer: ${result.issuer}`);
console.log(
`Valid from: ${new Date(result.valid_from!).toLocaleDateString()} to ${new Date(result.valid_to!).toLocaleDateString()}`,
);
console.log(`Fingerprint: ${result.fingerprint}`);
} else if (result.status === "self-signed") {
console.log(`Signature is valid (self-signed)`);
console.log(`WARNING: This extension is self-signed`);
console.log(`Signed by: ${result.publisher}`);
console.log(
`Valid from: ${new Date(result.valid_from!).toLocaleDateString()} to ${new Date(result.valid_to!).toLocaleDateString()}`,
);
console.log(`Fingerprint: ${result.fingerprint}`);
} else {
console.error(`ERROR: Extension is not signed`);
process.exit(1);
}
} catch (error) {
console.log(
`ERROR: Verification failed: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
})();
});
// Info command
program
.command("info <mcpb-file>")
.description("Display information about an MCPB extension file")
.action((mcpbFile: string) => {
void (async () => {
try {
const mcpbPath = resolve(mcpbFile);
if (!existsSync(mcpbPath)) {
console.error(`ERROR: MCPB file not found: ${mcpbFile}`);
process.exit(1);
}
const stat = statSync(mcpbPath);
console.log(`File: ${basename(mcpbPath)}`);
console.log(`Size: ${(stat.size / 1024).toFixed(2)} KB`);
// Check if signed
const signatureInfo = await verifyMcpbFile(mcpbPath);
if (signatureInfo.status === "signed") {
console.log(`\nSignature Information:`);
console.log(` Subject: ${signatureInfo.publisher}`);
console.log(` Issuer: ${signatureInfo.issuer}`);
console.log(
` Valid from: ${new Date(signatureInfo.valid_from!).toLocaleDateString()} to ${new Date(signatureInfo.valid_to!).toLocaleDateString()}`,
);
console.log(` Fingerprint: ${signatureInfo.fingerprint}`);
console.log(` Status: Valid`);
} else if (signatureInfo.status === "self-signed") {
console.log(`\nSignature Information:`);
console.log(` Subject: ${signatureInfo.publisher}`);
console.log(` Issuer: ${signatureInfo.issuer} (self-signed)`);
console.log(
` Valid from: ${new Date(signatureInfo.valid_from!).toLocaleDateString()} to ${new Date(signatureInfo.valid_to!).toLocaleDateString()}`,
);
console.log(` Fingerprint: ${signatureInfo.fingerprint}`);
console.log(` Status: Valid (self-signed)`);
} else {
console.log(`\nWARNING: Not signed`);
}
} catch (error) {
console.log(
`ERROR: Failed to read MCPB info: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
})();
});
// Unsign command (for development/testing)
program
.command("unsign <mcpb-file>")
.description("Remove signature from a MCPB bundle file")
.action((mcpbFile: string) => {
try {
const mcpbPath = resolve(mcpbFile);
if (!existsSync(mcpbPath)) {
console.error(`ERROR: MCPB file not found: ${mcpbFile}`);
process.exit(1);
}
console.log(`Removing signature from ${basename(mcpbPath)}...`);
unsignMcpbFile(mcpbPath);
console.log(`Signature removed`);
} catch (error) {
console.log(
`ERROR: Failed to remove signature: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
});
// Prepare-for-signing command (external/enterprise signing workflow)
program
.command("prepare-for-signing <mcpb-file>")
.description(
"Prepare an MCPB file for external signing (GaraSign, ESRP, SignServer, etc.)",
)
.option("-o, --output <path>", "Output path (default: overwrite input)")
.action(
(mcpbFile: string, options: { output?: string }) => {
try {
const mcpbPath = resolve(mcpbFile);
if (!existsSync(mcpbPath)) {
console.error(`ERROR: MCPB file not found: ${mcpbFile}`);
process.exit(1);
}
prepareForExternalSigning(mcpbPath, options.output);
const target = options.output
? basename(options.output)
: basename(mcpbPath);
console.log(
`Prepared ${target} for external signing (EOCD comment_length set to ${MAX_SIG_BLOCK_SIZE})`,
);
console.log(
`\nNext steps:\n` +
` 1. Sign the prepared file with your HSM/signing tool (detached PKCS#7, DER format)\n` +
` 2. Run: mcpb apply-signature ${mcpbFile} --signature <signature.p7s>`,
);
} catch (error) {
console.error(
`ERROR: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
},
);
// Apply-signature command (external/enterprise signing workflow)
program
.command("apply-signature <mcpb-file>")
.description(
"Apply a detached PKCS#7 signature to a prepared MCPB file",
)
.requiredOption(
"-s, --signature <path>",
"Path to detached PKCS#7 signature file (.p7s, DER format)",
)
.option("-o, --output <path>", "Output path (default: overwrite input)")
.action(
(mcpbFile: string, options: { signature: string; output?: string }) => {
try {
const mcpbPath = resolve(mcpbFile);
const sigPath = resolve(options.signature);
if (!existsSync(mcpbPath)) {
console.error(`ERROR: MCPB file not found: ${mcpbFile}`);
process.exit(1);
}
if (!existsSync(sigPath)) {
console.error(
`ERROR: Signature file not found: ${options.signature}`,
);
process.exit(1);
}
const sigSize = statSync(sigPath).size;
applyExternalSignature(mcpbPath, sigPath, options.output);
const target = options.output
? basename(options.output)
: basename(mcpbPath);
console.log(
`Applied signature to ${target} (${sigSize} byte PKCS#7, padded to ${MAX_SIG_BLOCK_SIZE})`,
);
} catch (error) {
console.error(
`ERROR: ${error instanceof Error ? error.message : "Unknown error"}`,
);
process.exit(1);
}
},
);
// Parse command line arguments
program.parse();