micro509 0.7.1 → 0.8.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 (110) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +5 -5
  3. package/dist/index.js +15 -1
  4. package/dist/internal/asn1/asn1.js +280 -2
  5. package/dist/internal/asn1/der.js +378 -2
  6. package/dist/internal/asn1/oids.js +103 -2
  7. package/dist/internal/crypto/algorithm-names.js +58 -2
  8. package/dist/internal/crypto/ecdsa.js +68 -2
  9. package/dist/internal/crypto/hash.js +286 -2
  10. package/dist/internal/crypto/pbes2.js +213 -2
  11. package/dist/internal/crypto/rsa-pss.js +184 -2
  12. package/dist/internal/crypto/sig-verify.js +192 -2
  13. package/dist/internal/crypto/signing.d.ts +1 -2
  14. package/dist/internal/crypto/signing.js +123 -2
  15. package/dist/internal/crypto/webcrypto.js +14 -2
  16. package/dist/internal/shared/base64.js +16 -2
  17. package/dist/internal/shared/dn.js +84 -2
  18. package/dist/internal/shared/ip.js +164 -2
  19. package/dist/internal/verify/name-constraints-engine.js +450 -2
  20. package/dist/internal/verify/policy-engine.js +382 -2
  21. package/dist/internal/verify/verify-path.js +298 -2
  22. package/dist/internal/x509/extension-bits.js +132 -2
  23. package/dist/internal/x509/extension-registry.js +229 -2
  24. package/dist/internal/x509/name-fields.js +93 -2
  25. package/dist/keys/keys.d.ts +231 -7
  26. package/dist/keys/keys.js +1087 -5
  27. package/dist/keys.d.ts +2 -2
  28. package/dist/keys.js +2 -1
  29. package/dist/pem/pem.d.ts +2 -2
  30. package/dist/pem/pem.js +172 -6
  31. package/dist/pem.js +2 -1
  32. package/dist/pkcs/pfx.d.ts +4 -5
  33. package/dist/pkcs/pfx.js +395 -2
  34. package/dist/pkcs/pkcs12-mac.d.ts +2 -2
  35. package/dist/pkcs/pkcs12-mac.js +175 -2
  36. package/dist/pkcs/pkcs7.d.ts +1 -2
  37. package/dist/pkcs/pkcs7.js +653 -2
  38. package/dist/pkcs.d.ts +2 -2
  39. package/dist/pkcs.js +4 -1
  40. package/dist/result/result.d.ts +1 -2
  41. package/dist/result/result.js +111 -2
  42. package/dist/result.js +2 -1
  43. package/dist/revocation/chain.d.ts +4 -5
  44. package/dist/revocation/chain.js +536 -2
  45. package/dist/revocation/crl.d.ts +2 -2
  46. package/dist/revocation/crl.js +1119 -2
  47. package/dist/revocation/ocsp.d.ts +3 -2
  48. package/dist/revocation/ocsp.js +958 -2
  49. package/dist/revocation/revocation.d.ts +1 -2
  50. package/dist/revocation/revocation.js +261 -2
  51. package/dist/revocation.d.ts +2 -2
  52. package/dist/revocation.js +5 -1
  53. package/dist/verify/identity.d.ts +1 -2
  54. package/dist/verify/identity.js +270 -2
  55. package/dist/verify/name-constraints.d.ts +1 -2
  56. package/dist/verify/policy.d.ts +1 -2
  57. package/dist/verify/verify.d.ts +1 -2
  58. package/dist/verify/verify.js +764 -2
  59. package/dist/verify.js +3 -1
  60. package/dist/x509/certificate.d.ts +1 -2
  61. package/dist/x509/certificate.js +151 -2
  62. package/dist/x509/csr.d.ts +1 -2
  63. package/dist/x509/csr.js +71 -2
  64. package/dist/x509/extensions.d.ts +1 -2
  65. package/dist/x509/extensions.js +387 -2
  66. package/dist/x509/name.d.ts +1 -2
  67. package/dist/x509/name.js +173 -2
  68. package/dist/x509/parse.d.ts +84 -2
  69. package/dist/x509/parse.js +1090 -2
  70. package/dist/x509.d.ts +2 -2
  71. package/dist/x509.js +6 -1
  72. package/package.json +74 -34
  73. package/dist/internal/asn1/asn1.js.map +0 -1
  74. package/dist/internal/asn1/der.js.map +0 -1
  75. package/dist/internal/asn1/oids.js.map +0 -1
  76. package/dist/internal/crypto/algorithm-names.js.map +0 -1
  77. package/dist/internal/crypto/ecdsa.js.map +0 -1
  78. package/dist/internal/crypto/hash.js.map +0 -1
  79. package/dist/internal/crypto/pbes2.d.ts +0 -23
  80. package/dist/internal/crypto/pbes2.js.map +0 -1
  81. package/dist/internal/crypto/rsa-pss.js.map +0 -1
  82. package/dist/internal/crypto/sig-verify.js.map +0 -1
  83. package/dist/internal/crypto/signing.js.map +0 -1
  84. package/dist/internal/crypto/webcrypto.js.map +0 -1
  85. package/dist/internal/shared/base64.js.map +0 -1
  86. package/dist/internal/shared/dn.js.map +0 -1
  87. package/dist/internal/shared/ip.js.map +0 -1
  88. package/dist/internal/verify/name-constraints-engine.js.map +0 -1
  89. package/dist/internal/verify/policy-engine.js.map +0 -1
  90. package/dist/internal/verify/verify-path.js.map +0 -1
  91. package/dist/internal/x509/extension-bits.js.map +0 -1
  92. package/dist/internal/x509/extension-registry.js.map +0 -1
  93. package/dist/internal/x509/name-fields.js.map +0 -1
  94. package/dist/keys/keys.js.map +0 -1
  95. package/dist/pem/pem.js.map +0 -1
  96. package/dist/pkcs/pfx.js.map +0 -1
  97. package/dist/pkcs/pkcs12-mac.js.map +0 -1
  98. package/dist/pkcs/pkcs7.js.map +0 -1
  99. package/dist/result/result.js.map +0 -1
  100. package/dist/revocation/chain.js.map +0 -1
  101. package/dist/revocation/crl.js.map +0 -1
  102. package/dist/revocation/ocsp.js.map +0 -1
  103. package/dist/revocation/revocation.js.map +0 -1
  104. package/dist/verify/identity.js.map +0 -1
  105. package/dist/verify/verify.js.map +0 -1
  106. package/dist/x509/certificate.js.map +0 -1
  107. package/dist/x509/csr.js.map +0 -1
  108. package/dist/x509/extensions.js.map +0 -1
  109. package/dist/x509/name.js.map +0 -1
  110. package/dist/x509/parse.js.map +0 -1
