@preeternal/jws-verifier 0.0.0-stage → 0.0.1-rc.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +85 -2
  4. package/dist/asn1/ber-reader.d.ts +57 -0
  5. package/dist/asn1/ber-reader.d.ts.map +1 -0
  6. package/dist/asn1/ber-reader.js +202 -0
  7. package/dist/asn1/der-reader.d.ts +68 -0
  8. package/dist/asn1/der-reader.d.ts.map +1 -0
  9. package/dist/asn1/der-reader.js +181 -0
  10. package/dist/index.d.ts +7 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +5 -0
  13. package/dist/jws/es256-signature.d.ts +3 -0
  14. package/dist/jws/es256-signature.d.ts.map +1 -0
  15. package/dist/jws/es256-signature.js +22 -0
  16. package/dist/jws/verifier.d.ts +94 -0
  17. package/dist/jws/verifier.d.ts.map +1 -0
  18. package/dist/jws/verifier.js +718 -0
  19. package/dist/ocsp/codec.d.ts +55 -0
  20. package/dist/ocsp/codec.d.ts.map +1 -0
  21. package/dist/ocsp/codec.js +465 -0
  22. package/dist/ocsp/transport.d.ts +6 -0
  23. package/dist/ocsp/transport.d.ts.map +1 -0
  24. package/dist/ocsp/transport.js +69 -0
  25. package/dist/receipt/utility.d.ts +27 -0
  26. package/dist/receipt/utility.d.ts.map +1 -0
  27. package/dist/receipt/utility.js +296 -0
  28. package/dist/types/index.d.ts +4 -0
  29. package/dist/types/index.d.ts.map +1 -0
  30. package/dist/types/index.js +1 -0
  31. package/dist/utils/formatting.d.ts +2 -0
  32. package/dist/utils/formatting.d.ts.map +1 -0
  33. package/dist/utils/formatting.js +9 -0
  34. package/dist/x509/certificate-metadata.d.ts +91 -0
  35. package/dist/x509/certificate-metadata.d.ts.map +1 -0
  36. package/dist/x509/certificate-metadata.js +588 -0
  37. package/dist/x509/prepared-certificates.d.ts +22 -0
  38. package/dist/x509/prepared-certificates.d.ts.map +1 -0
  39. package/dist/x509/prepared-certificates.js +27 -0
  40. package/package.json +81 -3
