@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.
@@ -0,0 +1,415 @@
1
+ /**
2
+ * key-resolver.js -- Ed25519 public key resolution for wrl-verify.
3
+ *
4
+ * Three trust levels, in descending order of security:
5
+ * 1. origin -- key fetched from {origin}/.well-known/signing-keys
6
+ * 2. pinned -- key supplied directly via --key or --key-file
7
+ * 3. embedded -- key from WACZ itself (--trust-embedded; self-asserted only)
8
+ *
9
+ * SECURITY: HTTP origins are rejected except localhost. An attacker on the
10
+ * network could serve a malicious signing key over plaintext HTTP.
11
+ */ // tva
12
+
13
+ import { readFileSync } from 'node:fs';
14
+
15
+ const KEY_FETCH_TIMEOUT_MS = 5_000;
16
+ const WACZ_FETCH_TIMEOUT_MS = 30_000;
17
+ const MAX_KEY_RESPONSE_BYTES = 1_024 * 1_024; // 1 MB
18
+ const MAX_WACZ_BYTES = 100 * 1_024 * 1_024; // 100 MB
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // URL helpers
22
+ // ---------------------------------------------------------------------------
23
+
24
+ /**
25
+ * Returns true for WRL capture URLs matching /v1/(captures|verify)/cap_<id>.
26
+ *
27
+ * @param {string} input
28
+ * @returns {boolean}
29
+ */
30
+ export function isWrlCaptureUrl(input) {
31
+ try {
32
+ const url = new URL(input);
33
+ return /\/v1\/(captures|verify)\/cap_[a-f0-9]{32}$/.test(url.pathname);
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Extracts the origin (scheme + host + port) from a URL string.
41
+ *
42
+ * @param {string} urlStr
43
+ * @returns {string}
44
+ */
45
+ export function originFromUrl(urlStr) {
46
+ const url = new URL(urlStr);
47
+ return url.origin;
48
+ }
49
+
50
+ /**
51
+ * Extracts the capture ID from a WRL capture URL.
52
+ *
53
+ * @param {string} urlStr
54
+ * @returns {string} e.g. "cap_abc123..."
55
+ */
56
+ export function captureIdFromUrl(urlStr) {
57
+ const url = new URL(urlStr);
58
+ const match = url.pathname.match(/\/(cap_[a-f0-9]{32})$/);
59
+ if (!match) throw new Error(`Cannot extract capture ID from URL: ${urlStr}`);
60
+ return match[1];
61
+ }
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // HTTP helpers
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /**
68
+ * Fetches a URL with a timeout and response-size guard.
69
+ *
70
+ * @param {string} url
71
+ * @param {{ timeoutMs?: number, maxBytes?: number }} opts
72
+ * @returns {Promise<Uint8Array>}
73
+ */
74
+ async function fetchBytes(url, { timeoutMs = KEY_FETCH_TIMEOUT_MS, maxBytes = MAX_KEY_RESPONSE_BYTES } = {}) {
75
+ const controller = new AbortController();
76
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
77
+
78
+ let response;
79
+ try {
80
+ response = await fetch(url, { signal: controller.signal });
81
+ } catch (err) {
82
+ clearTimeout(timer);
83
+ const cause = err.name === 'AbortError' ? 'timed out' : err.message;
84
+ throw new Error(`Network error fetching ${url}: ${cause}`);
85
+ }
86
+ clearTimeout(timer);
87
+
88
+ if (!response.ok) {
89
+ throw new Error(`HTTP ${response.status} fetching ${url}`);
90
+ }
91
+
92
+ // Stream with size guard
93
+ const reader = response.body.getReader();
94
+ const chunks = [];
95
+ let total = 0;
96
+ while (true) {
97
+ const { done, value } = await reader.read();
98
+ if (done) break;
99
+ total += value.byteLength;
100
+ if (total > maxBytes) {
101
+ reader.cancel();
102
+ throw new Error(`Response from ${url} exceeds ${maxBytes} byte limit`);
103
+ }
104
+ chunks.push(value);
105
+ }
106
+
107
+ const result = new Uint8Array(total);
108
+ let offset = 0;
109
+ for (const chunk of chunks) {
110
+ result.set(chunk, offset);
111
+ offset += chunk.byteLength;
112
+ }
113
+ return result;
114
+ }
115
+
116
+ // ---------------------------------------------------------------------------
117
+ // WACZ download
118
+ // ---------------------------------------------------------------------------
119
+
120
+ /**
121
+ * Downloads a WACZ file from a WRL capture URL.
122
+ * Derives the artifact URL from the capture origin and ID.
123
+ *
124
+ * @param {string} captureUrl
125
+ * @returns {Promise<{ waczBytes: Uint8Array, origin: string }>}
126
+ */
127
+ export async function fetchWaczFromCaptureUrl(captureUrl) {
128
+ const origin = originFromUrl(captureUrl);
129
+ const captureId = captureIdFromUrl(captureUrl);
130
+ const waczUrl = `${origin}/v1/captures/${captureId}/artifacts/wacz`;
131
+
132
+ process.stderr.write(`Fetching capture from ${waczUrl}\n`);
133
+
134
+ const waczBytes = await fetchBytes(waczUrl, {
135
+ timeoutMs: WACZ_FETCH_TIMEOUT_MS,
136
+ maxBytes: MAX_WACZ_BYTES,
137
+ });
138
+
139
+ return { waczBytes, origin };
140
+ }
141
+
142
+ /**
143
+ * Downloads a WACZ file from an arbitrary HTTPS URL.
144
+ *
145
+ * @param {string} url
146
+ * @returns {Promise<Uint8Array>}
147
+ */
148
+ export async function fetchWaczFromUrl(url) {
149
+ process.stderr.write(`Fetching capture from ${url}\n`);
150
+ return fetchBytes(url, { timeoutMs: WACZ_FETCH_TIMEOUT_MS, maxBytes: MAX_WACZ_BYTES });
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Key parsing helpers
155
+ // ---------------------------------------------------------------------------
156
+
157
+ /**
158
+ * Decodes a base64-encoded 32-byte Ed25519 public key.
159
+ *
160
+ * @param {string} b64
161
+ * @returns {Uint8Array}
162
+ */
163
+ function decodePublicKey(b64) {
164
+ const bytes = Buffer.from(b64, 'base64');
165
+ if (bytes.length !== 32) {
166
+ throw new Error(`Expected 32-byte Ed25519 key, got ${bytes.length} bytes`);
167
+ }
168
+ return new Uint8Array(bytes);
169
+ }
170
+
171
+ /**
172
+ * Extracts a short 8-hex-char key ID from a base64 public key.
173
+ * Mirrors the server convention: first 4 bytes of the key as lowercase hex.
174
+ *
175
+ * @param {string} b64
176
+ * @returns {string}
177
+ */
178
+ function keyIdFromBase64(b64) {
179
+ const bytes = Buffer.from(b64, 'base64');
180
+ return bytes.slice(0, 4).toString('hex');
181
+ }
182
+
183
+ // ---------------------------------------------------------------------------
184
+ // Origin key fetch
185
+ // ---------------------------------------------------------------------------
186
+
187
+ /**
188
+ * Fetches a signing key from {origin}/.well-known/signing-keys.
189
+ * Falls back to /.well-known/signing-key for v0.1.0 captures without keyId.
190
+ *
191
+ * @param {string} origin
192
+ * @param {string|null} keyId 8-char hex key ID from signedData, or null
193
+ * @returns {Promise<{ publicKeyBytes: Uint8Array, keyId: string, endpoint: string }>}
194
+ */
195
+ async function fetchKeyFromOrigin(origin, keyId) {
196
+ // Try the multi-key endpoint first
197
+ const keysUrl = `${origin}/.well-known/signing-keys`;
198
+ let keysData;
199
+ let usedFallback = false;
200
+
201
+ try {
202
+ const bytes = await fetchBytes(keysUrl);
203
+ keysData = JSON.parse(new TextDecoder().decode(bytes));
204
+ } catch (err) {
205
+ // If the multi-key endpoint fails and we have a keyId, propagate the error.
206
+ // If no keyId (v0.1.0), try the single-key fallback endpoint below.
207
+ if (keyId) {
208
+ throw new Error(
209
+ `Failed to fetch signing keys from ${keysUrl}: ${err.message}\n\n` +
210
+ `Specify the key directly with:\n` +
211
+ ` --key <base64> Provide key directly\n` +
212
+ ` --key-file <path> Read key from file`
213
+ );
214
+ }
215
+ keysData = null;
216
+ }
217
+
218
+ // Try to find a matching entry in the keys list
219
+ if (keysData && keyId) {
220
+ const keys = Array.isArray(keysData.keys) ? keysData.keys : (Array.isArray(keysData) ? keysData : []);
221
+ const entry = keys.find(k => k.keyId === keyId);
222
+ if (entry?.publicKey) {
223
+ return {
224
+ publicKeyBytes: decodePublicKey(entry.publicKey),
225
+ keyId,
226
+ endpoint: keysUrl,
227
+ };
228
+ }
229
+ }
230
+
231
+ // Fall back to the single-key endpoint
232
+ const singleUrl = `${origin}/.well-known/signing-key`;
233
+ usedFallback = true;
234
+ let singleData;
235
+ try {
236
+ const bytes = await fetchBytes(singleUrl);
237
+ singleData = JSON.parse(new TextDecoder().decode(bytes));
238
+ } catch (err) {
239
+ throw new Error(
240
+ `Failed to fetch signing key from ${singleUrl}: ${err.message}\n\n` +
241
+ `Specify the key directly with:\n` +
242
+ ` --key <base64> Provide key directly\n` +
243
+ ` --key-file <path> Read key from file`
244
+ );
245
+ }
246
+
247
+ const rawKey = singleData?.publicKey ?? singleData?.key ?? null;
248
+ if (!rawKey) {
249
+ throw new Error(`No publicKey field found in ${singleUrl}`);
250
+ }
251
+
252
+ const resolvedKeyId = keyIdFromBase64(rawKey);
253
+
254
+ // If we had a keyId and the fallback key doesn't match, fail explicitly
255
+ if (keyId && resolvedKeyId !== keyId) {
256
+ throw new Error(
257
+ `Key not found for keyId: ${keyId}\n\n` +
258
+ `The signing-keys endpoint did not contain the expected key, ` +
259
+ `and the fallback key has a different ID (${resolvedKeyId}).\n\n` +
260
+ `Specify the key directly with:\n` +
261
+ ` --key <base64> Provide key directly\n` +
262
+ ` --key-file <path> Read key from file`
263
+ );
264
+ }
265
+
266
+ return {
267
+ publicKeyBytes: decodePublicKey(rawKey),
268
+ keyId: resolvedKeyId,
269
+ endpoint: singleUrl,
270
+ };
271
+ }
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // Public API
275
+ // ---------------------------------------------------------------------------
276
+
277
+ /**
278
+ * Resolves the Ed25519 signing key from the configured trust source.
279
+ *
280
+ * @param {{
281
+ * origin?: string,
282
+ * key?: string,
283
+ * keyFile?: string,
284
+ * trustEmbedded?: boolean,
285
+ * signedData?: object,
286
+ * }} options
287
+ * @returns {Promise<{
288
+ * publicKeyBytes: Uint8Array,
289
+ * keyId: string,
290
+ * source: 'origin'|'pinned'|'embedded',
291
+ * origin: string|null,
292
+ * endpoint: string|null,
293
+ * }>}
294
+ */
295
+ export async function resolveKey(options) {
296
+ const { origin, key, keyFile, trustEmbedded, signedData } = options;
297
+
298
+ // HTTPS enforcement: reject insecure origins (except localhost for dev/testing)
299
+ if (origin &&
300
+ !origin.startsWith('https://') &&
301
+ !origin.startsWith('http://localhost') &&
302
+ !origin.startsWith('http://127.0.0.1')) {
303
+ throw new Error(
304
+ `Origin must use HTTPS (except localhost).\n` +
305
+ `Got: ${origin}\n\n` +
306
+ `An attacker on the network could serve a malicious signing key over HTTP.`
307
+ );
308
+ }
309
+
310
+ // --key: directly provided base64 key
311
+ if (key) {
312
+ const publicKeyBytes = decodePublicKey(key);
313
+ return {
314
+ publicKeyBytes,
315
+ keyId: keyIdFromBase64(key),
316
+ source: 'pinned',
317
+ origin: null,
318
+ endpoint: null,
319
+ };
320
+ }
321
+
322
+ // --key-file: read key from a file
323
+ if (keyFile) {
324
+ let raw;
325
+ try {
326
+ raw = readFileSync(keyFile, 'utf8').trim();
327
+ } catch (err) {
328
+ throw new Error(`Cannot read key file ${keyFile}: ${err.message}`);
329
+ }
330
+ const publicKeyBytes = decodePublicKey(raw);
331
+ return {
332
+ publicKeyBytes,
333
+ keyId: keyIdFromBase64(raw),
334
+ source: 'pinned',
335
+ origin: null,
336
+ endpoint: null,
337
+ };
338
+ }
339
+
340
+ // --trust-embedded: use the key from WACZ itself (insecure)
341
+ if (trustEmbedded) {
342
+ const version = signedData?.version ?? '0.1.0';
343
+ let embeddedKey = null;
344
+
345
+ if (version === '0.2.0') {
346
+ const selfSig = (signedData?.signatures ?? []).find(s => s.type === 'self');
347
+ embeddedKey = selfSig?.publicKey ?? null;
348
+ } else {
349
+ embeddedKey = signedData?.publicKey ?? null;
350
+ }
351
+
352
+ if (!embeddedKey) {
353
+ throw new Error('No embedded public key found in WACZ datapackage-digest.json');
354
+ }
355
+
356
+ process.stderr.write(
357
+ `Warning: Verification used the self-asserted key embedded in the WACZ.\n` +
358
+ `This proves internal consistency only -- not that the capture was\n` +
359
+ `produced by a trusted operator.\n`
360
+ );
361
+
362
+ const publicKeyBytes = decodePublicKey(embeddedKey);
363
+ return {
364
+ publicKeyBytes,
365
+ keyId: keyIdFromBase64(embeddedKey),
366
+ source: 'embedded',
367
+ origin: null,
368
+ endpoint: null,
369
+ };
370
+ }
371
+
372
+ // --origin (or auto-derived from capture URL): fetch from well-known endpoint
373
+ if (origin) {
374
+ // Extract keyId from signedData for matching
375
+ const version = signedData?.version ?? '0.1.0';
376
+ let keyId = null;
377
+ if (version === '0.2.0') {
378
+ const selfSig = (signedData?.signatures ?? []).find(s => s.type === 'self');
379
+ keyId = selfSig?.keyId ?? null;
380
+ }
381
+ // v0.1.0 captures have no keyId field -- will use fallback endpoint
382
+
383
+ const { publicKeyBytes, keyId: resolvedKeyId, endpoint } = await fetchKeyFromOrigin(origin, keyId);
384
+ return {
385
+ publicKeyBytes,
386
+ keyId: resolvedKeyId,
387
+ source: 'origin',
388
+ origin,
389
+ endpoint,
390
+ };
391
+ }
392
+
393
+ // No key source -- extract embedded keyId for the error message
394
+ const version = signedData?.version ?? '0.1.0';
395
+ let embeddedKeyId = 'unknown';
396
+ if (version === '0.2.0') {
397
+ const selfSig = (signedData?.signatures ?? []).find(s => s.type === 'self');
398
+ if (selfSig?.publicKey) embeddedKeyId = keyIdFromBase64(selfSig.publicKey);
399
+ else if (selfSig?.keyId) embeddedKeyId = selfSig.keyId;
400
+ } else if (signedData?.publicKey) {
401
+ embeddedKeyId = keyIdFromBase64(signedData.publicKey);
402
+ }
403
+
404
+ throw new Error(
405
+ `No signing key source specified for local verification.\n\n` +
406
+ `The WACZ file contains an embedded public key, but using it would be\n` +
407
+ `insecure -- an attacker who modifies the capture can also replace the\n` +
408
+ `embedded key.\n\n` +
409
+ `Specify one of:\n` +
410
+ ` --origin https://wrl.benpeter.workers.dev Fetch key from the operator\n` +
411
+ ` --key <base64> Provide key directly\n` +
412
+ ` --key-file <path> Read key from file\n\n` +
413
+ `The embedded keyId is: ${embeddedKeyId}`
414
+ );
415
+ }