@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/LICENSE +201 -0
- package/README.md +126 -0
- package/bin/wrl-verify.js +3 -0
- package/certs/trusted-roots/DigiCertSHA256RSA4096TimestampResponder20251.pem +40 -0
- package/certs/trusted-roots/DigiCertTrustedG4TimeStampingRSA4096SHA2562025CA1.pem +38 -0
- package/certs/trusted-roots/DigiCertTrustedRootG4.pem +32 -0
- package/lib/canonical-json.js +10 -0
- package/lib/cli.js +417 -0
- package/lib/cms-verify.js +301 -0
- package/lib/format.js +289 -0
- package/lib/key-resolver.js +415 -0
- package/lib/rfc3161.js +339 -0
- package/lib/sha256.js +7 -0
- package/lib/signing.js +22 -0
- package/lib/verify.js +285 -0
- package/package.json +47 -0
package/lib/rfc3161.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// Vendored from src/rfc3161.js -- verifyTimestamp, extractTSTInfo, parseTSTInfo,
|
|
2
|
+
// parseGeneralizedTime, and DER primitives only. Capture-time code excluded.
|
|
3
|
+
// Origin: https://github.com/benpeter/web-resource-ledger/blob/main/src/rfc3161.js
|
|
4
|
+
|
|
5
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
// OID value bytes (pre-encoded, without tag/length wrapper)
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
|
|
11
|
+
// 2.16.840.1.101.3.4.2.1 -- SHA-256
|
|
12
|
+
const OID_SHA256 = new Uint8Array([0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01]);
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// DER primitives
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Encodes DER definite length for a value of n bytes.
|
|
20
|
+
* Handles lengths up to 16,777,215 (3-byte long form), sufficient for 64 KB responses.
|
|
21
|
+
* @param {number} n
|
|
22
|
+
* @returns {Uint8Array}
|
|
23
|
+
*/
|
|
24
|
+
function writeLength(n) {
|
|
25
|
+
if (n < 0x80) return new Uint8Array([n]);
|
|
26
|
+
if (n <= 0xff) return new Uint8Array([0x81, n]);
|
|
27
|
+
if (n <= 0xffff) return new Uint8Array([0x82, n >> 8, n & 0xff]);
|
|
28
|
+
if (n <= 0xffffff) return new Uint8Array([0x83, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);
|
|
29
|
+
throw new Error(`DER length ${n} exceeds 3-byte encoding limit`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Encodes a DER TLV (tag-length-value).
|
|
34
|
+
* @param {number} tag
|
|
35
|
+
* @param {Uint8Array} content
|
|
36
|
+
* @returns {Uint8Array}
|
|
37
|
+
*/
|
|
38
|
+
function writeTLV(tag, content) {
|
|
39
|
+
const lenBytes = writeLength(content.length);
|
|
40
|
+
const out = new Uint8Array(1 + lenBytes.length + content.length);
|
|
41
|
+
out[0] = tag;
|
|
42
|
+
out.set(lenBytes, 1);
|
|
43
|
+
out.set(content, 1 + lenBytes.length);
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Decodes the DER length field starting at buf[offset].
|
|
49
|
+
* Returns { length, end } where end is the byte offset of the first value byte.
|
|
50
|
+
* Rejects indefinite-length encoding (DER forbids it).
|
|
51
|
+
* @param {Uint8Array} buf
|
|
52
|
+
* @param {number} offset
|
|
53
|
+
* @returns {{ length: number, end: number }}
|
|
54
|
+
*/
|
|
55
|
+
function readLength(buf, offset) {
|
|
56
|
+
if (offset >= buf.length) throw new Error('DER: length field past end of buffer');
|
|
57
|
+
const first = buf[offset];
|
|
58
|
+
if (first === 0x80) throw new Error('DER: indefinite length encoding rejected');
|
|
59
|
+
if (first < 0x80) return { length: first, end: offset + 1 };
|
|
60
|
+
|
|
61
|
+
const numBytes = first & 0x7f;
|
|
62
|
+
if (numBytes > 3) throw new Error(`DER: length encoding uses ${numBytes} bytes (max 3 supported)`);
|
|
63
|
+
if (offset + 1 + numBytes > buf.length) throw new Error('DER: length bytes past end of buffer');
|
|
64
|
+
|
|
65
|
+
let len = 0;
|
|
66
|
+
for (let i = 0; i < numBytes; i++) {
|
|
67
|
+
len = (len << 8) | buf[offset + 1 + i];
|
|
68
|
+
}
|
|
69
|
+
return { length: len, end: offset + 1 + numBytes };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Decodes a single DER TLV at buf[offset].
|
|
74
|
+
* Returns { tag, length, value, end } where:
|
|
75
|
+
* tag -- the raw tag byte
|
|
76
|
+
* length -- the declared content length
|
|
77
|
+
* value -- Uint8Array view of the content bytes
|
|
78
|
+
* end -- byte offset immediately after this TLV (= start of next sibling)
|
|
79
|
+
* Validates that the declared length does not exceed the remaining buffer.
|
|
80
|
+
* @param {Uint8Array} buf
|
|
81
|
+
* @param {number} offset Byte offset of the tag byte
|
|
82
|
+
* @returns {{ tag: number, length: number, value: Uint8Array, end: number }}
|
|
83
|
+
*/
|
|
84
|
+
function readTLV(buf, offset) {
|
|
85
|
+
if (offset >= buf.length) throw new Error('DER: read past end of buffer');
|
|
86
|
+
const tag = buf[offset];
|
|
87
|
+
const { length, end: valueStart } = readLength(buf, offset + 1);
|
|
88
|
+
if (valueStart + length > buf.length) {
|
|
89
|
+
throw new Error(
|
|
90
|
+
`DER: TLV at offset ${offset} declares length ${length} but only ` +
|
|
91
|
+
`${buf.length - valueStart} bytes remain`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
tag,
|
|
96
|
+
length,
|
|
97
|
+
value: buf.subarray(valueStart, valueStart + length),
|
|
98
|
+
end: valueStart + length,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Reads the nth child TLV (0-based) from inside a constructed TLV.
|
|
104
|
+
* The parent TLV's value bytes must already have been located; pass
|
|
105
|
+
* valueStart (first byte of parent content) and valueEnd (exclusive).
|
|
106
|
+
* @param {Uint8Array} buf
|
|
107
|
+
* @param {number} valueStart First byte of parent content
|
|
108
|
+
* @param {number} valueEnd One past last byte of parent content
|
|
109
|
+
* @param {number} index 0-based child index to retrieve
|
|
110
|
+
* @returns {{ tag: number, length: number, value: Uint8Array, end: number }}
|
|
111
|
+
*/
|
|
112
|
+
function childAt(buf, valueStart, valueEnd, index) {
|
|
113
|
+
let pos = valueStart;
|
|
114
|
+
let i = 0;
|
|
115
|
+
while (pos < valueEnd) {
|
|
116
|
+
const tlv = readTLV(buf, pos);
|
|
117
|
+
if (i === index) return tlv;
|
|
118
|
+
i++;
|
|
119
|
+
pos = tlv.end;
|
|
120
|
+
}
|
|
121
|
+
throw new Error(`DER: child index ${index} not found (only ${i} children present)`);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Concatenates multiple Uint8Arrays into one.
|
|
126
|
+
* @param {...Uint8Array} arrays
|
|
127
|
+
* @returns {Uint8Array}
|
|
128
|
+
*/
|
|
129
|
+
function concat(...arrays) {
|
|
130
|
+
const total = arrays.reduce((n, a) => n + a.length, 0);
|
|
131
|
+
const out = new Uint8Array(total);
|
|
132
|
+
let pos = 0;
|
|
133
|
+
for (const a of arrays) { out.set(a, pos); pos += a.length; }
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
// Public API
|
|
139
|
+
// ---------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Verifies a stored RFC 3161 timestamp token against a bundle hash.
|
|
143
|
+
* Does NOT verify the TSA's cryptographic signature (deferred --
|
|
144
|
+
* X.509 chain validation is handled by cms-verify.js in the CLI).
|
|
145
|
+
*
|
|
146
|
+
* @param {string} tokenBase64 Base64-encoded raw DER TimeStampToken
|
|
147
|
+
* @param {string} expectedBundleHash Hash string "sha256:<64 hex chars>"
|
|
148
|
+
* @returns {{ valid: boolean, genTime?: string, reason?: string }}
|
|
149
|
+
*/
|
|
150
|
+
export function verifyTimestamp(tokenBase64, expectedBundleHash) {
|
|
151
|
+
try {
|
|
152
|
+
const tokenDer = Buffer.from(tokenBase64, 'base64');
|
|
153
|
+
const { messageImprintHex, genTime } = extractTSTInfo(tokenDer, 0);
|
|
154
|
+
|
|
155
|
+
if (!expectedBundleHash.startsWith('sha256:')) {
|
|
156
|
+
return { valid: false, reason: 'expectedBundleHash must start with "sha256:"' };
|
|
157
|
+
}
|
|
158
|
+
const expectedHex = expectedBundleHash.slice(7);
|
|
159
|
+
const expectedBuf = Buffer.from(expectedHex, 'hex');
|
|
160
|
+
const actualBuf = Buffer.from(messageImprintHex, 'hex');
|
|
161
|
+
if (expectedBuf.length !== actualBuf.length || !timingSafeEqual(expectedBuf, actualBuf)) {
|
|
162
|
+
return { valid: false, reason: 'messageImprint hash does not match expectedBundleHash' };
|
|
163
|
+
}
|
|
164
|
+
return { valid: true, genTime };
|
|
165
|
+
} catch (err) {
|
|
166
|
+
return { valid: false, reason: err.message };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Extracts messageImprint hash hex, genTime ISO string, and optional nonce hex
|
|
172
|
+
* from a TimeStampToken (ContentInfo SEQUENCE) at tagOffset inside buf.
|
|
173
|
+
*
|
|
174
|
+
* Navigation path through CMS SignedData:
|
|
175
|
+
*
|
|
176
|
+
* ContentInfo SEQUENCE -- tagOffset
|
|
177
|
+
* OID id-signedData -- child 0 (skipped)
|
|
178
|
+
* [0] EXPLICIT (0xa0) { -- child 1
|
|
179
|
+
* SignedData SEQUENCE
|
|
180
|
+
* INTEGER version -- child 0 (skipped)
|
|
181
|
+
* SET digestAlgorithms -- child 1 (skipped)
|
|
182
|
+
* EncapContentInfo SEQUENCE -- child 2
|
|
183
|
+
* OID id-ct-TSTInfo -- child 0 (skipped)
|
|
184
|
+
* [0] EXPLICIT (0xa0) { -- child 1
|
|
185
|
+
* OCTET STRING <TSTInfo DER> -- child 0
|
|
186
|
+
* }
|
|
187
|
+
* ...
|
|
188
|
+
* }
|
|
189
|
+
* }
|
|
190
|
+
* }
|
|
191
|
+
*
|
|
192
|
+
* @param {Uint8Array} buf
|
|
193
|
+
* @param {number} tagOffset Byte offset of the ContentInfo tag byte
|
|
194
|
+
* @returns {{ messageImprintHex: string, genTime: string, nonceHex: string|null }}
|
|
195
|
+
*/
|
|
196
|
+
export function extractTSTInfo(buf, tagOffset) {
|
|
197
|
+
// ContentInfo SEQUENCE
|
|
198
|
+
const contentInfo = readTLV(buf, tagOffset);
|
|
199
|
+
if (contentInfo.tag !== 0x30) throw new Error('DER: ContentInfo must be SEQUENCE');
|
|
200
|
+
const ciVS = contentInfo.end - contentInfo.length;
|
|
201
|
+
const ciVE = contentInfo.end;
|
|
202
|
+
|
|
203
|
+
// child 0: OID id-signedData (skip)
|
|
204
|
+
// child 1: [0] EXPLICIT wrapping SignedData
|
|
205
|
+
const ctxTlv = childAt(buf, ciVS, ciVE, 1);
|
|
206
|
+
if (ctxTlv.tag !== 0xa0) {
|
|
207
|
+
throw new Error(`DER: ContentInfo[1] expected [0] EXPLICIT (0xa0), got 0x${ctxTlv.tag.toString(16)}`);
|
|
208
|
+
}
|
|
209
|
+
const ctxVS = ctxTlv.end - ctxTlv.length;
|
|
210
|
+
const ctxVE = ctxTlv.end;
|
|
211
|
+
|
|
212
|
+
// First (and only) child of [0]: SignedData SEQUENCE
|
|
213
|
+
const signedData = childAt(buf, ctxVS, ctxVE, 0);
|
|
214
|
+
if (signedData.tag !== 0x30) throw new Error('DER: SignedData must be SEQUENCE');
|
|
215
|
+
const sdVS = signedData.end - signedData.length;
|
|
216
|
+
const sdVE = signedData.end;
|
|
217
|
+
|
|
218
|
+
// SignedData child 2: EncapContentInfo SEQUENCE
|
|
219
|
+
// (child 0 = version INTEGER, child 1 = digestAlgorithms SET, child 2 = encapContentInfo)
|
|
220
|
+
const encapInfo = childAt(buf, sdVS, sdVE, 2);
|
|
221
|
+
if (encapInfo.tag !== 0x30) throw new Error('DER: encapContentInfo must be SEQUENCE');
|
|
222
|
+
const ecVS = encapInfo.end - encapInfo.length;
|
|
223
|
+
const ecVE = encapInfo.end;
|
|
224
|
+
|
|
225
|
+
// EncapContentInfo child 1: [0] EXPLICIT wrapping eContent OCTET STRING
|
|
226
|
+
// (child 0 = OID id-ct-TSTInfo, child 1 = [0] EXPLICIT { OCTET STRING })
|
|
227
|
+
const eContentCtx = childAt(buf, ecVS, ecVE, 1);
|
|
228
|
+
if (eContentCtx.tag !== 0xa0) {
|
|
229
|
+
throw new Error(`DER: eContent context expected 0xa0, got 0x${eContentCtx.tag.toString(16)}`);
|
|
230
|
+
}
|
|
231
|
+
const ecCtxVS = eContentCtx.end - eContentCtx.length;
|
|
232
|
+
const ecCtxVE = eContentCtx.end;
|
|
233
|
+
|
|
234
|
+
// [0] child 0: OCTET STRING containing TSTInfo DER
|
|
235
|
+
const octetStr = childAt(buf, ecCtxVS, ecCtxVE, 0);
|
|
236
|
+
if (octetStr.tag !== 0x04) {
|
|
237
|
+
throw new Error(`DER: eContent expected OCTET STRING (0x04), got 0x${octetStr.tag.toString(16)}`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Parse TSTInfo from the OCTET STRING payload
|
|
241
|
+
return parseTSTInfo(octetStr.value);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Parses TSTInfo SEQUENCE fields.
|
|
246
|
+
*
|
|
247
|
+
* TSTInfo SEQUENCE:
|
|
248
|
+
* child 0: INTEGER version
|
|
249
|
+
* child 1: OID policy
|
|
250
|
+
* child 2: MessageImprint SEQUENCE
|
|
251
|
+
* child 0: AlgorithmIdentifier SEQUENCE (skipped)
|
|
252
|
+
* child 1: OCTET STRING hashedMessage
|
|
253
|
+
* child 3: INTEGER serialNumber
|
|
254
|
+
* child 4: GeneralizedTime genTime
|
|
255
|
+
* child 5+: optional fields (accuracy, ordering, nonce, tsa, extensions)
|
|
256
|
+
* nonce is an INTEGER if present
|
|
257
|
+
*
|
|
258
|
+
* @param {Uint8Array} buf Buffer containing TSTInfo SEQUENCE at offset 0
|
|
259
|
+
* @returns {{ messageImprintHex: string, genTime: string, nonceHex: string|null }}
|
|
260
|
+
*/
|
|
261
|
+
export function parseTSTInfo(buf) {
|
|
262
|
+
const tstInfo = readTLV(buf, 0);
|
|
263
|
+
if (tstInfo.tag !== 0x30) throw new Error('DER: TSTInfo must be SEQUENCE');
|
|
264
|
+
|
|
265
|
+
const vs = tstInfo.end - tstInfo.length;
|
|
266
|
+
const ve = tstInfo.end;
|
|
267
|
+
|
|
268
|
+
let pos = vs;
|
|
269
|
+
let childIdx = 0;
|
|
270
|
+
let messageImprintHex = null;
|
|
271
|
+
let genTime = null;
|
|
272
|
+
let nonceHex = null;
|
|
273
|
+
|
|
274
|
+
while (pos < ve) {
|
|
275
|
+
const child = readTLV(buf, pos);
|
|
276
|
+
|
|
277
|
+
switch (childIdx) {
|
|
278
|
+
case 2: {
|
|
279
|
+
// MessageImprint SEQUENCE
|
|
280
|
+
if (child.tag !== 0x30) throw new Error('DER: TSTInfo MessageImprint must be SEQUENCE');
|
|
281
|
+
const miVS = child.end - child.length;
|
|
282
|
+
const miVE = child.end;
|
|
283
|
+
// child 0: AlgorithmIdentifier (skip)
|
|
284
|
+
const algId = childAt(buf, miVS, miVE, 0);
|
|
285
|
+
// child 1: OCTET STRING hashedMessage
|
|
286
|
+
const hashOctet = childAt(buf, miVS, miVE, 1);
|
|
287
|
+
if (hashOctet.tag !== 0x04) throw new Error('DER: messageImprint hashedMessage must be OCTET STRING');
|
|
288
|
+
messageImprintHex = [...hashOctet.value].map(b => b.toString(16).padStart(2, '0')).join('');
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
case 4: {
|
|
292
|
+
// GeneralizedTime (universal tag 0x18)
|
|
293
|
+
if (child.tag !== 0x18) {
|
|
294
|
+
throw new Error(
|
|
295
|
+
`DER: TSTInfo genTime expected GeneralizedTime (0x18), got 0x${child.tag.toString(16)}`
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
genTime = parseGeneralizedTime(String.fromCharCode(...child.value));
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
default:
|
|
302
|
+
// nonce is an optional INTEGER field after genTime (RFC 3161 TSTInfo field 7)
|
|
303
|
+
if (childIdx > 4 && child.tag === 0x02) {
|
|
304
|
+
nonceHex = [...child.value].map(b => b.toString(16).padStart(2, '0')).join('');
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
childIdx++;
|
|
309
|
+
pos = child.end;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (messageImprintHex === null) throw new Error('DER: TSTInfo missing MessageImprint');
|
|
313
|
+
if (genTime === null) throw new Error('DER: TSTInfo missing genTime');
|
|
314
|
+
|
|
315
|
+
return { messageImprintHex, genTime, nonceHex };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Converts an ASN.1 GeneralizedTime string to an ISO 8601 string.
|
|
320
|
+
* Input format: YYYYMMDDHHMMSS[.fff]Z (UTC, trailing Z required by DER)
|
|
321
|
+
*
|
|
322
|
+
* @param {string} gt
|
|
323
|
+
* @returns {string}
|
|
324
|
+
*/
|
|
325
|
+
export function parseGeneralizedTime(gt) {
|
|
326
|
+
if (!gt.endsWith('Z')) throw new Error('GeneralizedTime must be UTC (trailing Z required)');
|
|
327
|
+
const s = gt.slice(0, -1);
|
|
328
|
+
const year = s.slice(0, 4);
|
|
329
|
+
const month = s.slice(4, 6);
|
|
330
|
+
const day = s.slice(6, 8);
|
|
331
|
+
const hour = s.slice(8, 10);
|
|
332
|
+
const minute = s.slice(10, 12);
|
|
333
|
+
const second = s.slice(12, 14);
|
|
334
|
+
const frac = s.length > 14 ? s.slice(14) : '';
|
|
335
|
+
const ms = frac
|
|
336
|
+
? String(Math.round(parseFloat('0' + frac) * 1000)).padStart(3, '0')
|
|
337
|
+
: '000';
|
|
338
|
+
return `${year}-${month}-${day}T${hour}:${minute}:${second}.${ms}Z`;
|
|
339
|
+
}
|
package/lib/sha256.js
ADDED
package/lib/signing.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Vendored from src/signing.js -- verifySignature only
|
|
2
|
+
// Origin: https://github.com/benpeter/web-resource-ledger/blob/main/src/signing.js
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Verifies an Ed25519 signature.
|
|
6
|
+
*
|
|
7
|
+
* @param {Uint8Array} publicKeyBytes Raw 32-byte public key
|
|
8
|
+
* @param {Uint8Array} data
|
|
9
|
+
* @param {string} signatureBase64
|
|
10
|
+
* @returns {Promise<boolean>}
|
|
11
|
+
*/
|
|
12
|
+
export async function verifySignature(publicKeyBytes, data, signatureBase64) {
|
|
13
|
+
const pubKey = await crypto.subtle.importKey(
|
|
14
|
+
'raw',
|
|
15
|
+
publicKeyBytes,
|
|
16
|
+
'Ed25519',
|
|
17
|
+
true,
|
|
18
|
+
['verify'],
|
|
19
|
+
);
|
|
20
|
+
const signature = Buffer.from(signatureBase64, 'base64');
|
|
21
|
+
return crypto.subtle.verify('Ed25519', pubKey, signature, data);
|
|
22
|
+
}
|
package/lib/verify.js
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* verify.js -- WACZ verification module (Node.js CLI edition)
|
|
3
|
+
*
|
|
4
|
+
* Vendored from src/verify.js with the following adaptations:
|
|
5
|
+
* - sha256 import redirected to ./sha256.js (Node.js native, synchronous)
|
|
6
|
+
* - sha256 calls made synchronous (no await)
|
|
7
|
+
* - verifyWacz signature extended with options: { trustedRoots, verifyCmsChain }
|
|
8
|
+
* - 5th check (timestampChain) added for CMS certificate chain validation
|
|
9
|
+
* - Zip bomb pre-check: rejects total decompressed size > 100 MB
|
|
10
|
+
*
|
|
11
|
+
* Origin: https://github.com/benpeter/web-resource-ledger/blob/main/src/verify.js
|
|
12
|
+
*
|
|
13
|
+
* SECURITY:
|
|
14
|
+
* - publicKeyBytes must come from a trusted source -- never from the WACZ itself.
|
|
15
|
+
* - Embedded publicKey is returned for informational purposes only.
|
|
16
|
+
* - Failed check details never include expected/actual hash values.
|
|
17
|
+
* - All checks always run -- no short-circuiting.
|
|
18
|
+
* - A present-but-invalid timestamp fails verification. An absent timestamp
|
|
19
|
+
* (TSA unreachable at capture time) is tolerated as status: 'skip'.
|
|
20
|
+
*/ // tva
|
|
21
|
+
|
|
22
|
+
import { unzipSync } from 'fflate';
|
|
23
|
+
import { canonicalize } from './canonical-json.js';
|
|
24
|
+
import { sha256 } from './sha256.js';
|
|
25
|
+
import { verifySignature } from './signing.js';
|
|
26
|
+
import { verifyTimestamp } from './rfc3161.js';
|
|
27
|
+
import { verifyCmsChain } from './cms-verify.js';
|
|
28
|
+
|
|
29
|
+
const enc = new TextEncoder();
|
|
30
|
+
|
|
31
|
+
const MAX_DECOMPRESSED = 100 * 1024 * 1024; // 100 MB
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// Public API
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Verifies a WACZ file against a trusted Ed25519 public key.
|
|
39
|
+
*
|
|
40
|
+
* @param {Uint8Array} waczBytes Raw WACZ ZIP file bytes
|
|
41
|
+
* @param {Uint8Array} publicKeyBytes Trusted 32-byte Ed25519 public key
|
|
42
|
+
* @param {{ trustedRoots?: string[], verifyCmsChain?: boolean }} [options]
|
|
43
|
+
* trustedRoots Array of PEM-encoded trusted root certificates for CMS chain check.
|
|
44
|
+
* verifyCmsChain Boolean flag; if false, timestampChain check is skipped even when
|
|
45
|
+
* trustedRoots are provided. Defaults to true when trustedRoots present.
|
|
46
|
+
* @returns {Promise<{
|
|
47
|
+
* verified: boolean,
|
|
48
|
+
* checks: Array<{ name: string, status: 'pass'|'fail'|'skip', detail?: string }>,
|
|
49
|
+
* capture?: {
|
|
50
|
+
* bundleHash: string,
|
|
51
|
+
* signature: string,
|
|
52
|
+
* publicKey: string,
|
|
53
|
+
* signedAt: string,
|
|
54
|
+
* timestamp?: { genTime: string, tsa: string }
|
|
55
|
+
* }
|
|
56
|
+
* }>}
|
|
57
|
+
*/
|
|
58
|
+
export async function verifyWacz(waczBytes, publicKeyBytes, options = {}) {
|
|
59
|
+
const { trustedRoots, verifyCmsChain: doCmsChain = true } = options;
|
|
60
|
+
|
|
61
|
+
// Step 1: Parse ZIP -- fflate throws on malformed input, never returns null
|
|
62
|
+
let files;
|
|
63
|
+
try {
|
|
64
|
+
files = unzipSync(waczBytes);
|
|
65
|
+
} catch {
|
|
66
|
+
return {
|
|
67
|
+
verified: false,
|
|
68
|
+
checks: [
|
|
69
|
+
{ name: 'artifactHashes', status: 'fail', detail: 'WACZ bundle is not a valid ZIP archive' },
|
|
70
|
+
{ name: 'bundleHash', status: 'fail', detail: 'WACZ bundle is not a valid ZIP archive' },
|
|
71
|
+
{ name: 'signature', status: 'fail', detail: 'WACZ bundle is not a valid ZIP archive' },
|
|
72
|
+
],
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Zip bomb pre-check: reject if total decompressed size exceeds limit
|
|
77
|
+
const totalSize = Object.values(files).reduce((sum, f) => sum + f.byteLength, 0);
|
|
78
|
+
if (totalSize > MAX_DECOMPRESSED) {
|
|
79
|
+
const mb = Math.round(totalSize / (1024 * 1024));
|
|
80
|
+
const detail = `Decompressed WACZ exceeds ${MAX_DECOMPRESSED / (1024 * 1024)} MB limit (got ~${mb} MB)`;
|
|
81
|
+
return {
|
|
82
|
+
verified: false,
|
|
83
|
+
checks: [
|
|
84
|
+
{ name: 'artifactHashes', status: 'fail', detail },
|
|
85
|
+
{ name: 'bundleHash', status: 'fail', detail },
|
|
86
|
+
{ name: 'signature', status: 'fail', detail },
|
|
87
|
+
],
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Step 2: Extract required manifest files
|
|
92
|
+
const dpRaw = files['datapackage.json'];
|
|
93
|
+
const digestRaw = files['datapackage-digest.json'];
|
|
94
|
+
|
|
95
|
+
if (!dpRaw) {
|
|
96
|
+
return {
|
|
97
|
+
verified: false,
|
|
98
|
+
checks: [
|
|
99
|
+
{ name: 'artifactHashes', status: 'fail', detail: 'datapackage.json missing from WACZ' },
|
|
100
|
+
{ name: 'bundleHash', status: 'fail', detail: 'datapackage.json missing from WACZ' },
|
|
101
|
+
{ name: 'signature', status: 'fail', detail: 'datapackage.json missing from WACZ' },
|
|
102
|
+
],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (!digestRaw) {
|
|
107
|
+
return {
|
|
108
|
+
verified: false,
|
|
109
|
+
checks: [
|
|
110
|
+
{ name: 'artifactHashes', status: 'skip' },
|
|
111
|
+
{ name: 'bundleHash', status: 'fail', detail: 'datapackage-digest.json missing from WACZ' },
|
|
112
|
+
{ name: 'signature', status: 'fail', detail: 'datapackage-digest.json missing from WACZ' },
|
|
113
|
+
],
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
let datapackage, digest;
|
|
118
|
+
try {
|
|
119
|
+
datapackage = JSON.parse(new TextDecoder().decode(dpRaw));
|
|
120
|
+
digest = JSON.parse(new TextDecoder().decode(digestRaw));
|
|
121
|
+
} catch {
|
|
122
|
+
return {
|
|
123
|
+
verified: false,
|
|
124
|
+
checks: [
|
|
125
|
+
{ name: 'artifactHashes', status: 'fail', detail: 'Manifest JSON is malformed' },
|
|
126
|
+
{ name: 'bundleHash', status: 'fail', detail: 'Manifest JSON is malformed' },
|
|
127
|
+
{ name: 'signature', status: 'fail', detail: 'Manifest JSON is malformed' },
|
|
128
|
+
],
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const signedData = digest?.signedData;
|
|
133
|
+
const version = signedData?.version ?? '0.1.0';
|
|
134
|
+
|
|
135
|
+
// Run all checks independently -- no early exit
|
|
136
|
+
const checks = [];
|
|
137
|
+
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
// Check 1: artifactHashes
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
let artifactPass = true;
|
|
142
|
+
const resources = datapackage?.resources;
|
|
143
|
+
if (!Array.isArray(resources) || resources.length === 0) {
|
|
144
|
+
checks.push({ name: 'artifactHashes', status: 'fail', detail: 'No resources listed in datapackage.json' });
|
|
145
|
+
artifactPass = false;
|
|
146
|
+
} else {
|
|
147
|
+
for (const resource of resources) {
|
|
148
|
+
const fileBytes = files[resource.path];
|
|
149
|
+
if (!fileBytes) {
|
|
150
|
+
checks.push({ name: 'artifactHashes', status: 'fail', detail: 'One or more artifact hashes do not match' });
|
|
151
|
+
artifactPass = false;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
const computed = sha256(fileBytes);
|
|
155
|
+
if (computed !== resource.hash) {
|
|
156
|
+
checks.push({ name: 'artifactHashes', status: 'fail', detail: 'One or more artifact hashes do not match' });
|
|
157
|
+
artifactPass = false;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (artifactPass) {
|
|
162
|
+
checks.push({ name: 'artifactHashes', status: 'pass' });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
// Check 2: bundleHash
|
|
168
|
+
// ---------------------------------------------------------------------------
|
|
169
|
+
let bundleHashPass = false;
|
|
170
|
+
if (!signedData?.hash) {
|
|
171
|
+
checks.push({ name: 'bundleHash', status: 'fail', detail: 'signedData.hash missing from datapackage-digest.json' });
|
|
172
|
+
} else {
|
|
173
|
+
const recomputed = sha256(enc.encode(canonicalize(datapackage)));
|
|
174
|
+
if (recomputed === signedData.hash) {
|
|
175
|
+
checks.push({ name: 'bundleHash', status: 'pass' });
|
|
176
|
+
bundleHashPass = true;
|
|
177
|
+
} else {
|
|
178
|
+
checks.push({ name: 'bundleHash', status: 'fail', detail: 'Recomputed hash does not match stored bundleHash' });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
// Check 3: signature
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
// Normalize: for v0.2.0 find the self-signature entry; for v0.1.0 signature
|
|
187
|
+
// and publicKey sit directly on signedData.
|
|
188
|
+
const selfSig = version === '0.2.0'
|
|
189
|
+
? (signedData?.signatures ?? []).find(s => s.type === 'self')
|
|
190
|
+
: signedData;
|
|
191
|
+
|
|
192
|
+
const sigValue = selfSig?.signature ?? null;
|
|
193
|
+
|
|
194
|
+
if (!sigValue) {
|
|
195
|
+
checks.push({ name: 'signature', status: 'fail', detail: 'signedData.signature missing from datapackage-digest.json' });
|
|
196
|
+
} else {
|
|
197
|
+
// Signed payload: UTF-8 bytes of the bundleHash string ("sha256:{hex}")
|
|
198
|
+
const hashString = signedData?.hash ?? '';
|
|
199
|
+
const valid = await verifySignature(publicKeyBytes, enc.encode(hashString), sigValue);
|
|
200
|
+
if (valid) {
|
|
201
|
+
checks.push({ name: 'signature', status: 'pass' });
|
|
202
|
+
} else {
|
|
203
|
+
checks.push({ name: 'signature', status: 'fail', detail: 'Ed25519 signature verification failed' });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
// Check 4: timestamp (v0.2.0 only)
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
let timestampData = null;
|
|
211
|
+
let tsToken = null;
|
|
212
|
+
if (version === '0.2.0') {
|
|
213
|
+
const sigs = signedData?.signatures ?? [];
|
|
214
|
+
const tsEntry = sigs.find(s => s.type === 'rfc3161');
|
|
215
|
+
|
|
216
|
+
if (!tsEntry) {
|
|
217
|
+
checks.push({ name: 'timestamp', status: 'skip', detail: 'No independent timestamp was obtained for this capture' });
|
|
218
|
+
} else {
|
|
219
|
+
tsToken = tsEntry.token ?? null;
|
|
220
|
+
try {
|
|
221
|
+
const result = verifyTimestamp(tsEntry.token, signedData.hash);
|
|
222
|
+
if (result.valid) {
|
|
223
|
+
checks.push({ name: 'timestamp', status: 'pass' });
|
|
224
|
+
timestampData = { genTime: result.genTime, tsa: tsEntry.tsa };
|
|
225
|
+
} else {
|
|
226
|
+
checks.push({ name: 'timestamp', status: 'fail', detail: 'Independent timestamp verification failed' });
|
|
227
|
+
}
|
|
228
|
+
} catch {
|
|
229
|
+
checks.push({ name: 'timestamp', status: 'fail', detail: 'Independent timestamp verification failed' });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// For v0.1.0: no timestamp check at all (3 checks, not 4)
|
|
234
|
+
|
|
235
|
+
// ---------------------------------------------------------------------------
|
|
236
|
+
// Check 5: timestampChain (CLI only -- CMS certificate chain validation)
|
|
237
|
+
// ---------------------------------------------------------------------------
|
|
238
|
+
if (version === '0.2.0' && tsToken && trustedRoots && trustedRoots.length > 0 && doCmsChain) {
|
|
239
|
+
try {
|
|
240
|
+
const cmsResult = await verifyCmsChain(tsToken, trustedRoots, timestampData?.genTime);
|
|
241
|
+
if (cmsResult.valid) {
|
|
242
|
+
checks.push({ name: 'timestampChain', status: 'pass' });
|
|
243
|
+
} else {
|
|
244
|
+
checks.push({
|
|
245
|
+
name: 'timestampChain',
|
|
246
|
+
status: 'fail',
|
|
247
|
+
detail: cmsResult.detail ?? 'CMS certificate chain verification failed',
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
} catch (err) {
|
|
251
|
+
checks.push({
|
|
252
|
+
name: 'timestampChain',
|
|
253
|
+
status: 'fail',
|
|
254
|
+
detail: 'CMS certificate chain verification failed',
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
} else if (version === '0.2.0' && tsToken && (!trustedRoots || trustedRoots.length === 0)) {
|
|
258
|
+
checks.push({ name: 'timestampChain', status: 'skip', detail: 'No trusted roots provided; certificate chain not checked' });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ---------------------------------------------------------------------------
|
|
262
|
+
// Assemble result
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
// skip is tolerated: absent timestamps (TSA unreachable) and skipped chain checks
|
|
266
|
+
// do not fail verification. A present-but-invalid result DOES fail.
|
|
267
|
+
const verified = checks.every(c => c.status === 'pass' || c.status === 'skip');
|
|
268
|
+
|
|
269
|
+
const result = { verified, checks };
|
|
270
|
+
|
|
271
|
+
// Attach capture metadata when the digest doc is coherent enough to extract
|
|
272
|
+
if (signedData) {
|
|
273
|
+
result.capture = {
|
|
274
|
+
bundleHash: signedData.hash ?? null,
|
|
275
|
+
signature: selfSig?.signature ?? null,
|
|
276
|
+
publicKey: selfSig?.publicKey ?? null, // informational only -- NOT used for verification
|
|
277
|
+
signedAt: signedData.created ?? null,
|
|
278
|
+
};
|
|
279
|
+
if (timestampData) {
|
|
280
|
+
result.capture.timestamp = timestampData;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return result;
|
|
285
|
+
}
|