@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
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cms-verify.js -- CMS/PKCS#7 certificate chain verification for RFC 3161 tokens.
|
|
3
|
+
*
|
|
4
|
+
* Performs steps 1-4 of RFC 3161 §2.4.2 verification:
|
|
5
|
+
* 1. Parse the CMS ContentInfo envelope
|
|
6
|
+
* 2. Verify the CMS cryptographic signature (node:crypto createVerify)
|
|
7
|
+
* 3. Validate the TSA certificate chain (node:crypto X509Certificate)
|
|
8
|
+
* 4. Validate certificate properties (EKU, validity period)
|
|
9
|
+
*
|
|
10
|
+
* Step 5 (messageImprint) is handled separately by rfc3161.js/verifyTimestamp().
|
|
11
|
+
*
|
|
12
|
+
* Uses PKIjs for CMS structure parsing only. All cryptographic operations
|
|
13
|
+
* use node:crypto -- PKIjs SignedData.verify() has known issues with
|
|
14
|
+
* RFC 3161 TSTInfo content types (requires detached data, signature
|
|
15
|
+
* verification unreliable).
|
|
16
|
+
*
|
|
17
|
+
* NOTE: CRL/OCSP revocation checking is intentionally omitted -- this module
|
|
18
|
+
* is designed for offline use where network access is unavailable. Operators
|
|
19
|
+
* requiring revocation checking should supplement with online tools.
|
|
20
|
+
*/ // tva
|
|
21
|
+
|
|
22
|
+
import * as asn1js from 'asn1js';
|
|
23
|
+
import * as pkijs from 'pkijs';
|
|
24
|
+
import { readFileSync, readdirSync } from 'node:fs';
|
|
25
|
+
import { join, dirname } from 'node:path';
|
|
26
|
+
import { fileURLToPath } from 'node:url';
|
|
27
|
+
import { X509Certificate, createVerify } from 'node:crypto';
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// PKIjs crypto engine -- needed for schema parsing only
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
const _engine = new pkijs.CryptoEngine({ name: 'NodeJS', crypto: globalThis.crypto });
|
|
34
|
+
pkijs.setEngine('NodeJS', _engine);
|
|
35
|
+
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
// OIDs
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
const OID_ID_KP_TIMESTAMPING = '1.3.6.1.5.5.7.3.8';
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// Trusted root loading
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
47
|
+
const CERTS_DIR = join(__dirname, '..', 'certs', 'trusted-roots');
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Loads PEM files from the bundled trusted-roots directory.
|
|
51
|
+
* Optionally merges additional PEM paths provided by the caller.
|
|
52
|
+
*
|
|
53
|
+
* @param {string[]} [extraPaths=[]] Absolute paths to additional PEM files
|
|
54
|
+
* @returns {string[]} Array of PEM strings
|
|
55
|
+
*/
|
|
56
|
+
export function loadTrustedRoots(extraPaths = []) {
|
|
57
|
+
const bundled = readdirSync(CERTS_DIR)
|
|
58
|
+
.filter(f => f.endsWith('.pem'))
|
|
59
|
+
.map(f => readFileSync(join(CERTS_DIR, f), 'utf8'));
|
|
60
|
+
return [...bundled, ...extraPaths.map(p => readFileSync(p, 'utf8'))];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// Helpers
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Converts a PEM string to a node:crypto X509Certificate.
|
|
69
|
+
* @param {string} pem
|
|
70
|
+
* @returns {X509Certificate}
|
|
71
|
+
*/
|
|
72
|
+
function pemToX509(pem) {
|
|
73
|
+
return new X509Certificate(pem);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Converts a PKIjs Certificate to a node:crypto X509Certificate.
|
|
78
|
+
* @param {pkijs.Certificate} cert
|
|
79
|
+
* @returns {X509Certificate}
|
|
80
|
+
*/
|
|
81
|
+
function pkijsToX509(cert) {
|
|
82
|
+
const der = Buffer.from(cert.toSchema().toBER());
|
|
83
|
+
return new X509Certificate(der);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Extracts CN and issuer info from an X509Certificate.
|
|
88
|
+
* @param {X509Certificate} x509
|
|
89
|
+
* @returns {{ commonName: string, issuer: string, validFrom: string, validTo: string }}
|
|
90
|
+
*/
|
|
91
|
+
function extractSignerInfo(x509) {
|
|
92
|
+
// Extract CN from subject
|
|
93
|
+
const cnMatch = x509.subject.match(/CN=([^\n]+)/);
|
|
94
|
+
const commonName = cnMatch ? cnMatch[1] : '';
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
commonName,
|
|
98
|
+
issuer: x509.issuer.replace(/\n/g, ', '),
|
|
99
|
+
validFrom: new Date(x509.validFrom).toISOString(),
|
|
100
|
+
validTo: new Date(x509.validTo).toISOString(),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Checks if an X509Certificate has the id-kp-timeStamping EKU.
|
|
106
|
+
* @param {X509Certificate} x509
|
|
107
|
+
* @returns {boolean}
|
|
108
|
+
*/
|
|
109
|
+
function hasTimestampingEku(x509) {
|
|
110
|
+
// node:crypto X509Certificate exposes EKU OIDs via keyUsage (array of OID strings)
|
|
111
|
+
const ku = x509.keyUsage;
|
|
112
|
+
if (!Array.isArray(ku)) return false;
|
|
113
|
+
return ku.includes(OID_ID_KP_TIMESTAMPING);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Builds a certificate chain from a leaf cert to a trusted root.
|
|
118
|
+
* Returns the chain (leaf -> intermediate(s) -> root) or null if no chain found.
|
|
119
|
+
*
|
|
120
|
+
* Handles cross-signed roots: a cert is considered a trust anchor if it
|
|
121
|
+
* matches a trusted cert by subject (same key, same identity) even if
|
|
122
|
+
* the embedded version is cross-signed by a different root.
|
|
123
|
+
*
|
|
124
|
+
* @param {X509Certificate} leaf
|
|
125
|
+
* @param {X509Certificate[]} pool All available certs (embedded + bundled)
|
|
126
|
+
* @param {X509Certificate[]} trusted Bundled trusted certs
|
|
127
|
+
* @returns {X509Certificate[] | null}
|
|
128
|
+
*/
|
|
129
|
+
function buildChain(leaf, pool, trusted) {
|
|
130
|
+
const chain = [leaf];
|
|
131
|
+
let current = leaf;
|
|
132
|
+
const maxDepth = 10;
|
|
133
|
+
|
|
134
|
+
for (let i = 0; i < maxDepth; i++) {
|
|
135
|
+
// Self-signed = root reached
|
|
136
|
+
if (current.checkIssued(current)) return chain;
|
|
137
|
+
|
|
138
|
+
// Check if current cert is a trusted cert (by subject key match).
|
|
139
|
+
// Handles cross-signed roots where the embedded cert is signed by
|
|
140
|
+
// a different CA but represents the same identity/key as our
|
|
141
|
+
// bundled self-signed root.
|
|
142
|
+
const isTrusted = trusted.some(tc => tc.publicKey.equals(current.publicKey));
|
|
143
|
+
if (isTrusted) return chain;
|
|
144
|
+
|
|
145
|
+
// Find the issuer in the pool
|
|
146
|
+
const issuer = pool.find(c => {
|
|
147
|
+
try { return current.checkIssued(c); }
|
|
148
|
+
catch { return false; }
|
|
149
|
+
});
|
|
150
|
+
if (!issuer) return null;
|
|
151
|
+
|
|
152
|
+
chain.push(issuer);
|
|
153
|
+
current = issuer;
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
// Public API
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Verifies the CMS/PKCS#7 signature and certificate chain of an RFC 3161
|
|
164
|
+
* timestamp token.
|
|
165
|
+
*
|
|
166
|
+
* @param {string} tokenBase64 Base64-encoded DER timestamp token
|
|
167
|
+
* @param {string[]} trustedRootPems Array of PEM-encoded trusted root/intermediate certificates
|
|
168
|
+
* @param {string} [genTime] ISO 8601 genTime from the timestamp (for cert validity check)
|
|
169
|
+
* @returns {Promise<{
|
|
170
|
+
* valid: boolean,
|
|
171
|
+
* detail: string|null,
|
|
172
|
+
* signerInfo: { commonName: string, issuer: string, validFrom: string, validTo: string } | null
|
|
173
|
+
* }>}
|
|
174
|
+
*/
|
|
175
|
+
export async function verifyCmsChain(tokenBase64, trustedRootPems, genTime) {
|
|
176
|
+
if (!trustedRootPems || trustedRootPems.length === 0) {
|
|
177
|
+
return { valid: false, detail: 'No trusted root certificates provided', signerInfo: null };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// -------------------------------------------------------------------------
|
|
181
|
+
// Step 1: Parse the CMS ContentInfo envelope with PKIjs
|
|
182
|
+
// -------------------------------------------------------------------------
|
|
183
|
+
let signedData;
|
|
184
|
+
try {
|
|
185
|
+
const der = Buffer.from(tokenBase64, 'base64');
|
|
186
|
+
const asn1 = asn1js.fromBER(new Uint8Array(der).buffer);
|
|
187
|
+
if (asn1.offset === -1) {
|
|
188
|
+
return { valid: false, detail: 'Failed to parse DER token', signerInfo: null };
|
|
189
|
+
}
|
|
190
|
+
const contentInfo = new pkijs.ContentInfo({ schema: asn1.result });
|
|
191
|
+
signedData = new pkijs.SignedData({ schema: contentInfo.content });
|
|
192
|
+
} catch (err) {
|
|
193
|
+
return { valid: false, detail: `CMS parse error: ${err.message}`, signerInfo: null };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// -------------------------------------------------------------------------
|
|
197
|
+
// Collect all available certificates: embedded in CMS + bundled
|
|
198
|
+
// -------------------------------------------------------------------------
|
|
199
|
+
const bundledX509 = trustedRootPems.map(pemToX509);
|
|
200
|
+
|
|
201
|
+
// Convert any CMS-embedded certs to X509Certificate
|
|
202
|
+
const embeddedX509 = (signedData.certificates || []).map(c => {
|
|
203
|
+
try { return pkijsToX509(c); }
|
|
204
|
+
catch { return null; }
|
|
205
|
+
}).filter(Boolean);
|
|
206
|
+
|
|
207
|
+
const allCerts = [...embeddedX509, ...bundledX509];
|
|
208
|
+
|
|
209
|
+
// -------------------------------------------------------------------------
|
|
210
|
+
// Find the signer certificate
|
|
211
|
+
// -------------------------------------------------------------------------
|
|
212
|
+
const signerInfo = signedData.signerInfos?.[0];
|
|
213
|
+
if (!signerInfo) {
|
|
214
|
+
return { valid: false, detail: 'No SignerInfo in CMS token', signerInfo: null };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Match by issuer+serial (IssuerAndSerialNumber)
|
|
218
|
+
const sid = signerInfo.sid;
|
|
219
|
+
const signerSerial = Buffer.from(sid.serialNumber.valueBlock.valueHexView).toString('hex');
|
|
220
|
+
|
|
221
|
+
const signerX509 = allCerts.find(c => c.serialNumber.toLowerCase() === signerSerial);
|
|
222
|
+
if (!signerX509) {
|
|
223
|
+
return { valid: false, detail: 'Signer certificate not found in token or trusted store', signerInfo: null };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// -------------------------------------------------------------------------
|
|
227
|
+
// Step 2: Verify the CMS cryptographic signature using node:crypto
|
|
228
|
+
//
|
|
229
|
+
// In CMS, when signedAttrs are present, the signature is over the DER
|
|
230
|
+
// encoding of the signedAttrs with the IMPLICIT [0] tag replaced by
|
|
231
|
+
// the universal SET OF tag (0x31).
|
|
232
|
+
// -------------------------------------------------------------------------
|
|
233
|
+
try {
|
|
234
|
+
const signedAttrsDer = Buffer.from(signerInfo.signedAttrs.toSchema().toBER());
|
|
235
|
+
// Replace the IMPLICIT [0] tag (0xA0) with SET OF (0x31) for verification
|
|
236
|
+
signedAttrsDer[0] = 0x31;
|
|
237
|
+
|
|
238
|
+
const signature = Buffer.from(signerInfo.signature.valueBlock.valueHexView);
|
|
239
|
+
|
|
240
|
+
// Determine hash algorithm from digestAlgorithm
|
|
241
|
+
const digestAlgOid = signerInfo.digestAlgorithm.algorithmId;
|
|
242
|
+
const hashMap = {
|
|
243
|
+
'2.16.840.1.101.3.4.2.1': 'SHA256',
|
|
244
|
+
'2.16.840.1.101.3.4.2.2': 'SHA384',
|
|
245
|
+
'2.16.840.1.101.3.4.2.3': 'SHA512',
|
|
246
|
+
'1.3.14.3.2.26': 'SHA1',
|
|
247
|
+
};
|
|
248
|
+
const hashAlg = hashMap[digestAlgOid] || 'SHA256';
|
|
249
|
+
|
|
250
|
+
const verifier = createVerify(hashAlg);
|
|
251
|
+
verifier.update(signedAttrsDer);
|
|
252
|
+
const sigValid = verifier.verify(signerX509.publicKey, signature);
|
|
253
|
+
|
|
254
|
+
if (!sigValid) {
|
|
255
|
+
return { valid: false, detail: 'CMS signature verification failed', signerInfo: null };
|
|
256
|
+
}
|
|
257
|
+
} catch (err) {
|
|
258
|
+
return { valid: false, detail: `CMS signature verification error: ${err.message}`, signerInfo: null };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// -------------------------------------------------------------------------
|
|
262
|
+
// Step 3: Validate the certificate chain to a trusted root
|
|
263
|
+
//
|
|
264
|
+
// Uses node:crypto X509Certificate.checkIssued() to walk the chain.
|
|
265
|
+
// -------------------------------------------------------------------------
|
|
266
|
+
const chain = buildChain(signerX509, allCerts, bundledX509);
|
|
267
|
+
if (!chain) {
|
|
268
|
+
return { valid: false, detail: 'Certificate chain does not terminate at a trusted root', signerInfo: null };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The last cert in the chain must be in our trusted set (by public key match,
|
|
272
|
+
// handles cross-signed roots with different fingerprints but same key)
|
|
273
|
+
const root = chain[chain.length - 1];
|
|
274
|
+
const isTrusted = bundledX509.some(tc => tc.publicKey.equals(root.publicKey));
|
|
275
|
+
if (!isTrusted) {
|
|
276
|
+
return { valid: false, detail: 'Certificate chain does not terminate at a trusted root', signerInfo: null };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// -------------------------------------------------------------------------
|
|
280
|
+
// Step 4a: Extended Key Usage -- signer cert MUST have id-kp-timeStamping
|
|
281
|
+
// -------------------------------------------------------------------------
|
|
282
|
+
if (!hasTimestampingEku(signerX509)) {
|
|
283
|
+
return { valid: false, detail: 'Signer certificate missing id-kp-timeStamping EKU', signerInfo: null };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// -------------------------------------------------------------------------
|
|
287
|
+
// Step 4b: Validity period -- signer cert must have been valid at genTime
|
|
288
|
+
// -------------------------------------------------------------------------
|
|
289
|
+
const checkDate = genTime ? new Date(genTime) : new Date();
|
|
290
|
+
const notBefore = new Date(signerX509.validFrom);
|
|
291
|
+
const notAfter = new Date(signerX509.validTo);
|
|
292
|
+
if (checkDate < notBefore || checkDate > notAfter) {
|
|
293
|
+
return { valid: false, detail: 'Signer certificate was not valid at timestamp time', signerInfo: null };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
valid: true,
|
|
298
|
+
detail: null,
|
|
299
|
+
signerInfo: extractSignerInfo(signerX509),
|
|
300
|
+
};
|
|
301
|
+
}
|
package/lib/format.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* format.js -- Human-readable and JSON output formatters for wrl-verify.
|
|
3
|
+
*
|
|
4
|
+
* Human output is designed for terminal consumption with ANSI color.
|
|
5
|
+
* Color is suppressed when:
|
|
6
|
+
* - stdout is not a TTY
|
|
7
|
+
* - --no-color flag was passed
|
|
8
|
+
* - NO_COLOR env var is set
|
|
9
|
+
*
|
|
10
|
+
* JSON output is a single machine-readable object to stdout.
|
|
11
|
+
* All human messages in JSON mode go to stderr.
|
|
12
|
+
*/ // tva
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// ANSI color helpers
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
const ANSI_GREEN = '\x1b[32m';
|
|
19
|
+
const ANSI_RED = '\x1b[31m';
|
|
20
|
+
const ANSI_DIM = '\x1b[2m';
|
|
21
|
+
const ANSI_BOLD = '\x1b[1m';
|
|
22
|
+
const ANSI_RESET = '\x1b[0m';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Returns true when color output should be used.
|
|
26
|
+
*
|
|
27
|
+
* @param {{ noColor?: boolean }} opts
|
|
28
|
+
* @returns {boolean}
|
|
29
|
+
*/
|
|
30
|
+
function shouldColor(opts = {}) {
|
|
31
|
+
if (opts.noColor) return false;
|
|
32
|
+
if (process.env.NO_COLOR !== undefined) return false;
|
|
33
|
+
return process.stdout.isTTY === true;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function green(text, color) { return color ? `${ANSI_GREEN}${text}${ANSI_RESET}` : text; }
|
|
37
|
+
function red(text, color) { return color ? `${ANSI_RED}${text}${ANSI_RESET}` : text; }
|
|
38
|
+
function dim(text, color) { return color ? `${ANSI_DIM}${text}${ANSI_RESET}` : text; }
|
|
39
|
+
function bold(text, color) { return color ? `${ANSI_BOLD}${text}${ANSI_RESET}` : text; }
|
|
40
|
+
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
// Check label mapping
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
const CHECK_LABELS = {
|
|
46
|
+
artifactHashes: 'File integrity',
|
|
47
|
+
bundleHash: 'Bundle integrity',
|
|
48
|
+
signature: 'Digital signature',
|
|
49
|
+
timestamp: 'Timestamp imprint',
|
|
50
|
+
timestampChain: 'Timestamp chain',
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// Fixed display order
|
|
54
|
+
const CHECK_ORDER = [
|
|
55
|
+
'artifactHashes',
|
|
56
|
+
'bundleHash',
|
|
57
|
+
'signature',
|
|
58
|
+
'timestamp',
|
|
59
|
+
'timestampChain',
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Returns the human-readable label for a check name.
|
|
64
|
+
*
|
|
65
|
+
* @param {string} name
|
|
66
|
+
* @returns {string}
|
|
67
|
+
*/
|
|
68
|
+
function checkLabel(name) {
|
|
69
|
+
return CHECK_LABELS[name] ?? name;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Human-readable formatter
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Formats a verification result as human-readable text and writes to stdout.
|
|
78
|
+
*
|
|
79
|
+
* @param {{
|
|
80
|
+
* verified: boolean,
|
|
81
|
+
* checks: Array<{ name: string, status: string, detail?: string }>,
|
|
82
|
+
* capture?: {
|
|
83
|
+
* bundleHash?: string,
|
|
84
|
+
* signature?: string,
|
|
85
|
+
* publicKey?: string,
|
|
86
|
+
* signedAt?: string,
|
|
87
|
+
* timestamp?: { genTime: string, tsa: string }
|
|
88
|
+
* },
|
|
89
|
+
* keyResolution?: {
|
|
90
|
+
* keyId: string,
|
|
91
|
+
* source: string,
|
|
92
|
+
* origin?: string,
|
|
93
|
+
* endpoint?: string,
|
|
94
|
+
* },
|
|
95
|
+
* source: string,
|
|
96
|
+
* }} result
|
|
97
|
+
* @param {{ noColor?: boolean }} [opts]
|
|
98
|
+
*/
|
|
99
|
+
export function formatHuman(result, opts = {}) {
|
|
100
|
+
const color = shouldColor(opts);
|
|
101
|
+
|
|
102
|
+
// Sort checks into fixed display order, preserving any extras at the end
|
|
103
|
+
const orderedChecks = [];
|
|
104
|
+
for (const name of CHECK_ORDER) {
|
|
105
|
+
const c = result.checks.find(ch => ch.name === name);
|
|
106
|
+
if (c) orderedChecks.push(c);
|
|
107
|
+
}
|
|
108
|
+
for (const c of result.checks) {
|
|
109
|
+
if (!CHECK_ORDER.includes(c.name)) orderedChecks.push(c);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Line 1: verdict header
|
|
113
|
+
const headerLabel = result.verified
|
|
114
|
+
? bold(green('Verified', color), color)
|
|
115
|
+
: bold(red('FAILED', color), color);
|
|
116
|
+
process.stdout.write(`${headerLabel} ${result.source}\n\n`);
|
|
117
|
+
|
|
118
|
+
// Check table
|
|
119
|
+
const COL_WIDTH = 22; // label column width (padded to align status)
|
|
120
|
+
for (const check of orderedChecks) {
|
|
121
|
+
const label = checkLabel(check.name);
|
|
122
|
+
const padded = label.padEnd(COL_WIDTH);
|
|
123
|
+
|
|
124
|
+
let statusStr;
|
|
125
|
+
if (check.status === 'pass') {
|
|
126
|
+
statusStr = green('pass', color);
|
|
127
|
+
} else if (check.status === 'fail') {
|
|
128
|
+
statusStr = red('FAIL', color);
|
|
129
|
+
} else {
|
|
130
|
+
statusStr = dim('skip', color);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const detail = (check.status !== 'pass' && check.detail)
|
|
134
|
+
? ` ${dim(check.detail, color)}`
|
|
135
|
+
: '';
|
|
136
|
+
|
|
137
|
+
process.stdout.write(` ${padded}${statusStr}${detail}\n`);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Metadata block
|
|
141
|
+
process.stdout.write('\n');
|
|
142
|
+
|
|
143
|
+
const signedAt = result.capture?.signedAt;
|
|
144
|
+
if (signedAt) {
|
|
145
|
+
process.stdout.write(` Signed ${signedAt}\n`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const tsa = result.capture?.timestamp?.tsa;
|
|
149
|
+
if (tsa) {
|
|
150
|
+
process.stdout.write(` TSA ${tsa}\n`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const kr = result.keyResolution;
|
|
154
|
+
if (kr?.keyId) {
|
|
155
|
+
let keySource;
|
|
156
|
+
if (kr.source === 'origin' && kr.origin) {
|
|
157
|
+
const host = (() => {
|
|
158
|
+
try { return new URL(kr.origin).host; }
|
|
159
|
+
catch { return kr.origin; }
|
|
160
|
+
})();
|
|
161
|
+
keySource = `(from ${host})`;
|
|
162
|
+
} else if (kr.source === 'embedded') {
|
|
163
|
+
keySource = dim('(EMBEDDED -- self-asserted only)', color);
|
|
164
|
+
} else {
|
|
165
|
+
keySource = '(user-provided)';
|
|
166
|
+
}
|
|
167
|
+
process.stdout.write(` Key ${kr.keyId} ${keySource}\n`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const bundleHash = result.capture?.bundleHash;
|
|
171
|
+
if (bundleHash) {
|
|
172
|
+
// Truncate to first 16 hex chars after the "sha256:" prefix
|
|
173
|
+
const prefix = bundleHash.startsWith('sha256:') ? 'sha256:' : '';
|
|
174
|
+
const hex = bundleHash.startsWith('sha256:') ? bundleHash.slice(7) : bundleHash;
|
|
175
|
+
const truncated = `${prefix}${hex.slice(0, 16)}...`;
|
|
176
|
+
process.stdout.write(` Hash ${truncated}\n`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Verdict line
|
|
180
|
+
process.stdout.write('\n');
|
|
181
|
+
const verdict = buildVerdict(orderedChecks);
|
|
182
|
+
process.stdout.write(`Verdict: ${verdict}\n`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Builds the verdict sentence from the checks array.
|
|
187
|
+
*
|
|
188
|
+
* @param {Array<{ name: string, status: string, detail?: string }>} checks
|
|
189
|
+
* @returns {string}
|
|
190
|
+
*/
|
|
191
|
+
function buildVerdict(checks) {
|
|
192
|
+
const applicable = checks.filter(c => c.status !== 'skip');
|
|
193
|
+
const passed = applicable.filter(c => c.status === 'pass');
|
|
194
|
+
const failed = applicable.filter(c => c.status === 'fail');
|
|
195
|
+
const skipped = checks.filter(c => c.status === 'skip');
|
|
196
|
+
|
|
197
|
+
const allPass = failed.length === 0;
|
|
198
|
+
|
|
199
|
+
if (allPass && skipped.length === 0) {
|
|
200
|
+
return (
|
|
201
|
+
`All ${applicable.length} cryptographic checks passed. ` +
|
|
202
|
+
`This capture has not been modified since it was signed by the capture service.`
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (allPass && skipped.length > 0) {
|
|
207
|
+
return (
|
|
208
|
+
`${passed.length} of ${applicable.length} applicable checks passed. ` +
|
|
209
|
+
`${skipped.length} check${skipped.length === 1 ? '' : 's'} were not applicable (no timestamp data).`
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const failedLabels = failed.map(c => checkLabel(c.name)).join(', ');
|
|
214
|
+
return (
|
|
215
|
+
`${failed.length} of ${applicable.length} applicable check${applicable.length === 1 ? '' : 's'} failed. ` +
|
|
216
|
+
`This capture cannot be verified as authentic. ` +
|
|
217
|
+
`Failed: ${failedLabels}.`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
// JSON formatter
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Formats a verification result as a JSON object and writes to stdout.
|
|
227
|
+
* All human messages go to stderr in JSON mode.
|
|
228
|
+
*
|
|
229
|
+
* @param {{
|
|
230
|
+
* verified: boolean|null,
|
|
231
|
+
* checks: Array<{ name: string, status: string, detail?: string }>,
|
|
232
|
+
* capture?: object,
|
|
233
|
+
* keyResolution?: object,
|
|
234
|
+
* source: string,
|
|
235
|
+
* error?: string,
|
|
236
|
+
* }} result
|
|
237
|
+
*/
|
|
238
|
+
export function formatJson(result) {
|
|
239
|
+
const checks = (result.checks ?? []).map(c => ({
|
|
240
|
+
name: c.name,
|
|
241
|
+
label: checkLabel(c.name),
|
|
242
|
+
status: c.status,
|
|
243
|
+
detail: c.detail ?? null,
|
|
244
|
+
}));
|
|
245
|
+
|
|
246
|
+
// Remap capture: rename publicKey -> embeddedPublicKey per spec
|
|
247
|
+
let capture = null;
|
|
248
|
+
if (result.capture) {
|
|
249
|
+
const { publicKey, ...rest } = result.capture;
|
|
250
|
+
capture = { ...rest };
|
|
251
|
+
if (publicKey !== undefined) {
|
|
252
|
+
capture.embeddedPublicKey = publicKey;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const out = {
|
|
257
|
+
verified: result.verified ?? null,
|
|
258
|
+
checks,
|
|
259
|
+
capture,
|
|
260
|
+
keyResolution: result.keyResolution ?? null,
|
|
261
|
+
source: result.source,
|
|
262
|
+
verifiedAt: new Date().toISOString(),
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
if (result.error) {
|
|
266
|
+
out.error = result.error;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
process.stdout.write(JSON.stringify(out, null, 2) + '\n');
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Formats an error as JSON to stdout (for --json mode errors).
|
|
274
|
+
*
|
|
275
|
+
* @param {string} message
|
|
276
|
+
* @param {string} source
|
|
277
|
+
*/
|
|
278
|
+
export function formatJsonError(message, source) {
|
|
279
|
+
const out = {
|
|
280
|
+
verified: null,
|
|
281
|
+
checks: [],
|
|
282
|
+
capture: null,
|
|
283
|
+
keyResolution: null,
|
|
284
|
+
source: source ?? '',
|
|
285
|
+
verifiedAt: new Date().toISOString(),
|
|
286
|
+
error: message,
|
|
287
|
+
};
|
|
288
|
+
process.stdout.write(JSON.stringify(out, null, 2) + '\n');
|
|
289
|
+
}
|