micro509 0.7.2 → 0.9.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 (109) hide show
  1. package/dist/index.d.ts +5 -5
  2. package/dist/index.js +15 -1
  3. package/dist/internal/asn1/asn1.js +280 -2
  4. package/dist/internal/asn1/der.js +378 -2
  5. package/dist/internal/asn1/oids.js +103 -2
  6. package/dist/internal/crypto/algorithm-names.js +58 -2
  7. package/dist/internal/crypto/ecdsa.js +68 -2
  8. package/dist/internal/crypto/hash.js +286 -2
  9. package/dist/internal/crypto/pbes2.js +213 -2
  10. package/dist/internal/crypto/rsa-pss.js +184 -2
  11. package/dist/internal/crypto/sig-verify.js +192 -2
  12. package/dist/internal/crypto/signing.d.ts +1 -2
  13. package/dist/internal/crypto/signing.js +123 -2
  14. package/dist/internal/crypto/webcrypto.js +14 -2
  15. package/dist/internal/shared/base64.js +16 -2
  16. package/dist/internal/shared/dn.js +84 -2
  17. package/dist/internal/shared/ip.js +164 -2
  18. package/dist/internal/verify/name-constraints-engine.js +450 -2
  19. package/dist/internal/verify/policy-engine.js +382 -2
  20. package/dist/internal/verify/verify-path.js +298 -2
  21. package/dist/internal/x509/extension-bits.js +132 -2
  22. package/dist/internal/x509/extension-registry.js +229 -2
  23. package/dist/internal/x509/name-fields.js +93 -2
  24. package/dist/keys/keys.d.ts +380 -13
  25. package/dist/keys/keys.js +1247 -5
  26. package/dist/keys.d.ts +2 -2
  27. package/dist/keys.js +2 -1
  28. package/dist/pem/pem.d.ts +2 -2
  29. package/dist/pem/pem.js +172 -6
  30. package/dist/pem.js +2 -1
  31. package/dist/pkcs/pfx.d.ts +4 -5
  32. package/dist/pkcs/pfx.js +395 -2
  33. package/dist/pkcs/pkcs12-mac.d.ts +2 -2
  34. package/dist/pkcs/pkcs12-mac.js +175 -2
  35. package/dist/pkcs/pkcs7.d.ts +1 -2
  36. package/dist/pkcs/pkcs7.js +653 -2
  37. package/dist/pkcs.d.ts +2 -2
  38. package/dist/pkcs.js +4 -1
  39. package/dist/result/result.d.ts +1 -2
  40. package/dist/result/result.js +111 -2
  41. package/dist/result.js +2 -1
  42. package/dist/revocation/chain.d.ts +4 -5
  43. package/dist/revocation/chain.js +536 -2
  44. package/dist/revocation/crl.d.ts +2 -2
  45. package/dist/revocation/crl.js +1119 -2
  46. package/dist/revocation/ocsp.d.ts +5 -4
  47. package/dist/revocation/ocsp.js +958 -2
  48. package/dist/revocation/revocation.d.ts +1 -2
  49. package/dist/revocation/revocation.js +261 -2
  50. package/dist/revocation.d.ts +2 -2
  51. package/dist/revocation.js +5 -1
  52. package/dist/verify/identity.d.ts +1 -2
  53. package/dist/verify/identity.js +270 -2
  54. package/dist/verify/name-constraints.d.ts +1 -2
  55. package/dist/verify/policy.d.ts +1 -2
  56. package/dist/verify/verify.d.ts +1 -2
  57. package/dist/verify/verify.js +764 -2
  58. package/dist/verify.js +3 -1
  59. package/dist/x509/certificate.d.ts +1 -2
  60. package/dist/x509/certificate.js +151 -2
  61. package/dist/x509/csr.d.ts +1 -2
  62. package/dist/x509/csr.js +71 -2
  63. package/dist/x509/extensions.d.ts +1 -2
  64. package/dist/x509/extensions.js +387 -2
  65. package/dist/x509/name.d.ts +1 -2
  66. package/dist/x509/name.js +173 -2
  67. package/dist/x509/parse.d.ts +84 -2
  68. package/dist/x509/parse.js +1090 -2
  69. package/dist/x509.d.ts +2 -2
  70. package/dist/x509.js +6 -1
  71. package/package.json +74 -34
  72. package/dist/internal/asn1/asn1.js.map +0 -1
  73. package/dist/internal/asn1/der.js.map +0 -1
  74. package/dist/internal/asn1/oids.js.map +0 -1
  75. package/dist/internal/crypto/algorithm-names.js.map +0 -1
  76. package/dist/internal/crypto/ecdsa.js.map +0 -1
  77. package/dist/internal/crypto/hash.js.map +0 -1
  78. package/dist/internal/crypto/pbes2.d.ts +0 -23
  79. package/dist/internal/crypto/pbes2.js.map +0 -1
  80. package/dist/internal/crypto/rsa-pss.js.map +0 -1
  81. package/dist/internal/crypto/sig-verify.js.map +0 -1
  82. package/dist/internal/crypto/signing.js.map +0 -1
  83. package/dist/internal/crypto/webcrypto.js.map +0 -1
  84. package/dist/internal/shared/base64.js.map +0 -1
  85. package/dist/internal/shared/dn.js.map +0 -1
  86. package/dist/internal/shared/ip.js.map +0 -1
  87. package/dist/internal/verify/name-constraints-engine.js.map +0 -1
  88. package/dist/internal/verify/policy-engine.js.map +0 -1
  89. package/dist/internal/verify/verify-path.js.map +0 -1
  90. package/dist/internal/x509/extension-bits.js.map +0 -1
  91. package/dist/internal/x509/extension-registry.js.map +0 -1
  92. package/dist/internal/x509/name-fields.js.map +0 -1
  93. package/dist/keys/keys.js.map +0 -1
  94. package/dist/pem/pem.js.map +0 -1
  95. package/dist/pkcs/pfx.js.map +0 -1
  96. package/dist/pkcs/pkcs12-mac.js.map +0 -1
  97. package/dist/pkcs/pkcs7.js.map +0 -1
  98. package/dist/result/result.js.map +0 -1
  99. package/dist/revocation/chain.js.map +0 -1
  100. package/dist/revocation/crl.js.map +0 -1
  101. package/dist/revocation/ocsp.js.map +0 -1
  102. package/dist/revocation/revocation.js.map +0 -1
  103. package/dist/verify/identity.js.map +0 -1
  104. package/dist/verify/verify.js.map +0 -1
  105. package/dist/x509/certificate.js.map +0 -1
  106. package/dist/x509/csr.js.map +0 -1
  107. package/dist/x509/extensions.js.map +0 -1
  108. package/dist/x509/name.js.map +0 -1
  109. package/dist/x509/parse.js.map +0 -1