@@ -0,0 +1,718 @@
1
+ // biome-ignore lint/correctness/noNodejsModules: Native crypto is the intentional verification boundary.
2
+ import { verify as verifySignature } from "node:crypto";
3
+ import { array, boolean, custom, literal, looseObject, number, object, strictObject, string, enum as zodEnum, } from "zod";
4
+ import { DerReader } from "../asn1/der-reader.js";
5
+ import { buildOcspRequest, ocspBytesEqual, ocspCertIdFor, ocspKeyHash, ocspNameValue, parseOcspResponse, } from "../ocsp/codec.js";
6
+ import { fetchOcspResponse } from "../ocsp/transport.js";
7
+ import { CertificatePreparation, prepareCertificate, } from "../x509/prepared-certificates.js";
8
+ import { es256SignatureToDer } from "./es256-signature.js";
9
+ const MAX_DEFAULT_COMPACT_JWS_BYTES = 1024 * 1024;
10
+ const MAX_DEFAULT_PROTECTED_HEADER_BYTES = 16 * 1024;
11
+ const MAX_DEFAULT_PAYLOAD_BYTES = 512 * 1024;
12
+ const MAX_DEFAULT_X5C_ENTRIES = 3;
13
+ const MAX_DEFAULT_CERTIFICATE_BYTES = 1024 * 1024;
14
+ const MAX_DEFAULT_CACHE_ENTRIES = 128;
15
+ const MAX_DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000;
16
+ const compactSegmentPattern = /^[A-Za-z0-9_-]+$/;
17
+ const standardBase64Pattern = /^[A-Za-z0-9+/]*={0,2}$/;
18
+ const base64UrlPaddingPattern = /={0,2}$/u;
19
+ const trailingPaddingPattern = /=+$/u;
20
+ const textDecoder = new TextDecoder("utf-8", { fatal: true });
21
+ const claimPathSchema = array(string().min(1)).min(1);
22
+ const oidSchema = string().regex(/^[012](\.(0|[1-9][0-9]*)){1,63}$/u);
23
+ const protectedHeaderSchema = looseObject({ alg: string(), x5c: array(string()) });
24
+ const ocspPolicySchema = strictObject({
25
+ allowedEndpoints: array(string().min(1)).optional(),
26
+ timeoutMs: number().int().positive().max(60_000).default(5_000),
27
+ maxResponseBytes: number()
28
+ .int()
29
+ .positive()
30
+ .max(16 * 1024 * 1024)
31
+ .default(256 * 1024),
32
+ allowMissingNextUpdate: boolean().default(false),
33
+ maxAgeMs: number()
34
+ .int()
35
+ .positive()
36
+ .default(15 * 60 * 1000),
37
+ allowedSignatureAlgorithms: array(string().min(1)).default([
38
+ "1.2.840.10045.4.3.2",
39
+ "1.2.840.10045.4.3.3",
40
+ "1.2.840.10045.4.3.4",
41
+ "1.2.840.113549.1.1.11",
42
+ "1.2.840.113549.1.1.12",
43
+ "1.2.840.113549.1.1.13",
44
+ ]),
45
+ });
46
+ const verifierPolicySchema = strictObject({
47
+ mode: zodEnum(["offline", "online"]).default("offline"),
48
+ algorithm: literal("ES256").default("ES256"),
49
+ application: string().min(1).optional(),
50
+ environment: string().min(1).optional(),
51
+ claimPaths: strictObject({
52
+ application: claimPathSchema.optional(),
53
+ environment: claimPathSchema.optional(),
54
+ }).optional(),
55
+ signedTimePath: claimPathSchema.optional(),
56
+ requiredExtensions: strictObject({
57
+ leaf: array(oidSchema).optional(),
58
+ intermediate: array(oidSchema).optional(),
59
+ }).optional(),
60
+ ocsp: ocspPolicySchema.optional(),
61
+ validateClaims: custom((value) => typeof value === "function").optional(),
62
+ })
63
+ .refine(({ application, claimPaths }) => application === undefined || !!claimPaths?.application, {
64
+ message: "An expected application requires an explicit application claim path",
65
+ })
66
+ .refine(({ environment, claimPaths }) => environment === undefined || !!claimPaths?.environment, {
67
+ message: "An expected environment requires an explicit environment claim path",
68
+ });
69
+ const verifierLimitsSchema = object({
70
+ maxCompactJwsBytes: number().int().positive().default(MAX_DEFAULT_COMPACT_JWS_BYTES),
71
+ maxProtectedHeaderBytes: number().int().positive().default(MAX_DEFAULT_PROTECTED_HEADER_BYTES),
72
+ maxPayloadBytes: number().int().positive().default(MAX_DEFAULT_PAYLOAD_BYTES),
73
+ maxX5cEntries: number().int().min(2).max(MAX_DEFAULT_X5C_ENTRIES).default(3),
74
+ maxCertificateBytes: number().int().positive().default(MAX_DEFAULT_CERTIFICATE_BYTES),
75
+ maxCacheEntries: number().int().positive().max(4096).default(MAX_DEFAULT_CACHE_ENTRIES),
76
+ cacheTtlMs: number()
77
+ .int()
78
+ .positive()
79
+ .max(365 * 24 * 60 * 60 * 1000)
80
+ .default(MAX_DEFAULT_CACHE_TTL_MS),
81
+ }).passthrough();
82
+ const standardBase64 = (value, field) => {
83
+ const paddingStart = value.indexOf("=");
84
+ const unpadded = value.replace(base64UrlPaddingPattern, "");
85
+ if (!standardBase64Pattern.test(value) ||
86
+ unpadded.length % 4 === 1 ||
87
+ (paddingStart >= 0 && value.length % 4 !== 0)) {
88
+ throw new VerificationError("invalid-header", `${field} is not valid base64`);
89
+ }
90
+ const padded = value + "=".repeat((4 - (value.length % 4)) % 4);
91
+ const decoded = Buffer.from(padded, "base64");
92
+ const canonical = decoded.toString("base64");
93
+ if (canonical.replace(trailingPaddingPattern, "") !== unpadded) {
94
+ throw new VerificationError("invalid-header", `${field} is not canonical base64`);
95
+ }
96
+ return new Uint8Array(decoded);
97
+ };
98
+ const base64Url = (value, field) => {
99
+ if (!value || !compactSegmentPattern.test(value) || value.length % 4 === 1) {
100
+ throw new VerificationError("invalid-jws", `${field} is not valid base64url`);
101
+ }
102
+ const padded = value.replace(/-/gu, "+").replace(/_/gu, "/") + "=".repeat((4 - (value.length % 4)) % 4);
103
+ const decoded = new Uint8Array(Buffer.from(padded, "base64"));
104
+ const canonical = Buffer.from(decoded)
105
+ .toString("base64")
106
+ .replace(trailingPaddingPattern, "")
107
+ .replace(/\+/gu, "-")
108
+ .replace(/\//gu, "_");
109
+ if (canonical !== value) {
110
+ throw new VerificationError("invalid-jws", `${field} is not canonical base64url`);
111
+ }
112
+ return decoded;
113
+ };
114
+ const decodeJson = (bytes, field, code = "invalid-jws") => {
115
+ try {
116
+ return JSON.parse(textDecoder.decode(bytes));
117
+ }
118
+ catch (error) {
119
+ throw new VerificationError(code, `${field} is not valid UTF-8 JSON`, error);
120
+ }
121
+ };
122
+ const defaultOcspPolicy = {
123
+ timeoutMs: 5_000,
124
+ maxResponseBytes: 256 * 1024,
125
+ allowMissingNextUpdate: false,
126
+ maxAgeMs: 15 * 60 * 1000,
127
+ allowedSignatureAlgorithms: [
128
+ "1.2.840.10045.4.3.2",
129
+ "1.2.840.10045.4.3.3",
130
+ "1.2.840.10045.4.3.4",
131
+ "1.2.840.113549.1.1.11",
132
+ "1.2.840.113549.1.1.12",
133
+ "1.2.840.113549.1.1.13",
134
+ ],
135
+ };
136
+ const bytesEqual = (left, right) => {
137
+ if (left.length !== right.length)
138
+ return false;
139
+ for (let index = 0; index < left.length; index += 1) {
140
+ if (left[index] !== right[index])
141
+ return false;
142
+ }
143
+ return true;
144
+ };
145
+ const rangeBytes = (certificate, range) => certificate.der.subarray(range.offset, range.offset + range.length);
146
+ const issuerMatches = (certificate, issuer) => bytesEqual(rangeBytes(certificate, certificate.metadata.issuer), rangeBytes(issuer, issuer.metadata.subject));
147
+ const claimAt = (payload, path) => {
148
+ let current = payload;
149
+ for (const key of path) {
150
+ if (typeof current !== "object" || current === null || !Object.hasOwn(current, key)) {
151
+ return undefined;
152
+ }
153
+ current = current[key];
154
+ }
155
+ return current;
156
+ };
157
+ const validateClaims = (payload, policy) => {
158
+ const { application, environment, claimPaths } = policy;
159
+ if (application !== undefined &&
160
+ claimAt(payload, claimPaths?.application ?? []) !== application) {
161
+ throw new VerificationError("claim-policy", "The application claim does not match policy");
162
+ }
163
+ if (environment !== undefined &&
164
+ claimAt(payload, claimPaths?.environment ?? []) !== environment) {
165
+ throw new VerificationError("claim-policy", "The environment claim does not match policy");
166
+ }
167
+ if (policy.validateClaims !== undefined && policy.validateClaims(payload) !== true) {
168
+ throw new VerificationError("claim-policy", "The payload claims were rejected by policy");
169
+ }
170
+ };
171
+ const isEffectiveTime = (value) => typeof value === "number" && Number.isSafeInteger(value) && Math.abs(value) <= 8.64e15;
172
+ const getEffectiveTime = (explicitTime, payload, signedTimePath) => {
173
+ if (explicitTime !== undefined)
174
+ return explicitTime;
175
+ const signedTime = signedTimePath === undefined ? undefined : claimAt(payload, signedTimePath);
176
+ if (!isEffectiveTime(signedTime)) {
177
+ throw new VerificationError("invalid-effective-time", "Offline verification requires an explicit effectiveTime or a valid signed time claim");
178
+ }
179
+ return signedTime;
180
+ };
181
+ const verifyExtensions = (certificate, requiredOids, name) => {
182
+ const { extensions } = certificate.metadata;
183
+ for (const { critical, oid, parsed } of extensions) {
184
+ if (critical && parsed?.kind !== "basicConstraints" && parsed?.kind !== "keyUsage") {
185
+ throw new VerificationError("certificate-policy", `${name} has unsupported critical extension ${oid}`);
186
+ }
187
+ }
188
+ for (const oid of requiredOids) {
189
+ if (!extensions.some((extension) => extension.oid === oid)) {
190
+ throw new VerificationError("certificate-policy", `${name} lacks required extension ${oid}`);
191
+ }
192
+ }
193
+ };
194
+ const ensureValidity = (certificate, effectiveTime, name) => {
195
+ const { notBeforeMs, notAfterMs } = certificate.metadata.validity;
196
+ if (effectiveTime < notBeforeMs || effectiveTime > notAfterMs) {
197
+ throw new VerificationError("certificate-policy", `${name} is not valid at the verification time`);
198
+ }
199
+ };
200
+ const verifyCertificateSignature = (certificate, issuer, name) => {
201
+ try {
202
+ if (!certificate.certificate.verify(issuer.certificate.publicKey)) {
203
+ throw new VerificationError("certificate-chain", `${name} signature is invalid`);
204
+ }
205
+ }
206
+ catch (error) {
207
+ if (error instanceof VerificationError)
208
+ throw error;
209
+ throw new VerificationError("certificate-chain", `${name} signature could not be verified`, error);
210
+ }
211
+ };
212
+ const verifyTrustAnchor = (chain, presentedRootDer, effectiveTime) => {
213
+ const { intermediate, roots } = chain;
214
+ let failure;
215
+ for (const root of roots) {
216
+ if (presentedRootDer !== undefined && !bytesEqual(root.der, presentedRootDer))
217
+ continue;
218
+ if (!issuerMatches(intermediate, root))
219
+ continue;
220
+ try {
221
+ verifyCertificateSignature(intermediate, root, "Intermediate certificate");
222
+ ensureValidity(root, effectiveTime, "Trusted root");
223
+ return root;
224
+ }
225
+ catch (error) {
226
+ if (!(error instanceof VerificationError))
227
+ throw error;
228
+ if (failure === undefined || error.code === "certificate-policy")
229
+ failure = error;
230
+ }
231
+ }
232
+ throw (failure ??
233
+ new VerificationError("certificate-chain", "JWS chain does not terminate at a trusted root"));
234
+ };
235
+ const ensurePublicKey = (key) => {
236
+ if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
237
+ throw new VerificationError("certificate-policy", "The JWS certificate key is not P-256");
238
+ }
239
+ };
240
+ export class VerificationError extends Error {
241
+ code;
242
+ constructor(code, message, cause) {
243
+ super(message, cause === undefined ? undefined : { cause });
244
+ this.name = "VerificationError";
245
+ this.code = code;
246
+ }
247
+ }
248
+ const freezeHeader = (header) => Object.freeze({ ...header, x5c: Object.freeze([...header.x5c]) });
249
+ const normalizePolicy = (policy) => {
250
+ const parsed = verifierPolicySchema.safeParse(policy);
251
+ if (!parsed.success) {
252
+ throw new TypeError(`Invalid verifier policy: ${parsed.error.message}`);
253
+ }
254
+ return parsed.data;
255
+ };
256
+ const normalizeLimits = (limits) => {
257
+ const parsed = verifierLimitsSchema.safeParse(limits ?? {});
258
+ if (!parsed.success) {
259
+ throw new TypeError(`Invalid verifier limits: ${parsed.error.message}`);
260
+ }
261
+ return parsed.data;
262
+ };
263
+ const normalizeRoots = (roots) => {
264
+ if (!Array.isArray(roots) || roots.length === 0) {
265
+ throw new TypeError("At least one trusted root is required");
266
+ }
267
+ return Object.freeze(roots.map((root) => {
268
+ const der = root instanceof Uint8Array ? root : root?.der;
269
+ if (!(der instanceof Uint8Array))
270
+ throw new TypeError("Trusted roots must contain DER bytes");
271
+ return new Uint8Array(der);
272
+ }));
273
+ };
274
+ const prepareRoots = (roots) => {
275
+ try {
276
+ return new CertificatePreparation(roots);
277
+ }
278
+ catch (error) {
279
+ throw new VerificationError("invalid-trust-anchor", "A trusted root is not a valid certificate", error);
280
+ }
281
+ };
282
+ const parseCompactJws = (compactJws, limits, algorithm) => {
283
+ if (typeof compactJws !== "string" || compactJws.length > limits.maxCompactJwsBytes) {
284
+ throw new VerificationError("invalid-jws", "Compact JWS exceeds the configured limit");
285
+ }
286
+ const parts = compactJws.split(".");
287
+ if (parts.length !== 3 || parts.some((part) => part.length === 0)) {
288
+ throw new VerificationError("invalid-jws", "Compact JWS must contain three non-empty segments");
289
+ }
290
+ const [protectedSegment, payloadSegment, signatureSegment] = parts;
291
+ const protectedBytes = base64Url(protectedSegment, "Protected header");
292
+ const payloadBytes = base64Url(payloadSegment, "Payload");
293
+ const signature = base64Url(signatureSegment, "Signature");
294
+ if (protectedBytes.length > limits.maxProtectedHeaderBytes) {
295
+ throw new VerificationError("invalid-jws", "Protected header exceeds the configured limit");
296
+ }
297
+ if (payloadBytes.length > limits.maxPayloadBytes) {
298
+ throw new VerificationError("invalid-jws", "Payload exceeds the configured limit");
299
+ }
300
+ if (signature.length !== 64) {
301
+ throw new VerificationError("invalid-signature", "ES256 JWS signature must be 64 bytes");
302
+ }
303
+ const protectedValue = decodeJson(protectedBytes, "Protected header", "invalid-header");
304
+ const headerResult = protectedHeaderSchema.safeParse(protectedValue);
305
+ if (!headerResult.success) {
306
+ throw new VerificationError("invalid-header", "Protected header does not match the JWS contract");
307
+ }
308
+ const header = headerResult.data;
309
+ if (Object.hasOwn(header, "crit") || Object.hasOwn(header, "b64")) {
310
+ throw new VerificationError("invalid-header", "Unsupported critical JWS header parameter");
311
+ }
312
+ if (header.alg !== algorithm) {
313
+ throw new VerificationError("unsupported-algorithm", `Only ${algorithm} is supported`);
314
+ }
315
+ if (header.x5c.length < 2 || header.x5c.length > limits.maxX5cEntries) {
316
+ throw new VerificationError("invalid-header", "JWS x5c must contain a leaf and an intermediate certificate");
317
+ }
318
+ const certificates = header.x5c.map((value, index) => {
319
+ const der = standardBase64(value, `x5c[${index}]`);
320
+ if (der.length > limits.maxCertificateBytes) {
321
+ throw new VerificationError("invalid-header", `x5c[${index}] exceeds the configured certificate limit`);
322
+ }
323
+ return der;
324
+ });
325
+ return {
326
+ protectedSegment,
327
+ payloadSegment,
328
+ signature,
329
+ protectedHeader: freezeHeader(header),
330
+ payloadBytes,
331
+ certificates,
332
+ cacheKey: header.x5c.map((value) => `${value.length}:${value}`).join("|"),
333
+ };
334
+ };
335
+ const verifyJwsSignature = (parsed, leafKey) => {
336
+ const signingInput = Buffer.from(`${parsed.protectedSegment}.${parsed.payloadSegment}`, "ascii");
337
+ try {
338
+ // workerd accepts a direct KeyObject for verify(), with a DER ECDSA signature.
339
+ if (!verifySignature("sha256", signingInput, leafKey, es256SignatureToDer(parsed.signature))) {
340
+ throw new VerificationError("invalid-signature", "JWS signature is invalid");
341
+ }
342
+ }
343
+ catch (error) {
344
+ if (error instanceof VerificationError)
345
+ throw error;
346
+ throw new VerificationError("invalid-signature", "JWS signature could not be verified", error);
347
+ }
348
+ };
349
+ const ocspPolicyFor = (policy) => policy.ocsp === undefined
350
+ ? defaultOcspPolicy
351
+ : {
352
+ ...defaultOcspPolicy,
353
+ ...policy.ocsp,
354
+ allowedSignatureAlgorithms: policy.ocsp.allowedSignatureAlgorithms ?? defaultOcspPolicy.allowedSignatureAlgorithms,
355
+ };
356
+ const normalizedHttpUrl = (value) => {
357
+ let url;
358
+ try {
359
+ url = new URL(value);
360
+ }
361
+ catch (error) {
362
+ throw new VerificationError("ocsp-policy", "OCSP endpoint is not a valid URL", error);
363
+ }
364
+ if ((url.protocol !== "http:" && url.protocol !== "https:") ||
365
+ url.username ||
366
+ url.password ||
367
+ url.hash) {
368
+ throw new VerificationError("ocsp-policy", "OCSP endpoint must be an HTTP(S) URL without credentials");
369
+ }
370
+ return url.href;
371
+ };
372
+ const chooseOcspEndpoint = (certificate, policy) => {
373
+ const allowed = (policy.allowedEndpoints ?? []).map(normalizedHttpUrl);
374
+ const candidates = certificate.metadata.authorityInfoAccess?.ocspUrls.map(({ value }) => value) ?? [];
375
+ for (const candidate of candidates) {
376
+ const normalized = normalizedHttpUrl(candidate);
377
+ if (allowed.includes(normalized))
378
+ return normalized;
379
+ }
380
+ throw new VerificationError("ocsp-policy", "No certificate OCSP endpoint is allowed by policy");
381
+ };
382
+ const subjectValue = (certificate) => {
383
+ const reader = new DerReader(certificate.der, {}, certificate.metadata.subject.offset, certificate.metadata.subject.offset + certificate.metadata.subject.length);
384
+ const element = reader.readElement();
385
+ reader.assertEnd();
386
+ return element.value;
387
+ };
388
+ const responderMatches = (responder, certificate) => {
389
+ if (responder.kind === "key")
390
+ return ocspBytesEqual(responder.value, ocspKeyHash(certificate));
391
+ const expected = responder.implicit ? subjectValue(certificate) : ocspNameValue(certificate);
392
+ return ocspBytesEqual(responder.value, expected);
393
+ };
394
+ const verifyResponderCertificate = (signer, issuer, effectiveTime) => {
395
+ if (!issuerMatches(signer, issuer)) {
396
+ throw new VerificationError("ocsp-policy", "OCSP delegated responder has the wrong issuer");
397
+ }
398
+ verifyCertificateSignature(signer, issuer, "OCSP delegated responder");
399
+ ensureValidity(signer, effectiveTime, "OCSP delegated responder");
400
+ if (signer.metadata.basicConstraints?.ca === true) {
401
+ throw new VerificationError("ocsp-policy", "OCSP delegated responder must not be a CA");
402
+ }
403
+ if (!signer.metadata.extendedKeyUsage?.ocspSigning) {
404
+ throw new VerificationError("ocsp-policy", "OCSP delegated responder lacks OCSPSigning");
405
+ }
406
+ if (signer.metadata.keyUsage !== undefined &&
407
+ !signer.metadata.keyUsage.names.includes("digitalSignature")) {
408
+ throw new VerificationError("ocsp-policy", "OCSP delegated responder lacks digitalSignature");
409
+ }
410
+ for (const extension of signer.metadata.extensions) {
411
+ if (extension.critical &&
412
+ extension.parsed?.kind !== "basicConstraints" &&
413
+ extension.parsed?.kind !== "keyUsage" &&
414
+ extension.parsed?.kind !== "extendedKeyUsage") {
415
+ throw new VerificationError("ocsp-policy", `OCSP delegated responder has unsupported critical extension ${extension.oid}`);
416
+ }
417
+ }
418
+ };
419
+ const authorizedDelegate = (der, responder, issuer, effectiveTime) => {
420
+ try {
421
+ const candidate = prepareCertificate(der);
422
+ if (!responderMatches(responder, candidate))
423
+ return undefined;
424
+ verifyResponderCertificate(candidate, issuer, effectiveTime);
425
+ return candidate;
426
+ }
427
+ catch {
428
+ return undefined;
429
+ }
430
+ };
431
+ const hasValidOcspSignature = (response, signer) => {
432
+ try {
433
+ const key = signer.certificate.publicKey;
434
+ if (key.asymmetricKeyType !== response.signatureAlgorithm.key)
435
+ return false;
436
+ return verifySignature(response.signatureAlgorithm.hash, response.tbsResponseData, key, response.signature);
437
+ }
438
+ catch {
439
+ return false;
440
+ }
441
+ };
442
+ const verifyOcspSignature = (response, issuer, effectiveTime) => {
443
+ if (response.criticalExtensionOids.length > 0) {
444
+ throw new VerificationError("ocsp-policy", "OCSP response contains unsupported critical extensions");
445
+ }
446
+ let authorized = responderMatches(response.responderId, issuer);
447
+ if (authorized && hasValidOcspSignature(response, issuer)) {
448
+ return issuer.metadata.validity.notAfterMs;
449
+ }
450
+ for (const der of response.certificates) {
451
+ const candidate = authorizedDelegate(der, response.responderId, issuer, effectiveTime);
452
+ if (candidate === undefined)
453
+ continue;
454
+ authorized = true;
455
+ if (hasValidOcspSignature(response, candidate)) {
456
+ return candidate.metadata.validity.notAfterMs;
457
+ }
458
+ }
459
+ if (authorized) {
460
+ throw new VerificationError("ocsp-signature", "OCSP response signature is invalid");
461
+ }
462
+ throw new VerificationError("ocsp-policy", "OCSP responder is not the issuer or an authorized delegate");
463
+ };
464
+ const verifyOcspStatus = (response, certificate, issuer, effectiveTime, policy) => {
465
+ if (response.producedAtMs > effectiveTime) {
466
+ throw new VerificationError("ocsp-stale", "OCSP response was produced in the future");
467
+ }
468
+ const expected = ocspCertIdFor(certificate, issuer);
469
+ const matching = response.responses.filter(({ certId }) => certId.hashAlgorithm === expected.hashAlgorithm &&
470
+ ocspBytesEqual(certId.issuerNameHash, expected.issuerNameHash) &&
471
+ ocspBytesEqual(certId.issuerKeyHash, expected.issuerKeyHash) &&
472
+ ocspBytesEqual(certId.serialNumber, expected.serialNumber));
473
+ if (matching.length === 0)
474
+ throw new VerificationError("ocsp-policy", "OCSP response CertID does not match the request");
475
+ if (matching.length !== 1)
476
+ throw new VerificationError("ocsp-policy", "OCSP response contains duplicate matching CertID entries");
477
+ const result = matching[0];
478
+ if (result === undefined)
479
+ throw new VerificationError("ocsp-policy", "OCSP response is missing its matching SingleResponse");
480
+ if (result.status === "revoked")
481
+ throw new VerificationError("ocsp-revoked", "Certificate is revoked according to OCSP");
482
+ if (result.status === "unknown")
483
+ throw new VerificationError("ocsp-unknown", "OCSP responder returned unknown status");
484
+ if (result.thisUpdateMs > effectiveTime ||
485
+ (result.nextUpdateMs !== undefined && result.nextUpdateMs < result.thisUpdateMs)) {
486
+ throw new VerificationError("ocsp-stale", "OCSP response has invalid update times");
487
+ }
488
+ if (result.nextUpdateMs === undefined) {
489
+ if (!policy.allowMissingNextUpdate || effectiveTime - result.thisUpdateMs > policy.maxAgeMs) {
490
+ throw new VerificationError("ocsp-stale", "OCSP response has no acceptable nextUpdate");
491
+ }
492
+ }
493
+ else if (effectiveTime > result.nextUpdateMs) {
494
+ throw new VerificationError("ocsp-stale", "OCSP response is expired");
495
+ }
496
+ if (result.criticalExtensionOids.length > 0) {
497
+ throw new VerificationError("ocsp-policy", "OCSP SingleResponse contains critical extensions");
498
+ }
499
+ return result.nextUpdateMs ?? result.thisUpdateMs + policy.maxAgeMs;
500
+ };
501
+ export class JwsVerifier {
502
+ #policy;
503
+ preparation;
504
+ limits;
505
+ clock;
506
+ ocspTransport;
507
+ certificateCache = new Map();
508
+ constructor(options) {
509
+ if (options === null || typeof options !== "object") {
510
+ throw new TypeError("Verifier options are required");
511
+ }
512
+ this.#policy = normalizePolicy(options.policy);
513
+ this.limits = normalizeLimits(options.limits);
514
+ this.preparation = prepareRoots(normalizeRoots(options.trustedRoots));
515
+ this.clock = options.clock ?? (() => Date.now());
516
+ if (typeof this.clock !== "function")
517
+ throw new TypeError("clock must be a function");
518
+ if (options.ocspTransport !== undefined && typeof options.ocspTransport !== "function") {
519
+ throw new TypeError("ocspTransport must be a function");
520
+ }
521
+ this.ocspTransport = options.ocspTransport;
522
+ }
523
+ async verify(compactJws, options = {}) {
524
+ if (this.#policy.mode === "online")
525
+ return this.verifyOnline(compactJws, options);
526
+ return this.verifySync(compactJws, options);
527
+ }
528
+ verifySync(compactJws, options = {}) {
529
+ if (this.#policy.mode === "online") {
530
+ throw new VerificationError("online-unavailable", "Online verification requires the asynchronous verify() method");
531
+ }
532
+ if (options.effectiveTime !== undefined && !isEffectiveTime(options.effectiveTime)) {
533
+ throw new VerificationError("invalid-effective-time", "effectiveTime must be Unix milliseconds");
534
+ }
535
+ const parsed = parseCompactJws(compactJws, this.limits, this.#policy.algorithm);
536
+ const [leafDer, intermediateDer, presentedRootDer] = parsed.certificates;
537
+ const prepared = this.prepareChain(leafDer, intermediateDer);
538
+ const leafKey = prepared.leaf.certificate.publicKey;
539
+ ensurePublicKey(leafKey);
540
+ verifyJwsSignature(parsed, leafKey);
541
+ const payload = decodeJson(parsed.payloadBytes, "Payload");
542
+ const effectiveTime = getEffectiveTime(options.effectiveTime, payload, this.#policy.signedTimePath);
543
+ this.verifyChain(prepared, effectiveTime);
544
+ verifyTrustAnchor(prepared, presentedRootDer, effectiveTime);
545
+ validateClaims(payload, this.#policy);
546
+ return Object.freeze({
547
+ compactJws,
548
+ protectedHeader: parsed.protectedHeader,
549
+ payload: payload,
550
+ });
551
+ }
552
+ async verifyOnline(compactJws, options) {
553
+ if (options.effectiveTime !== undefined) {
554
+ throw new VerificationError("invalid-effective-time", "effectiveTime is only supported in offline verification");
555
+ }
556
+ const parsed = parseCompactJws(compactJws, this.limits, this.#policy.algorithm);
557
+ const [leafDer, intermediateDer, presentedRootDer] = parsed.certificates;
558
+ const cached = this.getCacheEntry(parsed.cacheKey);
559
+ const prepared = cached?.chain ?? this.prepareChain(leafDer, intermediateDer);
560
+ const leafKey = cached?.leafKey ?? prepared.leaf.certificate.publicKey;
561
+ ensurePublicKey(leafKey);
562
+ verifyJwsSignature(parsed, leafKey);
563
+ const payload = decodeJson(parsed.payloadBytes, "Payload");
564
+ const effectiveTime = this.clock();
565
+ if (!isEffectiveTime(effectiveTime)) {
566
+ throw new VerificationError("invalid-effective-time", "clock must return Unix milliseconds");
567
+ }
568
+ const cachedHit = cached !== undefined &&
569
+ cached.verifiedAtMs <= effectiveTime &&
570
+ effectiveTime < cached.expiresAtMs;
571
+ if (cachedHit) {
572
+ this.ensureCachedValidity(prepared, cached.root, effectiveTime);
573
+ validateClaims(payload, this.#policy);
574
+ return Object.freeze({
575
+ compactJws,
576
+ protectedHeader: parsed.protectedHeader,
577
+ payload: payload,
578
+ });
579
+ }
580
+ this.certificateCache.delete(parsed.cacheKey);
581
+ this.verifyChain(prepared, effectiveTime);
582
+ const root = verifyTrustAnchor(prepared, presentedRootDer, effectiveTime);
583
+ validateClaims(payload, this.#policy);
584
+ const ocspPolicy = ocspPolicyFor(this.#policy);
585
+ const leafEndpoint = chooseOcspEndpoint(prepared.leaf, ocspPolicy);
586
+ const intermediateEndpoint = chooseOcspEndpoint(prepared.intermediate, ocspPolicy);
587
+ const leafOcspExpiry = await this.verifyOcsp(prepared.leaf, prepared.intermediate, effectiveTime, leafEndpoint);
588
+ const intermediateOcspExpiry = await this.verifyOcsp(prepared.intermediate, root, effectiveTime, intermediateEndpoint);
589
+ const expiresAtMs = Math.min(effectiveTime + this.limits.cacheTtlMs, prepared.leaf.metadata.validity.notAfterMs, prepared.intermediate.metadata.validity.notAfterMs, root.metadata.validity.notAfterMs, leafOcspExpiry, intermediateOcspExpiry);
590
+ if (effectiveTime < expiresAtMs) {
591
+ this.storeCacheEntry(parsed.cacheKey, {
592
+ chain: prepared,
593
+ root,
594
+ leafKey,
595
+ verifiedAtMs: effectiveTime,
596
+ expiresAtMs,
597
+ });
598
+ }
599
+ return Object.freeze({
600
+ compactJws,
601
+ protectedHeader: parsed.protectedHeader,
602
+ payload: payload,
603
+ });
604
+ }
605
+ async requestOcsp(url, body) {
606
+ const policy = ocspPolicyFor(this.#policy);
607
+ const controller = new AbortController();
608
+ const timer = setTimeout(() => controller.abort(), policy.timeoutMs);
609
+ let raceTimer;
610
+ const request = this.ocspTransport ??
611
+ ((input) => fetchOcspResponse(input.url, input.body, input.signal, {
612
+ maxResponseBytes: policy.maxResponseBytes,
613
+ }));
614
+ try {
615
+ const response = await Promise.race([
616
+ request({ url, body, signal: controller.signal }),
617
+ new Promise((_, reject) => {
618
+ raceTimer = setTimeout(() => reject(new Error("OCSP request timed out")), policy.timeoutMs);
619
+ }),
620
+ ]);
621
+ if (!(response instanceof Uint8Array) || response.byteLength > policy.maxResponseBytes) {
622
+ throw new Error("OCSP response exceeds the configured body limit");
623
+ }
624
+ return response;
625
+ }
626
+ catch (error) {
627
+ if (error instanceof VerificationError)
628
+ throw error;
629
+ throw new VerificationError("transport-error", "OCSP transport failed", error);
630
+ }
631
+ finally {
632
+ clearTimeout(timer);
633
+ if (raceTimer !== undefined)
634
+ clearTimeout(raceTimer);
635
+ }
636
+ }
637
+ async verifyOcsp(certificate, issuer, effectiveTime, endpoint) {
638
+ const policy = ocspPolicyFor(this.#policy);
639
+ const request = buildOcspRequest(certificate, issuer);
640
+ const responseBytes = await this.requestOcsp(endpoint, request);
641
+ let response;
642
+ try {
643
+ response = parseOcspResponse(responseBytes);
644
+ }
645
+ catch (error) {
646
+ throw new VerificationError("ocsp-format", "OCSP response is malformed", error);
647
+ }
648
+ if (response.responseStatus !== 0) {
649
+ throw new VerificationError("ocsp-status", `OCSP responder returned status ${response.responseStatus}`);
650
+ }
651
+ if (response.responseType !== "1.3.6.1.5.5.7.48.1.1" || response.basic === undefined) {
652
+ throw new VerificationError("ocsp-format", "OCSP response is not BasicOCSPResponse");
653
+ }
654
+ if (!policy.allowedSignatureAlgorithms.includes(response.basic.signatureAlgorithm.oid)) {
655
+ throw new VerificationError("ocsp-policy", "OCSP signature algorithm is not allowed");
656
+ }
657
+ const signerExpiry = verifyOcspSignature(response.basic, issuer, effectiveTime);
658
+ const freshnessExpiry = verifyOcspStatus(response.basic, certificate, issuer, effectiveTime, policy);
659
+ return Math.min(signerExpiry, freshnessExpiry);
660
+ }
661
+ ensureCachedValidity(chain, root, effectiveTime) {
662
+ ensureValidity(chain.leaf, effectiveTime, "Leaf certificate");
663
+ ensureValidity(chain.intermediate, effectiveTime, "Intermediate certificate");
664
+ ensureValidity(root, effectiveTime, "Trusted root");
665
+ }
666
+ getCacheEntry(key) {
667
+ const entry = this.certificateCache.get(key);
668
+ if (entry === undefined)
669
+ return undefined;
670
+ this.certificateCache.delete(key);
671
+ this.certificateCache.set(key, entry);
672
+ return entry;
673
+ }
674
+ storeCacheEntry(key, entry) {
675
+ this.certificateCache.delete(key);
676
+ this.certificateCache.set(key, entry);
677
+ while (this.certificateCache.size > this.limits.maxCacheEntries) {
678
+ const oldest = this.certificateCache.keys().next().value;
679
+ if (oldest === undefined)
680
+ break;
681
+ this.certificateCache.delete(oldest);
682
+ }
683
+ }
684
+ prepareChain(leafDer, intermediateDer) {
685
+ try {
686
+ return this.preparation.prepareChain(leafDer, intermediateDer);
687
+ }
688
+ catch (error) {
689
+ throw new VerificationError("certificate-chain", "JWS certificate chain is malformed", error);
690
+ }
691
+ }
692
+ verifyChain({ leaf, intermediate }, effectiveTime) {
693
+ ensureValidity(leaf, effectiveTime, "Leaf certificate");
694
+ ensureValidity(intermediate, effectiveTime, "Intermediate certificate");
695
+ const required = this.#policy.requiredExtensions;
696
+ verifyExtensions(leaf, required?.leaf ?? [], "Leaf certificate");
697
+ verifyExtensions(intermediate, required?.intermediate ?? [], "Intermediate certificate");
698
+ if (leaf.metadata.basicConstraints?.ca === true) {
699
+ throw new VerificationError("certificate-policy", "Leaf certificate must not be a CA");
700
+ }
701
+ if (leaf.metadata.keyUsage !== undefined &&
702
+ !leaf.metadata.keyUsage.names.includes("digitalSignature")) {
703
+ throw new VerificationError("certificate-policy", "Leaf certificate lacks digitalSignature key usage");
704
+ }
705
+ if (intermediate.metadata.basicConstraints?.ca !== true) {
706
+ throw new VerificationError("certificate-policy", "Intermediate certificate must be a CA");
707
+ }
708
+ if (intermediate.metadata.keyUsage !== undefined &&
709
+ !intermediate.metadata.keyUsage.names.includes("keyCertSign")) {
710
+ throw new VerificationError("certificate-policy", "Intermediate certificate lacks keyCertSign key usage");
711
+ }
712
+ if (!issuerMatches(leaf, intermediate)) {
713
+ throw new VerificationError("certificate-chain", "Leaf issuer does not match intermediate subject");
714
+ }
715
+ verifyCertificateSignature(leaf, intermediate, "Leaf certificate");
716
+ }
717
+ }
718
+ export const createVerifier = (options) => new JwsVerifier(options);