@w-r-l/verify 0.1.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/lib/cli.js ADDED
@@ -0,0 +1,417 @@
1
+ /**
2
+ * cli.js -- Argument parsing and orchestration for wrl-verify.
3
+ *
4
+ * Parses process.argv manually (no dependencies).
5
+ * Loads the WACZ, resolves the signing key, runs verification,
6
+ * and formats output.
7
+ *
8
+ * Exit codes:
9
+ * 0 -- All checks passed (verified)
10
+ * 1 -- One or more checks failed (not verified)
11
+ * 2 -- Usage error (bad arguments, missing file, network error)
12
+ */ // tva
13
+
14
+ import { readFileSync } from 'node:fs';
15
+ import { readFile } from 'node:fs/promises';
16
+ import { unzipSync } from 'fflate';
17
+ import { createRequire } from 'node:module';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { dirname, join } from 'node:path';
20
+
21
+ import { verifyWacz } from './verify.js';
22
+ import { loadTrustedRoots } from './cms-verify.js';
23
+ import { formatHuman, formatJson, formatJsonError } from './format.js';
24
+ import {
25
+ resolveKey,
26
+ isWrlCaptureUrl,
27
+ originFromUrl,
28
+ fetchWaczFromCaptureUrl,
29
+ fetchWaczFromUrl,
30
+ } from './key-resolver.js';
31
+
32
+ const __dirname = dirname(fileURLToPath(import.meta.url));
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Help text
36
+ // ---------------------------------------------------------------------------
37
+
38
+ const HELP = `
39
+ USAGE
40
+ $ wrl-verify <file-or-url> [options]
41
+
42
+ Verify the cryptographic integrity of a WRL WACZ capture.
43
+
44
+ ARGUMENTS
45
+ <file-or-url> Path to a .wacz file, or a WRL capture URL
46
+
47
+ OPTIONS
48
+ --origin <url> WRL instance URL for key resolution
49
+ --key <base64> Ed25519 public key (base64)
50
+ --key-file <path> Read public key from file
51
+ --trust-embedded Use the embedded key (insecure, see below)
52
+ --trust-root <path> Additional trusted root certificate (PEM)
53
+ --json Output machine-readable JSON to stdout
54
+ --no-color Disable colored output
55
+ -h, --help Show this help message
56
+ --version Show version number
57
+
58
+ EXIT CODES
59
+ 0 All checks passed (verified)
60
+ 1 One or more checks failed (not verified)
61
+ 2 Usage error (bad arguments, missing file, network error)
62
+
63
+ TRUST MODEL
64
+ Remote URLs: key is fetched automatically from the server origin.
65
+ Local files: you must specify --origin, --key, or --key-file.
66
+ --trust-embedded uses the key embedded in the WACZ (proves internal
67
+ consistency only, not that the capture came from a trusted operator).
68
+ `.trimStart();
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Argument parser
72
+ // ---------------------------------------------------------------------------
73
+
74
+ /**
75
+ * Parses the argv array (process.argv.slice(2)) into a structured options
76
+ * object.
77
+ *
78
+ * @param {string[]} argv
79
+ * @returns {{
80
+ * target: string|null,
81
+ * origin: string|null,
82
+ * key: string|null,
83
+ * keyFile: string|null,
84
+ * trustEmbedded: boolean,
85
+ * trustRoots: string[],
86
+ * json: boolean,
87
+ * noColor: boolean,
88
+ * help: boolean,
89
+ * version: boolean,
90
+ * }}
91
+ * @throws {Error} on unknown or malformed flags
92
+ */
93
+ export function parseArgs(argv) {
94
+ const opts = {
95
+ target: null,
96
+ origin: null,
97
+ key: null,
98
+ keyFile: null,
99
+ trustEmbedded: false,
100
+ trustRoots: [],
101
+ json: false,
102
+ noColor: false,
103
+ help: false,
104
+ version: false,
105
+ };
106
+
107
+ const VALUE_FLAGS = new Set(['--origin', '--key', '--key-file', '--trust-root']);
108
+ const BOOL_FLAGS = new Set(['--trust-embedded', '--json', '--no-color', '-h', '--help', '--version']);
109
+
110
+ let i = 0;
111
+ while (i < argv.length) {
112
+ const arg = argv[i];
113
+
114
+ if (arg === '-h' || arg === '--help') {
115
+ opts.help = true;
116
+ i++;
117
+ continue;
118
+ }
119
+
120
+ if (arg === '--version') {
121
+ opts.version = true;
122
+ i++;
123
+ continue;
124
+ }
125
+
126
+ if (arg === '--trust-embedded') {
127
+ opts.trustEmbedded = true;
128
+ i++;
129
+ continue;
130
+ }
131
+
132
+ if (arg === '--json') {
133
+ opts.json = true;
134
+ i++;
135
+ continue;
136
+ }
137
+
138
+ if (arg === '--no-color') {
139
+ opts.noColor = true;
140
+ i++;
141
+ continue;
142
+ }
143
+
144
+ if (arg === '--origin') {
145
+ if (i + 1 >= argv.length) throw new Error('--origin requires a value');
146
+ opts.origin = argv[++i];
147
+ i++;
148
+ continue;
149
+ }
150
+
151
+ if (arg === '--key') {
152
+ if (i + 1 >= argv.length) throw new Error('--key requires a value');
153
+ opts.key = argv[++i];
154
+ i++;
155
+ continue;
156
+ }
157
+
158
+ if (arg === '--key-file') {
159
+ if (i + 1 >= argv.length) throw new Error('--key-file requires a value');
160
+ opts.keyFile = argv[++i];
161
+ i++;
162
+ continue;
163
+ }
164
+
165
+ if (arg === '--trust-root') {
166
+ if (i + 1 >= argv.length) throw new Error('--trust-root requires a value');
167
+ opts.trustRoots.push(argv[++i]);
168
+ i++;
169
+ continue;
170
+ }
171
+
172
+ // Reject any other flags
173
+ if (arg.startsWith('-')) {
174
+ throw new Error(`Unknown flag: ${arg}`);
175
+ }
176
+
177
+ // Positional argument
178
+ if (opts.target === null) {
179
+ opts.target = arg;
180
+ } else {
181
+ throw new Error(`Unexpected argument: ${arg}`);
182
+ }
183
+
184
+ i++;
185
+ }
186
+
187
+ return opts;
188
+ }
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // Version helper
192
+ // ---------------------------------------------------------------------------
193
+
194
+ function getVersion() {
195
+ try {
196
+ const pkgPath = join(__dirname, '..', 'package.json');
197
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
198
+ return pkg.version ?? '0.0.0';
199
+ } catch {
200
+ return '0.0.0';
201
+ }
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // WACZ digest extraction
206
+ // ---------------------------------------------------------------------------
207
+
208
+ /**
209
+ * Extracts the signedData object from WACZ bytes by reading
210
+ * datapackage-digest.json from the ZIP.
211
+ *
212
+ * @param {Uint8Array} waczBytes
213
+ * @returns {object|null} signedData or null on failure
214
+ */
215
+ function extractSignedData(waczBytes) {
216
+ try {
217
+ const files = unzipSync(waczBytes);
218
+ const digestRaw = files['datapackage-digest.json'];
219
+ if (!digestRaw) return null;
220
+ const digest = JSON.parse(new TextDecoder().decode(digestRaw));
221
+ return digest?.signedData ?? null;
222
+ } catch {
223
+ return null;
224
+ }
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Key source mutual exclusivity check
229
+ // ---------------------------------------------------------------------------
230
+
231
+ /**
232
+ * Returns an error message if more than one key source is specified.
233
+ *
234
+ * @param {{ origin, key, keyFile, trustEmbedded }} opts
235
+ * @returns {string|null}
236
+ */
237
+ function checkKeySourceExclusion(opts) {
238
+ const sources = [
239
+ opts.origin && '--origin',
240
+ opts.key && '--key',
241
+ opts.keyFile && '--key-file',
242
+ opts.trustEmbedded && '--trust-embedded',
243
+ ].filter(Boolean);
244
+
245
+ if (sources.length > 1) {
246
+ return `These key source options are mutually exclusive: ${sources.join(', ')}`;
247
+ }
248
+ return null;
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // Main entry point
253
+ // ---------------------------------------------------------------------------
254
+
255
+ /**
256
+ * CLI entry point. Parses arguments and runs the full verification pipeline.
257
+ *
258
+ * @param {string[]} argv process.argv.slice(2)
259
+ */
260
+ export async function run(argv) {
261
+ let opts;
262
+ let jsonMode = argv.includes('--json');
263
+ const noColor = argv.includes('--no-color');
264
+
265
+ // Parse arguments -- handle parse errors immediately
266
+ try {
267
+ opts = parseArgs(argv);
268
+ } catch (err) {
269
+ if (jsonMode) {
270
+ formatJsonError(err.message, '');
271
+ } else {
272
+ process.stderr.write(`Error: ${err.message}\n\nRun with --help for usage.\n`);
273
+ }
274
+ process.exit(2);
275
+ }
276
+
277
+ jsonMode = opts.json;
278
+
279
+ // Early exits: --help and --version
280
+ if (opts.help) {
281
+ process.stdout.write(HELP);
282
+ process.exit(0);
283
+ }
284
+
285
+ if (opts.version) {
286
+ process.stdout.write(`${getVersion()}\n`);
287
+ process.exit(0);
288
+ }
289
+
290
+ // Node.js version check
291
+ const nodeVersion = process.versions.node;
292
+ const nodeMajor = parseInt(nodeVersion.split('.')[0], 10);
293
+ if (nodeMajor < 20) {
294
+ const msg = `@w-r-l/verify requires Node.js 20 or later.\nYou are running Node.js ${nodeVersion}.`;
295
+ if (jsonMode) {
296
+ formatJsonError(msg, opts.target ?? '');
297
+ } else {
298
+ process.stderr.write(`Error: ${msg}\n`);
299
+ }
300
+ process.exit(2);
301
+ }
302
+
303
+ // Require target
304
+ if (!opts.target) {
305
+ const msg = 'Missing required argument: <file-or-url>';
306
+ if (jsonMode) {
307
+ formatJsonError(msg, '');
308
+ } else {
309
+ process.stderr.write(`Error: ${msg}\n\nRun with --help for usage.\n`);
310
+ }
311
+ process.exit(2);
312
+ }
313
+
314
+ // Mutually exclusive key sources
315
+ const keyConflict = checkKeySourceExclusion(opts);
316
+ if (keyConflict) {
317
+ if (jsonMode) {
318
+ formatJsonError(keyConflict, opts.target);
319
+ } else {
320
+ process.stderr.write(`Error: ${keyConflict}\n\nRun with --help for usage.\n`);
321
+ }
322
+ process.exit(2);
323
+ }
324
+
325
+ // From here on, all errors are caught and formatted consistently
326
+ let waczBytes;
327
+ let origin = opts.origin;
328
+ let sourceName = opts.target;
329
+
330
+ try {
331
+ // -----------------------------------------------------------------------
332
+ // Load / fetch WACZ bytes
333
+ // -----------------------------------------------------------------------
334
+ if (isWrlCaptureUrl(opts.target)) {
335
+ // WRL capture URL: auto-derive origin (unless --origin overrides)
336
+ if (!origin) {
337
+ origin = originFromUrl(opts.target);
338
+ }
339
+ const result = await fetchWaczFromCaptureUrl(opts.target);
340
+ waczBytes = result.waczBytes;
341
+ sourceName = opts.target;
342
+ } else {
343
+ let isUrl = false;
344
+ try { new URL(opts.target); isUrl = true; } catch { /* not a URL */ }
345
+
346
+ if (isUrl) {
347
+ // Arbitrary HTTPS URL -- no auto-origin derivation
348
+ waczBytes = await fetchWaczFromUrl(opts.target);
349
+ sourceName = opts.target;
350
+ } else {
351
+ // Local file
352
+ try {
353
+ waczBytes = await readFile(opts.target);
354
+ } catch (err) {
355
+ throw new Error(`Cannot read file ${opts.target}: ${err.message}`);
356
+ }
357
+ // Extract filename for display
358
+ sourceName = opts.target.split('/').pop() ?? opts.target;
359
+ }
360
+ }
361
+
362
+ // -----------------------------------------------------------------------
363
+ // Extract signedData for key resolution
364
+ // -----------------------------------------------------------------------
365
+ const signedData = extractSignedData(waczBytes);
366
+
367
+ // -----------------------------------------------------------------------
368
+ // Resolve signing key
369
+ // -----------------------------------------------------------------------
370
+ const keyResolution = await resolveKey({
371
+ origin,
372
+ key: opts.key,
373
+ keyFile: opts.keyFile,
374
+ trustEmbedded: opts.trustEmbedded,
375
+ signedData,
376
+ });
377
+
378
+ // -----------------------------------------------------------------------
379
+ // Load trusted roots
380
+ // -----------------------------------------------------------------------
381
+ const trustedRoots = loadTrustedRoots(opts.trustRoots);
382
+
383
+ // -----------------------------------------------------------------------
384
+ // Run verification
385
+ // -----------------------------------------------------------------------
386
+ const result = await verifyWacz(waczBytes, keyResolution.publicKeyBytes, { trustedRoots });
387
+
388
+ // Attach resolution metadata for output
389
+ result.source = sourceName;
390
+ result.keyResolution = {
391
+ keyId: keyResolution.keyId,
392
+ source: keyResolution.source,
393
+ origin: keyResolution.origin ?? null,
394
+ endpoint: keyResolution.endpoint ?? null,
395
+ };
396
+
397
+ // -----------------------------------------------------------------------
398
+ // Format and output
399
+ // -----------------------------------------------------------------------
400
+ if (opts.json) {
401
+ formatJson(result);
402
+ } else {
403
+ formatHuman(result, { noColor: opts.noColor });
404
+ }
405
+
406
+ process.exit(result.verified ? 0 : 1);
407
+
408
+ } catch (err) {
409
+ const msg = err.message ?? String(err);
410
+ if (opts.json) {
411
+ formatJsonError(msg, sourceName);
412
+ } else {
413
+ process.stderr.write(`Error: ${msg}\n`);
414
+ }
415
+ process.exit(2);
416
+ }
417
+ }