@@ -1,2 +1,1119 @@
1
- import{bitString as e,concatBytes as t,explicitContext as n,generalizedTime as r,implicitConstructedContext as i,implicitPrimitiveContext as a,integer as o,integerFromNumber as s,readElement as c,readRootElement as l,readSequenceChildren as u,sequence as d,time as f,tlv as p}from"../internal/asn1/der.js";import{childrenOf as m,decodeBoolean as ee,decodeIntegerNumber as h,decodeObjectIdentifier as g,decodeString as _,extractBitStringValue as v,hexToBytes as y,parseTime as b,requireElement as x,toHex as S}from"../internal/asn1/asn1.js";import{OIDS as C}from"../internal/asn1/oids.js";import{base64Encode as w}from"../internal/shared/base64.js";import{failureResult as T,rethrowIfInvariant as E,successResult as D}from"../result/result.js";import{pemDecodeOrThrow as te,pemEncode as ne}from"../pem/pem.js";import{exportSpkiDer as re}from"../keys/keys.js";import{describeSignatureAlgorithm as ie}from"../internal/crypto/algorithm-names.js";import{decodeIpAddress as ae}from"../internal/shared/ip.js";import{encodeDistributionPointReasonFlagsContent as oe,parseDistributionPointReasonFlagsContent as O}from"../internal/x509/extension-bits.js";import{nameFieldKeyFromOid as se}from"../internal/x509/name-fields.js";import{encodeName as ce,encodeRelativeDistinguishedName as le}from"../x509/name.js";import{buildSubjectKeyIdentifier as ue,encodeCrlDistributionPoints as de,encodeExtension as k,encodeSubjectAltName as fe}from"../x509/extensions.js";import{parseCertificateDerOrThrow as pe,parseCertificateFromSource as A}from"../x509/parse.js";import{verifySignedDataDetailed as j}from"../internal/crypto/sig-verify.js";import{encodeAlgorithmIdentifier as M,getSignatureAlgorithm as me,signBytes as he}from"../internal/crypto/signing.js";import{compareDistinguishedNames as N,compareNameAttributeValue as ge}from"../internal/shared/dn.js";const _e={unspecified:0,keyCompromise:1,cACompromise:2,affiliationChanged:3,superseded:4,cessationOfOperation:5,certificateHold:6,removeFromCRL:8,privilegeWithdrawn:9,aACompromise:10};async function ve(t){let r=me(t.signerPrivateKey),i=t.thisUpdate??new Date,a=t.nextUpdate,o=await Ie(t.issuerPublicKey,t.crlNumber,t.baseCrlNumber,t.issuingDistributionPoint,t.freshestCrlDistributionPoints),c=t.revokedCertificates??[],l=c.length===0?[]:[d(c.map(e=>Le(e,i)))],u=d([s(1),M(r),ce(t.issuer),f(i),...a===void 0?[]:[f(a)],...l,...o.length===0?[]:[n(0,d(o))]]),p=await he(t.signerPrivateKey,r,u),m=d([u,M(r),e(p)]);return{der:m,pem:ne(`X509 CRL`,m),base64:w(m)}}function P(e){let t=u(e,{maxDepth:64});if(t.length!==3)throw Error(`Malformed CRL`);let n=x(t[0],`TBSCertList`),r=x(t[1],`signatureAlgorithm`),i=x(t[2],`signatureValue`),a=ot(e.slice(n.start-n.headerLength,n.end)),o=tt(e,r);return{der:new Uint8Array(e),version:a.version,tbsCertListDer:e.slice(n.start-n.headerLength,n.end),signatureValue:v(i),issuer:a.issuer,thisUpdate:a.thisUpdate,...a.nextUpdate===void 0?{}:{nextUpdate:a.nextUpdate},signatureAlgorithmOid:o.oid,signatureAlgorithmName:ie(o.oid,o.parametersDer),...o.parametersDer===void 0?{}:{signatureAlgorithmParametersDer:o.parametersDer},...a.authorityKeyIdentifier===void 0?{}:{authorityKeyIdentifier:a.authorityKeyIdentifier},...a.crlNumber===void 0?{}:{crlNumber:a.crlNumber},...a.baseCrlNumber===void 0?{}:{baseCrlNumber:a.baseCrlNumber},...a.issuingDistributionPoint===void 0?{}:{issuingDistributionPoint:a.issuingDistributionPoint},...a.freshestCrlDistributionPoints===void 0?{}:{freshestCrlDistributionPoints:a.freshestCrlDistributionPoints},revokedCertificates:a.revokedCertificates}}function F(e){return P(te(`X509 CRL`,e))}function ye(e){try{return D(P(e))}catch(e){return E(e),T(`malformed`,e instanceof Error?e.message:`Malformed CRL`)}}function be(e){try{return D(F(e))}catch(e){return E(e),T(`malformed`,e instanceof Error?e.message:`Malformed CRL`)}}async function xe(e,t){let n,r;try{n=typeof e==`string`?F(e):P(new Uint8Array(e)),r=typeof t==`string`?it(t):rt(new Uint8Array(t))}catch{return L(`signature_invalid`,`certificate revocation list or issuer certificate input is malformed`)}let i;try{i=await j(n.signatureAlgorithmOid,n.signatureAlgorithmParametersDer,r.publicKeyAlgorithmOid,r.publicKeyParametersOid,r.subjectPublicKeyInfoDer,n.signatureValue,n.tbsCertListDer)}catch{return L(`signature_invalid`,`certificate revocation list signature verification failed`)}return i.ok?i.valid?{ok:!0,value:n}:L(`signature_invalid`,`certificate revocation list signature does not verify`):i.code===`verification_error`?L(`signature_invalid`,`certificate revocation list signature verification failed`):L(`signature_invalid`,`certificate revocation list signature uses unsupported algorithm parameters`)}async function I(e){let t;try{t=at(e.crl)}catch{return R(`signature_invalid`,`certificate revocation list signed content is malformed`)}let n;try{n=Q(e.issuerCertificate)}catch{return R(`signature_invalid`,`issuer certificate input is malformed`)}if(!N(t.issuer,n.subject))return R(`issuer_mismatch`,`CRL issuer name does not match certificate subject`);if(t.authorityKeyIdentifier!==void 0&&n.subjectKeyIdentifier!==void 0&&t.authorityKeyIdentifier!==n.subjectKeyIdentifier)return R(`issuer_mismatch`,`CRL authority key identifier does not match issuer subject key identifier`);if(n.keyUsage!==void 0&&!n.keyUsage.flags.includes(`cRLSign`))return R(`crl_sign_not_permitted`,`issuer certificate key usage does not permit CRL signing`);let r;try{r=await j(t.signatureAlgorithmOid,t.signatureAlgorithmParametersDer,n.publicKeyAlgorithmOid,n.publicKeyParametersOid,n.subjectPublicKeyInfoDer,t.signatureValue,t.tbsCertListDer)}catch{return R(`signature_invalid`,`certificate revocation list signature verification failed`)}if(!r.ok)return r.code===`verification_error`?R(`signature_invalid`,`certificate revocation list signature verification failed`):R(`signature_invalid`,`certificate revocation list signature uses unsupported algorithm parameters`);if(!r.valid)return R(`signature_invalid`,`certificate revocation list signature does not verify`);let i=e.at??new Date,a=e.clockSkewMs??0;return t.thisUpdate.getTime()-a>i.getTime()||t.nextUpdate!==void 0&&t.nextUpdate.getTime()+a<i.getTime()?R(`stale_crl`,`CRL is not valid at requested time`):{ok:!0,value:t}}async function Se(e){let t;try{t=Q(e.certificate)}catch{return z(`non_applicable`,`certificate input is malformed`)}let n=await I({crl:e.crl,issuerCertificate:e.issuerCertificate,...e.at===void 0?{}:{at:e.at},...e.clockSkewMs===void 0?{}:{clockSkewMs:e.clockSkewMs}});if(!n.ok)return z(n.code,n.message);let r;if(e.deltaCrl!==void 0){let t=await I({crl:e.deltaCrl,issuerCertificate:e.issuerCertificate,...e.at===void 0?{}:{at:e.at},...e.clockSkewMs===void 0?{}:{clockSkewMs:e.clockSkewMs}});if(!t.ok)return z(t.code,t.message);let i=we(n.value,t.value);if(i!==void 0)return i;r=t.value}let i=H(t,n.value);if(i!==void 0)return i;if(r!==void 0){let e=H(t,r,!0);if(e!==void 0)return e}let a=V(t,n.value);if(!a.ok)return a;let o;if(r!==void 0){let e=V(t,r);if(!e.ok)return e;o=e.entry}return De(t,e.at??new Date,n.value,a.entry,o)}function L(e,t){return T(e,t)}function R(e,t){return T(e,t)}function z(e,t,n){return T(e,t,n)}function B(e){return{ok:!0,value:e}}function Ce(e,t){let n=typeof e==`string`?Z(e):S(e);return t.revokedCertificates.some(e=>Z(e.serialNumberHex)===n)}function V(e,t){let n=Z(e.serialNumberHex),r,i=!1,a;for(let o of t.revokedCertificates){if(o.certificateIssuer!==void 0&&(r=o.certificateIssuer),Z(o.serialNumberHex)!==n)continue;let s=Ee(e,t,r);if(s===`match`){if(a!==void 0)return z(`signature_invalid`,`CRL contains multiple revoked entries for certificate`);a=o;continue}s===`unsupported`&&(i=!0)}return a===void 0?i?U(`unsupported_indirect_crl`,`indirect CRL entry certificateIssuer must include a directoryName`):{ok:!0}:{ok:!0,entry:a}}function H(e,t,n=!1){if(!n&&t.baseCrlNumber!==void 0)return U(`unsupported_delta_crl`,`a delta CRL cannot be used as the primary complete CRL input`);let r=t.issuingDistributionPoint,i=r?.indirectCrl===!0;if(!i&&!N(e.issuer,t.issuer))return U(`issuer_mismatch`,`CRL issuer does not match certificate issuer for direct CRL processing`);if(r?.onlyContainsAttributeCerts===!0)return U(`certificate_scope_mismatch`,`attribute-certificate-only CRLs are not applicable to public-key certificates`);let a=e.basicConstraints?.ca===!0;if(r?.onlyContainsUserCerts===!0&&a)return U(`certificate_scope_mismatch`,`CRL only applies to end-entity certificates`);if(r?.onlyContainsCACerts===!0&&!a)return U(`certificate_scope_mismatch`,`CRL only applies to CA certificates`);let o=e.crlDistributionPoints??[];if(o.length===0)return r?.distributionPoint===void 0?i&&!N(e.issuer,t.issuer)?U(`issuer_mismatch`,`indirect CRLs for alternate certificate issuers require matching CRLIssuer distribution points`):void 0:U(`distribution_point_mismatch`,`certificates without CRL distribution points only accept full-scope CRLs`);let s=!1,c=!1,l=!1,u=!1,d=!1;for(let n of o){if(!i&&n.crlIssuer!==void 0){s=!0;continue}if(i&&(!N(e.issuer,t.issuer)||n.crlIssuer!==void 0)){let e=Te(n.crlIssuer,t);if(e===`unsupported`){u=!0;continue}if(!e){l=!0;continue}}if(!Oe(n.distributionPoint,r?.distributionPoint,t.issuer)){c=!0;continue}if(!Pe(n.reasons,r?.onlySomeReasons)){d=!0;continue}return}return d?U(`reasons_mismatch`,`certificate distribution point reasons do not overlap the CRL reason scope`):u?U(`unsupported_indirect_crl`,`indirect CRL distribution points must identify the CRL issuer with directoryName`):l?U(`issuer_mismatch`,`certificate distribution points do not authorize this indirect CRL issuer`):c?U(`distribution_point_mismatch`,`certificate distribution points do not match the CRL issuing distribution point`):s?U(`unsupported_indirect_crl`,`certificate distribution points that name alternate CRL issuers are not supported yet`):U(`distribution_point_mismatch`,`certificate distribution points do not match the CRL scope`)}function we(e,t){if(e.baseCrlNumber!==void 0)return U(`delta_crl_incompatible`,`complete CRL input must not itself be a delta CRL`);if(t.baseCrlNumber===void 0)return U(`delta_crl_incompatible`,`delta CRL input must include a delta CRL indicator`);if(!N(e.issuer,t.issuer))return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same issuer`);if(e.authorityKeyIdentifier!==t.authorityKeyIdentifier)return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same authority key identifier`);if(!Ae(e.issuingDistributionPoint,t.issuingDistributionPoint))return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same issuing distribution point scope`);if(e.crlNumber===void 0||t.crlNumber===void 0)return U(`delta_crl_incompatible`,`complete and delta CRLs must both carry CRL numbers for delta processing`);if(e.crlNumber<t.baseCrlNumber)return U(`delta_crl_incompatible`,`delta CRL base number must not exceed the complete CRL number`);if(e.crlNumber>=t.crlNumber)return U(`delta_crl_incompatible`,`delta CRL number must be newer than the complete CRL number`)}function Te(e,t){if(e===void 0)return!1;let n=!1;for(let r of e){if(r.type===`directoryName`){if(Qe(r.derHex,t.issuer))return!0;continue}n=!0}return n?`unsupported`:!1}function Ee(e,t,n){if(n===void 0)return N(e.issuer,t.issuer)?`match`:`mismatch`;let r=!1;for(let t of n){if(t.type===`directoryName`){if(Qe(t.derHex,e.issuer))return`match`;continue}r=!0}return r?`unsupported`:`mismatch`}function U(e,t){return z(`non_applicable`,t,{reason:e})}function De(e,t,n,r,i){if(i!==void 0)if(i.reasonCode===`removeFromCRL`){if(r?.reasonCode===`certificateHold`||e.notAfter.getTime()<t.getTime())return B({status:`good`,crl:n})}else return B({status:`revoked`,crl:n,revocationDate:i.revocationDate,...i.reasonCode===void 0?{}:{reasonCode:i.reasonCode}});return B(r===void 0?{status:`good`,crl:n}:{status:`revoked`,crl:n,revocationDate:r.revocationDate,...r.reasonCode===void 0?{}:{reasonCode:r.reasonCode}})}function Oe(e,t,n){if(t===void 0)return!0;if(e===void 0)return!1;if(e.fullName!==void 0&&t.fullName!==void 0)return e.fullName.some(e=>t.fullName?.some(t=>G(e,t))===!0);if(e.relativeName!==void 0&&t.fullName!==void 0){let r=W(n,e.relativeName);return t.fullName.some(e=>e.type===`directoryName`&&e.derHex===r)}if(e.relativeName!==void 0&&t.relativeName!==void 0)return K(e.relativeName,t.relativeName);if(e.fullName!==void 0&&t.relativeName!==void 0){let r=W(n,t.relativeName);return e.fullName.some(e=>e.type===`directoryName`&&e.derHex===r)}return!1}function W(e,t){let n=e.rdns.map(e=>y(e.derHex)),r=ke(y(t.derHex));return n.push(r),S(d(n))}function ke(e){return p(49,l(e,{maxDepth:64}).value)}function Ae(e,t){return e===void 0||t===void 0?e===t:je(e.distributionPoint,t.distributionPoint)&&e.onlyContainsUserCerts===!0==(t.onlyContainsUserCerts===!0)&&e.onlyContainsCACerts===!0==(t.onlyContainsCACerts===!0)&&e.indirectCrl===!0==(t.indirectCrl===!0)&&e.onlyContainsAttributeCerts===!0==(t.onlyContainsAttributeCerts===!0)&&Ne(e.onlySomeReasons,t.onlySomeReasons)}function je(e,t){return e===void 0||t===void 0?e===t:e.fullName!==void 0||t.fullName!==void 0?e.fullName===void 0||t.fullName===void 0?!1:Me(e.fullName,t.fullName):e.relativeName===void 0||t.relativeName===void 0?!1:K(e.relativeName,t.relativeName)}function Me(e,t){if(e.length!==t.length)return!1;let n=Array(t.length).fill(!1);for(let r of e){let e=!1;for(let i=0;i<t.length;i+=1){let a=t[i];if(!(a===void 0||n[i])&&G(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}function Ne(e,t){return e===void 0||t===void 0?e===t:e.flags.length===t.flags.length?e.flags.every(e=>t.flags.includes(e)):!1}function Pe(e,t){return e===void 0||t===void 0?!0:e.flags.some(e=>t.flags.includes(e))}function G(e,t){if(e.type===`dns`&&t.type===`dns`||e.type===`email`&&t.type===`email`||e.type===`ip`&&t.type===`ip`||e.type===`uri`&&t.type===`uri`)return e.value===t.value;if(e.type===`directoryName`&&t.type===`directoryName`){let n=X(e.derHex),r=X(t.derHex);return n===void 0||r===void 0?!1:N(n,r)}return e.type===`unknown`&&t.type===`unknown`?e.tag===t.tag&&Fe(e.value,t.value):!1}function Fe(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function K(e,t){if(e.attributes.length!==t.attributes.length)return!1;let n=Array(t.attributes.length).fill(!1);for(let r of e.attributes){let e=!1;for(let i=0;i<t.attributes.length;i+=1){let a=t.attributes[i];if(!(a===void 0||n[i])&&ge(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}async function Ie(e,t,n,r,i){let o=[];if(e!==void 0){let t=await re(e);o.push(k(C.authorityKeyIdentifier,d([a(0,ue(t))])))}return t!==void 0&&o.push(k(C.cRLNumber,s(t))),n!==void 0&&o.push(k(C.deltaCRLIndicator,s(n),!0)),r!==void 0&&o.push(k(C.issuingDistributionPoint,Ke(r),!0)),i!==void 0&&i.length>0&&o.push(k(C.freshestCRL,de(i))),o}function Le(e,t){let n=Re(e);return d([o(e.serialNumber),f(e.revocationDate??t),...n.length===0?[]:[d(n)]])}function Re(e){let t=[];return e.reasonCode!==void 0&&t.push(k(C.cRLReason,p(10,Uint8Array.of(_e[e.reasonCode])))),e.invalidityDate!==void 0&&t.push(k(C.invalidityDate,r(e.invalidityDate))),t}function ze(e,t){if(e===void 0||t===void 0)return{};let n,r,i,a=new Set;for(let o of m(e,t)){let t=m(e,o);if(t.length<2||t.length>3||t.length===3&&t[1]?.tag!==1)throw Error(`Malformed revoked certificate extension`);let s=g(x(t[0],`revoked certificate extension OID`).value);if(a.has(s))throw Error(`Duplicate revoked certificate extension OID: ${s}`);a.add(s);let u=x(t[t.length-1],`revoked certificate extension value`);if(u.tag!==4)throw Error(`Revoked certificate extension value must use OCTET STRING`);if(s===C.cRLReason&&(n=nt(c(u.value).value[0])),s===C.invalidityDate&&(r=b(c(u.value))),s===C.certificateIssuer){let e=l(u.value,{maxDepth:64});if(e.tag!==48)throw Error(`certificateIssuer must use SEQUENCE`);i=J(u.value,e)}}return{...n===void 0?{}:{reasonCode:n},...r===void 0?{}:{invalidityDate:r},...i===void 0?{}:{certificateIssuer:i}}}function Be(e){let t=l(e,{maxDepth:64}),n,r,i,a,o,s;for(let c of m(e,t))if(c.tag===160){if(n!==void 0)throw Error(`IssuingDistributionPoint distributionPoint must not repeat`);let t=q(e,c);t!==void 0&&(n=t)}else if(c.tag===129){if(r!==void 0)throw Error(`IssuingDistributionPoint onlyContainsUserCerts must not repeat`);r=Y(c)}else if(c.tag===130){if(i!==void 0)throw Error(`IssuingDistributionPoint onlyContainsCACerts must not repeat`);i=Y(c)}else if(c.tag===131){if(a!==void 0)throw Error(`IssuingDistributionPoint onlySomeReasons must not repeat`);a=O(c.value)}else if(c.tag===132){if(o!==void 0)throw Error(`IssuingDistributionPoint indirectCrl must not repeat`);o=Y(c)}else if(c.tag===133){if(s!==void 0)throw Error(`IssuingDistributionPoint onlyContainsAttributeCerts must not repeat`);s=Y(c)}else throw Error(`Unsupported IssuingDistributionPoint field tag: ${String(c.tag)}`);if([r,i,s].filter(e=>e===!0).length>1)throw Error(`IssuingDistributionPoint scope booleans are mutually exclusive`);return{...n===void 0?{}:{distributionPoint:n},...r===void 0?{}:{onlyContainsUserCerts:r},...i===void 0?{}:{onlyContainsCACerts:i},...a===void 0?{}:{onlySomeReasons:a},...o===void 0?{}:{indirectCrl:o},...s===void 0?{}:{onlyContainsAttributeCerts:s}}}function Ve(e){let t=l(e,{maxDepth:64});if(t.tag!==48)throw Error(`DistributionPoints must use SEQUENCE`);let n=m(e,t);if(n.length===0)throw Error(`DistributionPoints must not be empty`);return n.map(t=>He(e,t))}function q(e,t){let n=m(e,t);if(n.length!==1)throw Error(`distributionPointName must contain exactly one choice`);let r=x(n[0],`distributionPointName`);if(r.tag===160){let t=m(e,r);if(t.length===0)throw Error(`distributionPointName fullName must not be empty`);for(let e of t)if((e.tag&192)!=128)throw Error(`distributionPointName fullName must contain GeneralName entries`);return{fullName:t.map(e=>Ue(e))}}if(r.tag===161)return{relativeName:We(e,r)};throw Error(`Unsupported distributionPointName tag: ${String(r.tag)}`)}function He(e,t){if(t.tag!==48)throw Error(`DistributionPoint must use SEQUENCE`);let n,r,i;for(let a of m(e,t))if(a.tag===160){if(n!==void 0)throw Error(`DistributionPoint distributionPoint must not repeat`);let t=q(e,a);t!==void 0&&(n=t)}else if(a.tag===129){if(r!==void 0)throw Error(`DistributionPoint reasons must not repeat`);r=O(a.value)}else if(a.tag===162){if(i!==void 0)throw Error(`DistributionPoint crlIssuer must not repeat`);i=J(e,a)}else throw Error(`Unsupported DistributionPoint field tag: ${String(a.tag)}`);if(n===void 0&&i===void 0)throw Error(`DistributionPoint must include distributionPoint or crlIssuer`);return{...n===void 0?{}:{distributionPoint:n},...r===void 0?{}:{reasons:r},...i===void 0?{}:{crlIssuer:i}}}function Ue(e){switch(e.tag){case 129:return{type:`email`,value:$.decode(e.value)};case 130:return{type:`dns`,value:$.decode(e.value)};case 134:return{type:`uri`,value:$.decode(e.value)};case 135:return{type:`ip`,value:ae(e.value)};case 164:return{type:`directoryName`,derHex:S(Ye(e))};default:return{type:`unknown`,tag:e.tag,value:new Uint8Array(e.value)}}}function J(e,t){let n=m(e,t);if(n.length===0)throw Error(`GeneralNames must not be empty`);for(let e of n)if((e.tag&192)!=128)throw Error(`GeneralNames must contain GeneralName entries`);return n.map(e=>Ue(e))}function We(e,t){let n=[],r={};for(let i of m(e,t)){let t=m(e,i),a=g(x(t[0],`name OID`).value),o=x(t[1],`name value`),s=se(a),c=Ge(o),l=s===void 0?{oid:a,valueTag:o.tag,value:c}:{oid:a,key:s,valueTag:o.tag,value:c};n.push(l),s!==void 0&&r[s]===void 0&&(r[s]=c)}return{derHex:S(e.slice(t.start-t.headerLength,t.end)),attributes:n,values:r}}function Ge(e){return _(e.tag,e.value)}function Y(e){return(e.value[0]??0)!==0}function Ke(e){if([e.onlyContainsUserCerts===!0,e.onlyContainsCACerts===!0,e.onlyContainsAttributeCerts===!0].filter(Boolean).length>1)throw Error(`IssuingDistributionPoint can assert at most one of user, CA, or attribute cert scope`);let t=[];return e.distributionPoint!==void 0&&t.push(i(0,qe(e.distributionPoint))),e.onlyContainsUserCerts&&t.push(a(1,Uint8Array.of(255))),e.onlyContainsCACerts&&t.push(a(2,Uint8Array.of(255))),e.onlySomeReasons!==void 0&&e.onlySomeReasons.length>0&&t.push(a(3,oe(e.onlySomeReasons))),e.indirectCrl&&t.push(a(4,Uint8Array.of(255))),e.onlyContainsAttributeCerts&&t.push(a(5,Uint8Array.of(255))),d(t)}function qe(e){if(e===void 0)throw Error(`IssuingDistributionPoint distributionPoint is required`);if(e.fullName!==void 0&&e.relativeName!==void 0)throw Error(`DistributionPointName cannot contain both fullName and relativeName`);if(e.fullName!==void 0){if(e.fullName.length===0)throw Error(`DistributionPointName fullName must not be empty`);return i(0,Je(e.fullName))}if(e.relativeName!==void 0){let t=le(e.relativeName),n=c(t);return i(1,t.slice(n.start,n.end))}throw Error(`DistributionPointName must contain fullName or relativeName`)}function Je(e){return t(e.map(e=>fe(e)))}function Ye(e){return e.value.length>0&&e.value[0]===48?new Uint8Array(e.value):p(48,e.value)}function Xe(e,t){let n=S(e.slice(t.start-t.headerLength,t.end)),r=[],i=[],a={};for(let n of m(e,t)){let t=[],o={};for(let r of m(e,n)){let n=m(e,r),s=x(n[0],`issuer attribute OID`),c=x(n[1],`issuer attribute value`),l=g(s.value),u;try{u=_(c.tag,c.value)}catch{u=$.decode(c.value)}let d=se(l),f=d===void 0?{oid:l,valueTag:c.tag,value:u}:{oid:l,key:d,valueTag:c.tag,value:u};t.push(f),i.push(f),d!==void 0&&(o[d]===void 0&&(o[d]=u),a[d]===void 0&&(a[d]=u))}r.push({derHex:S(e.slice(n.start-n.headerLength,n.end)),attributes:t,values:o})}return{derHex:n,rdns:r,attributes:i,values:a}}function X(e){try{let t=y(e),n=Ze(t,l(t,{maxDepth:64}));return n.tag===48?Xe(t,n):void 0}catch{return}}function Ze(e,t){if(t.tag!==48)return t;let n=m(e,t),r=n[0];return n.length===1&&r?.tag===48?r:t}function Qe(e,t){let n=X(e);return n===void 0?!1:N(n,t)}function $e(e){let t=l(e,{maxDepth:64,allowOpaqueConstructedTags:[161,162]});if(t.tag!==48)throw Error(`authorityKeyIdentifier must use SEQUENCE`);let n,r=!1,i=!1,a=-1;for(let o of m(e,t)){if(o.tag===128){if(n!==void 0)throw Error(`authorityKeyIdentifier keyIdentifier must not repeat`);if(a>=0)throw Error(`authorityKeyIdentifier fields must preserve DER order`);n=S(o.value),a=0;continue}if(o.tag===161){if(r)throw Error(`authorityKeyIdentifier authorityCertIssuer must not repeat`);if(a>=1)throw Error(`authorityKeyIdentifier fields must preserve DER order`);J(e,o),r=!0,a=1;continue}if(o.tag===130){if(i)throw Error(`authorityKeyIdentifier authorityCertSerialNumber must not repeat`);if(a>=2||!r)throw Error(`authorityKeyIdentifier fields must preserve DER order`);et(o.value,`authorityKeyIdentifier authorityCertSerialNumber`),i=!0,a=2;continue}throw Error(`Unsupported authorityKeyIdentifier field tag: ${String(o.tag)}`)}return n}function et(e,t){let n=e[0];if(n===void 0)throw Error(`${t} must not be empty`);if(n&128)throw Error(`${t} must be non-negative`);if(e.length>1&&n===0&&!((e[1]??0)&128))throw Error(`${t} must use minimal encoding`)}function tt(e,t){let n=m(e,t),r=x(n[0],`algorithm OID`),i=n[1];return i===void 0?{oid:g(r.value)}:{oid:g(r.value),parametersDer:e.slice(i.start-i.headerLength,i.end)}}function Z(e){return e.toLowerCase()}function nt(e){switch(e){case 0:return`unspecified`;case 1:return`keyCompromise`;case 2:return`cACompromise`;case 3:return`affiliationChanged`;case 4:return`superseded`;case 5:return`cessationOfOperation`;case 6:return`certificateHold`;case 8:return`removeFromCRL`;case 9:return`privilegeWithdrawn`;case 10:return`aACompromise`}}function rt(e){return A(e)}function it(e){return A(e)}function at(e){if(typeof e==`string`)return F(e);if(e instanceof Uint8Array)return P(new Uint8Array(e));if(ct(e))return P(new Uint8Array(e.der));throw Error(`certificate revocation list input is malformed`)}function ot(e){let t=m(e,l(e,{maxDepth:64})),n=0,r=1,i=t[n];if(i!==void 0&&i.tag!==2&&i.tag!==48)throw Error(`version must use INTEGER`);if(i?.tag===2){let e=x(t[n],`version`);if(e.tag!==2)throw Error(`version must use INTEGER`);if(r=h(e.value)+1,r!==2)throw Error(`Unsupported CRL version: ${String(r)}`);n+=1}n+=1;let a=x(t[n],`issuer`),o=x(t[n+1],`thisUpdate`),s=n+2,d=t[s],f=d!==void 0&&(d.tag===23||d.tag===24)?b(d):void 0;f!==void 0&&(s+=1);let p=[],_=t[s];_?.tag===48&&(p=m(e,_).map(t=>{let n=e.slice(t.start-t.headerLength,t.end),i=u(n),a=x(i[0],`revoked serialNumber`);if(a.tag!==2)throw Error(`revoked serialNumber must use INTEGER`);let o=i[2];if(o!==void 0&&r!==2)throw Error(`revoked certificate extensions require CRL version 2`);let s=ze(n,o);return{serialNumberHex:S(a.value),revocationDate:b(x(i[1],`revocationDate`)),...s.reasonCode===void 0?{}:{reasonCode:s.reasonCode},...s.invalidityDate===void 0?{}:{invalidityDate:s.invalidityDate},...s.certificateIssuer===void 0?{}:{certificateIssuer:s.certificateIssuer}}}),s+=1);let v,y,w,T,E,D=t[s];if(D?.tag===160){if(r!==2)throw Error(`CRL extensions require version 2`);let t=new Set,n=x(m(e,D)[0],`crl extensions`);for(let r of m(e,n)){let n=m(e,r);if(n.length<2||n.length>3||n.length===3&&n[1]?.tag!==1)throw Error(`Malformed CRL extension`);let i=g(x(n[0],`extension OID`).value);if(t.has(i))throw Error(`Duplicate CRL extension OID: ${i}`);t.add(i);let a=n.length===3?ee(x(n[1],`extension critical`).value):!1,o=x(n[n.length-1],`extension value`);if(o.tag!==4)throw Error(`CRL extension value must use OCTET STRING`);if(i!==C.authorityKeyIdentifier&&i!==C.cRLNumber&&i!==C.deltaCRLIndicator&&i!==C.issuingDistributionPoint&&i!==C.freshestCRL&&a)throw Error(`Unsupported critical CRL extension OID: ${i}`);i===C.authorityKeyIdentifier&&(v=$e(o.value)),i===C.cRLNumber&&(y=h(c(o.value).value)),i===C.deltaCRLIndicator&&(w=h(c(o.value).value)),i===C.issuingDistributionPoint&&(T=Be(o.value)),i===C.freshestCRL&&(E=Ve(o.value))}}return{version:r,issuer:Xe(e,a),thisUpdate:b(o),...f===void 0?{}:{nextUpdate:f},...v===void 0?{}:{authorityKeyIdentifier:v},...y===void 0?{}:{crlNumber:y},...w===void 0?{}:{baseCrlNumber:w},...T===void 0?{}:{issuingDistributionPoint:T},...E===void 0?{}:{freshestCrlDistributionPoints:E},revokedCertificates:p}}function Q(e){return st(e)?pe(new Uint8Array(e.der)):A(e)}function st(e){return typeof e!=`string`&&`subjectPublicKeyInfoDer`in e}function ct(e){return`der`in e&&e.der instanceof Uint8Array}const $=new TextDecoder;export{Se as checkCertificateRevocationAgainstCrl,ve as createCertificateRevocationList,Ce as isCertificateRevoked,ye as parseCertificateRevocationListDer,P as parseCertificateRevocationListDerOrThrow,be as parseCertificateRevocationListPem,F as parseCertificateRevocationListPemOrThrow,nt as revocationReasonFromCode,I as validateCertificateRevocationList,xe as verifyCertificateRevocationListSignature};
2
- //# sourceMappingURL=crl.js.map
1
+ import { bitString, concatBytes, explicitContext, generalizedTime, implicitConstructedContext, implicitPrimitiveContext, integer, integerFromNumber, readElement, readRootElement, readSequenceChildren, sequence, time, tlv } from "../internal/asn1/der.js";
2
+ import { childrenOf, decodeBoolean, decodeIntegerNumber, decodeObjectIdentifier, decodeString, extractBitStringValue, hexToBytes, parseTime, requireElement, toHex } from "../internal/asn1/asn1.js";
3
+ import { OIDS } from "../internal/asn1/oids.js";
4
+ import { base64Encode } from "../internal/shared/base64.js";
5
+ import { failureResult, rethrowIfInvariant, successResult } from "../result/result.js";
6
+ import { pemDecodeOrThrow, pemEncode } from "../pem/pem.js";
7
+ import { exportSpkiDer } from "../keys/keys.js";
8
+ import { describeSignatureAlgorithm } from "../internal/crypto/algorithm-names.js";
9
+ import { decodeIpAddress } from "../internal/shared/ip.js";
10
+ import { encodeDistributionPointReasonFlagsContent, parseDistributionPointReasonFlagsContent } from "../internal/x509/extension-bits.js";
11
+ import { nameFieldKeyFromOid } from "../internal/x509/name-fields.js";
12
+ import { encodeName, encodeRelativeDistinguishedName } from "../x509/name.js";
13
+ import { buildSubjectKeyIdentifier, encodeCrlDistributionPoints, encodeExtension, encodeSubjectAltName } from "../x509/extensions.js";
14
+ import { parseCertificateDerOrThrow, parseCertificateFromSource } from "../x509/parse.js";
15
+ import { verifySignedDataDetailed } from "../internal/crypto/sig-verify.js";
16
+ import { encodeAlgorithmIdentifier, getSignatureAlgorithm, signBytes } from "../internal/crypto/signing.js";
17
+ import { compareDistinguishedNames, compareNameAttributeValue } from "../internal/shared/dn.js";
18
+ //#region src/revocation/crl.ts
19
+ /**
20
+ * Full CRL lifecycle: create, parse, verify, validate, and revocation check.
21
+ *
22
+ * Supports complete and delta CRLs, issuing distribution point scoping,
23
+ * indirect CRL processing, per-entry reason codes, and invalidity dates.
24
+ *
25
+ * @module
26
+ */
27
+ /** RFC 5280 §5.3.1 CRLReason integer codes, keyed by reason name. */
28
+ const REVOCATION_REASON_CODES = {
29
+ unspecified: 0,
30
+ keyCompromise: 1,
31
+ cACompromise: 2,
32
+ affiliationChanged: 3,
33
+ superseded: 4,
34
+ cessationOfOperation: 5,
35
+ certificateHold: 6,
36
+ removeFromCRL: 8,
37
+ privilegeWithdrawn: 9,
38
+ aACompromise: 10
39
+ };
40
+ /**
41
+ * Signs and encodes an X.509 v2 CRL.
42
+ *
43
+ * Embeds Authority Key Identifier, CRLNumber, delta CRL indicator,
44
+ * issuing distribution point, and freshest-CRL extensions as configured.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import { createCertificateRevocationList } from 'micro509';
49
+ *
50
+ * const crl = await createCertificateRevocationList({
51
+ * issuer: { commonName: 'Example CA' },
52
+ * signerPrivateKey: caPrivateKey,
53
+ * issuerPublicKey: caPublicKey,
54
+ * thisUpdate: new Date('2025-01-01'),
55
+ * nextUpdate: new Date('2025-02-01'),
56
+ * crlNumber: 42,
57
+ * revokedCertificates: [
58
+ * { serialNumber: revokedSerial, reasonCode: 'keyCompromise' },
59
+ * ],
60
+ * });
61
+ * // crl.pem, crl.der, crl.base64
62
+ * ```
63
+ */
64
+ async function createCertificateRevocationList(input) {
65
+ const signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey);
66
+ const thisUpdate = input.thisUpdate ?? /* @__PURE__ */ new Date();
67
+ const nextUpdate = input.nextUpdate;
68
+ const extensions = await buildCrlExtensions(input.issuerPublicKey, input.crlNumber, input.baseCrlNumber, input.issuingDistributionPoint, input.freshestCrlDistributionPoints);
69
+ const revoked = input.revokedCertificates ?? [];
70
+ const revokedSequence = revoked.length === 0 ? [] : [sequence(revoked.map((entry) => createRevokedCertificate(entry, thisUpdate)))];
71
+ const tbsCertList = sequence([
72
+ integerFromNumber(1),
73
+ encodeAlgorithmIdentifier(signatureAlgorithm),
74
+ encodeName(input.issuer),
75
+ time(thisUpdate),
76
+ ...nextUpdate === void 0 ? [] : [time(nextUpdate)],
77
+ ...revokedSequence,
78
+ ...extensions.length === 0 ? [] : [explicitContext(0, sequence(extensions))]
79
+ ]);
80
+ const signatureValue = await signBytes(input.signerPrivateKey, signatureAlgorithm, tbsCertList);
81
+ const der = sequence([
82
+ tbsCertList,
83
+ encodeAlgorithmIdentifier(signatureAlgorithm),
84
+ bitString(signatureValue)
85
+ ]);
86
+ return {
87
+ der,
88
+ pem: pemEncode("X509 CRL", der),
89
+ base64: base64Encode(der)
90
+ };
91
+ }
92
+ /**
93
+ * Throwing core for {@linkcode parseCertificateRevocationListDer}.
94
+ *
95
+ * Does not verify the signature — call {@linkcode verifyCertificateRevocationListSignature} or
96
+ * {@linkcode validateCertificateRevocationList} for that.
97
+ */
98
+ function parseCertificateRevocationListDerOrThrow(der) {
99
+ const top = readSequenceChildren(der, { maxDepth: 64 });
100
+ if (top.length !== 3) throw new Error("Malformed CRL");
101
+ const tbsCertList = requireElement(top[0], "TBSCertList");
102
+ const signatureAlgorithm = requireElement(top[1], "signatureAlgorithm");
103
+ const signatureValue = requireElement(top[2], "signatureValue");
104
+ const signedFields = parseSignedCrlFields(der.slice(tbsCertList.start - tbsCertList.headerLength, tbsCertList.end));
105
+ const parsedSignatureAlgorithm = parseAlgorithmIdentifier(der, signatureAlgorithm);
106
+ return {
107
+ der: new Uint8Array(der),
108
+ version: signedFields.version,
109
+ tbsCertListDer: der.slice(tbsCertList.start - tbsCertList.headerLength, tbsCertList.end),
110
+ signatureValue: extractBitStringValue(signatureValue),
111
+ issuer: signedFields.issuer,
112
+ thisUpdate: signedFields.thisUpdate,
113
+ ...signedFields.nextUpdate === void 0 ? {} : { nextUpdate: signedFields.nextUpdate },
114
+ signatureAlgorithmOid: parsedSignatureAlgorithm.oid,
115
+ signatureAlgorithmName: describeSignatureAlgorithm(parsedSignatureAlgorithm.oid, parsedSignatureAlgorithm.parametersDer),
116
+ ...parsedSignatureAlgorithm.parametersDer === void 0 ? {} : { signatureAlgorithmParametersDer: parsedSignatureAlgorithm.parametersDer },
117
+ ...signedFields.authorityKeyIdentifier === void 0 ? {} : { authorityKeyIdentifier: signedFields.authorityKeyIdentifier },
118
+ ...signedFields.crlNumber === void 0 ? {} : { crlNumber: signedFields.crlNumber },
119
+ ...signedFields.baseCrlNumber === void 0 ? {} : { baseCrlNumber: signedFields.baseCrlNumber },
120
+ ...signedFields.issuingDistributionPoint === void 0 ? {} : { issuingDistributionPoint: signedFields.issuingDistributionPoint },
121
+ ...signedFields.freshestCrlDistributionPoints === void 0 ? {} : { freshestCrlDistributionPoints: signedFields.freshestCrlDistributionPoints },
122
+ revokedCertificates: signedFields.revokedCertificates
123
+ };
124
+ }
125
+ /**
126
+ * Decodes a PEM-encoded X.509 CRL (`-----BEGIN X509 CRL-----`).
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * import { parseCertificateRevocationListPemOrThrow } from 'micro509';
131
+ *
132
+ * const crl = parseCertificateRevocationListPemOrThrow(pemString); // throws if malformed
133
+ * console.log(crl.issuer.values.commonName, crl.revokedCertificates.length);
134
+ * ```
135
+ */
136
+ function parseCertificateRevocationListPemOrThrow(pem) {
137
+ return parseCertificateRevocationListDerOrThrow(pemDecodeOrThrow("X509 CRL", pem));
138
+ }
139
+ /**
140
+ * Decodes a DER-encoded X.509 CRL into a structured {@linkcode ParsedCertificateRevocationList}.
141
+ *
142
+ * Returns a typed failure (`code: 'malformed'`) on malformed input. For the
143
+ * throwing form use {@linkcode parseCertificateRevocationListDerOrThrow}.
144
+ * Does not verify the signature — call {@linkcode verifyCertificateRevocationListSignature} or
145
+ * {@linkcode validateCertificateRevocationList} for that.
146
+ */
147
+ function parseCertificateRevocationListDer(der) {
148
+ try {
149
+ return successResult(parseCertificateRevocationListDerOrThrow(der));
150
+ } catch (error) {
151
+ rethrowIfInvariant(error);
152
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed CRL");
153
+ }
154
+ }
155
+ /**
156
+ * Decodes a PEM-encoded X.509 CRL (`-----BEGIN X509 CRL-----`).
157
+ *
158
+ * Returns a typed failure (`code: 'malformed'`) on malformed input. For the
159
+ * throwing form use {@linkcode parseCertificateRevocationListPemOrThrow}.
160
+ */
161
+ function parseCertificateRevocationListPem(pem) {
162
+ try {
163
+ return successResult(parseCertificateRevocationListPemOrThrow(pem));
164
+ } catch (error) {
165
+ rethrowIfInvariant(error);
166
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed CRL");
167
+ }
168
+ }
169
+ /**
170
+ * Verifies the CRL signature against the issuer certificate's public key.
171
+ *
172
+ * Does **not** check issuer name match, key-usage, or freshness — use
173
+ * {@linkcode validateCertificateRevocationList} for full validation.
174
+ */
175
+ async function verifyCertificateRevocationListSignature(crl, issuerCertificate) {
176
+ let parsedCrl;
177
+ let issuer;
178
+ try {
179
+ parsedCrl = typeof crl === "string" ? parseCertificateRevocationListPemOrThrow(crl) : parseCertificateRevocationListDerOrThrow(new Uint8Array(crl));
180
+ issuer = typeof issuerCertificate === "string" ? parseIssuerCertificatePem(issuerCertificate) : parseIssuerCertificateDer(new Uint8Array(issuerCertificate));
181
+ } catch {
182
+ return verifyCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list or issuer certificate input is malformed");
183
+ }
184
+ let verifiedResult;
185
+ try {
186
+ verifiedResult = await verifySignedDataDetailed(parsedCrl.signatureAlgorithmOid, parsedCrl.signatureAlgorithmParametersDer, issuer.publicKeyAlgorithmOid, issuer.publicKeyParametersOid, issuer.subjectPublicKeyInfoDer, parsedCrl.signatureValue, parsedCrl.tbsCertListDer);
187
+ } catch {
188
+ return verifyCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature verification failed");
189
+ }
190
+ if (!verifiedResult.ok) {
191
+ if (verifiedResult.code === "verification_error") return verifyCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature verification failed");
192
+ return verifyCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature uses unsupported algorithm parameters");
193
+ }
194
+ return verifiedResult.valid ? {
195
+ ok: true,
196
+ value: parsedCrl
197
+ } : verifyCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature does not verify");
198
+ }
199
+ /**
200
+ * Full CRL validation: issuer name match, authority key identifier match,
201
+ * cRLSign key-usage check, signature verification, and `thisUpdate`/`nextUpdate`
202
+ * freshness check (with optional clock-skew tolerance).
203
+ */
204
+ async function validateCertificateRevocationList(input) {
205
+ let parsedCrl;
206
+ try {
207
+ parsedCrl = normalizeCrl(input.crl);
208
+ } catch {
209
+ return validateCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signed content is malformed");
210
+ }
211
+ let issuer;
212
+ try {
213
+ issuer = normalizeCrlCertificate(input.issuerCertificate);
214
+ } catch {
215
+ return validateCertificateRevocationListFailureResult("signature_invalid", "issuer certificate input is malformed");
216
+ }
217
+ if (!compareDistinguishedNames(parsedCrl.issuer, issuer.subject)) return validateCertificateRevocationListFailureResult("issuer_mismatch", "CRL issuer name does not match certificate subject");
218
+ if (parsedCrl.authorityKeyIdentifier !== void 0 && issuer.subjectKeyIdentifier !== void 0 && parsedCrl.authorityKeyIdentifier !== issuer.subjectKeyIdentifier) return validateCertificateRevocationListFailureResult("issuer_mismatch", "CRL authority key identifier does not match issuer subject key identifier");
219
+ if (issuer.keyUsage !== void 0 && !issuer.keyUsage.flags.includes("cRLSign")) return validateCertificateRevocationListFailureResult("crl_sign_not_permitted", "issuer certificate key usage does not permit CRL signing");
220
+ let verifiedResult;
221
+ try {
222
+ verifiedResult = await verifySignedDataDetailed(parsedCrl.signatureAlgorithmOid, parsedCrl.signatureAlgorithmParametersDer, issuer.publicKeyAlgorithmOid, issuer.publicKeyParametersOid, issuer.subjectPublicKeyInfoDer, parsedCrl.signatureValue, parsedCrl.tbsCertListDer);
223
+ } catch {
224
+ return validateCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature verification failed");
225
+ }
226
+ if (!verifiedResult.ok) {
227
+ if (verifiedResult.code === "verification_error") return validateCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature verification failed");
228
+ return validateCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature uses unsupported algorithm parameters");
229
+ }
230
+ if (!verifiedResult.valid) return validateCertificateRevocationListFailureResult("signature_invalid", "certificate revocation list signature does not verify");
231
+ const at = input.at ?? /* @__PURE__ */ new Date();
232
+ const skew = input.clockSkewMs ?? 0;
233
+ if (parsedCrl.thisUpdate.getTime() - skew > at.getTime() || parsedCrl.nextUpdate !== void 0 && parsedCrl.nextUpdate.getTime() + skew < at.getTime()) return validateCertificateRevocationListFailureResult("stale_crl", "CRL is not valid at requested time");
234
+ return {
235
+ ok: true,
236
+ value: parsedCrl
237
+ };
238
+ }
239
+ /**
240
+ * End-to-end revocation check: validates the CRL (and optional delta CRL),
241
+ * verifies applicability via distribution-point and scope matching, then
242
+ * resolves the certificate's revocation status.
243
+ *
244
+ * Returns `good` if the serial is absent, `revoked` with date/reason if present,
245
+ * or an error if the CRL cannot be validated or is non-applicable.
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * import { checkCertificateRevocationAgainstCrl } from 'micro509';
250
+ *
251
+ * const result = await checkCertificateRevocationAgainstCrl({
252
+ * certificate: leafPem,
253
+ * issuerCertificate: caPem,
254
+ * crl: crlPem,
255
+ * });
256
+ * if (result.ok && result.value.status === 'revoked') {
257
+ * console.log('revoked on', result.value.revocationDate);
258
+ * }
259
+ * ```
260
+ */
261
+ async function checkCertificateRevocationAgainstCrl(input) {
262
+ let certificate;
263
+ try {
264
+ certificate = normalizeCrlCertificate(input.certificate);
265
+ } catch {
266
+ return checkCertificateRevocationAgainstCrlFailureResult("non_applicable", "certificate input is malformed");
267
+ }
268
+ const validated = await validateCertificateRevocationList({
269
+ crl: input.crl,
270
+ issuerCertificate: input.issuerCertificate,
271
+ ...input.at === void 0 ? {} : { at: input.at },
272
+ ...input.clockSkewMs === void 0 ? {} : { clockSkewMs: input.clockSkewMs }
273
+ });
274
+ if (!validated.ok) return checkCertificateRevocationAgainstCrlFailureResult(validated.code, validated.message);
275
+ let validatedDelta;
276
+ if (input.deltaCrl !== void 0) {
277
+ const deltaValidation = await validateCertificateRevocationList({
278
+ crl: input.deltaCrl,
279
+ issuerCertificate: input.issuerCertificate,
280
+ ...input.at === void 0 ? {} : { at: input.at },
281
+ ...input.clockSkewMs === void 0 ? {} : { clockSkewMs: input.clockSkewMs }
282
+ });
283
+ if (!deltaValidation.ok) return checkCertificateRevocationAgainstCrlFailureResult(deltaValidation.code, deltaValidation.message);
284
+ const compatibilityFailure = checkDeltaCrlCompatibility(validated.value, deltaValidation.value);
285
+ if (compatibilityFailure !== void 0) return compatibilityFailure;
286
+ validatedDelta = deltaValidation.value;
287
+ }
288
+ const applicabilityFailure = checkCrlApplicability(certificate, validated.value);
289
+ if (applicabilityFailure !== void 0) return applicabilityFailure;
290
+ if (validatedDelta !== void 0) {
291
+ const deltaApplicabilityFailure = checkCrlApplicability(certificate, validatedDelta, true);
292
+ if (deltaApplicabilityFailure !== void 0) return deltaApplicabilityFailure;
293
+ }
294
+ const completeRevoked = findRevokedCertificateEntry(certificate, validated.value);
295
+ if (!completeRevoked.ok) return completeRevoked;
296
+ let deltaRevoked;
297
+ if (validatedDelta !== void 0) {
298
+ const deltaLookup = findRevokedCertificateEntry(certificate, validatedDelta);
299
+ if (!deltaLookup.ok) return deltaLookup;
300
+ deltaRevoked = deltaLookup.entry;
301
+ }
302
+ return resolveCertificateRevocationStatus(certificate, input.at ?? /* @__PURE__ */ new Date(), validated.value, completeRevoked.entry, deltaRevoked);
303
+ }
304
+ /** Builds a `VerifyCertificateRevocationListSignatureFailureResult`. */
305
+ function verifyCertificateRevocationListFailureResult(code, message) {
306
+ return failureResult(code, message);
307
+ }
308
+ /** Builds a `ValidateCertificateRevocationListFailureResult`. */
309
+ function validateCertificateRevocationListFailureResult(code, message) {
310
+ return failureResult(code, message);
311
+ }
312
+ /** Builds a `CheckCertificateRevocationAgainstCrlFailureResult`. */
313
+ function checkCertificateRevocationAgainstCrlFailureResult(code, message, details) {
314
+ return failureResult(code, message, details);
315
+ }
316
+ /** Wraps a success value into a `CheckCertificateRevocationAgainstCrlResult`. */
317
+ function checkCertificateRevocationAgainstCrlSuccess(value) {
318
+ return {
319
+ ok: true,
320
+ value
321
+ };
322
+ }
323
+ /**
324
+ * Quick serial-number lookup — returns `true` if the serial appears in the
325
+ * CRL's revoked entries. Does **not** validate the CRL or check applicability.
326
+ */
327
+ function isCertificateRevoked(certificateSerialNumber, crl) {
328
+ const serialNumberHex = typeof certificateSerialNumber === "string" ? normalizeHex(certificateSerialNumber) : toHex(certificateSerialNumber);
329
+ return crl.revokedCertificates.some((entry) => normalizeHex(entry.serialNumberHex) === serialNumberHex);
330
+ }
331
+ /** Searches CRL entries for the certificate's serial, respecting indirect-CRL issuer overrides. */
332
+ function findRevokedCertificateEntry(certificate, crl) {
333
+ const serialNumberHex = normalizeHex(certificate.serialNumberHex);
334
+ let effectiveIssuer;
335
+ let sawUnsupportedIssuer = false;
336
+ let matchedEntry;
337
+ for (const entry of crl.revokedCertificates) {
338
+ if (entry.certificateIssuer !== void 0) effectiveIssuer = entry.certificateIssuer;
339
+ if (normalizeHex(entry.serialNumberHex) !== serialNumberHex) continue;
340
+ const issuerMatch = matchesRevokedEntryIssuer(certificate, crl, effectiveIssuer);
341
+ if (issuerMatch === "match") {
342
+ if (matchedEntry !== void 0) return checkCertificateRevocationAgainstCrlFailureResult("signature_invalid", "CRL contains multiple revoked entries for certificate");
343
+ matchedEntry = entry;
344
+ continue;
345
+ }
346
+ if (issuerMatch === "unsupported") sawUnsupportedIssuer = true;
347
+ }
348
+ if (matchedEntry !== void 0) return {
349
+ ok: true,
350
+ entry: matchedEntry
351
+ };
352
+ if (sawUnsupportedIssuer) return nonApplicable("unsupported_indirect_crl", "indirect CRL entry certificateIssuer must include a directoryName");
353
+ return { ok: true };
354
+ }
355
+ /** RFC 5280 §6.3 CRL applicability: scope, distribution-point, reason, and indirect-CRL checks. */
356
+ function checkCrlApplicability(certificate, crl, allowDeltaCrl = false) {
357
+ if (!allowDeltaCrl && crl.baseCrlNumber !== void 0) return nonApplicable("unsupported_delta_crl", "a delta CRL cannot be used as the primary complete CRL input");
358
+ const issuingDistributionPoint = crl.issuingDistributionPoint;
359
+ const isIndirectCrl = issuingDistributionPoint?.indirectCrl === true;
360
+ if (!isIndirectCrl && !compareDistinguishedNames(certificate.issuer, crl.issuer)) return nonApplicable("issuer_mismatch", "CRL issuer does not match certificate issuer for direct CRL processing");
361
+ if (issuingDistributionPoint?.onlyContainsAttributeCerts === true) return nonApplicable("certificate_scope_mismatch", "attribute-certificate-only CRLs are not applicable to public-key certificates");
362
+ const isCaCertificate = certificate.basicConstraints?.ca === true;
363
+ if (issuingDistributionPoint?.onlyContainsUserCerts === true && isCaCertificate) return nonApplicable("certificate_scope_mismatch", "CRL only applies to end-entity certificates");
364
+ if (issuingDistributionPoint?.onlyContainsCACerts === true && !isCaCertificate) return nonApplicable("certificate_scope_mismatch", "CRL only applies to CA certificates");
365
+ const distributionPoints = certificate.crlDistributionPoints ?? [];
366
+ if (distributionPoints.length === 0) {
367
+ if (issuingDistributionPoint?.distributionPoint !== void 0) return nonApplicable("distribution_point_mismatch", "certificates without CRL distribution points only accept full-scope CRLs");
368
+ if (isIndirectCrl && !compareDistinguishedNames(certificate.issuer, crl.issuer)) return nonApplicable("issuer_mismatch", "indirect CRLs for alternate certificate issuers require matching CRLIssuer distribution points");
369
+ return;
370
+ }
371
+ let sawIndirectDistributionPoint = false;
372
+ let sawDistributionMismatch = false;
373
+ let sawIndirectIssuerMismatch = false;
374
+ let sawIndirectIssuerUnsupported = false;
375
+ let sawReasonsMismatch = false;
376
+ for (const distributionPoint of distributionPoints) {
377
+ if (!isIndirectCrl && distributionPoint.crlIssuer !== void 0) {
378
+ sawIndirectDistributionPoint = true;
379
+ continue;
380
+ }
381
+ if (isIndirectCrl) {
382
+ if (!compareDistinguishedNames(certificate.issuer, crl.issuer) || distributionPoint.crlIssuer !== void 0) {
383
+ const issuerMatch = matchesIndirectCrlIssuer(distributionPoint.crlIssuer, crl);
384
+ if (issuerMatch === "unsupported") {
385
+ sawIndirectIssuerUnsupported = true;
386
+ continue;
387
+ }
388
+ if (!issuerMatch) {
389
+ sawIndirectIssuerMismatch = true;
390
+ continue;
391
+ }
392
+ }
393
+ }
394
+ if (!matchesDistributionPointName(distributionPoint.distributionPoint, issuingDistributionPoint?.distributionPoint, crl.issuer)) {
395
+ sawDistributionMismatch = true;
396
+ continue;
397
+ }
398
+ if (!hasOverlappingReasons(distributionPoint.reasons, issuingDistributionPoint?.onlySomeReasons)) {
399
+ sawReasonsMismatch = true;
400
+ continue;
401
+ }
402
+ return;
403
+ }
404
+ if (sawReasonsMismatch) return nonApplicable("reasons_mismatch", "certificate distribution point reasons do not overlap the CRL reason scope");
405
+ if (sawIndirectIssuerUnsupported) return nonApplicable("unsupported_indirect_crl", "indirect CRL distribution points must identify the CRL issuer with directoryName");
406
+ if (sawIndirectIssuerMismatch) return nonApplicable("issuer_mismatch", "certificate distribution points do not authorize this indirect CRL issuer");
407
+ if (sawDistributionMismatch) return nonApplicable("distribution_point_mismatch", "certificate distribution points do not match the CRL issuing distribution point");
408
+ if (sawIndirectDistributionPoint) return nonApplicable("unsupported_indirect_crl", "certificate distribution points that name alternate CRL issuers are not supported yet");
409
+ return nonApplicable("distribution_point_mismatch", "certificate distribution points do not match the CRL scope");
410
+ }
411
+ /** Verifies that a delta CRL is compatible with the given complete CRL (same issuer, AKI, IDP, and valid numbering). */
412
+ function checkDeltaCrlCompatibility(completeCrl, deltaCrl) {
413
+ if (completeCrl.baseCrlNumber !== void 0) return nonApplicable("delta_crl_incompatible", "complete CRL input must not itself be a delta CRL");
414
+ if (deltaCrl.baseCrlNumber === void 0) return nonApplicable("delta_crl_incompatible", "delta CRL input must include a delta CRL indicator");
415
+ if (!compareDistinguishedNames(completeCrl.issuer, deltaCrl.issuer)) return nonApplicable("delta_crl_incompatible", "complete and delta CRLs must share the same issuer");
416
+ if (completeCrl.authorityKeyIdentifier !== deltaCrl.authorityKeyIdentifier) return nonApplicable("delta_crl_incompatible", "complete and delta CRLs must share the same authority key identifier");
417
+ if (!sameIssuingDistributionPoint(completeCrl.issuingDistributionPoint, deltaCrl.issuingDistributionPoint)) return nonApplicable("delta_crl_incompatible", "complete and delta CRLs must share the same issuing distribution point scope");
418
+ if (completeCrl.crlNumber === void 0 || deltaCrl.crlNumber === void 0) return nonApplicable("delta_crl_incompatible", "complete and delta CRLs must both carry CRL numbers for delta processing");
419
+ if (completeCrl.crlNumber < deltaCrl.baseCrlNumber) return nonApplicable("delta_crl_incompatible", "delta CRL base number must not exceed the complete CRL number");
420
+ if (completeCrl.crlNumber >= deltaCrl.crlNumber) return nonApplicable("delta_crl_incompatible", "delta CRL number must be newer than the complete CRL number");
421
+ }
422
+ /** Checks whether any `crlIssuer` GeneralName matches the CRL's issuer via directoryName DER comparison. */
423
+ function matchesIndirectCrlIssuer(crlIssuerNames, crl) {
424
+ if (crlIssuerNames === void 0) return false;
425
+ let sawUnsupportedName = false;
426
+ for (const generalName of crlIssuerNames) {
427
+ if (generalName.type === "directoryName") {
428
+ if (directoryNameDerHexMatchesParsedName(generalName.derHex, crl.issuer)) return true;
429
+ continue;
430
+ }
431
+ sawUnsupportedName = true;
432
+ }
433
+ return sawUnsupportedName ? "unsupported" : false;
434
+ }
435
+ /** Determines whether a revoked entry's effective issuer matches the certificate's issuer. */
436
+ function matchesRevokedEntryIssuer(certificate, crl, effectiveIssuer) {
437
+ if (effectiveIssuer === void 0) return compareDistinguishedNames(certificate.issuer, crl.issuer) ? "match" : "mismatch";
438
+ let sawUnsupportedName = false;
439
+ for (const generalName of effectiveIssuer) {
440
+ if (generalName.type === "directoryName") {
441
+ if (directoryNameDerHexMatchesParsedName(generalName.derHex, certificate.issuer)) return "match";
442
+ continue;
443
+ }
444
+ sawUnsupportedName = true;
445
+ }
446
+ return sawUnsupportedName ? "unsupported" : "mismatch";
447
+ }
448
+ /** Shorthand for building a `non_applicable` failure result with the given reason. */
449
+ function nonApplicable(reason, message) {
450
+ return checkCertificateRevocationAgainstCrlFailureResult("non_applicable", message, { reason });
451
+ }
452
+ /** Merges complete and delta CRL entries per RFC 5280 §5.2.4 to produce a final `good`/`revoked` status. */
453
+ function resolveCertificateRevocationStatus(certificate, at, completeCrl, completeEntry, deltaEntry) {
454
+ if (deltaEntry !== void 0) if (deltaEntry.reasonCode === "removeFromCRL") {
455
+ if (completeEntry?.reasonCode === "certificateHold" || certificate.notAfter.getTime() < at.getTime()) return checkCertificateRevocationAgainstCrlSuccess({
456
+ status: "good",
457
+ crl: completeCrl
458
+ });
459
+ } else return checkCertificateRevocationAgainstCrlSuccess({
460
+ status: "revoked",
461
+ crl: completeCrl,
462
+ revocationDate: deltaEntry.revocationDate,
463
+ ...deltaEntry.reasonCode === void 0 ? {} : { reasonCode: deltaEntry.reasonCode }
464
+ });
465
+ if (completeEntry === void 0) return checkCertificateRevocationAgainstCrlSuccess({
466
+ status: "good",
467
+ crl: completeCrl
468
+ });
469
+ return checkCertificateRevocationAgainstCrlSuccess({
470
+ status: "revoked",
471
+ crl: completeCrl,
472
+ revocationDate: completeEntry.revocationDate,
473
+ ...completeEntry.reasonCode === void 0 ? {} : { reasonCode: completeEntry.reasonCode }
474
+ });
475
+ }
476
+ /**
477
+ * Returns `true` if the certificate's distribution-point name matches the CRL's IDP name.
478
+ *
479
+ * Per RFC 5280 §4.2.1.13, when the certificate uses `nameRelativeToCRLIssuer` (relativeName),
480
+ * the full distribution point name is formed by appending that RDN to the CRL issuer's DN.
481
+ * This resolved name is then compared against the CRL's IDP fullName directoryName entries.
482
+ */
483
+ function matchesDistributionPointName(certificatePoint, crlPoint, crlIssuer) {
484
+ if (crlPoint === void 0) return true;
485
+ if (certificatePoint === void 0) return false;
486
+ if (certificatePoint.fullName !== void 0 && crlPoint.fullName !== void 0) return certificatePoint.fullName.some((leftName) => crlPoint.fullName?.some((rightName) => compareGeneralNames(leftName, rightName)) === true);
487
+ if (certificatePoint.relativeName !== void 0 && crlPoint.fullName !== void 0) {
488
+ const resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, certificatePoint.relativeName);
489
+ return crlPoint.fullName.some((name) => name.type === "directoryName" && name.derHex === resolvedDnHex);
490
+ }
491
+ if (certificatePoint.relativeName !== void 0 && crlPoint.relativeName !== void 0) return compareRelativeDistinguishedNames(certificatePoint.relativeName, crlPoint.relativeName);
492
+ if (certificatePoint.fullName !== void 0 && crlPoint.relativeName !== void 0) {
493
+ const resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, crlPoint.relativeName);
494
+ return certificatePoint.fullName.some((name) => name.type === "directoryName" && name.derHex === resolvedDnHex);
495
+ }
496
+ return false;
497
+ }
498
+ /** Constructs a full DN by appending an RDN to an existing Name, returning hex-encoded DER. */
499
+ function resolveRelativeNameToDnHex(issuer, relativeName) {
500
+ const rdnDerParts = issuer.rdns.map((rdn) => hexToBytes(rdn.derHex));
501
+ const relativeNameRdnDer = rebuildRelativeNameAsSet(hexToBytes(relativeName.derHex));
502
+ rdnDerParts.push(relativeNameRdnDer);
503
+ return toHex(sequence(rdnDerParts));
504
+ }
505
+ /** Converts an implicit-tagged [1] relativeName to a proper SET-tagged RDN. */
506
+ function rebuildRelativeNameAsSet(implicitTaggedDer) {
507
+ return tlv(49, readRootElement(implicitTaggedDer, { maxDepth: 64 }).value);
508
+ }
509
+ /** Deep-compares two issuing distribution point extensions for delta-CRL compatibility. */
510
+ function sameIssuingDistributionPoint(left, right) {
511
+ if (left === void 0 || right === void 0) return left === right;
512
+ return sameDistributionPointName(left.distributionPoint, right.distributionPoint) && left.onlyContainsUserCerts === true === (right.onlyContainsUserCerts === true) && left.onlyContainsCACerts === true === (right.onlyContainsCACerts === true) && left.indirectCrl === true === (right.indirectCrl === true) && left.onlyContainsAttributeCerts === true === (right.onlyContainsAttributeCerts === true) && sameReasonSet(left.onlySomeReasons, right.onlySomeReasons);
513
+ }
514
+ /** Compares two DistributionPointName values (fullName set or relativeName). */
515
+ function sameDistributionPointName(left, right) {
516
+ if (left === void 0 || right === void 0) return left === right;
517
+ if (left.fullName !== void 0 || right.fullName !== void 0) {
518
+ if (left.fullName === void 0 || right.fullName === void 0) return false;
519
+ return sameGeneralNameSet(left.fullName, right.fullName);
520
+ }
521
+ if (left.relativeName === void 0 || right.relativeName === void 0) return false;
522
+ return compareRelativeDistinguishedNames(left.relativeName, right.relativeName);
523
+ }
524
+ /** Set-equality comparison for GeneralName arrays (order-independent). */
525
+ function sameGeneralNameSet(left, right) {
526
+ if (left.length !== right.length) return false;
527
+ const matched = new Array(right.length).fill(false);
528
+ for (const leftName of left) {
529
+ let found = false;
530
+ for (let index = 0; index < right.length; index += 1) {
531
+ const rightName = right[index];
532
+ if (rightName === void 0 || matched[index]) continue;
533
+ if (!compareGeneralNames(leftName, rightName)) continue;
534
+ matched[index] = true;
535
+ found = true;
536
+ break;
537
+ }
538
+ if (!found) return false;
539
+ }
540
+ return true;
541
+ }
542
+ /** Set-equality comparison for DistributionPointReason arrays. */
543
+ function sameReasonSet(left, right) {
544
+ if (left === void 0 || right === void 0) return left === right;
545
+ if (left.flags.length !== right.flags.length) return false;
546
+ return left.flags.every((reason) => right.flags.includes(reason));
547
+ }
548
+ /** Returns `true` if the certificate's DP reasons overlap the CRL's `onlySomeReasons`, or if either is absent (= all reasons). */
549
+ function hasOverlappingReasons(certificateReasons, crlReasons) {
550
+ if (certificateReasons === void 0 || crlReasons === void 0) return true;
551
+ return certificateReasons.flags.some((reason) => crlReasons.flags.includes(reason));
552
+ }
553
+ /** Value-equality for two GeneralName entries, using DER comparison for directoryName. */
554
+ function compareGeneralNames(left, right) {
555
+ if (left.type === "dns" && right.type === "dns") return left.value === right.value;
556
+ if (left.type === "email" && right.type === "email") return left.value === right.value;
557
+ if (left.type === "ip" && right.type === "ip") return left.value === right.value;
558
+ if (left.type === "uri" && right.type === "uri") return left.value === right.value;
559
+ if (left.type === "directoryName" && right.type === "directoryName") {
560
+ const leftName = parseDerHexName(left.derHex);
561
+ const rightName = parseDerHexName(right.derHex);
562
+ if (leftName === void 0 || rightName === void 0) return false;
563
+ return compareDistinguishedNames(leftName, rightName);
564
+ }
565
+ if (left.type === "unknown" && right.type === "unknown") return left.tag === right.tag && bytesEqual(left.value, right.value);
566
+ return false;
567
+ }
568
+ /** Constant-length byte-array equality check. */
569
+ function bytesEqual(left, right) {
570
+ if (left.length !== right.length) return false;
571
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
572
+ return true;
573
+ }
574
+ /** Set-equality comparison for RDN attribute sets (order-independent, RFC 4518 string prep). */
575
+ function compareRelativeDistinguishedNames(left, right) {
576
+ if (left.attributes.length !== right.attributes.length) return false;
577
+ const matched = new Array(right.attributes.length).fill(false);
578
+ for (const leftAttribute of left.attributes) {
579
+ let found = false;
580
+ for (let index = 0; index < right.attributes.length; index += 1) {
581
+ const rightAttribute = right.attributes[index];
582
+ if (rightAttribute === void 0 || matched[index]) continue;
583
+ if (!compareNameAttributeValue(leftAttribute, rightAttribute)) continue;
584
+ matched[index] = true;
585
+ found = true;
586
+ break;
587
+ }
588
+ if (!found) return false;
589
+ }
590
+ return true;
591
+ }
592
+ /** Assembles the CRL-level v2 extensions (AKI, CRLNumber, deltaCRLIndicator, IDP, freshestCRL). */
593
+ async function buildCrlExtensions(issuerPublicKey, crlNumber, baseCrlNumber, issuingDistributionPoint, freshestCrlDistributionPoints) {
594
+ const extensions = [];
595
+ if (issuerPublicKey !== void 0) {
596
+ const spki = await exportSpkiDer(issuerPublicKey);
597
+ extensions.push(encodeExtension(OIDS.authorityKeyIdentifier, sequence([implicitPrimitiveContext(0, buildSubjectKeyIdentifier(spki))])));
598
+ }
599
+ if (crlNumber !== void 0) extensions.push(encodeExtension(OIDS.cRLNumber, integerFromNumber(crlNumber)));
600
+ if (baseCrlNumber !== void 0) extensions.push(encodeExtension(OIDS.deltaCRLIndicator, integerFromNumber(baseCrlNumber), true));
601
+ if (issuingDistributionPoint !== void 0) extensions.push(encodeExtension(OIDS.issuingDistributionPoint, encodeIssuingDistributionPoint(issuingDistributionPoint), true));
602
+ if (freshestCrlDistributionPoints !== void 0 && freshestCrlDistributionPoints.length > 0) extensions.push(encodeExtension(OIDS.freshestCRL, encodeCrlDistributionPoints(freshestCrlDistributionPoints)));
603
+ return extensions;
604
+ }
605
+ /** DER-encodes a single revokedCertificate SEQUENCE (serial, date, optional extensions). */
606
+ function createRevokedCertificate(entry, thisUpdate) {
607
+ const extensions = buildRevokedCertificateExtensions(entry);
608
+ return sequence([
609
+ integer(entry.serialNumber),
610
+ time(entry.revocationDate ?? thisUpdate),
611
+ ...extensions.length === 0 ? [] : [sequence(extensions)]
612
+ ]);
613
+ }
614
+ /** Encodes CRL entry extensions (reasonCode, invalidityDate). */
615
+ function buildRevokedCertificateExtensions(entry) {
616
+ const extensions = [];
617
+ if (entry.reasonCode !== void 0) extensions.push(encodeExtension(OIDS.cRLReason, tlv(10, Uint8Array.of(REVOCATION_REASON_CODES[entry.reasonCode]))));
618
+ if (entry.invalidityDate !== void 0) extensions.push(encodeExtension(OIDS.invalidityDate, generalizedTime(entry.invalidityDate)));
619
+ return extensions;
620
+ }
621
+ /** Decodes per-entry CRL extensions (reasonCode, invalidityDate, certificateIssuer). */
622
+ function parseRevokedCertificateExtensions(entryDer, element) {
623
+ if (entryDer === void 0 || element === void 0) return {};
624
+ let reasonCode;
625
+ let invalidityDate;
626
+ let certificateIssuer;
627
+ const seenOids = /* @__PURE__ */ new Set();
628
+ for (const extension of childrenOf(entryDer, element)) {
629
+ const parts = childrenOf(entryDer, extension);
630
+ if (parts.length < 2 || parts.length > 3) throw new Error("Malformed revoked certificate extension");
631
+ if (parts.length === 3 && parts[1]?.tag !== 1) throw new Error("Malformed revoked certificate extension");
632
+ const oid = decodeObjectIdentifier(requireElement(parts[0], "revoked certificate extension OID").value);
633
+ if (seenOids.has(oid)) throw new Error(`Duplicate revoked certificate extension OID: ${oid}`);
634
+ seenOids.add(oid);
635
+ const valueElement = requireElement(parts[parts.length - 1], "revoked certificate extension value");
636
+ if (valueElement.tag !== 4) throw new Error("Revoked certificate extension value must use OCTET STRING");
637
+ if (oid === OIDS.cRLReason) reasonCode = revocationReasonFromCode(readElement(valueElement.value).value[0]);
638
+ if (oid === OIDS.invalidityDate) invalidityDate = parseTime(readElement(valueElement.value));
639
+ if (oid === OIDS.certificateIssuer) {
640
+ const generalNames = readRootElement(valueElement.value, { maxDepth: 64 });
641
+ if (generalNames.tag !== 48) throw new Error("certificateIssuer must use SEQUENCE");
642
+ certificateIssuer = parseGeneralNames(valueElement.value, generalNames);
643
+ }
644
+ }
645
+ return {
646
+ ...reasonCode === void 0 ? {} : { reasonCode },
647
+ ...invalidityDate === void 0 ? {} : { invalidityDate },
648
+ ...certificateIssuer === void 0 ? {} : { certificateIssuer }
649
+ };
650
+ }
651
+ /** Decodes the IssuingDistributionPoint extension from its OCTET STRING content. */
652
+ function parseIssuingDistributionPoint(valueDer) {
653
+ const sequenceElement = readRootElement(valueDer, { maxDepth: 64 });
654
+ let distributionPoint;
655
+ let onlyContainsUserCerts;
656
+ let onlyContainsCACerts;
657
+ let onlySomeReasons;
658
+ let indirectCrl;
659
+ let onlyContainsAttributeCerts;
660
+ for (const child of childrenOf(valueDer, sequenceElement)) if (child.tag === 160) {
661
+ if (distributionPoint !== void 0) throw new Error("IssuingDistributionPoint distributionPoint must not repeat");
662
+ const parsedDistributionPoint = parseDistributionPointName(valueDer, child);
663
+ if (parsedDistributionPoint !== void 0) distributionPoint = parsedDistributionPoint;
664
+ } else if (child.tag === 129) {
665
+ if (onlyContainsUserCerts !== void 0) throw new Error("IssuingDistributionPoint onlyContainsUserCerts must not repeat");
666
+ onlyContainsUserCerts = parseImplicitBoolean(child);
667
+ } else if (child.tag === 130) {
668
+ if (onlyContainsCACerts !== void 0) throw new Error("IssuingDistributionPoint onlyContainsCACerts must not repeat");
669
+ onlyContainsCACerts = parseImplicitBoolean(child);
670
+ } else if (child.tag === 131) {
671
+ if (onlySomeReasons !== void 0) throw new Error("IssuingDistributionPoint onlySomeReasons must not repeat");
672
+ onlySomeReasons = parseDistributionPointReasonFlagsContent(child.value);
673
+ } else if (child.tag === 132) {
674
+ if (indirectCrl !== void 0) throw new Error("IssuingDistributionPoint indirectCrl must not repeat");
675
+ indirectCrl = parseImplicitBoolean(child);
676
+ } else if (child.tag === 133) {
677
+ if (onlyContainsAttributeCerts !== void 0) throw new Error("IssuingDistributionPoint onlyContainsAttributeCerts must not repeat");
678
+ onlyContainsAttributeCerts = parseImplicitBoolean(child);
679
+ } else throw new Error(`Unsupported IssuingDistributionPoint field tag: ${String(child.tag)}`);
680
+ if ([
681
+ onlyContainsUserCerts,
682
+ onlyContainsCACerts,
683
+ onlyContainsAttributeCerts
684
+ ].filter((value) => value === true).length > 1) throw new Error("IssuingDistributionPoint scope booleans are mutually exclusive");
685
+ return {
686
+ ...distributionPoint === void 0 ? {} : { distributionPoint },
687
+ ...onlyContainsUserCerts === void 0 ? {} : { onlyContainsUserCerts },
688
+ ...onlyContainsCACerts === void 0 ? {} : { onlyContainsCACerts },
689
+ ...onlySomeReasons === void 0 ? {} : { onlySomeReasons },
690
+ ...indirectCrl === void 0 ? {} : { indirectCrl },
691
+ ...onlyContainsAttributeCerts === void 0 ? {} : { onlyContainsAttributeCerts }
692
+ };
693
+ }
694
+ /** Decodes a SEQUENCE OF DistributionPoint from DER. */
695
+ function parseDistributionPoints(valueDer) {
696
+ const sequenceElement = readRootElement(valueDer, { maxDepth: 64 });
697
+ if (sequenceElement.tag !== 48) throw new Error("DistributionPoints must use SEQUENCE");
698
+ const elements = childrenOf(valueDer, sequenceElement);
699
+ if (elements.length === 0) throw new Error("DistributionPoints must not be empty");
700
+ return elements.map((distributionPoint) => parseDistributionPoint(valueDer, distributionPoint));
701
+ }
702
+ /** Decodes a DistributionPointName (fullName or relativeName). */
703
+ function parseDistributionPointName(valueDer, element) {
704
+ const children = childrenOf(valueDer, element);
705
+ if (children.length !== 1) throw new Error("distributionPointName must contain exactly one choice");
706
+ const distributionPointName = requireElement(children[0], "distributionPointName");
707
+ if (distributionPointName.tag === 160) {
708
+ const fullName = childrenOf(valueDer, distributionPointName);
709
+ if (fullName.length === 0) throw new Error("distributionPointName fullName must not be empty");
710
+ for (const name of fullName) if ((name.tag & 192) !== 128) throw new Error("distributionPointName fullName must contain GeneralName entries");
711
+ return { fullName: fullName.map((name) => parseGeneralName(name)) };
712
+ }
713
+ if (distributionPointName.tag === 161) return { relativeName: parseRelativeName(valueDer, distributionPointName) };
714
+ throw new Error(`Unsupported distributionPointName tag: ${String(distributionPointName.tag)}`);
715
+ }
716
+ /** Decodes a single DistributionPoint SEQUENCE. */
717
+ function parseDistributionPoint(valueDer, element) {
718
+ if (element.tag !== 48) throw new Error("DistributionPoint must use SEQUENCE");
719
+ let distributionPoint;
720
+ let reasons;
721
+ let crlIssuer;
722
+ for (const child of childrenOf(valueDer, element)) if (child.tag === 160) {
723
+ if (distributionPoint !== void 0) throw new Error("DistributionPoint distributionPoint must not repeat");
724
+ const parsedDistributionPoint = parseDistributionPointName(valueDer, child);
725
+ if (parsedDistributionPoint !== void 0) distributionPoint = parsedDistributionPoint;
726
+ } else if (child.tag === 129) {
727
+ if (reasons !== void 0) throw new Error("DistributionPoint reasons must not repeat");
728
+ reasons = parseDistributionPointReasonFlagsContent(child.value);
729
+ } else if (child.tag === 162) {
730
+ if (crlIssuer !== void 0) throw new Error("DistributionPoint crlIssuer must not repeat");
731
+ crlIssuer = parseGeneralNames(valueDer, child);
732
+ } else throw new Error(`Unsupported DistributionPoint field tag: ${String(child.tag)}`);
733
+ if (distributionPoint === void 0 && crlIssuer === void 0) throw new Error("DistributionPoint must include distributionPoint or crlIssuer");
734
+ return {
735
+ ...distributionPoint === void 0 ? {} : { distributionPoint },
736
+ ...reasons === void 0 ? {} : { reasons },
737
+ ...crlIssuer === void 0 ? {} : { crlIssuer }
738
+ };
739
+ }
740
+ /** Decodes a GeneralName from its context-tagged ASN.1 element. */
741
+ function parseGeneralName(element) {
742
+ switch (element.tag) {
743
+ case 129: return {
744
+ type: "email",
745
+ value: textDecoder.decode(element.value)
746
+ };
747
+ case 130: return {
748
+ type: "dns",
749
+ value: textDecoder.decode(element.value)
750
+ };
751
+ case 134: return {
752
+ type: "uri",
753
+ value: textDecoder.decode(element.value)
754
+ };
755
+ case 135: return {
756
+ type: "ip",
757
+ value: decodeIpAddress(element.value)
758
+ };
759
+ case 164: return {
760
+ type: "directoryName",
761
+ derHex: toHex(rebuildDirectoryNameFromImplicit(element))
762
+ };
763
+ default: return {
764
+ type: "unknown",
765
+ tag: element.tag,
766
+ value: new Uint8Array(element.value)
767
+ };
768
+ }
769
+ }
770
+ function parseGeneralNames(valueDer, element) {
771
+ const names = childrenOf(valueDer, element);
772
+ if (names.length === 0) throw new Error("GeneralNames must not be empty");
773
+ for (const name of names) if ((name.tag & 192) !== 128) throw new Error("GeneralNames must contain GeneralName entries");
774
+ return names.map((name) => parseGeneralName(name));
775
+ }
776
+ /** Decodes a RelativeDistinguishedName SET from an implicitly-tagged context element. */
777
+ function parseRelativeName(valueDer, element) {
778
+ const attributes = [];
779
+ const values = {};
780
+ for (const attributeSequence of childrenOf(valueDer, element)) {
781
+ const parts = childrenOf(valueDer, attributeSequence);
782
+ const oid = decodeObjectIdentifier(requireElement(parts[0], "name OID").value);
783
+ const valueElement = requireElement(parts[1], "name value");
784
+ const fieldKey = nameFieldKeyFromOid(oid);
785
+ const fieldValue = decodeNameValue(valueElement);
786
+ const attribute = fieldKey === void 0 ? {
787
+ oid,
788
+ valueTag: valueElement.tag,
789
+ value: fieldValue
790
+ } : {
791
+ oid,
792
+ key: fieldKey,
793
+ valueTag: valueElement.tag,
794
+ value: fieldValue
795
+ };
796
+ attributes.push(attribute);
797
+ if (fieldKey !== void 0 && values[fieldKey] === void 0) values[fieldKey] = fieldValue;
798
+ }
799
+ return {
800
+ derHex: toHex(valueDer.slice(element.start - element.headerLength, element.end)),
801
+ attributes,
802
+ values
803
+ };
804
+ }
805
+ /** Decodes an ASN.1 string element (UTF8String, PrintableString, etc.) to a JS string. */
806
+ function decodeNameValue(element) {
807
+ return decodeString(element.tag, element.value);
808
+ }
809
+ /** Reads an implicitly-tagged BOOLEAN from a context element. Absent content → `false`. */
810
+ function parseImplicitBoolean(element) {
811
+ return (element.value[0] ?? 0) !== 0;
812
+ }
813
+ /** DER-encodes an IssuingDistributionPoint extension value. Throws on mutually-exclusive scope flags. */
814
+ function encodeIssuingDistributionPoint(value) {
815
+ if ([
816
+ value.onlyContainsUserCerts === true,
817
+ value.onlyContainsCACerts === true,
818
+ value.onlyContainsAttributeCerts === true
819
+ ].filter(Boolean).length > 1) throw new Error("IssuingDistributionPoint can assert at most one of user, CA, or attribute cert scope");
820
+ const fields = [];
821
+ if (value.distributionPoint !== void 0) fields.push(implicitConstructedContext(0, encodeDistributionPointName(value.distributionPoint)));
822
+ if (value.onlyContainsUserCerts) fields.push(implicitPrimitiveContext(1, Uint8Array.of(255)));
823
+ if (value.onlyContainsCACerts) fields.push(implicitPrimitiveContext(2, Uint8Array.of(255)));
824
+ if (value.onlySomeReasons !== void 0 && value.onlySomeReasons.length > 0) fields.push(implicitPrimitiveContext(3, encodeDistributionPointReasonFlagsContent(value.onlySomeReasons)));
825
+ if (value.indirectCrl) fields.push(implicitPrimitiveContext(4, Uint8Array.of(255)));
826
+ if (value.onlyContainsAttributeCerts) fields.push(implicitPrimitiveContext(5, Uint8Array.of(255)));
827
+ return sequence(fields);
828
+ }
829
+ /** DER-encodes a DistributionPointName (fullName or relativeName). */
830
+ function encodeDistributionPointName(value) {
831
+ if (value === void 0) throw new Error("IssuingDistributionPoint distributionPoint is required");
832
+ if (value.fullName !== void 0 && value.relativeName !== void 0) throw new Error("DistributionPointName cannot contain both fullName and relativeName");
833
+ if (value.fullName !== void 0) {
834
+ if (value.fullName.length === 0) throw new Error("DistributionPointName fullName must not be empty");
835
+ return implicitConstructedContext(0, concatGeneralNames(value.fullName));
836
+ }
837
+ if (value.relativeName !== void 0) {
838
+ const relativeName = encodeRelativeDistinguishedName(value.relativeName);
839
+ const relativeNameElement = readElement(relativeName);
840
+ return implicitConstructedContext(1, relativeName.slice(relativeNameElement.start, relativeNameElement.end));
841
+ }
842
+ throw new Error("DistributionPointName must contain fullName or relativeName");
843
+ }
844
+ /** DER-encodes and concatenates a list of GeneralName values. */
845
+ function concatGeneralNames(names) {
846
+ return concatBytes(names.map((name) => encodeSubjectAltName(name)));
847
+ }
848
+ /** Re-wraps an implicitly-tagged directoryName as an explicit SEQUENCE (tag 0x30). */
849
+ /**
850
+ * Extracts the Name SEQUENCE from an implicitly-tagged directoryName [4].
851
+ *
852
+ * Handles two encoding styles found in the wild:
853
+ * - Proper implicit: [4] replaces SEQUENCE tag, content is RDN SETs directly → wrap with 0x30
854
+ * - Explicit-like: [4] wraps entire SEQUENCE, content starts with 0x30 → return content as-is
855
+ */
856
+ function rebuildDirectoryNameFromImplicit(element) {
857
+ if (element.value.length > 0 && element.value[0] === 48) return new Uint8Array(element.value);
858
+ return tlv(48, element.value);
859
+ }
860
+ /** Parses a Name SEQUENCE element into a full {@linkcode ParsedName}. */
861
+ function parseIssuer(source, element) {
862
+ const derHex = toHex(source.slice(element.start - element.headerLength, element.end));
863
+ const rdns = [];
864
+ const allAttributes = [];
865
+ const values = {};
866
+ for (const setElement of childrenOf(source, element)) {
867
+ const rdnAttributes = [];
868
+ const rdnValues = {};
869
+ for (const attrSequence of childrenOf(source, setElement)) {
870
+ const parts = childrenOf(source, attrSequence);
871
+ const oidElement = requireElement(parts[0], "issuer attribute OID");
872
+ const valueElement = requireElement(parts[1], "issuer attribute value");
873
+ const oid = decodeObjectIdentifier(oidElement.value);
874
+ let fieldValue;
875
+ try {
876
+ fieldValue = decodeString(valueElement.tag, valueElement.value);
877
+ } catch {
878
+ fieldValue = textDecoder.decode(valueElement.value);
879
+ }
880
+ const fieldKey = nameFieldKeyFromOid(oid);
881
+ const attribute = fieldKey !== void 0 ? {
882
+ oid,
883
+ key: fieldKey,
884
+ valueTag: valueElement.tag,
885
+ value: fieldValue
886
+ } : {
887
+ oid,
888
+ valueTag: valueElement.tag,
889
+ value: fieldValue
890
+ };
891
+ rdnAttributes.push(attribute);
892
+ allAttributes.push(attribute);
893
+ if (fieldKey !== void 0) {
894
+ if (rdnValues[fieldKey] === void 0) rdnValues[fieldKey] = fieldValue;
895
+ if (values[fieldKey] === void 0) values[fieldKey] = fieldValue;
896
+ }
897
+ }
898
+ rdns.push({
899
+ derHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),
900
+ attributes: rdnAttributes,
901
+ values: rdnValues
902
+ });
903
+ }
904
+ return {
905
+ derHex,
906
+ rdns,
907
+ attributes: allAttributes,
908
+ values
909
+ };
910
+ }
911
+ /** Re-parses a hex-encoded DER Name into a {@linkcode ParsedName}. Returns `undefined` on malformed input. */
912
+ function parseDerHexName(hex) {
913
+ try {
914
+ const bytes = hexToBytes(hex);
915
+ const element = unwrapNameElement(bytes, readRootElement(bytes, { maxDepth: 64 }));
916
+ if (element.tag !== 48) return;
917
+ return parseIssuer(bytes, element);
918
+ } catch {
919
+ return;
920
+ }
921
+ }
922
+ function unwrapNameElement(source, element) {
923
+ if (element.tag !== 48) return element;
924
+ const children = childrenOf(source, element);
925
+ const child = children[0];
926
+ if (children.length === 1 && child?.tag === 48) return child;
927
+ return element;
928
+ }
929
+ /** Semantic comparison of a GeneralName directoryName `derHex` against a {@linkcode ParsedName}. */
930
+ function directoryNameDerHexMatchesParsedName(derHex, name) {
931
+ const parsed = parseDerHexName(derHex);
932
+ if (parsed === void 0) return false;
933
+ return compareDistinguishedNames(parsed, name);
934
+ }
935
+ /** Extracts the keyIdentifier field from an AuthorityKeyIdentifier extension value. */
936
+ function parseAuthorityKeyIdentifier(bytes) {
937
+ const sequenceElement = readRootElement(bytes, {
938
+ maxDepth: 64,
939
+ allowOpaqueConstructedTags: [161, 162]
940
+ });
941
+ if (sequenceElement.tag !== 48) throw new Error("authorityKeyIdentifier must use SEQUENCE");
942
+ let keyIdentifier;
943
+ let sawAuthorityCertIssuer = false;
944
+ let sawAuthorityCertSerialNumber = false;
945
+ let lastFieldOrder = -1;
946
+ for (const child of childrenOf(bytes, sequenceElement)) {
947
+ if (child.tag === 128) {
948
+ if (keyIdentifier !== void 0) throw new Error("authorityKeyIdentifier keyIdentifier must not repeat");
949
+ if (lastFieldOrder >= 0) throw new Error("authorityKeyIdentifier fields must preserve DER order");
950
+ keyIdentifier = toHex(child.value);
951
+ lastFieldOrder = 0;
952
+ continue;
953
+ }
954
+ if (child.tag === 161) {
955
+ if (sawAuthorityCertIssuer) throw new Error("authorityKeyIdentifier authorityCertIssuer must not repeat");
956
+ if (lastFieldOrder >= 1) throw new Error("authorityKeyIdentifier fields must preserve DER order");
957
+ parseGeneralNames(bytes, child);
958
+ sawAuthorityCertIssuer = true;
959
+ lastFieldOrder = 1;
960
+ continue;
961
+ }
962
+ if (child.tag === 130) {
963
+ if (sawAuthorityCertSerialNumber) throw new Error("authorityKeyIdentifier authorityCertSerialNumber must not repeat");
964
+ if (lastFieldOrder >= 2 || !sawAuthorityCertIssuer) throw new Error("authorityKeyIdentifier fields must preserve DER order");
965
+ validateImplicitSerialNumberEncoding(child.value, "authorityKeyIdentifier authorityCertSerialNumber");
966
+ sawAuthorityCertSerialNumber = true;
967
+ lastFieldOrder = 2;
968
+ continue;
969
+ }
970
+ throw new Error(`Unsupported authorityKeyIdentifier field tag: ${String(child.tag)}`);
971
+ }
972
+ return keyIdentifier;
973
+ }
974
+ function validateImplicitSerialNumberEncoding(bytes, label) {
975
+ const first = bytes[0];
976
+ if (first === void 0) throw new Error(`${label} must not be empty`);
977
+ if ((first & 128) !== 0) throw new Error(`${label} must be non-negative`);
978
+ if (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 128) === 0) throw new Error(`${label} must use minimal encoding`);
979
+ }
980
+ /** Extracts the algorithm OID from an AlgorithmIdentifier SEQUENCE. */
981
+ function parseAlgorithmIdentifier(source, element) {
982
+ const children = childrenOf(source, element);
983
+ const oid = requireElement(children[0], "algorithm OID");
984
+ const parameters = children[1];
985
+ return parameters === void 0 ? { oid: decodeObjectIdentifier(oid.value) } : {
986
+ oid: decodeObjectIdentifier(oid.value),
987
+ parametersDer: source.slice(parameters.start - parameters.headerLength, parameters.end)
988
+ };
989
+ }
990
+ /** Lowercases a hex string for bytewise serial-number comparison. */
991
+ function normalizeHex(value) {
992
+ return value.toLowerCase();
993
+ }
994
+ /** Maps an integer CRLReason code back to its {@linkcode RevocationReason} string, or `undefined` for unknown codes. */
995
+ function revocationReasonFromCode(code) {
996
+ switch (code) {
997
+ case 0: return "unspecified";
998
+ case 1: return "keyCompromise";
999
+ case 2: return "cACompromise";
1000
+ case 3: return "affiliationChanged";
1001
+ case 4: return "superseded";
1002
+ case 5: return "cessationOfOperation";
1003
+ case 6: return "certificateHold";
1004
+ case 8: return "removeFromCRL";
1005
+ case 9: return "privilegeWithdrawn";
1006
+ case 10: return "aACompromise";
1007
+ }
1008
+ }
1009
+ /** Thin wrapper — parses a DER-encoded certificate for use as a CRL issuer. */
1010
+ function parseIssuerCertificateDer(der) {
1011
+ return parseCertificateFromSource(der);
1012
+ }
1013
+ /** Thin wrapper — parses a PEM-encoded certificate for use as a CRL issuer. */
1014
+ function parseIssuerCertificatePem(pem) {
1015
+ return parseCertificateFromSource(pem);
1016
+ }
1017
+ /** Accepts PEM, DER, or already-parsed CRL and returns a parsed CRL. */
1018
+ function normalizeCrl(source) {
1019
+ if (typeof source === "string") return parseCertificateRevocationListPemOrThrow(source);
1020
+ if (source instanceof Uint8Array) return parseCertificateRevocationListDerOrThrow(new Uint8Array(source));
1021
+ if (hasReparseableCrlShape(source)) return parseCertificateRevocationListDerOrThrow(new Uint8Array(source.der));
1022
+ throw new Error("certificate revocation list input is malformed");
1023
+ }
1024
+ function parseSignedCrlFields(tbsCertListDer) {
1025
+ const tbsChildren = childrenOf(tbsCertListDer, readRootElement(tbsCertListDer, { maxDepth: 64 }));
1026
+ let index = 0;
1027
+ let version = 1;
1028
+ const firstChild = tbsChildren[index];
1029
+ if (firstChild !== void 0 && firstChild.tag !== 2 && firstChild.tag !== 48) throw new Error("version must use INTEGER");
1030
+ if (firstChild?.tag === 2) {
1031
+ const versionElement = requireElement(tbsChildren[index], "version");
1032
+ if (versionElement.tag !== 2) throw new Error("version must use INTEGER");
1033
+ version = decodeIntegerNumber(versionElement.value) + 1;
1034
+ if (version !== 2) throw new Error(`Unsupported CRL version: ${String(version)}`);
1035
+ index += 1;
1036
+ }
1037
+ index += 1;
1038
+ const issuerElement = requireElement(tbsChildren[index], "issuer");
1039
+ const thisUpdateElement = requireElement(tbsChildren[index + 1], "thisUpdate");
1040
+ let cursor = index + 2;
1041
+ const maybeNextUpdate = tbsChildren[cursor];
1042
+ const nextUpdate = maybeNextUpdate !== void 0 && (maybeNextUpdate.tag === 23 || maybeNextUpdate.tag === 24) ? parseTime(maybeNextUpdate) : void 0;
1043
+ if (nextUpdate !== void 0) cursor += 1;
1044
+ let revokedCertificates = [];
1045
+ const maybeRevoked = tbsChildren[cursor];
1046
+ if (maybeRevoked?.tag === 48) {
1047
+ revokedCertificates = childrenOf(tbsCertListDer, maybeRevoked).map((entry) => {
1048
+ const entryDer = tbsCertListDer.slice(entry.start - entry.headerLength, entry.end);
1049
+ const parts = readSequenceChildren(entryDer);
1050
+ const serialNumber = requireElement(parts[0], "revoked serialNumber");
1051
+ if (serialNumber.tag !== 2) throw new Error("revoked serialNumber must use INTEGER");
1052
+ const entryExtensions = parts[2];
1053
+ if (entryExtensions !== void 0 && version !== 2) throw new Error("revoked certificate extensions require CRL version 2");
1054
+ const parsedEntryExtensions = parseRevokedCertificateExtensions(entryDer, entryExtensions);
1055
+ return {
1056
+ serialNumberHex: toHex(serialNumber.value),
1057
+ revocationDate: parseTime(requireElement(parts[1], "revocationDate")),
1058
+ ...parsedEntryExtensions.reasonCode === void 0 ? {} : { reasonCode: parsedEntryExtensions.reasonCode },
1059
+ ...parsedEntryExtensions.invalidityDate === void 0 ? {} : { invalidityDate: parsedEntryExtensions.invalidityDate },
1060
+ ...parsedEntryExtensions.certificateIssuer === void 0 ? {} : { certificateIssuer: parsedEntryExtensions.certificateIssuer }
1061
+ };
1062
+ });
1063
+ cursor += 1;
1064
+ }
1065
+ let authorityKeyIdentifier;
1066
+ let crlNumber;
1067
+ let baseCrlNumber;
1068
+ let issuingDistributionPoint;
1069
+ let freshestCrlDistributionPoints;
1070
+ const maybeExtensions = tbsChildren[cursor];
1071
+ if (maybeExtensions?.tag === 160) {
1072
+ if (version !== 2) throw new Error("CRL extensions require version 2");
1073
+ const seenOids = /* @__PURE__ */ new Set();
1074
+ const extensionSequence = requireElement(childrenOf(tbsCertListDer, maybeExtensions)[0], "crl extensions");
1075
+ for (const extension of childrenOf(tbsCertListDer, extensionSequence)) {
1076
+ const parts = childrenOf(tbsCertListDer, extension);
1077
+ if (parts.length < 2 || parts.length > 3) throw new Error("Malformed CRL extension");
1078
+ if (parts.length === 3 && parts[1]?.tag !== 1) throw new Error("Malformed CRL extension");
1079
+ const oid = decodeObjectIdentifier(requireElement(parts[0], "extension OID").value);
1080
+ if (seenOids.has(oid)) throw new Error(`Duplicate CRL extension OID: ${oid}`);
1081
+ seenOids.add(oid);
1082
+ const critical = parts.length === 3 ? decodeBoolean(requireElement(parts[1], "extension critical").value) : false;
1083
+ const valueElement = requireElement(parts[parts.length - 1], "extension value");
1084
+ if (valueElement.tag !== 4) throw new Error("CRL extension value must use OCTET STRING");
1085
+ if (oid !== OIDS.authorityKeyIdentifier && oid !== OIDS.cRLNumber && oid !== OIDS.deltaCRLIndicator && oid !== OIDS.issuingDistributionPoint && oid !== OIDS.freshestCRL && critical) throw new Error(`Unsupported critical CRL extension OID: ${oid}`);
1086
+ if (oid === OIDS.authorityKeyIdentifier) authorityKeyIdentifier = parseAuthorityKeyIdentifier(valueElement.value);
1087
+ if (oid === OIDS.cRLNumber) crlNumber = decodeIntegerNumber(readElement(valueElement.value).value);
1088
+ if (oid === OIDS.deltaCRLIndicator) baseCrlNumber = decodeIntegerNumber(readElement(valueElement.value).value);
1089
+ if (oid === OIDS.issuingDistributionPoint) issuingDistributionPoint = parseIssuingDistributionPoint(valueElement.value);
1090
+ if (oid === OIDS.freshestCRL) freshestCrlDistributionPoints = parseDistributionPoints(valueElement.value);
1091
+ }
1092
+ }
1093
+ return {
1094
+ version,
1095
+ issuer: parseIssuer(tbsCertListDer, issuerElement),
1096
+ thisUpdate: parseTime(thisUpdateElement),
1097
+ ...nextUpdate === void 0 ? {} : { nextUpdate },
1098
+ ...authorityKeyIdentifier === void 0 ? {} : { authorityKeyIdentifier },
1099
+ ...crlNumber === void 0 ? {} : { crlNumber },
1100
+ ...baseCrlNumber === void 0 ? {} : { baseCrlNumber },
1101
+ ...issuingDistributionPoint === void 0 ? {} : { issuingDistributionPoint },
1102
+ ...freshestCrlDistributionPoints === void 0 ? {} : { freshestCrlDistributionPoints },
1103
+ revokedCertificates
1104
+ };
1105
+ }
1106
+ /** Accepts PEM, DER, or already-parsed certificate and returns a parsed certificate. */
1107
+ function normalizeCrlCertificate(source) {
1108
+ return hasParsedCertificateShape(source) ? parseCertificateDerOrThrow(new Uint8Array(source.der)) : parseCertificateFromSource(source);
1109
+ }
1110
+ function hasParsedCertificateShape(value) {
1111
+ return typeof value !== "string" && "subjectPublicKeyInfoDer" in value;
1112
+ }
1113
+ function hasReparseableCrlShape(crl) {
1114
+ return "der" in crl && crl.der instanceof Uint8Array;
1115
+ }
1116
+ /** Shared UTF-8 decoder instance. */
1117
+ const textDecoder = new TextDecoder();
1118
+ //#endregion
1119
+ export { checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, revocationReasonFromCode, validateCertificateRevocationList, verifyCertificateRevocationListSignature };