@@ -1,2 +1,536 @@
1
- import{parseCertificateFromSource as e}from"../x509/parse.js";import{checkCertificateRevocationAgainstCrl as t,parseCertificateRevocationListDerOrThrow as n,parseCertificateRevocationListPemOrThrow as r,revocationReasonFromCode as i}from"./crl.js";import{parseOcspResponseDerOrThrow as a,parseOcspResponsePemOrThrow as o,validateOcspResponse as s}from"./ocsp.js";const c=[`no_applicable_crl`,`no_applicable_ocsp`,`distribution_point_mismatch`,`issuer_name_mismatch`,`reason_scope_mismatch`,`indirect_crl_scope_mismatch`,`reason_coverage_incomplete`,`crl_signer_not_found`,`crl_signer_not_authorized`,`crl_signer_revoked`,`crl_signer_indeterminate`,`ocsp_responder_not_found`,`ocsp_responder_not_authorized`,`ocsp_responder_revoked`,`ocsp_responder_indeterminate`,`crl_expired`,`ocsp_response_expired`,`ocsp_status_unknown`];function l(e){return typeof e==`object`&&`issuer`in e?e:typeof e==`string`?r(e):n(e)}function u(t){try{return e(t)}catch{return}}function d(e,t){if(e.der.length!==t.der.length)return!1;for(let n=0;n<e.der.length;n++)if(e.der[n]!==t.der[n])return!1;return!0}function f(e,t,n){let r=[];for(let e of t){let t=u(e);t!==void 0&&r.push(t)}let i=[...r,...n];if(e.authorityKeyIdentifier!==void 0){for(let t of i)if(t.subjectKeyIdentifier!==void 0&&p(e.authorityKeyIdentifier)===p(t.subjectKeyIdentifier))return t}for(let t of i)if(e.issuer.derHex===t.subject.derHex)return t}function p(e){return e.toLowerCase()}function m(e){return`${e.issuer.derHex}:${e.serialNumberHex}`}async function h(e,t){let n=m(e),r=t.cache.get(n);if(r===`visiting`)return`resolved-indeterminate`;if(r!==void 0)return r;t.cache.set(n,`visiting`);let i=t.chain[t.chain.length-1];if(i!==void 0&&d(e,i)||t.chain.some(t=>d(t,e)))return t.cache.set(n,`resolved-valid`),`resolved-valid`;let a=g(e,t);if(a===void 0)return t.cache.set(n,`resolved-indeterminate`),`resolved-indeterminate`;let o=await _(e,a,t);return t.cache.set(n,o),o}function g(e,t){let n=[];for(let e of t.extraCertificates){let t=u(e);t!==void 0&&n.push(t)}let r=[...t.chain,...n];for(let t of r)if(e.authorityKeyIdentifier!==void 0&&t.subjectKeyIdentifier!==void 0&&p(e.authorityKeyIdentifier)===p(t.subjectKeyIdentifier)||e.issuer.derHex===t.subject.derHex)return t}async function _(e,n,r){let i=r.chain.some(e=>d(e,n));for(let i of r.crls){let a;try{a=l(i)}catch{continue}let o=await t({certificate:e,issuerCertificate:n,crl:a,at:r.at});if(o.ok){if(o.value.status===`revoked`)return`resolved-revoked`;if(o.value.status===`good`&&await h(n,r)===`resolved-valid`)return`resolved-valid`}}return i?`resolved-valid`:`resolved-indeterminate`}function v(e,t,n,r,i){return{certificate:e,status:`revoked`,source:{kind:`crl`,signerCertificate:t,thisUpdate:n},revocationInfo:{revocationDate:r,...i===void 0?{}:{reason:i}}}}function y(e){return typeof e==`string`?o(e):a(e)}function b(e){switch(e){case`stale_response`:return`ocsp_response_expired`;case`responder_id_mismatch`:case`responder_chain_invalid`:case`ocsp_signing_missing`:return`ocsp_responder_not_authorized`;case`responder_revoked`:return`ocsp_responder_revoked`;case`signature_invalid`:case`responder_revocation_unknown`:return`ocsp_responder_indeterminate`;case`response_status_invalid`:case`issuer_mismatch`:case`nonce_mismatch`:case`request_mismatch`:return`no_applicable_ocsp`}}const x=new Set([`signature_invalid`,`responder_id_mismatch`,`responder_chain_invalid`,`ocsp_signing_missing`]);async function S(e,t,n,r){let i={issuerCertificate:t,at:r,...n.trustedOcspResponders===void 0?{}:{trustedOcspResponders:n.trustedOcspResponders},...n.policy?.ocspResponderRevocation===void 0?{}:{responderRevocationPolicy:n.policy.ocspResponderRevocation},...n.crls===void 0?{}:{responderRevocationCrls:n.crls}},a=await s({response:e,...i});if(a.ok||!x.has(a.code))return a;for(let t of n.extraCertificates??[]){let n=u(t);if(n===void 0)continue;let r=await s({response:e,...i,responderCertificate:n});if(r.ok)return r}return a}async function C(e,t,n){let{ocspResponses:r=[],at:a=new Date}=n,o=[],s=new Set;for(let c of r){let r;try{r=y(c)}catch(e){o.push({kind:`parse_error`,message:e instanceof Error?e.message:`OCSP response parse failed`});continue}let l=(r.responses??[]).find(t=>p(t.certId.serialNumberHex)===p(e.serialNumberHex));if(l===void 0)continue;let u=await S(r,t,n,a);if(!u.ok){s.add(b(u.code));continue}if(l.certStatus===`revoked`){let t=i(l.revocationReasonCode);return{status:{certificate:e,status:`revoked`,source:{kind:`ocsp`,thisUpdate:l.thisUpdate},revocationInfo:{revocationDate:l.revokedAt??l.thisUpdate,...t===void 0?{}:{reason:t}}},executionErrors:o}}if(l.certStatus===`good`)return{status:{certificate:e,status:`good`,source:{kind:`ocsp`,thisUpdate:l.thisUpdate}},executionErrors:o};s.add(`ocsp_status_unknown`)}return s.size===0&&s.add(`no_applicable_ocsp`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...s]},executionErrors:o}}const w=[`keyCompromise`,`cACompromise`,`affiliationChanged`,`superseded`,`cessationOfOperation`,`certificateHold`,`privilegeWithdrawn`,`aACompromise`];async function T(e,n,r,i){let{crls:a=[],extraCertificates:o=[],chain:s=[],at:c=new Date}=r,u=[],p=!1,m=!1,g=!1,_,y=new Set,b=[];for(let e of a)try{b.push(l(e))}catch(e){u.push({kind:`parse_error`,message:e instanceof Error?e.message:`CRL parse failed`})}let x=b.filter(e=>e.baseCrlNumber===void 0),S=b.filter(e=>e.baseCrlNumber!==void 0),C=async(n,r,i)=>t({certificate:e,issuerCertificate:i,crl:n,...r===void 0?{}:{deltaCrl:r},at:c});for(let t of x){let r=S.find(e=>e.issuer.derHex===t.issuer.derHex&&e.baseCrlNumber!==void 0&&t.crlNumber!==void 0&&BigInt(e.baseCrlNumber)<=BigInt(t.crlNumber)),a=await C(t,r,n),c=n;if(!a.ok){let e=f(t,o,s);e!==void 0&&!d(e,n)&&(a=await C(t,r,e),c=e)}if(!a.ok)continue;let l=await h(c,i);if(l===`resolved-revoked`){p=!0;continue}if(l===`resolved-indeterminate`){m=!0;continue}let b=r!==void 0&&r.thisUpdate.getTime()>t.thisUpdate.getTime()?r.thisUpdate:t.thisUpdate;if(a.value.status===`revoked`)return{status:v(e,c,b,a.value.revocationDate,a.value.reasonCode),executionErrors:u};g=!0,(_===void 0||b.getTime()>_.thisUpdate.getTime())&&(_={signer:c,thisUpdate:b});let x=t.issuingDistributionPoint?.onlySomeReasons?.flags;if(x===void 0)for(let e of w)y.add(e);else for(let e of x)y.add(e)}if(g&&_!==void 0)return w.every(e=>y.has(e))?{status:{certificate:e,status:`good`,source:{kind:`crl`,signerCertificate:_.signer,thisUpdate:_.thisUpdate}},executionErrors:u}:{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[`reason_coverage_incomplete`]},executionErrors:u};let T=[];return p?T.push(`crl_signer_revoked`):m?T.push(`crl_signer_indeterminate`):T.push(`no_applicable_crl`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:T},executionErrors:u}}async function E(e,t,n,r){let i=n.policy?.prefer??`best-available`,a=await C(e,t,n),o=await T(e,t,n,r),s=[...a.executionErrors,...o.executionErrors],c=i===`crl`?[o,a]:i===`ocsp`?[a,o]:[a,o].sort((e,t)=>(t.status.source?.thisUpdate?.getTime()??0)-(e.status.source?.thisUpdate?.getTime()??0)),l=c.find(e=>e.status.status===`revoked`);if(l!==void 0)return{status:l.status,executionErrors:s};let u=c.find(e=>e.status.status===`good`);if(u!==void 0)return{status:u.status,executionErrors:s};let d=new Set;for(let e of c)for(let t of e.status.indeterminateReasons??[])d.add(t);return{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...d]},executionErrors:s}}async function D(e){let{chain:t,policy:n,crls:r=[],extraCertificates:i=[],at:a=new Date}=e,o=n?.mode??`hard-fail`;if(t.length===0)return{ok:!0,value:{decision:`allow`,summary:{revokedCertificates:[],indeterminateCertificates:[]},certificates:[]}};let s={cache:new Map,chain:t,crls:r,extraCertificates:i,at:a},c=t.slice(0,-1),l=[],u=[],d=[],f=[];for(let n=0;n<c.length;n++){let r=c[n],i=t[n+1];if(r===void 0||i===void 0)continue;let{status:a,executionErrors:o}=await E(r,i,e,s);l.push(a),f.push(...o),a.status===`revoked`?u.push(r):a.status===`indeterminate`&&d.push(r)}let p=u.length>0,m=d.length>0;return{ok:!0,value:{decision:p||m&&o===`hard-fail`?`deny`:`allow`,summary:{revokedCertificates:u,indeterminateCertificates:d},certificates:l,...f.length>0?{executionErrors:f}:{}}}}export{c as REVOCATION_INDETERMINATE_REASONS,D as checkChainRevocation};
2
- //# sourceMappingURL=chain.js.map
1
+ import { parseCertificateFromSource } from "../x509/parse.js";
2
+ import { checkCertificateRevocationAgainstCrl, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPemOrThrow, revocationReasonFromCode } from "./crl.js";
3
+ import { parseOcspResponseDerOrThrow, parseOcspResponsePemOrThrow, validateOcspResponse } from "./ocsp.js";
4
+ //#region src/revocation/chain.ts
5
+ /**
6
+ * Granular reasons why revocation status could not be determined.
7
+ *
8
+ * Returned in {@linkcode CertificateRevocationStatus}'s `indeterminateReasons`
9
+ * when `status` is `'indeterminate'`. Grouped by category:
10
+ *
11
+ * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`
12
+ * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,
13
+ * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`
14
+ * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,
15
+ * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents
16
+ * - **Freshness**: `crl_expired`, `ocsp_response_expired`
17
+ */
18
+ const REVOCATION_INDETERMINATE_REASONS = [
19
+ "no_applicable_crl",
20
+ "no_applicable_ocsp",
21
+ "distribution_point_mismatch",
22
+ "issuer_name_mismatch",
23
+ "reason_scope_mismatch",
24
+ "indirect_crl_scope_mismatch",
25
+ "reason_coverage_incomplete",
26
+ "crl_signer_not_found",
27
+ "crl_signer_not_authorized",
28
+ "crl_signer_revoked",
29
+ "crl_signer_indeterminate",
30
+ "ocsp_responder_not_found",
31
+ "ocsp_responder_not_authorized",
32
+ "ocsp_responder_revoked",
33
+ "ocsp_responder_indeterminate",
34
+ "crl_expired",
35
+ "ocsp_response_expired",
36
+ "ocsp_status_unknown"
37
+ ];
38
+ /**
39
+ * Parses a CRL from various source formats.
40
+ */
41
+ function parseCrlFromSource(source) {
42
+ if (typeof source === "object" && "issuer" in source) return source;
43
+ if (typeof source === "string") return parseCertificateRevocationListPemOrThrow(source);
44
+ return parseCertificateRevocationListDerOrThrow(source);
45
+ }
46
+ /**
47
+ * Parses a certificate from various source formats, returning undefined on failure.
48
+ */
49
+ function parseCertificateSafe(source) {
50
+ try {
51
+ return parseCertificateFromSource(source);
52
+ } catch {
53
+ return;
54
+ }
55
+ }
56
+ /**
57
+ * Compares two certificates by DER bytes for identity.
58
+ * Reference equality fails when same cert is parsed from different sources.
59
+ */
60
+ function sameCertificate(a, b) {
61
+ if (a.der.length !== b.der.length) return false;
62
+ for (let i = 0; i < a.der.length; i++) if (a.der[i] !== b.der[i]) return false;
63
+ return true;
64
+ }
65
+ /**
66
+ * Searches for a certificate that could have signed the given CRL.
67
+ * Matches by AKI/SKI or issuer/subject DN.
68
+ */
69
+ function findIndirectCrlIssuer(crl, extraCertificates, chain) {
70
+ const parsedExtras = [];
71
+ for (const source of extraCertificates) {
72
+ const parsed = parseCertificateSafe(source);
73
+ if (parsed !== void 0) parsedExtras.push(parsed);
74
+ }
75
+ const candidates = [...parsedExtras, ...chain];
76
+ if (crl.authorityKeyIdentifier !== void 0) {
77
+ for (const candidate of candidates) if (candidate.subjectKeyIdentifier !== void 0 && normalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)) return candidate;
78
+ }
79
+ for (const candidate of candidates) if (crl.issuer.derHex === candidate.subject.derHex) return candidate;
80
+ }
81
+ /** Lowercases a hex string for bytewise comparison. */
82
+ function normalizeHex(value) {
83
+ return value.toLowerCase();
84
+ }
85
+ /**
86
+ * Builds a unique cache key for a certificate.
87
+ * Uses issuer DN + serial number which uniquely identifies a cert.
88
+ */
89
+ function certCacheKey(cert) {
90
+ return `${cert.issuer.derHex}:${cert.serialNumberHex}`;
91
+ }
92
+ /**
93
+ * Validates that a CRL signer certificate is not revoked.
94
+ * Uses memoization to avoid redundant checks and detect cycles.
95
+ */
96
+ async function validateCrlSigner(signer, ctx) {
97
+ const key = certCacheKey(signer);
98
+ const cached = ctx.cache.get(key);
99
+ if (cached === "visiting") return "resolved-indeterminate";
100
+ if (cached !== void 0) return cached;
101
+ ctx.cache.set(key, "visiting");
102
+ const trustAnchor = ctx.chain[ctx.chain.length - 1];
103
+ if (trustAnchor !== void 0 && sameCertificate(signer, trustAnchor)) {
104
+ ctx.cache.set(key, "resolved-valid");
105
+ return "resolved-valid";
106
+ }
107
+ if (ctx.chain.some((c) => sameCertificate(c, signer))) {
108
+ ctx.cache.set(key, "resolved-valid");
109
+ return "resolved-valid";
110
+ }
111
+ const signerIssuer = findSignerIssuer(signer, ctx);
112
+ if (signerIssuer === void 0) {
113
+ ctx.cache.set(key, "resolved-indeterminate");
114
+ return "resolved-indeterminate";
115
+ }
116
+ const signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);
117
+ ctx.cache.set(key, signerRevocation);
118
+ return signerRevocation;
119
+ }
120
+ /**
121
+ * Finds the issuer certificate for a CRL signer.
122
+ * Searches the chain and extraCertificates by AKI/SKI or DN matching.
123
+ */
124
+ function findSignerIssuer(signer, ctx) {
125
+ const parsedExtras = [];
126
+ for (const source of ctx.extraCertificates) {
127
+ const parsed = parseCertificateSafe(source);
128
+ if (parsed !== void 0) parsedExtras.push(parsed);
129
+ }
130
+ const candidates = [...ctx.chain, ...parsedExtras];
131
+ for (const candidate of candidates) {
132
+ if (signer.authorityKeyIdentifier !== void 0 && candidate.subjectKeyIdentifier !== void 0 && normalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)) return candidate;
133
+ if (signer.issuer.derHex === candidate.subject.derHex) return candidate;
134
+ }
135
+ }
136
+ /**
137
+ * Checks if a CRL signer certificate is revoked by examining available CRLs.
138
+ * Recursively validates the CRL signer of any CRL used to check revocation.
139
+ */
140
+ async function checkSignerRevocation(signer, issuer, ctx) {
141
+ const issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));
142
+ for (const crlSource of ctx.crls) {
143
+ let crl;
144
+ try {
145
+ crl = parseCrlFromSource(crlSource);
146
+ } catch {
147
+ continue;
148
+ }
149
+ const result = await checkCertificateRevocationAgainstCrl({
150
+ certificate: signer,
151
+ issuerCertificate: issuer,
152
+ crl,
153
+ at: ctx.at
154
+ });
155
+ if (result.ok) {
156
+ if (result.value.status === "revoked") return "resolved-revoked";
157
+ if (result.value.status === "good") {
158
+ if (await validateCrlSigner(issuer, ctx) === "resolved-valid") return "resolved-valid";
159
+ }
160
+ }
161
+ }
162
+ if (issuerInChain) return "resolved-valid";
163
+ return "resolved-indeterminate";
164
+ }
165
+ /** Builds the `revoked` CertificateRevocationStatus for a CRL hit. */
166
+ function buildCrlRevokedStatus(cert, signer, thisUpdate, revocationDate, reasonCode) {
167
+ return {
168
+ certificate: cert,
169
+ status: "revoked",
170
+ source: {
171
+ kind: "crl",
172
+ signerCertificate: signer,
173
+ thisUpdate
174
+ },
175
+ revocationInfo: {
176
+ revocationDate,
177
+ ...reasonCode !== void 0 ? { reason: reasonCode } : {}
178
+ }
179
+ };
180
+ }
181
+ /** Parses an OCSP response from PEM string or DER bytes. */
182
+ function parseOcspResponseFromSource(source) {
183
+ if (typeof source === "string") return parseOcspResponsePemOrThrow(source);
184
+ return parseOcspResponseDerOrThrow(source);
185
+ }
186
+ /** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */
187
+ function ocspIndeterminateReasonFromFailure(code) {
188
+ switch (code) {
189
+ case "stale_response": return "ocsp_response_expired";
190
+ case "responder_id_mismatch":
191
+ case "responder_chain_invalid":
192
+ case "ocsp_signing_missing": return "ocsp_responder_not_authorized";
193
+ case "responder_revoked": return "ocsp_responder_revoked";
194
+ case "signature_invalid":
195
+ case "responder_revocation_unknown": return "ocsp_responder_indeterminate";
196
+ case "response_status_invalid":
197
+ case "issuer_mismatch":
198
+ case "nonce_mismatch":
199
+ case "request_mismatch": return "no_applicable_ocsp";
200
+ }
201
+ }
202
+ /** Validation failures worth retrying with an explicit responder certificate. */
203
+ const OCSP_RESPONDER_FAILURE_CODES = /* @__PURE__ */ new Set([
204
+ "signature_invalid",
205
+ "responder_id_mismatch",
206
+ "responder_chain_invalid",
207
+ "ocsp_signing_missing"
208
+ ]);
209
+ /**
210
+ * Validates an OCSP response, retrying with caller-provided extra certificates
211
+ * as explicit responder certificates when embedded discovery fails.
212
+ */
213
+ async function validateOcspResponseWithResponderFallback(response, issuer, input, at) {
214
+ const shared = {
215
+ issuerCertificate: issuer,
216
+ at,
217
+ ...input.trustedOcspResponders !== void 0 ? { trustedOcspResponders: input.trustedOcspResponders } : {},
218
+ ...input.policy?.ocspResponderRevocation !== void 0 ? { responderRevocationPolicy: input.policy.ocspResponderRevocation } : {},
219
+ ...input.crls !== void 0 ? { responderRevocationCrls: input.crls } : {}
220
+ };
221
+ const primary = await validateOcspResponse({
222
+ response,
223
+ ...shared
224
+ });
225
+ if (primary.ok || !OCSP_RESPONDER_FAILURE_CODES.has(primary.code)) return primary;
226
+ for (const source of input.extraCertificates ?? []) {
227
+ const responder = parseCertificateSafe(source);
228
+ if (responder === void 0) continue;
229
+ const retry = await validateOcspResponse({
230
+ response,
231
+ ...shared,
232
+ responderCertificate: responder
233
+ });
234
+ if (retry.ok) return retry;
235
+ }
236
+ return primary;
237
+ }
238
+ /**
239
+ * Evaluates OCSP evidence for a single certificate (RFC 6960).
240
+ *
241
+ * Every response is fully validated — signature, responder binding and
242
+ * authorization, and freshness — via {@linkcode validateOcspResponse} before
243
+ * its status entry is trusted. Issuer binding of each CertID is enforced by
244
+ * the validator, so a serial-number match on a validated response is
245
+ * sufficient to attribute the entry to `cert`.
246
+ */
247
+ async function evaluateOcspEvidence(cert, issuer, input) {
248
+ const { ocspResponses = [], at = /* @__PURE__ */ new Date() } = input;
249
+ const executionErrors = [];
250
+ const reasons = /* @__PURE__ */ new Set();
251
+ for (const source of ocspResponses) {
252
+ let parsed;
253
+ try {
254
+ parsed = parseOcspResponseFromSource(source);
255
+ } catch (e) {
256
+ executionErrors.push({
257
+ kind: "parse_error",
258
+ message: e instanceof Error ? e.message : "OCSP response parse failed"
259
+ });
260
+ continue;
261
+ }
262
+ const entry = (parsed.responses ?? []).find((single) => normalizeHex(single.certId.serialNumberHex) === normalizeHex(cert.serialNumberHex));
263
+ if (entry === void 0) continue;
264
+ const validation = await validateOcspResponseWithResponderFallback(parsed, issuer, input, at);
265
+ if (!validation.ok) {
266
+ reasons.add(ocspIndeterminateReasonFromFailure(validation.code));
267
+ continue;
268
+ }
269
+ if (entry.certStatus === "revoked") {
270
+ const reason = revocationReasonFromCode(entry.revocationReasonCode);
271
+ return {
272
+ status: {
273
+ certificate: cert,
274
+ status: "revoked",
275
+ source: {
276
+ kind: "ocsp",
277
+ thisUpdate: entry.thisUpdate
278
+ },
279
+ revocationInfo: {
280
+ revocationDate: entry.revokedAt ?? entry.thisUpdate,
281
+ ...reason !== void 0 ? { reason } : {}
282
+ }
283
+ },
284
+ executionErrors
285
+ };
286
+ }
287
+ if (entry.certStatus === "good") return {
288
+ status: {
289
+ certificate: cert,
290
+ status: "good",
291
+ source: {
292
+ kind: "ocsp",
293
+ thisUpdate: entry.thisUpdate
294
+ }
295
+ },
296
+ executionErrors
297
+ };
298
+ reasons.add("ocsp_status_unknown");
299
+ }
300
+ if (reasons.size === 0) reasons.add("no_applicable_ocsp");
301
+ return {
302
+ status: {
303
+ certificate: cert,
304
+ status: "indeterminate",
305
+ indeterminateReasons: [...reasons]
306
+ },
307
+ executionErrors
308
+ };
309
+ }
310
+ /**
311
+ * Evaluates revocation status for a single certificate using available CRLs.
312
+ * Returns both status and any execution errors encountered.
313
+ *
314
+ * Tries the chain issuer first; if that fails, searches extraCertificates
315
+ * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.
316
+ *
317
+ * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).
318
+ */
319
+ const ALL_REASON_FLAGS = [
320
+ "keyCompromise",
321
+ "cACompromise",
322
+ "affiliationChanged",
323
+ "superseded",
324
+ "cessationOfOperation",
325
+ "certificateHold",
326
+ "privilegeWithdrawn",
327
+ "aACompromise"
328
+ ];
329
+ async function evaluateCrlEvidence(cert, issuer, input, signerCtx) {
330
+ const { crls = [], extraCertificates = [], chain = [], at = /* @__PURE__ */ new Date() } = input;
331
+ const executionErrors = [];
332
+ let sawCrlSignerRevoked = false;
333
+ let sawCrlSignerIndeterminate = false;
334
+ let sawGood = false;
335
+ let freshestGood;
336
+ const coveredReasons = /* @__PURE__ */ new Set();
337
+ const parsedCrls = [];
338
+ for (const crlSource of crls) try {
339
+ parsedCrls.push(parseCrlFromSource(crlSource));
340
+ } catch (e) {
341
+ executionErrors.push({
342
+ kind: "parse_error",
343
+ message: e instanceof Error ? e.message : "CRL parse failed"
344
+ });
345
+ }
346
+ const baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === void 0);
347
+ const deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== void 0);
348
+ const checkWithIssuer = (crl, deltaCrl, crlIssuer) => {
349
+ return checkCertificateRevocationAgainstCrl({
350
+ certificate: cert,
351
+ issuerCertificate: crlIssuer,
352
+ crl,
353
+ ...deltaCrl !== void 0 ? { deltaCrl } : {},
354
+ at
355
+ });
356
+ };
357
+ for (const baseCrl of baseCrls) {
358
+ const applicableDelta = deltaCrls.find((d) => d.issuer.derHex === baseCrl.issuer.derHex && d.baseCrlNumber !== void 0 && baseCrl.crlNumber !== void 0 && BigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber));
359
+ let result = await checkWithIssuer(baseCrl, applicableDelta, issuer);
360
+ let effectiveSigner = issuer;
361
+ if (!result.ok) {
362
+ const indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);
363
+ if (indirectIssuer !== void 0 && !sameCertificate(indirectIssuer, issuer)) {
364
+ result = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);
365
+ effectiveSigner = indirectIssuer;
366
+ }
367
+ }
368
+ if (!result.ok) continue;
369
+ const signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);
370
+ if (signerStatus === "resolved-revoked") {
371
+ sawCrlSignerRevoked = true;
372
+ continue;
373
+ }
374
+ if (signerStatus === "resolved-indeterminate") {
375
+ sawCrlSignerIndeterminate = true;
376
+ continue;
377
+ }
378
+ const crlThisUpdate = applicableDelta !== void 0 && applicableDelta.thisUpdate.getTime() > baseCrl.thisUpdate.getTime() ? applicableDelta.thisUpdate : baseCrl.thisUpdate;
379
+ if (result.value.status === "revoked") return {
380
+ status: buildCrlRevokedStatus(cert, effectiveSigner, crlThisUpdate, result.value.revocationDate, result.value.reasonCode),
381
+ executionErrors
382
+ };
383
+ sawGood = true;
384
+ if (freshestGood === void 0 || crlThisUpdate.getTime() > freshestGood.thisUpdate.getTime()) freshestGood = {
385
+ signer: effectiveSigner,
386
+ thisUpdate: crlThisUpdate
387
+ };
388
+ const crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;
389
+ if (crlReasons === void 0) for (const reason of ALL_REASON_FLAGS) coveredReasons.add(reason);
390
+ else for (const reason of crlReasons) coveredReasons.add(reason);
391
+ }
392
+ if (sawGood && freshestGood !== void 0) {
393
+ if (ALL_REASON_FLAGS.every((r) => coveredReasons.has(r))) return {
394
+ status: {
395
+ certificate: cert,
396
+ status: "good",
397
+ source: {
398
+ kind: "crl",
399
+ signerCertificate: freshestGood.signer,
400
+ thisUpdate: freshestGood.thisUpdate
401
+ }
402
+ },
403
+ executionErrors
404
+ };
405
+ return {
406
+ status: {
407
+ certificate: cert,
408
+ status: "indeterminate",
409
+ indeterminateReasons: ["reason_coverage_incomplete"]
410
+ },
411
+ executionErrors
412
+ };
413
+ }
414
+ const reasons = [];
415
+ if (sawCrlSignerRevoked) reasons.push("crl_signer_revoked");
416
+ else if (sawCrlSignerIndeterminate) reasons.push("crl_signer_indeterminate");
417
+ else reasons.push("no_applicable_crl");
418
+ return {
419
+ status: {
420
+ certificate: cert,
421
+ status: "indeterminate",
422
+ indeterminateReasons: reasons
423
+ },
424
+ executionErrors
425
+ };
426
+ }
427
+ /**
428
+ * Evaluates revocation status for a single certificate by combining OCSP and
429
+ * CRL evidence.
430
+ *
431
+ * Both evidence kinds are always evaluated: a validated `revoked` verdict from
432
+ * either source wins regardless of {@linkcode RevocationPolicy.prefer}
433
+ * (fail-closed). Otherwise the preferred source's `good` verdict is reported —
434
+ * for `'best-available'` the source with the later evidence `thisUpdate` wins,
435
+ * ties favoring OCSP. If neither source is definitive, indeterminate reasons
436
+ * from both are merged.
437
+ */
438
+ async function evaluateCertificateRevocation(cert, issuer, input, signerCtx) {
439
+ const prefer = input.policy?.prefer ?? "best-available";
440
+ const ocsp = await evaluateOcspEvidence(cert, issuer, input);
441
+ const crl = await evaluateCrlEvidence(cert, issuer, input, signerCtx);
442
+ const executionErrors = [...ocsp.executionErrors, ...crl.executionErrors];
443
+ const ordered = prefer === "crl" ? [crl, ocsp] : prefer === "ocsp" ? [ocsp, crl] : [ocsp, crl].sort((a, b) => (b.status.source?.thisUpdate?.getTime() ?? 0) - (a.status.source?.thisUpdate?.getTime() ?? 0));
444
+ const revoked = ordered.find((evaluation) => evaluation.status.status === "revoked");
445
+ if (revoked !== void 0) return {
446
+ status: revoked.status,
447
+ executionErrors
448
+ };
449
+ const good = ordered.find((evaluation) => evaluation.status.status === "good");
450
+ if (good !== void 0) return {
451
+ status: good.status,
452
+ executionErrors
453
+ };
454
+ const reasons = /* @__PURE__ */ new Set();
455
+ for (const evaluation of ordered) for (const reason of evaluation.status.indeterminateReasons ?? []) reasons.add(reason);
456
+ return {
457
+ status: {
458
+ certificate: cert,
459
+ status: "indeterminate",
460
+ indeterminateReasons: [...reasons]
461
+ },
462
+ executionErrors
463
+ };
464
+ }
465
+ /**
466
+ * Checks revocation status for all certificates in a validated chain.
467
+ *
468
+ * Evaluates CRL and OCSP evidence against each certificate (except the trust
469
+ * anchor), applies the revocation policy, and returns a unified decision.
470
+ *
471
+ * @example
472
+ * ```ts
473
+ * const result = await checkChainRevocation({
474
+ * chain: validatedChain,
475
+ * crls: [crl1, crl2],
476
+ * ocspResponses: [ocspResponseDer],
477
+ * policy: { mode: 'hard-fail' },
478
+ * });
479
+ * if (result.value.decision === 'deny') {
480
+ * console.log('Revocation check failed');
481
+ * }
482
+ * ```
483
+ */
484
+ async function checkChainRevocation(input) {
485
+ const { chain, policy, crls = [], extraCertificates = [], at = /* @__PURE__ */ new Date() } = input;
486
+ const mode = policy?.mode ?? "hard-fail";
487
+ if (chain.length === 0) return {
488
+ ok: true,
489
+ value: {
490
+ decision: "allow",
491
+ summary: {
492
+ revokedCertificates: [],
493
+ indeterminateCertificates: []
494
+ },
495
+ certificates: []
496
+ }
497
+ };
498
+ const signerCtx = {
499
+ cache: /* @__PURE__ */ new Map(),
500
+ chain,
501
+ crls,
502
+ extraCertificates,
503
+ at
504
+ };
505
+ const certsToCheck = chain.slice(0, -1);
506
+ const certificates = [];
507
+ const revokedCertificates = [];
508
+ const indeterminateCertificates = [];
509
+ const allExecutionErrors = [];
510
+ for (let i = 0; i < certsToCheck.length; i++) {
511
+ const cert = certsToCheck[i];
512
+ const issuer = chain[i + 1];
513
+ if (cert === void 0 || issuer === void 0) continue;
514
+ const { status, executionErrors } = await evaluateCertificateRevocation(cert, issuer, input, signerCtx);
515
+ certificates.push(status);
516
+ allExecutionErrors.push(...executionErrors);
517
+ if (status.status === "revoked") revokedCertificates.push(cert);
518
+ else if (status.status === "indeterminate") indeterminateCertificates.push(cert);
519
+ }
520
+ const hasRevoked = revokedCertificates.length > 0;
521
+ const hasIndeterminate = indeterminateCertificates.length > 0;
522
+ return {
523
+ ok: true,
524
+ value: {
525
+ decision: hasRevoked ? "deny" : hasIndeterminate && mode === "hard-fail" ? "deny" : "allow",
526
+ summary: {
527
+ revokedCertificates,
528
+ indeterminateCertificates
529
+ },
530
+ certificates,
531
+ ...allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}
532
+ }
533
+ };
534
+ }
535
+ //#endregion
536
+ export { REVOCATION_INDETERMINATE_REASONS, checkChainRevocation };
@@ -255,6 +255,7 @@ declare function createCertificateRevocationList(input: CreateCertificateRevocat
255
255
  type ParseCertificateRevocationListErrorCode = "malformed";
256
256
  /** Structured failure payload for CRL parsing. */
257
257
  interface ParseCertificateRevocationListFailure extends Micro509Error<ParseCertificateRevocationListErrorCode> {
258
+ /** Always `false` for failures. */
258
259
  readonly ok: false;
259
260
  }
260
261
  /** Success-or-failure result from {@linkcode parseCertificateRevocationListDer} / {@linkcode parseCertificateRevocationListPem}. */
@@ -339,5 +340,4 @@ declare function checkCertificateRevocationAgainstCrl(input: CheckCertificateRev
339
340
  */
340
341
  declare function isCertificateRevoked(certificateSerialNumber: Uint8Array | string, crl: ParsedCertificateRevocationList): boolean;
341
342
  //#endregion
342
- export { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailure, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlGoodValue, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CheckCertificateRevocationAgainstCrlRevokedValue, CheckCertificateRevocationAgainstCrlValue, CreateCertificateRevocationListInput, CrlApplicabilityFailureReason, CrlCertificateSource, CrlSource, ParseCertificateRevocationListErrorCode, ParseCertificateRevocationListFailure, ParseCertificateRevocationListResult, ParsedCertificateRevocationList, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListSignatureFailure, VerifyCertificateRevocationListSignatureResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, validateCertificateRevocationList, verifyCertificateRevocationListSignature };
343
- //# sourceMappingURL=crl.d.ts.map
343
+ export { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailure, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlGoodValue, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CheckCertificateRevocationAgainstCrlRevokedValue, CheckCertificateRevocationAgainstCrlValue, CreateCertificateRevocationListInput, CrlApplicabilityFailureReason, CrlCertificateSource, CrlSource, ParseCertificateRevocationListErrorCode, ParseCertificateRevocationListFailure, ParseCertificateRevocationListResult, ParsedCertificateRevocationList, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListSignatureFailure, VerifyCertificateRevocationListSignatureResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, validateCertificateRevocationList, verifyCertificateRevocationListSignature };