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,1090 @@
1
- import{encodeLength as e,readElement as t,readRootElement as n,readSequenceChildren as r}from"../internal/asn1/der.js";import{childrenOf as i,decodeBoolean as a,decodeIntegerNumber as o,decodeNonNegativeIntegerNumber as s,decodeObjectIdentifier as c,decodeString as l,extractBitStringValue as u,parseTime as d,requireElement as f,toHex as p}from"../internal/asn1/asn1.js";import{OIDS as m}from"../internal/asn1/oids.js";import{failureResult as h,rethrowIfInvariant as g,successResult as _}from"../result/result.js";import{pemDecodeOrThrow as v,splitPemBlocksOrThrow as y}from"../pem/pem.js";import{describePublicKeyAlgorithm as b,describeSignatureAlgorithm as x}from"../internal/crypto/algorithm-names.js";import{decodeIpAddress as S}from"../internal/shared/ip.js";import{parseDistributionPointReasonFlagsContent as C,parseKeyUsageExtension as w}from"../internal/x509/extension-bits.js";import{nameFieldKeyFromOid as T}from"../internal/x509/name-fields.js";import{parseAuthorityInfoAccessMethodOid as E,parseExtendedKeyUsageOid as D}from"./extensions.js";import{decodeAndApplyKnownExtension as O}from"../internal/x509/extension-registry.js";const k=new TextDecoder;function A(e){return e}function j(e){return e}function M(e,t){let n=r(e,{maxDepth:64});if(n.length!==3)throw Error(`Malformed Certificate`);let a=f(n[0],`TBSCertificate`),s=f(n[1],`signatureAlgorithm`),c=f(n[2],`signatureValue`),l=i(e,a),d=0,m=1,h=l[d];if(h?.tag===160){let t=i(e,h),n=f(t[0],`version INTEGER`);if(t.length!==1||n.tag!==2)throw Error(`version must use INTEGER`);if(m=o(n.value)+1,m<1||m>3)throw Error(`Unsupported certificate version: ${String(m)}`);d+=1}let g=f(l[d],`serialNumber`);if(g.tag!==2)throw Error(`serialNumber must use INTEGER`);let _=f(l[d+1],`TBSCertificate signature`),v=f(l[d+2],`issuer`),y=f(l[d+3],`validity`),S=f(l[d+4],`subject`),C=f(l[d+5],`subjectPublicKeyInfo`),w=d+6,T=l[w];if(T?.tag===129){if(m<2)throw Error(`issuerUniqueID requires certificate version 2 or 3`);$(T.value,`issuerUniqueID`),w+=1}let E=l[w];if(E?.tag===130){if(m<2)throw Error(`subjectUniqueID requires certificate version 2 or 3`);$(E.value,`subjectUniqueID`),w+=1}let D=l[w]?.tag===163?l[w]:void 0;if(D!==void 0){if(m!==3)throw Error(`extensions require certificate version 3`);w+=1}if(w!==l.length)throw Error(`Unsupported TBSCertificate field tag: ${String(f(l[w],`TBSCertificate field`).tag)}`);let O=se(e,D),k=le(e,y),A=K(e,C),j=q(e,_),M=q(e,s);ue(j,M);let N=t?.decoders===void 0?void 0:B(O.all,t.decoders),P=t?.decoderMap===void 0?void 0:V(O.all,t.decoderMap);return{der:new Uint8Array(e),version:m,serialNumberHex:p(g.value),tbsCertificateDer:e.slice(a.start-a.headerLength,a.end),subjectPublicKeyInfoDer:e.slice(C.start-C.headerLength,C.end),signatureValue:u(c),issuer:U(e,v),subject:U(e,S),notBefore:k.notBefore,notAfter:k.notAfter,signatureAlgorithmOid:M.oid,signatureAlgorithmName:x(M.oid,M.parametersDer),...M.parametersDer===void 0?{}:{signatureAlgorithmParametersDer:M.parametersDer},publicKeyAlgorithmOid:A.oid,publicKeyAlgorithmName:b(A.oid,A.parametersOid),...A.parametersDer===void 0?{}:{publicKeyAlgorithmParametersDer:A.parametersDer},...A.parametersOid===void 0?{}:{publicKeyParametersOid:A.parametersOid},extensions:O.all,...O.basicConstraints===void 0?{}:{basicConstraints:O.basicConstraints},...O.keyUsage===void 0?{}:{keyUsage:O.keyUsage},...O.extendedKeyUsage===void 0?{}:{extendedKeyUsage:O.extendedKeyUsage},...O.subjectAltNames===void 0?{}:{subjectAltNames:O.subjectAltNames},...O.nameConstraints===void 0?{}:{nameConstraints:O.nameConstraints},...O.certificatePolicies===void 0?{}:{certificatePolicies:O.certificatePolicies},...O.policyMappings===void 0?{}:{policyMappings:O.policyMappings},...O.policyConstraints===void 0?{}:{policyConstraints:O.policyConstraints},...O.inhibitAnyPolicy===void 0?{}:{inhibitAnyPolicy:O.inhibitAnyPolicy},...O.authorityInfoAccess===void 0?{}:{authorityInfoAccess:O.authorityInfoAccess},...O.crlDistributionPoints===void 0?{}:{crlDistributionPoints:O.crlDistributionPoints},...N===void 0?{}:{decodedExtensions:N},...P===void 0?{}:{decodedExtensionMap:P},...O.subjectKeyIdentifier===void 0?{}:{subjectKeyIdentifier:O.subjectKeyIdentifier},...O.authorityKeyIdentifier===void 0?{}:{authorityKeyIdentifier:O.authorityKeyIdentifier}}}function N(e,t){try{return _(M(e,t))}catch(e){return g(e),h(`malformed`,e instanceof Error?e.message:`Malformed certificate`)}}function P(e,t){return M(v(`CERTIFICATE`,e),t)}function ee(e,t){try{return _(P(e,t))}catch(e){return g(e),h(`malformed`,e instanceof Error?e.message:`Malformed certificate`)}}function te(e,t){return typeof e==`string`?I(e,t):[M(new Uint8Array(e),t)]}function ne(e,t){return typeof e==`string`?P(e,t):ae(e)?e:M(new Uint8Array(e),t)}function re(e,t){return I(e,t)}function F(e,t){let n=r(e,{maxDepth:64});if(n.length!==3)throw Error(`Malformed CertificationRequest`);let a=f(n[0],`CertificationRequestInfo`),s=f(n[1],`signatureAlgorithm`),c=f(n[2],`signatureValue`),l=i(e,a);if(l.length<3||l.length>4)throw Error(`Malformed CertificationRequestInfo`);let d=f(l[0],`version`);if(d.tag!==2)throw Error(`version must use INTEGER`);let p=o(d.value)+1;if(p!==1)throw Error(`Unsupported CertificationRequestInfo version: ${String(p)}`);let m=f(l[1],`subject`),h=f(l[2],`subjectPublicKeyInfo`),g=l[3];if(g!==void 0&&g.tag!==160)throw Error(`CertificationRequestInfo attributes must use [0]`);let _=ce(e,g),v=K(e,h),y=q(e,s),S=t?.decoders===void 0?void 0:B(_.all,t.decoders),C=t?.decoderMap===void 0?void 0:V(_.all,t.decoderMap);return{version:p,certificationRequestInfoDer:e.slice(a.start-a.headerLength,a.end),subjectPublicKeyInfoDer:e.slice(h.start-h.headerLength,h.end),signatureValue:u(c),subject:U(e,m),signatureAlgorithmOid:y.oid,signatureAlgorithmName:x(y.oid,y.parametersDer),...y.parametersDer===void 0?{}:{signatureAlgorithmParametersDer:y.parametersDer},publicKeyAlgorithmOid:v.oid,publicKeyAlgorithmName:b(v.oid,v.parametersOid),...v.parametersDer===void 0?{}:{publicKeyAlgorithmParametersDer:v.parametersDer},...v.parametersOid===void 0?{}:{publicKeyParametersOid:v.parametersOid},requestedExtensions:_.all,..._.basicConstraints===void 0?{}:{basicConstraints:_.basicConstraints},..._.keyUsage===void 0?{}:{keyUsage:_.keyUsage},..._.extendedKeyUsage===void 0?{}:{extendedKeyUsage:_.extendedKeyUsage},..._.subjectAltNames===void 0?{}:{subjectAltNames:_.subjectAltNames},..._.nameConstraints===void 0?{}:{nameConstraints:_.nameConstraints},..._.certificatePolicies===void 0?{}:{certificatePolicies:_.certificatePolicies},..._.policyMappings===void 0?{}:{policyMappings:_.policyMappings},..._.policyConstraints===void 0?{}:{policyConstraints:_.policyConstraints},..._.inhibitAnyPolicy===void 0?{}:{inhibitAnyPolicy:_.inhibitAnyPolicy},..._.authorityInfoAccess===void 0?{}:{authorityInfoAccess:_.authorityInfoAccess},..._.crlDistributionPoints===void 0?{}:{crlDistributionPoints:_.crlDistributionPoints},...S===void 0?{}:{decodedExtensions:S},...C===void 0?{}:{decodedExtensionMap:C}}}function ie(e,t){try{return _(F(e,t))}catch(e){return g(e),h(`malformed`,e instanceof Error?e.message:`Malformed certificate signing request`)}}function I(e,t){return y(e).filter(e=>e.label===`CERTIFICATE`).map(e=>M(e.bytes,t))}function ae(e){return`subjectPublicKeyInfoDer`in e}function L(e,t){return F(v(`CERTIFICATE REQUEST`,e),t)}function oe(e,t){try{return _(L(e,t))}catch(e){return g(e),h(`malformed`,e instanceof Error?e.message:`Malformed certificate signing request`)}}function R(e,t){return e.find(e=>e.oid===t)}function z(e,t){let n=R(e,t.oid);if(n!==void 0)return t.decode(n)}function B(e,t){let n=[];for(let r of t){let t=R(e,r.oid);t!==void 0&&n.push({oid:t.oid,critical:t.critical,value:r.decode(t)})}return n}function V(e,t){let n={};for(let r in t){let i=t[r];if(i===void 0)continue;let a=R(e,i.oid);a!==void 0&&(n={...n,[r]:{oid:a.oid,critical:a.critical,value:i.decode(a)}})}return n}function se(e,t){return t===void 0?{all:[]}:H(e,f(i(e,t)[0],`extensions sequence`),`certificate`)}function ce(e,t){if(t===void 0)return{all:[]};if(t.tag!==160)throw Error(`CertificationRequestInfo attributes must use [0]`);let n;for(let r of i(e,t)){let t=i(e,r);if(t.length!==2)throw Error(`Malformed CSR attribute`);if(c(f(t[0],`attribute OID`).value)!==m.extensionRequest)continue;if(n!==void 0)throw Error(`extensionRequest attribute must not repeat`);let a=f(t[1],`attribute values`);if(a.tag!==49)throw Error(`extensionRequest attribute values must use SET`);let o=i(e,a);if(o.length!==1)throw Error(`extensionRequest attribute must contain exactly one value`);n=H(e,f(o[0],`requested extensions`),`csr`)}return n??{all:[]}}function H(e,t,n){let r=[],o={},s=new Set;for(let l of i(e,t)){let t=i(e,l);if(t.length<2||t.length>3)throw Error(`Malformed Extension`);let u=c(f(t[0],`extension OID`).value);if(s.has(u))throw Error(`Duplicate extension OID: ${u}`);s.add(u);let d=1,m=!1,h=t[d];h?.tag===1&&(m=a(h.value),d+=1);let g=f(t[d],`extension value`);if(g.tag!==4||d!==t.length-1)throw Error(`Extension value must use OCTET STRING`);r.push({oid:u,critical:m,valueDer:new Uint8Array(g.value),valueHex:p(g.value)}),O(n,u,o,g.value)}return{all:r,...o}}function U(e,t){let n=[],r=[],a={};for(let o of i(e,t)){let t=G(e,o);n.push(t);for(let e of t.attributes)r.push(e),e.key!==void 0&&a[e.key]===void 0&&(a[e.key]=e.value)}return{derHex:p(e.slice(t.start-t.headerLength,t.end)),rdns:n,attributes:r,values:a}}function W(e,t){return G(e,t)}function G(e,t){let n=[],r={};for(let a of i(e,t)){let t=i(e,a),o=c(f(t[0],`name OID`).value),s=f(t[1],`name value`),u=T(o),d=l(s.tag,s.value),p=u===void 0?{oid:o,valueTag:s.tag,value:d}:{oid:o,key:u,valueTag:s.tag,value:d};n.push(p),u!==void 0&&r[u]===void 0&&(r[u]=d)}return{derHex:p(e.slice(t.start-t.headerLength,t.end)),attributes:n,values:r}}function le(e,t){let n=i(e,t);return{notBefore:d(f(n[0],`notBefore`)),notAfter:d(f(n[1],`notAfter`))}}function K(e,t){if(t.tag!==48)throw Error(`SubjectPublicKeyInfo must use SEQUENCE`);let n=i(e,t);if(n.length!==2)throw Error(`SubjectPublicKeyInfo must contain algorithm and subjectPublicKey`);let r=f(n[0],`SPKI algorithm`);if(r.tag!==48)throw Error(`SubjectPublicKeyInfo algorithm must use SEQUENCE`);let a=q(e,r);return u(f(n[1],`subjectPublicKey BIT STRING`)),a}function q(e,t){let n=i(e,t);if(n.length===0||n.length>2)throw Error(`Malformed AlgorithmIdentifier`);let r=c(f(n[0],`algorithm OID`).value),a=n[1];if(a===void 0)return{oid:r};let o=e.slice(a.start-a.headerLength,a.end);return a?.tag===6?{oid:r,parametersDer:o,parametersOid:c(a.value)}:{oid:r,parametersDer:o}}function ue(e,t){if(e.oid!==t.oid||!de(e.parametersDer,t.parametersDer))throw Error(`Certificate signatureAlgorithm must match TBSCertificate signature`)}function de(e,t){if(e===void 0||t===void 0)return 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 fe(e){let t=n(e,{maxDepth:64});if(t.tag!==48)throw Error(`basicConstraints must use SEQUENCE`);let r=i(e,t),o=!1,c,l=!1,u=!1;for(let e of r){if(e.tag===1){if(l)throw Error(`basicConstraints cA must not repeat`);if(u)throw Error(`basicConstraints cA must precede pathLength`);l=!0,o=a(e.value);continue}if(e.tag===2){if(u)throw Error(`basicConstraints pathLength must not repeat`);u=!0,c=s(e.value,`basicConstraints pathLength`);continue}throw Error(`Unsupported basicConstraints field tag: ${String(e.tag)}`)}if(c!==void 0&&o!==!0)throw Error(`basicConstraints pathLength requires cA = true`);return o?c===void 0?{ca:!0}:{ca:!0,pathLength:c}:{ca:!1}}function pe(e){return w(e)}function me(e){return i(e,f(n(e,{maxDepth:64}),`extendedKeyUsage sequence`)).map(e=>D(c(e.value)))}function he(e){let t=i(e,f(n(e,{maxDepth:64}),`certificatePolicies sequence`));if(t.length===0)throw Error(`certificatePolicies must not be empty`);return t.map(t=>J(e,t))}function J(e,t){let n=i(e,t),r=c(f(n[0],`policyIdentifier`).value),a=n[1];if(n.length>2)throw Error(`policyInformation has unexpected trailing fields`);if(a===void 0)return{policyIdentifier:r};let o=i(e,a);if(o.length===0)throw Error(`policyQualifiers must not be empty`);return{policyIdentifier:r,policyQualifiers:o.map(t=>ge(e,t))}}function ge(e,t){let n=i(e,t),r=c(f(n[0],`policyQualifierId`).value),a=f(n[1],`policyQualifier`);if(n.length>2)throw Error(`policyQualifierInfo has unexpected trailing fields`);if(r===m.cpsPolicyQualifier){if(a.tag!==22)throw Error(`cps policy qualifier must use IA5String`);return{type:`cps`,uri:l(a.tag,a.value)}}return r===m.userNoticePolicyQualifier?{type:`userNotice`,..._e(e,a)}:{type:`oid`,oid:r,qualifierDer:e.slice(a.start-a.headerLength,a.end)}}function _e(e,t){let n=i(e,t),r,a;for(let t of n){if(t.tag===48){if(r!==void 0)throw Error(`userNotice must not contain multiple noticeRef values`);r=ve(e,t);continue}if(a!==void 0)throw Error(`userNotice must not contain multiple explicitText values`);a=Q(t)}return{...r===void 0?{}:{noticeRef:r},...a===void 0?{}:{explicitText:a}}}function ve(e,t){if(t.tag!==48)throw Error(`noticeRef must use SEQUENCE`);let n=i(e,t),r=Q(f(n[0],`noticeRef organization`)),a=f(n[1],`noticeRef noticeNumbers`);if(n.length>2)throw Error(`noticeRef has unexpected trailing fields`);return{organization:r,noticeNumbers:ye(e,a)}}function ye(e,t){if(t.tag!==48)throw Error(`noticeRef noticeNumbers must use SEQUENCE`);let n=i(e,t);if(n.length===0)throw Error(`noticeRef noticeNumbers must not be empty`);return n.map(e=>{if(e.tag!==2)throw Error(`noticeRef noticeNumber must use INTEGER`);return s(e.value,`noticeRef noticeNumber`)})}function be(e){let t=i(e,f(n(e,{maxDepth:64}),`policyMappings sequence`));if(t.length===0)throw Error(`policyMappings must not be empty`);return t.map(t=>{let n=i(e,t),r=c(f(n[0],`policyMappings issuerDomainPolicy`).value),a=c(f(n[1],`policyMappings subjectDomainPolicy`).value);if(n.length>2)throw Error(`policyMappings entry has unexpected trailing fields`);if(r===m.anyPolicy||a===m.anyPolicy)throw Error(`policyMappings must not use anyPolicy`);return{issuerDomainPolicy:r,subjectDomainPolicy:a}})}function xe(e){let t=f(n(e,{maxDepth:64}),`policyConstraints sequence`),r,a;for(let n of i(e,t)){if(n.tag===128){if(r!==void 0)throw Error(`policyConstraints must not repeat requireExplicitPolicy`);r=s(n.value,`policyConstraints requireExplicitPolicy`);continue}if(n.tag===129){if(a!==void 0)throw Error(`policyConstraints must not repeat inhibitPolicyMapping`);a=s(n.value,`policyConstraints inhibitPolicyMapping`);continue}throw Error(`Unsupported policyConstraints field tag: ${n.tag}`)}if(r===void 0&&a===void 0)throw Error(`policyConstraints must set requireExplicitPolicy or inhibitPolicyMapping`);return{...r===void 0?{}:{requireExplicitPolicy:r},...a===void 0?{}:{inhibitPolicyMapping:a}}}function Se(e){let t=f(n(e,{maxDepth:64}),`inhibitAnyPolicy integer`);if(t.tag!==2)throw Error(`inhibitAnyPolicy must be an INTEGER`);return{skipCerts:s(t.value,`inhibitAnyPolicy skipCerts`)}}function Ce(e){return i(e,f(n(e,{maxDepth:64}),`subjectAltName sequence`)).map(t=>Y(e,t))}function we(e){let t=f(n(e,{maxDepth:64}),`authorityInfoAccess sequence`);if(t.tag!==48)throw Error(`authorityInfoAccess must use SEQUENCE`);let r=i(e,t);if(r.length===0)throw Error(`authorityInfoAccess must not be empty`);return r.map(t=>{if(t.tag!==48)throw Error(`authorityInfoAccess entry must use SEQUENCE`);let n=i(e,t);if(n.length!==2)throw Error(`authorityInfoAccess entry must contain method and location only`);let r=f(n[0],`authorityInfoAccess method`),a=f(n[1],`authorityInfoAccess location`);if(r.tag!==6)throw Error(`authorityInfoAccess method must use OBJECT IDENTIFIER`);if(a.tag!==134)throw Error(`Unsupported authorityInfoAccess location tag: ${a.tag}`);return{method:E(c(r.value)),uri:k.decode(a.value)}})}function Te(e){let t=f(n(e,{maxDepth:64}),`CRLDistributionPoints sequence`);if(t.tag!==48)throw Error(`CRLDistributionPoints must use SEQUENCE`);let r=i(e,t);if(r.length===0)throw Error(`CRLDistributionPoints must not be empty`);let a=[];for(let t of r)a.push(Ee(e,t));return a}function Ee(e,t){if(t.tag!==48)throw Error(`DistributionPoint must use SEQUENCE`);let n,r,a;for(let o of i(e,t))if(o.tag===160){if(n!==void 0)throw Error(`DistributionPoint distributionPoint must not repeat`);n=De(e,o)}else if(o.tag===129){if(r!==void 0)throw Error(`DistributionPoint reasons must not repeat`);r=C(o.value)}else if(o.tag===162){if(a!==void 0)throw Error(`DistributionPoint crlIssuer must not repeat`);a=Oe(e,o)}else throw Error(`Unsupported DistributionPoint field tag: ${String(o.tag)}`);if(n===void 0&&a===void 0)throw Error(`DistributionPoint must include distributionPoint or crlIssuer`);return{...n===void 0?{}:{distributionPoint:n},...r===void 0?{}:{reasons:r},...a===void 0?{}:{crlIssuer:a}}}function De(e,t){let n=i(e,t);if(n.length!==1)throw Error(`distributionPointName must contain exactly one choice`);let r=f(n[0],`distributionPointName`);if(r.tag===160){let t=i(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(t=>Y(e,t))}}if(r.tag===161)return{relativeName:W(e,r)};throw Error(`Unsupported distributionPointName tag: ${r.tag}`)}function Oe(e,t){let n=i(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(t=>Y(e,t))}function Y(e,t){switch(t.tag){case 160:{let n=ke(e,t);return n===void 0?{type:`unknown`,tag:t.tag,value:e.slice(t.start,t.end)}:n}case 129:return{type:`email`,value:k.decode(t.value)};case 130:return{type:`dns`,value:k.decode(t.value)};case 134:return{type:`uri`,value:k.decode(t.value)};case 135:return{type:`ip`,value:S(t.value)};case 164:return{type:`directoryName`,derHex:p(Z(t,e))};default:return{type:`unknown`,tag:t.tag,value:e.slice(t.start,t.end)}}}function ke(e,t){let n=i(e,t);if(n.length!==1)throw Error(`otherName must contain exactly one SEQUENCE`);let r=i(e,f(n[0],`otherName sequence`));if(r.length!==2)throw Error(`otherName must contain exactly type-id and value`);let a=f(r[0],`otherName type-id`),o=f(r[1],`otherName value`);if(c(a.value)!==m.idOnDnsSrv)return;if(o.tag!==160)throw Error(`SRV-ID otherName value must use explicit [0]`);let s=i(e,o);if(s.length!==1)throw Error(`SRV-ID otherName value must contain exactly one IA5String`);let u=f(s[0],`SRV-ID IA5String`);if(u.tag!==22)throw Error(`SRV-ID otherName value must be an IA5String`);return{type:`srv`,value:l(u.tag,u.value)}}function Ae(e){let t=f(n(e,{maxDepth:64,allowOpaqueConstructedTags:[160,163,165]}),`nameConstraints sequence`);if(t.tag!==48)throw Error(`nameConstraints must use SEQUENCE`);let r,a;for(let n of i(e,t))if(n.tag===160){if(r!==void 0)throw Error(`nameConstraints permittedSubtrees must not repeat`);r=X(e,n)}else if(n.tag===161){if(a!==void 0)throw Error(`nameConstraints excludedSubtrees must not repeat`);a=X(e,n)}else throw Error(`Unsupported nameConstraints field tag: ${String(n.tag)}`);return{...r===void 0?{}:{permittedSubtrees:r},...a===void 0?{}:{excludedSubtrees:a}}}function X(e,t){let n=[],r=i(e,t);if(r.length===0)throw Error(`name constraints GeneralSubtrees must not be empty`);for(let t of r){if(t.tag!==48)throw Error(`name constraints GeneralSubtree must use SEQUENCE`);let r=i(e,t),a=r[0];if(a===void 0)throw Error(`name constraints GeneralSubtree base is required`);let o=!1;for(let e=1;e<r.length;e+=1){let t=r[e];if(t!==void 0)if(t.tag===128){if(o)throw Error(`name constraints GeneralSubtree minimum must not repeat`);if(o=!0,s(t.value,`name constraints GeneralSubtree minimum`)!==0)throw Error(`name constraints GeneralSubtree minimum must be 0`)}else if(t.tag===129)throw Error(`name constraints GeneralSubtree maximum is not supported`);else throw Error(`Unsupported name constraints GeneralSubtree field tag: ${String(t.tag)}`)}let c=je(e,a);c!==void 0&&n.push({base:c})}return n}function je(e,t){switch(t.tag){case 160:return{type:`otherName`,value:new Uint8Array(t.value)};case 129:return{type:`email`,value:k.decode(t.value)};case 130:return{type:`dns`,value:k.decode(t.value)};case 163:return{type:`x400Address`,value:new Uint8Array(t.value)};case 134:return{type:`uri`,value:k.decode(t.value)};case 135:if(t.value.length===8)return{type:`ip`,addressBytes:t.value.slice(0,4),maskBytes:t.value.slice(4,8)};if(t.value.length===32)return{type:`ip`,addressBytes:t.value.slice(0,16),maskBytes:t.value.slice(16,32)};throw Error(`Invalid IP name constraint: expected 8 (IPv4) or 32 (IPv6) bytes, got ${String(t.value.length)}`);case 164:return{type:`directoryName`,derHex:p(Z(t,e))};case 165:return{type:`ediPartyName`,value:new Uint8Array(t.value)};case 136:return{type:`registeredID`,value:c(t.value)}}throw Error(`Unsupported name constraint GeneralName tag: ${String(t.tag)}`)}function Z(t,n){if(t.value.length>0&&t.value[0]===48)return new Uint8Array(t.value);let r=e(t.value.length),i=new Uint8Array(1+r.length+t.value.length);return i[0]=48,i.set(r,1),i.set(t.value,1+r.length),i}function Q(e){switch(e.tag){case 12:case 22:case 26:return k.decode(e.value);case 30:return Me(e.value);default:throw Error(`Unsupported DisplayText tag: ${e.tag}`)}}function Me(e){if(e.length%2!=0)throw Error(`Invalid BMPString length`);let t=``;for(let n=0;n<e.length;n+=2){let r=e[n],i=e[n+1];if(r===void 0||i===void 0)throw Error(`Invalid BMPString content`);t+=String.fromCharCode(r<<8|i)}return t}function Ne(e){let n=f(t(e,0),`authorityKeyIdentifier sequence`);if(n.end!==e.length)throw Error(`Trailing data after DER element`);let r,a=!1,o=!1,s=-1,c=n.start;for(;c<n.end;){let l=t(e,c);if(l.end>n.end)throw Error(`DER child exceeds parent length`);if(l.tag===128){if(r!==void 0)throw Error(`authorityKeyIdentifier keyIdentifier must not repeat`);if(s>=0)throw Error(`authorityKeyIdentifier fields must preserve DER order`);r=p(l.value),s=0}else if(l.tag===161){if(a)throw Error(`authorityKeyIdentifier authorityCertIssuer must not repeat`);if(s>=1)throw Error(`authorityKeyIdentifier fields must preserve DER order`);let t=i(e,l);if(t.length===0)throw Error(`authorityKeyIdentifier authorityCertIssuer must contain GeneralName entries`);for(let n of t){if((n.tag&192)!=128)throw Error(`authorityKeyIdentifier authorityCertIssuer must contain GeneralName entries`);Y(e,n)}a=!0,s=1}else if(l.tag===130){if(o)throw Error(`authorityKeyIdentifier authorityCertSerialNumber must not repeat`);if(s>=2||!a)throw Error(`authorityKeyIdentifier fields must preserve DER order`);Pe(l.value,`authorityKeyIdentifier authorityCertSerialNumber`),o=!0,s=2}else throw Error(`Unsupported authorityKeyIdentifier field tag: ${String(l.tag)}`);c=l.end}if(c!==n.end)throw Error(`Malformed DER sequence`);if(a!==o)throw Error(`authorityKeyIdentifier authorityCertIssuer and authorityCertSerialNumber must appear together`);return r}function Pe(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 $(e,t){let n=e[0];if(n===void 0||n>7)throw Error(`${t} must use BIT STRING encoding`);let r=e.slice(1);if(r.length===0){if(n!==0)throw Error(`${t} must use BIT STRING encoding`);return}if(n===0)return;let i=r[r.length-1];if(i===void 0)throw Error(`${t} must use BIT STRING encoding`);if(i&(1<<n)-1)throw Error(`${t} BIT STRING must not set padding bits`)}export{z as decodeExtension,V as decodeExtensionMap,B as decodeExtensions,A as defineExtensionDecoder,j as defineExtensionDecoderMap,R as findExtension,we as parseAuthorityInfoAccess,Ne as parseAuthorityKeyIdentifier,fe as parseBasicConstraints,re as parseCertificateChainPem,N as parseCertificateDer,M as parseCertificateDerOrThrow,ne as parseCertificateFromSource,ee as parseCertificatePem,P as parseCertificatePemOrThrow,he as parseCertificatePolicies,ie as parseCertificateSigningRequestDer,F as parseCertificateSigningRequestDerOrThrow,oe as parseCertificateSigningRequestPem,L as parseCertificateSigningRequestPemOrThrow,te as parseCertificatesFromSource,Te as parseCrlDistributionPoints,me as parseExtendedKeyUsage,Se as parseInhibitAnyPolicy,pe as parseKeyUsage,Ae as parseNameConstraints,xe as parsePolicyConstraints,be as parsePolicyMappings,Ce as parseSubjectAltNames};
2
- //# sourceMappingURL=parse.js.map
1
+ import { encodeLength, readElement, readRootElement, readSequenceChildren } from "../internal/asn1/der.js";
2
+ import { childrenOf, decodeBoolean, decodeIntegerNumber, decodeNonNegativeIntegerNumber, decodeObjectIdentifier, decodeString, extractBitStringValue, parseTime, requireElement, toHex } from "../internal/asn1/asn1.js";
3
+ import { OIDS } from "../internal/asn1/oids.js";
4
+ import { failureResult, rethrowIfInvariant, successResult } from "../result/result.js";
5
+ import { pemDecodeOrThrow, splitPemBlocksOrThrow } from "../pem/pem.js";
6
+ import { importSpkiDer, importSpkiDerOrThrow } from "../keys/keys.js";
7
+ import { describePublicKeyAlgorithm, describeSignatureAlgorithm } from "../internal/crypto/algorithm-names.js";
8
+ import { decodeIpAddress } from "../internal/shared/ip.js";
9
+ import { parseDistributionPointReasonFlagsContent, parseKeyUsageExtension } from "../internal/x509/extension-bits.js";
10
+ import { nameFieldKeyFromOid } from "../internal/x509/name-fields.js";
11
+ import { parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
12
+ import { decodeAndApplyKnownExtension } from "../internal/x509/extension-registry.js";
13
+ //#region src/x509/parse.ts
14
+ /**
15
+ * Certificate and CSR parse boundary.
16
+ *
17
+ * Decodes DER and PEM inputs into typed {@linkcode ParsedCertificate} and
18
+ * {@linkcode ParsedCertificateSigningRequest} structures.\
19
+ * Includes an extension-decoder framework for callers that need richer metadata beyond the built-in
20
+ * extensions.
21
+ *
22
+ * @module
23
+ */
24
+ /** Shared UTF-8 decoder for IA5String / UTF8String values. */
25
+ const textDecoder = new TextDecoder();
26
+ /**
27
+ * Identity helper that narrows the type of a custom {@linkcode ExtensionDecoder} literal.
28
+ *
29
+ * @param decoder Decoder definition to return unchanged.
30
+ * @returns The same decoder, properly typed.
31
+ */
32
+ function defineExtensionDecoder(decoder) {
33
+ return decoder;
34
+ }
35
+ /**
36
+ * Identity helper that narrows the type of a custom {@linkcode ExtensionDecoderMap} literal.
37
+ *
38
+ * @param decoderMap Map of named decoders to return unchanged.
39
+ * @returns The same map, properly typed.
40
+ */
41
+ function defineExtensionDecoderMap(decoderMap) {
42
+ return decoderMap;
43
+ }
44
+ /**
45
+ * Throwing core for {@linkcode parseCertificateDer}.
46
+ *
47
+ * Decodes a DER-encoded X.509 certificate into a {@linkcode ParsedCertificate},
48
+ * throwing on malformed input. All built-in extensions (basicConstraints,
49
+ * keyUsage, subjectAltNames, etc.) are decoded automatically.\
50
+ * Pass {@linkcode ParseOptions} to also decode custom extensions.
51
+ *
52
+ * @param der Raw DER bytes of an X.509 certificate.
53
+ * @param options Custom extension decoders to apply during parsing.
54
+ */
55
+ function parseCertificateDerOrThrow(der, options) {
56
+ const topLevel = readSequenceChildren(der, { maxDepth: 64 });
57
+ if (topLevel.length !== 3) throw new Error("Malformed Certificate");
58
+ const tbsCertificate = requireElement(topLevel[0], "TBSCertificate");
59
+ const signatureAlgorithm = requireElement(topLevel[1], "signatureAlgorithm");
60
+ const signatureValue = requireElement(topLevel[2], "signatureValue");
61
+ const tbsChildren = childrenOf(der, tbsCertificate);
62
+ let index = 0;
63
+ let version = 1;
64
+ const maybeVersion = tbsChildren[index];
65
+ if (maybeVersion?.tag === 160) {
66
+ const versionChildren = childrenOf(der, maybeVersion);
67
+ const versionElement = requireElement(versionChildren[0], "version INTEGER");
68
+ if (versionChildren.length !== 1 || versionElement.tag !== 2) throw new Error("version must use INTEGER");
69
+ version = decodeIntegerNumber(versionElement.value) + 1;
70
+ if (version < 1 || version > 3) throw new Error(`Unsupported certificate version: ${String(version)}`);
71
+ index += 1;
72
+ }
73
+ const serialNumber = requireElement(tbsChildren[index], "serialNumber");
74
+ if (serialNumber.tag !== 2) throw new Error("serialNumber must use INTEGER");
75
+ const tbsSignatureAlgorithm = requireElement(tbsChildren[index + 1], "TBSCertificate signature");
76
+ const issuer = requireElement(tbsChildren[index + 2], "issuer");
77
+ const validity = requireElement(tbsChildren[index + 3], "validity");
78
+ const subject = requireElement(tbsChildren[index + 4], "subject");
79
+ const subjectPublicKeyInfo = requireElement(tbsChildren[index + 5], "subjectPublicKeyInfo");
80
+ let cursor = index + 6;
81
+ const issuerUniqueIdElement = tbsChildren[cursor];
82
+ if (issuerUniqueIdElement?.tag === 129) {
83
+ if (version < 2) throw new Error("issuerUniqueID requires certificate version 2 or 3");
84
+ validateImplicitBitStringContent(issuerUniqueIdElement.value, "issuerUniqueID");
85
+ cursor += 1;
86
+ }
87
+ const subjectUniqueIdElement = tbsChildren[cursor];
88
+ if (subjectUniqueIdElement?.tag === 130) {
89
+ if (version < 2) throw new Error("subjectUniqueID requires certificate version 2 or 3");
90
+ validateImplicitBitStringContent(subjectUniqueIdElement.value, "subjectUniqueID");
91
+ cursor += 1;
92
+ }
93
+ const extensions = tbsChildren[cursor]?.tag === 163 ? tbsChildren[cursor] : void 0;
94
+ if (extensions !== void 0) {
95
+ if (version !== 3) throw new Error("extensions require certificate version 3");
96
+ cursor += 1;
97
+ }
98
+ if (cursor !== tbsChildren.length) throw new Error(`Unsupported TBSCertificate field tag: ${String(requireElement(tbsChildren[cursor], "TBSCertificate field").tag)}`);
99
+ const parsedExtensions = parseExtensionContainer(der, extensions);
100
+ const parsedValidity = parseValidity(der, validity);
101
+ const parsedSpki = parseSubjectPublicKeyInfo(der, subjectPublicKeyInfo);
102
+ const parsedTbsSignatureAlgorithm = parseAlgorithmIdentifier(der, tbsSignatureAlgorithm);
103
+ const parsedSignatureAlgorithm = parseAlgorithmIdentifier(der, signatureAlgorithm);
104
+ assertMatchingCertificateSignatureAlgorithms(parsedTbsSignatureAlgorithm, parsedSignatureAlgorithm);
105
+ const decodedExtensions = options?.decoders === void 0 ? void 0 : decodeExtensions(parsedExtensions.all, options.decoders);
106
+ const decodedExtensionMap = options?.decoderMap === void 0 ? void 0 : decodeExtensionMap(parsedExtensions.all, options.decoderMap);
107
+ return {
108
+ der: new Uint8Array(der),
109
+ version,
110
+ serialNumberHex: toHex(serialNumber.value),
111
+ tbsCertificateDer: der.slice(tbsCertificate.start - tbsCertificate.headerLength, tbsCertificate.end),
112
+ subjectPublicKeyInfoDer: der.slice(subjectPublicKeyInfo.start - subjectPublicKeyInfo.headerLength, subjectPublicKeyInfo.end),
113
+ signatureValue: extractBitStringValue(signatureValue),
114
+ issuer: parseName(der, issuer),
115
+ subject: parseName(der, subject),
116
+ notBefore: parsedValidity.notBefore,
117
+ notAfter: parsedValidity.notAfter,
118
+ signatureAlgorithmOid: parsedSignatureAlgorithm.oid,
119
+ signatureAlgorithmName: describeSignatureAlgorithm(parsedSignatureAlgorithm.oid, parsedSignatureAlgorithm.parametersDer),
120
+ ...parsedSignatureAlgorithm.parametersDer !== void 0 ? { signatureAlgorithmParametersDer: parsedSignatureAlgorithm.parametersDer } : {},
121
+ publicKeyAlgorithmOid: parsedSpki.oid,
122
+ publicKeyAlgorithmName: describePublicKeyAlgorithm(parsedSpki.oid, parsedSpki.parametersOid),
123
+ ...parsedSpki.parametersDer !== void 0 ? { publicKeyAlgorithmParametersDer: parsedSpki.parametersDer } : {},
124
+ ...parsedSpki.parametersOid !== void 0 ? { publicKeyParametersOid: parsedSpki.parametersOid } : {},
125
+ extensions: parsedExtensions.all,
126
+ ...parsedExtensions.basicConstraints !== void 0 ? { basicConstraints: parsedExtensions.basicConstraints } : {},
127
+ ...parsedExtensions.keyUsage !== void 0 ? { keyUsage: parsedExtensions.keyUsage } : {},
128
+ ...parsedExtensions.extendedKeyUsage !== void 0 ? { extendedKeyUsage: parsedExtensions.extendedKeyUsage } : {},
129
+ ...parsedExtensions.subjectAltNames !== void 0 ? { subjectAltNames: parsedExtensions.subjectAltNames } : {},
130
+ ...parsedExtensions.nameConstraints !== void 0 ? { nameConstraints: parsedExtensions.nameConstraints } : {},
131
+ ...parsedExtensions.certificatePolicies !== void 0 ? { certificatePolicies: parsedExtensions.certificatePolicies } : {},
132
+ ...parsedExtensions.policyMappings !== void 0 ? { policyMappings: parsedExtensions.policyMappings } : {},
133
+ ...parsedExtensions.policyConstraints !== void 0 ? { policyConstraints: parsedExtensions.policyConstraints } : {},
134
+ ...parsedExtensions.inhibitAnyPolicy !== void 0 ? { inhibitAnyPolicy: parsedExtensions.inhibitAnyPolicy } : {},
135
+ ...parsedExtensions.authorityInfoAccess !== void 0 ? { authorityInfoAccess: parsedExtensions.authorityInfoAccess } : {},
136
+ ...parsedExtensions.crlDistributionPoints !== void 0 ? { crlDistributionPoints: parsedExtensions.crlDistributionPoints } : {},
137
+ ...decodedExtensions !== void 0 ? { decodedExtensions } : {},
138
+ ...decodedExtensionMap !== void 0 ? { decodedExtensionMap } : {},
139
+ ...parsedExtensions.subjectKeyIdentifier !== void 0 ? { subjectKeyIdentifier: parsedExtensions.subjectKeyIdentifier } : {},
140
+ ...parsedExtensions.authorityKeyIdentifier !== void 0 ? { authorityKeyIdentifier: parsedExtensions.authorityKeyIdentifier } : {}
141
+ };
142
+ }
143
+ /**
144
+ * Decode a DER-encoded X.509 certificate into a {@linkcode ParsedCertificate}.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * import { parseCertificateDer } from 'micro509';
149
+ *
150
+ * const result = parseCertificateDer(derBytes);
151
+ * if (result.ok) {
152
+ * console.log(result.value.subject.values.commonName); // "example.com"
153
+ * }
154
+ * ```
155
+ *
156
+ * @param der Raw DER bytes of an X.509 certificate.
157
+ * @param options Custom extension decoders to apply during parsing.
158
+ */
159
+ function parseCertificateDer(der, options) {
160
+ try {
161
+ return successResult(parseCertificateDerOrThrow(der, options));
162
+ } catch (error) {
163
+ rethrowIfInvariant(error);
164
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed certificate");
165
+ }
166
+ }
167
+ /**
168
+ * Decode a PEM-encoded X.509 certificate into a {@linkcode ParsedCertificate}.
169
+ *
170
+ * Expects a single `-----BEGIN CERTIFICATE-----` block. For bundles
171
+ * containing multiple certificates, use {@linkcode parseCertificateChainPem}.
172
+ *
173
+ * @example
174
+ * Throws on malformed input. For a typed failure instead, use the
175
+ * Result-returning {@linkcode parseCertificatePem}.
176
+ *
177
+ * ```ts
178
+ * const certificate = parseCertificatePemOrThrow(pemString); // throws if malformed
179
+ * console.log(certificate.issuer.values.organization); // "Let's Encrypt"
180
+ * ```
181
+ *
182
+ * @param pem PEM string with a CERTIFICATE block.
183
+ * @param options Custom extension decoders to apply during parsing.
184
+ */
185
+ function parseCertificatePemOrThrow(pem, options) {
186
+ return parseCertificateDerOrThrow(pemDecodeOrThrow("CERTIFICATE", pem), options);
187
+ }
188
+ /**
189
+ * Decode a PEM-encoded X.509 certificate into a {@linkcode ParsedCertificate}.
190
+ *
191
+ * Expects a single `-----BEGIN CERTIFICATE-----` block. For bundles
192
+ * containing multiple certificates, use {@linkcode parseCertificateChainPem}.
193
+ *
194
+ * @param pem PEM string with a CERTIFICATE block.
195
+ * @param options Custom extension decoders to apply during parsing.
196
+ */
197
+ function parseCertificatePem(pem, options) {
198
+ try {
199
+ return successResult(parseCertificatePemOrThrow(pem, options));
200
+ } catch (error) {
201
+ rethrowIfInvariant(error);
202
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed certificate");
203
+ }
204
+ }
205
+ /** Normalizes a PEM bundle or single DER certificate source into parsed certificates. */
206
+ function parseCertificatesFromSource(source, options) {
207
+ return typeof source === "string" ? parseCertificatesFromPemBlocks(source, options) : [parseCertificateDerOrThrow(new Uint8Array(source), options)];
208
+ }
209
+ /** Normalizes a PEM, DER, or already-parsed certificate source into one parsed certificate. */
210
+ function parseCertificateFromSource(source, options) {
211
+ if (typeof source === "string") return parseCertificatePemOrThrow(source, options);
212
+ if (hasParsedCertificateShape(source)) return source;
213
+ return parseCertificateDerOrThrow(new Uint8Array(source), options);
214
+ }
215
+ /**
216
+ * Decode a PEM bundle containing one or more certificates.
217
+ *
218
+ * Non-CERTIFICATE blocks (e.g. private keys) are silently skipped.
219
+ *
220
+ * @param pemBundle PEM text that may contain multiple CERTIFICATE blocks.
221
+ * @param options Custom extension decoders to apply during parsing.
222
+ */
223
+ function parseCertificateChainPem(pemBundle, options) {
224
+ return parseCertificatesFromPemBlocks(pemBundle, options);
225
+ }
226
+ /**
227
+ * Decode a DER-encoded PKCS#10 CSR into a {@linkcode ParsedCertificateSigningRequest}.
228
+ *
229
+ * @param der Raw DER bytes of a PKCS#10 certificate signing request.
230
+ * @param options Custom extension decoders to apply during parsing.
231
+ */
232
+ function parseCertificateSigningRequestDerOrThrow(der, options) {
233
+ const topLevel = readSequenceChildren(der, { maxDepth: 64 });
234
+ if (topLevel.length !== 3) throw new Error("Malformed CertificationRequest");
235
+ const certificationRequestInfo = requireElement(topLevel[0], "CertificationRequestInfo");
236
+ const signatureAlgorithm = requireElement(topLevel[1], "signatureAlgorithm");
237
+ const signatureValue = requireElement(topLevel[2], "signatureValue");
238
+ const criChildren = childrenOf(der, certificationRequestInfo);
239
+ if (criChildren.length < 3 || criChildren.length > 4) throw new Error("Malformed CertificationRequestInfo");
240
+ const versionElement = requireElement(criChildren[0], "version");
241
+ if (versionElement.tag !== 2) throw new Error("version must use INTEGER");
242
+ const version = decodeIntegerNumber(versionElement.value) + 1;
243
+ if (version !== 1) throw new Error(`Unsupported CertificationRequestInfo version: ${String(version)}`);
244
+ const subject = requireElement(criChildren[1], "subject");
245
+ const subjectPublicKeyInfo = requireElement(criChildren[2], "subjectPublicKeyInfo");
246
+ const attributes = criChildren[3];
247
+ if (attributes !== void 0 && attributes.tag !== 160) throw new Error("CertificationRequestInfo attributes must use [0]");
248
+ const parsedExtensions = parseRequestedExtensions(der, attributes);
249
+ const parsedSpki = parseSubjectPublicKeyInfo(der, subjectPublicKeyInfo);
250
+ const parsedSignatureAlgorithm = parseAlgorithmIdentifier(der, signatureAlgorithm);
251
+ const decodedExtensions = options?.decoders === void 0 ? void 0 : decodeExtensions(parsedExtensions.all, options.decoders);
252
+ const decodedExtensionMap = options?.decoderMap === void 0 ? void 0 : decodeExtensionMap(parsedExtensions.all, options.decoderMap);
253
+ return {
254
+ version,
255
+ certificationRequestInfoDer: der.slice(certificationRequestInfo.start - certificationRequestInfo.headerLength, certificationRequestInfo.end),
256
+ subjectPublicKeyInfoDer: der.slice(subjectPublicKeyInfo.start - subjectPublicKeyInfo.headerLength, subjectPublicKeyInfo.end),
257
+ signatureValue: extractBitStringValue(signatureValue),
258
+ subject: parseName(der, subject),
259
+ signatureAlgorithmOid: parsedSignatureAlgorithm.oid,
260
+ signatureAlgorithmName: describeSignatureAlgorithm(parsedSignatureAlgorithm.oid, parsedSignatureAlgorithm.parametersDer),
261
+ ...parsedSignatureAlgorithm.parametersDer !== void 0 ? { signatureAlgorithmParametersDer: parsedSignatureAlgorithm.parametersDer } : {},
262
+ publicKeyAlgorithmOid: parsedSpki.oid,
263
+ publicKeyAlgorithmName: describePublicKeyAlgorithm(parsedSpki.oid, parsedSpki.parametersOid),
264
+ ...parsedSpki.parametersDer !== void 0 ? { publicKeyAlgorithmParametersDer: parsedSpki.parametersDer } : {},
265
+ ...parsedSpki.parametersOid !== void 0 ? { publicKeyParametersOid: parsedSpki.parametersOid } : {},
266
+ requestedExtensions: parsedExtensions.all,
267
+ ...parsedExtensions.basicConstraints !== void 0 ? { basicConstraints: parsedExtensions.basicConstraints } : {},
268
+ ...parsedExtensions.keyUsage !== void 0 ? { keyUsage: parsedExtensions.keyUsage } : {},
269
+ ...parsedExtensions.extendedKeyUsage !== void 0 ? { extendedKeyUsage: parsedExtensions.extendedKeyUsage } : {},
270
+ ...parsedExtensions.subjectAltNames !== void 0 ? { subjectAltNames: parsedExtensions.subjectAltNames } : {},
271
+ ...parsedExtensions.nameConstraints !== void 0 ? { nameConstraints: parsedExtensions.nameConstraints } : {},
272
+ ...parsedExtensions.certificatePolicies !== void 0 ? { certificatePolicies: parsedExtensions.certificatePolicies } : {},
273
+ ...parsedExtensions.policyMappings !== void 0 ? { policyMappings: parsedExtensions.policyMappings } : {},
274
+ ...parsedExtensions.policyConstraints !== void 0 ? { policyConstraints: parsedExtensions.policyConstraints } : {},
275
+ ...parsedExtensions.inhibitAnyPolicy !== void 0 ? { inhibitAnyPolicy: parsedExtensions.inhibitAnyPolicy } : {},
276
+ ...parsedExtensions.authorityInfoAccess !== void 0 ? { authorityInfoAccess: parsedExtensions.authorityInfoAccess } : {},
277
+ ...parsedExtensions.crlDistributionPoints !== void 0 ? { crlDistributionPoints: parsedExtensions.crlDistributionPoints } : {},
278
+ ...decodedExtensions !== void 0 ? { decodedExtensions } : {},
279
+ ...decodedExtensionMap !== void 0 ? { decodedExtensionMap } : {}
280
+ };
281
+ }
282
+ /**
283
+ * Decode a DER-encoded PKCS#10 CSR into a {@linkcode ParsedCertificateSigningRequest}.
284
+ *
285
+ * @param der Raw DER bytes of a PKCS#10 certificate signing request.
286
+ * @param options Custom extension decoders to apply during parsing.
287
+ */
288
+ function parseCertificateSigningRequestDer(der, options) {
289
+ try {
290
+ return successResult(parseCertificateSigningRequestDerOrThrow(der, options));
291
+ } catch (error) {
292
+ rethrowIfInvariant(error);
293
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed certificate signing request");
294
+ }
295
+ }
296
+ function parseCertificatesFromPemBlocks(pemBundle, options) {
297
+ return splitPemBlocksOrThrow(pemBundle).filter((block) => block.label === "CERTIFICATE").map((block) => parseCertificateDerOrThrow(block.bytes, options));
298
+ }
299
+ function hasParsedCertificateShape(value) {
300
+ return "subjectPublicKeyInfoDer" in value;
301
+ }
302
+ /**
303
+ * Decode a PEM-encoded PKCS#10 CSR into a {@linkcode ParsedCertificateSigningRequest}.
304
+ *
305
+ * @param pem PEM string with a CERTIFICATE REQUEST block.
306
+ * @param options Custom extension decoders to apply during parsing.
307
+ */
308
+ function parseCertificateSigningRequestPemOrThrow(pem, options) {
309
+ return parseCertificateSigningRequestDerOrThrow(pemDecodeOrThrow("CERTIFICATE REQUEST", pem), options);
310
+ }
311
+ /**
312
+ * Decode a PEM-encoded PKCS#10 CSR into a {@linkcode ParsedCertificateSigningRequest}.
313
+ *
314
+ * @param pem PEM string with a CERTIFICATE REQUEST block.
315
+ * @param options Custom extension decoders to apply during parsing.
316
+ */
317
+ function parseCertificateSigningRequestPem(pem, options) {
318
+ try {
319
+ return successResult(parseCertificateSigningRequestPemOrThrow(pem, options));
320
+ } catch (error) {
321
+ rethrowIfInvariant(error);
322
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed certificate signing request");
323
+ }
324
+ }
325
+ /**
326
+ * Import the subject public key of a parsed certificate or CSR as a WebCrypto `CryptoKey`.
327
+ *
328
+ * The key algorithm — and, for EC keys, the curve — is inferred from the
329
+ * SubjectPublicKeyInfo's own AlgorithmIdentifier (the same resolution
330
+ * {@linkcode importSpkiDerOrThrow} applies when no algorithm is given), so
331
+ * callers never map {@linkcode ParsedCertificate.publicKeyAlgorithmOid} /
332
+ * {@linkcode ParsedCertificate.publicKeyParametersOid} by hand.\
333
+ * RSA keys import with the default `pkcs1-v1_5`/`SHA-256` parameters (a plain
334
+ * `rsaEncryption` SPKI encodes neither padding scheme nor hash); pass
335
+ * `algorithm` to choose other RSA parameters or to assert an expected
336
+ * algorithm.
337
+ *
338
+ * @param parsed Parsed certificate or CSR whose subject public key to import.
339
+ * @param algorithm Optional expected algorithm; must match the key contents when given.
340
+ * @returns Extractable `CryptoKey` with `verify` usage.
341
+ *
342
+ * @throws {Error} If the SubjectPublicKeyInfo is malformed, encodes an
343
+ * unsupported algorithm, or doesn't match `algorithm`
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * const parsed = parseCertificatePemOrThrow(pem);
348
+ * const publicKey = await getSubjectPublicKeyOrThrow(parsed);
349
+ * ```
350
+ *
351
+ * @see {@linkcode getSubjectPublicKey} for the non-throwing variant
352
+ */
353
+ function getSubjectPublicKeyOrThrow(parsed, algorithm) {
354
+ return importSpkiDerOrThrow(parsed.subjectPublicKeyInfoDer, algorithm);
355
+ }
356
+ /**
357
+ * Import the subject public key of a parsed certificate or CSR as a WebCrypto `CryptoKey`.
358
+ *
359
+ * @see `getSubjectPublicKeyOrThrow` for the throwing variant
360
+ */
361
+ function getSubjectPublicKey(parsed, algorithm) {
362
+ return importSpkiDer(parsed.subjectPublicKeyInfoDer, algorithm);
363
+ }
364
+ /**
365
+ * Find a raw extension by OID within a parsed extension list.
366
+ *
367
+ * @param extensions Extension list from a {@linkcode ParsedCertificate} or CSR.
368
+ * @param oid Dotted-decimal OID to look up.
369
+ * @returns The matching extension, or `undefined` if not present.
370
+ */
371
+ function findExtension(extensions, oid) {
372
+ return extensions.find((extension) => extension.oid === oid);
373
+ }
374
+ /**
375
+ * Decode a single extension using a custom {@linkcode ExtensionDecoder}.
376
+ *
377
+ * @param extensions Extension list to search.
378
+ * @param decoder Decoder whose OID will be matched.
379
+ * @returns The decoded value, or `undefined` if the extension is absent.
380
+ */
381
+ function decodeExtension(extensions, decoder) {
382
+ const extension = findExtension(extensions, decoder.oid);
383
+ if (extension === void 0) return;
384
+ return decoder.decode(extension);
385
+ }
386
+ /**
387
+ * Decode all matching extensions using an array of {@linkcode ExtensionDecoder}s.
388
+ *
389
+ * @param extensions Extension list to search.
390
+ * @param decoders Decoders to apply. Only matching OIDs produce output.
391
+ */
392
+ function decodeExtensions(extensions, decoders) {
393
+ const decoded = [];
394
+ for (const decoder of decoders) {
395
+ const extension = findExtension(extensions, decoder.oid);
396
+ if (extension === void 0) continue;
397
+ decoded.push({
398
+ oid: extension.oid,
399
+ critical: extension.critical,
400
+ value: decoder.decode(extension)
401
+ });
402
+ }
403
+ return decoded;
404
+ }
405
+ /**
406
+ * Decode all matching extensions using a named {@linkcode ExtensionDecoderMap}.
407
+ *
408
+ * @param extensions Extension list to search.
409
+ * @param decoderMap Named decoders. Results are keyed by the same map keys.
410
+ */
411
+ function decodeExtensionMap(extensions, decoderMap) {
412
+ let decoded = {};
413
+ for (const key in decoderMap) {
414
+ const decoder = decoderMap[key];
415
+ if (decoder === void 0) continue;
416
+ const extension = findExtension(extensions, decoder.oid);
417
+ if (extension === void 0) continue;
418
+ decoded = {
419
+ ...decoded,
420
+ [key]: {
421
+ oid: extension.oid,
422
+ critical: extension.critical,
423
+ value: decoder.decode(extension)
424
+ }
425
+ };
426
+ }
427
+ return decoded;
428
+ }
429
+ /** Decode the explicit [3] extensions wrapper from a TBSCertificate. */
430
+ function parseExtensionContainer(source, container) {
431
+ if (container === void 0) return { all: [] };
432
+ return parseExtensionSequence(source, requireElement(childrenOf(source, container)[0], "extensions sequence"), "certificate");
433
+ }
434
+ /** Extract extensions from the CSR extensionRequest attribute. */
435
+ function parseRequestedExtensions(source, attributes) {
436
+ if (attributes === void 0) return { all: [] };
437
+ if (attributes.tag !== 160) throw new Error("CertificationRequestInfo attributes must use [0]");
438
+ let requestedExtensions;
439
+ for (const attribute of childrenOf(source, attributes)) {
440
+ const attributeChildren = childrenOf(source, attribute);
441
+ if (attributeChildren.length !== 2) throw new Error("Malformed CSR attribute");
442
+ if (decodeObjectIdentifier(requireElement(attributeChildren[0], "attribute OID").value) !== OIDS.extensionRequest) continue;
443
+ if (requestedExtensions !== void 0) throw new Error("extensionRequest attribute must not repeat");
444
+ const valuesSet = requireElement(attributeChildren[1], "attribute values");
445
+ if (valuesSet.tag !== 49) throw new Error("extensionRequest attribute values must use SET");
446
+ const values = childrenOf(source, valuesSet);
447
+ if (values.length !== 1) throw new Error("extensionRequest attribute must contain exactly one value");
448
+ requestedExtensions = parseExtensionSequence(source, requireElement(values[0], "requested extensions"), "csr");
449
+ }
450
+ return requestedExtensions ?? { all: [] };
451
+ }
452
+ /** Walk a SEQUENCE OF Extension and decode each one, populating known-extension slots. */
453
+ function parseExtensionSequence(source, sequenceElement, context) {
454
+ const parsed = [];
455
+ const knownParsed = {};
456
+ const seenOids = /* @__PURE__ */ new Set();
457
+ for (const extension of childrenOf(source, sequenceElement)) {
458
+ const children = childrenOf(source, extension);
459
+ if (children.length < 2 || children.length > 3) throw new Error("Malformed Extension");
460
+ const oid = decodeObjectIdentifier(requireElement(children[0], "extension OID").value);
461
+ if (seenOids.has(oid)) throw new Error(`Duplicate extension OID: ${oid}`);
462
+ seenOids.add(oid);
463
+ let offset = 1;
464
+ let critical = false;
465
+ const maybeCritical = children[offset];
466
+ if (maybeCritical?.tag === 1) {
467
+ critical = decodeBoolean(maybeCritical.value);
468
+ offset += 1;
469
+ }
470
+ const extnValue = requireElement(children[offset], "extension value");
471
+ if (extnValue.tag !== 4 || offset !== children.length - 1) throw new Error("Extension value must use OCTET STRING");
472
+ parsed.push({
473
+ oid,
474
+ critical,
475
+ valueDer: new Uint8Array(extnValue.value),
476
+ valueHex: toHex(extnValue.value)
477
+ });
478
+ decodeAndApplyKnownExtension(context, oid, knownParsed, extnValue.value);
479
+ }
480
+ return {
481
+ all: parsed,
482
+ ...knownParsed
483
+ };
484
+ }
485
+ /** Decode an X.501 Name (issuer / subject) into a {@linkcode ParsedName}. */
486
+ function parseName(source, element) {
487
+ const rdns = [];
488
+ const attributes = [];
489
+ const values = {};
490
+ for (const setElement of childrenOf(source, element)) {
491
+ const rdn = parseNameAttributeSet(source, setElement);
492
+ rdns.push(rdn);
493
+ for (const attribute of rdn.attributes) {
494
+ attributes.push(attribute);
495
+ if (attribute.key !== void 0 && values[attribute.key] === void 0) values[attribute.key] = attribute.value;
496
+ }
497
+ }
498
+ return {
499
+ derHex: toHex(source.slice(element.start - element.headerLength, element.end)),
500
+ rdns,
501
+ attributes,
502
+ values
503
+ };
504
+ }
505
+ /** Decode a single RDN SET element. */
506
+ function parseRelativeDistinguishedName(source, element) {
507
+ return parseNameAttributeSet(source, element);
508
+ }
509
+ /** Decode the AttributeTypeAndValue pairs within a SET element. */
510
+ function parseNameAttributeSet(source, setElement) {
511
+ const attributes = [];
512
+ const values = {};
513
+ for (const attributeSequence of childrenOf(source, setElement)) {
514
+ const parts = childrenOf(source, attributeSequence);
515
+ const oid = decodeObjectIdentifier(requireElement(parts[0], "name OID").value);
516
+ const valueElement = requireElement(parts[1], "name value");
517
+ const fieldKey = nameFieldKeyFromOid(oid);
518
+ const fieldValue = decodeString(valueElement.tag, valueElement.value);
519
+ const attribute = fieldKey !== void 0 ? {
520
+ oid,
521
+ key: fieldKey,
522
+ valueTag: valueElement.tag,
523
+ value: fieldValue
524
+ } : {
525
+ oid,
526
+ valueTag: valueElement.tag,
527
+ value: fieldValue
528
+ };
529
+ attributes.push(attribute);
530
+ if (fieldKey !== void 0 && values[fieldKey] === void 0) values[fieldKey] = fieldValue;
531
+ }
532
+ return {
533
+ derHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),
534
+ attributes,
535
+ values
536
+ };
537
+ }
538
+ /** Decode the Validity SEQUENCE into notBefore / notAfter Dates. */
539
+ function parseValidity(source, element) {
540
+ const children = childrenOf(source, element);
541
+ return {
542
+ notBefore: parseTime(requireElement(children[0], "notBefore")),
543
+ notAfter: parseTime(requireElement(children[1], "notAfter"))
544
+ };
545
+ }
546
+ /** Extract the algorithm identifier from a SubjectPublicKeyInfo SEQUENCE. */
547
+ function parseSubjectPublicKeyInfo(source, element) {
548
+ if (element.tag !== 48) throw new Error("SubjectPublicKeyInfo must use SEQUENCE");
549
+ const children = childrenOf(source, element);
550
+ if (children.length !== 2) throw new Error("SubjectPublicKeyInfo must contain algorithm and subjectPublicKey");
551
+ const algorithmElement = requireElement(children[0], "SPKI algorithm");
552
+ if (algorithmElement.tag !== 48) throw new Error("SubjectPublicKeyInfo algorithm must use SEQUENCE");
553
+ const algorithm = parseAlgorithmIdentifier(source, algorithmElement);
554
+ extractBitStringValue(requireElement(children[1], "subjectPublicKey BIT STRING"));
555
+ return algorithm;
556
+ }
557
+ /** Decode an AlgorithmIdentifier SEQUENCE (OID + optional parameters). */
558
+ function parseAlgorithmIdentifier(source, element) {
559
+ const children = childrenOf(source, element);
560
+ if (children.length === 0 || children.length > 2) throw new Error("Malformed AlgorithmIdentifier");
561
+ const oid = decodeObjectIdentifier(requireElement(children[0], "algorithm OID").value);
562
+ const parameters = children[1];
563
+ if (parameters === void 0) return { oid };
564
+ const parametersDer = source.slice(parameters.start - parameters.headerLength, parameters.end);
565
+ if (parameters?.tag === 6) return {
566
+ oid,
567
+ parametersDer,
568
+ parametersOid: decodeObjectIdentifier(parameters.value)
569
+ };
570
+ return {
571
+ oid,
572
+ parametersDer
573
+ };
574
+ }
575
+ function assertMatchingCertificateSignatureAlgorithms(tbsSignatureAlgorithm, signatureAlgorithm) {
576
+ if (tbsSignatureAlgorithm.oid !== signatureAlgorithm.oid || !optionalBytesEqual(tbsSignatureAlgorithm.parametersDer, signatureAlgorithm.parametersDer)) throw new Error("Certificate signatureAlgorithm must match TBSCertificate signature");
577
+ }
578
+ function optionalBytesEqual(left, right) {
579
+ if (left === void 0 || right === void 0) return left === right;
580
+ if (left.length !== right.length) return false;
581
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
582
+ return true;
583
+ }
584
+ /** @internal Decode the Basic Constraints extension value DER. */
585
+ function parseBasicConstraints(bytes) {
586
+ const element = readRootElement(bytes, { maxDepth: 64 });
587
+ if (element.tag !== 48) throw new Error("basicConstraints must use SEQUENCE");
588
+ const children = childrenOf(bytes, element);
589
+ let ca = false;
590
+ let pathLength;
591
+ let sawCa = false;
592
+ let sawPathLength = false;
593
+ for (const child of children) {
594
+ if (child.tag === 1) {
595
+ if (sawCa) throw new Error("basicConstraints cA must not repeat");
596
+ if (sawPathLength) throw new Error("basicConstraints cA must precede pathLength");
597
+ sawCa = true;
598
+ ca = decodeBoolean(child.value);
599
+ continue;
600
+ }
601
+ if (child.tag === 2) {
602
+ if (sawPathLength) throw new Error("basicConstraints pathLength must not repeat");
603
+ sawPathLength = true;
604
+ pathLength = decodeNonNegativeIntegerNumber(child.value, "basicConstraints pathLength");
605
+ continue;
606
+ }
607
+ throw new Error(`Unsupported basicConstraints field tag: ${String(child.tag)}`);
608
+ }
609
+ if (pathLength !== void 0 && ca !== true) throw new Error("basicConstraints pathLength requires cA = true");
610
+ if (ca) return pathLength !== void 0 ? {
611
+ ca: true,
612
+ pathLength
613
+ } : { ca: true };
614
+ return { ca: false };
615
+ }
616
+ /** @internal Decode the Key Usage BIT STRING extension value. */
617
+ function parseKeyUsage(bytes) {
618
+ return parseKeyUsageExtension(bytes);
619
+ }
620
+ /** @internal Decode the Extended Key Usage SEQUENCE OF OIDs. */
621
+ function parseExtendedKeyUsage(bytes) {
622
+ return childrenOf(bytes, requireElement(readRootElement(bytes, { maxDepth: 64 }), "extendedKeyUsage sequence")).map((element) => parseExtendedKeyUsageOid(decodeObjectIdentifier(element.value)));
623
+ }
624
+ /** @internal Decode the Certificate Policies extension value. */
625
+ function parseCertificatePolicies(bytes) {
626
+ const policyElements = childrenOf(bytes, requireElement(readRootElement(bytes, { maxDepth: 64 }), "certificatePolicies sequence"));
627
+ if (policyElements.length === 0) throw new Error("certificatePolicies must not be empty");
628
+ return policyElements.map((policyElement) => parsePolicyInformation(bytes, policyElement));
629
+ }
630
+ /** Decode a single PolicyInformation SEQUENCE (OID + optional qualifiers). */
631
+ function parsePolicyInformation(source, element) {
632
+ const children = childrenOf(source, element);
633
+ const policyIdentifier = decodeObjectIdentifier(requireElement(children[0], "policyIdentifier").value);
634
+ const qualifiersElement = children[1];
635
+ if (children.length > 2) throw new Error("policyInformation has unexpected trailing fields");
636
+ if (qualifiersElement === void 0) return { policyIdentifier };
637
+ const qualifiers = childrenOf(source, qualifiersElement);
638
+ if (qualifiers.length === 0) throw new Error("policyQualifiers must not be empty");
639
+ return {
640
+ policyIdentifier,
641
+ policyQualifiers: qualifiers.map((qualifierElement) => parsePolicyQualifierInfo(source, qualifierElement))
642
+ };
643
+ }
644
+ /** Decode a PolicyQualifierInfo (CPS URI, UserNotice, or opaque OID). */
645
+ function parsePolicyQualifierInfo(source, element) {
646
+ const children = childrenOf(source, element);
647
+ const qualifierId = decodeObjectIdentifier(requireElement(children[0], "policyQualifierId").value);
648
+ const qualifierValue = requireElement(children[1], "policyQualifier");
649
+ if (children.length > 2) throw new Error("policyQualifierInfo has unexpected trailing fields");
650
+ if (qualifierId === OIDS.cpsPolicyQualifier) {
651
+ if (qualifierValue.tag !== 22) throw new Error("cps policy qualifier must use IA5String");
652
+ return {
653
+ type: "cps",
654
+ uri: decodeString(qualifierValue.tag, qualifierValue.value)
655
+ };
656
+ }
657
+ if (qualifierId === OIDS.userNoticePolicyQualifier) return {
658
+ type: "userNotice",
659
+ ...parseUserNoticePolicyQualifierInfo(source, qualifierValue)
660
+ };
661
+ return {
662
+ type: "oid",
663
+ oid: qualifierId,
664
+ qualifierDer: source.slice(qualifierValue.start - qualifierValue.headerLength, qualifierValue.end)
665
+ };
666
+ }
667
+ /** Decode a UserNotice qualifier (optional noticeRef + optional explicitText). */
668
+ function parseUserNoticePolicyQualifierInfo(source, element) {
669
+ const children = childrenOf(source, element);
670
+ let noticeRef;
671
+ let explicitText;
672
+ for (const child of children) {
673
+ if (child.tag === 48) {
674
+ if (noticeRef !== void 0) throw new Error("userNotice must not contain multiple noticeRef values");
675
+ noticeRef = parsePolicyNoticeReference(source, child);
676
+ continue;
677
+ }
678
+ if (explicitText !== void 0) throw new Error("userNotice must not contain multiple explicitText values");
679
+ explicitText = parseDisplayText(child);
680
+ }
681
+ return {
682
+ ...noticeRef === void 0 ? {} : { noticeRef },
683
+ ...explicitText === void 0 ? {} : { explicitText }
684
+ };
685
+ }
686
+ /** Decode a NoticeReference (organization name + notice number list). */
687
+ function parsePolicyNoticeReference(source, element) {
688
+ if (element.tag !== 48) throw new Error("noticeRef must use SEQUENCE");
689
+ const children = childrenOf(source, element);
690
+ const organization = parseDisplayText(requireElement(children[0], "noticeRef organization"));
691
+ const noticeNumbersElement = requireElement(children[1], "noticeRef noticeNumbers");
692
+ if (children.length > 2) throw new Error("noticeRef has unexpected trailing fields");
693
+ return {
694
+ organization,
695
+ noticeNumbers: parsePolicyNoticeNumbers(source, noticeNumbersElement)
696
+ };
697
+ }
698
+ /** Decode a SEQUENCE OF INTEGER notice numbers. */
699
+ function parsePolicyNoticeNumbers(source, element) {
700
+ if (element.tag !== 48) throw new Error("noticeRef noticeNumbers must use SEQUENCE");
701
+ const noticeNumberElements = childrenOf(source, element);
702
+ if (noticeNumberElements.length === 0) throw new Error("noticeRef noticeNumbers must not be empty");
703
+ return noticeNumberElements.map((noticeNumberElement) => {
704
+ if (noticeNumberElement.tag !== 2) throw new Error("noticeRef noticeNumber must use INTEGER");
705
+ return decodeNonNegativeIntegerNumber(noticeNumberElement.value, "noticeRef noticeNumber");
706
+ });
707
+ }
708
+ /** @internal Decode the Policy Mappings extension value. */
709
+ function parsePolicyMappings(bytes) {
710
+ const mappingElements = childrenOf(bytes, requireElement(readRootElement(bytes, { maxDepth: 64 }), "policyMappings sequence"));
711
+ if (mappingElements.length === 0) throw new Error("policyMappings must not be empty");
712
+ return mappingElements.map((mappingElement) => {
713
+ const children = childrenOf(bytes, mappingElement);
714
+ const issuerDomainPolicy = decodeObjectIdentifier(requireElement(children[0], "policyMappings issuerDomainPolicy").value);
715
+ const subjectDomainPolicy = decodeObjectIdentifier(requireElement(children[1], "policyMappings subjectDomainPolicy").value);
716
+ if (children.length > 2) throw new Error("policyMappings entry has unexpected trailing fields");
717
+ if (issuerDomainPolicy === OIDS.anyPolicy || subjectDomainPolicy === OIDS.anyPolicy) throw new Error("policyMappings must not use anyPolicy");
718
+ return {
719
+ issuerDomainPolicy,
720
+ subjectDomainPolicy
721
+ };
722
+ });
723
+ }
724
+ /** @internal Decode the Policy Constraints extension value. */
725
+ function parsePolicyConstraints(bytes) {
726
+ const sequenceElement = requireElement(readRootElement(bytes, { maxDepth: 64 }), "policyConstraints sequence");
727
+ let requireExplicitPolicy;
728
+ let inhibitPolicyMapping;
729
+ for (const child of childrenOf(bytes, sequenceElement)) {
730
+ if (child.tag === 128) {
731
+ if (requireExplicitPolicy !== void 0) throw new Error("policyConstraints must not repeat requireExplicitPolicy");
732
+ requireExplicitPolicy = decodeNonNegativeIntegerNumber(child.value, "policyConstraints requireExplicitPolicy");
733
+ continue;
734
+ }
735
+ if (child.tag === 129) {
736
+ if (inhibitPolicyMapping !== void 0) throw new Error("policyConstraints must not repeat inhibitPolicyMapping");
737
+ inhibitPolicyMapping = decodeNonNegativeIntegerNumber(child.value, "policyConstraints inhibitPolicyMapping");
738
+ continue;
739
+ }
740
+ throw new Error(`Unsupported policyConstraints field tag: ${child.tag}`);
741
+ }
742
+ if (requireExplicitPolicy === void 0 && inhibitPolicyMapping === void 0) throw new Error("policyConstraints must set requireExplicitPolicy or inhibitPolicyMapping");
743
+ return {
744
+ ...requireExplicitPolicy === void 0 ? {} : { requireExplicitPolicy },
745
+ ...inhibitPolicyMapping === void 0 ? {} : { inhibitPolicyMapping }
746
+ };
747
+ }
748
+ /** @internal Decode the Inhibit anyPolicy extension (single INTEGER). */
749
+ function parseInhibitAnyPolicy(bytes) {
750
+ const integerElement = requireElement(readRootElement(bytes, { maxDepth: 64 }), "inhibitAnyPolicy integer");
751
+ if (integerElement.tag !== 2) throw new Error("inhibitAnyPolicy must be an INTEGER");
752
+ return { skipCerts: decodeNonNegativeIntegerNumber(integerElement.value, "inhibitAnyPolicy skipCerts") };
753
+ }
754
+ /** @internal Decode the Subject Alternative Names SEQUENCE OF GeneralName. */
755
+ function parseSubjectAltNames(bytes) {
756
+ return childrenOf(bytes, requireElement(readRootElement(bytes, { maxDepth: 64 }), "subjectAltName sequence")).map((element) => parseGeneralName(bytes, element));
757
+ }
758
+ /** @internal Decode the Authority Information Access extension value. */
759
+ function parseAuthorityInfoAccess(bytes) {
760
+ const sequenceElement = requireElement(readRootElement(bytes, { maxDepth: 64 }), "authorityInfoAccess sequence");
761
+ if (sequenceElement.tag !== 48) throw new Error("authorityInfoAccess must use SEQUENCE");
762
+ const accessDescriptions = childrenOf(bytes, sequenceElement);
763
+ if (accessDescriptions.length === 0) throw new Error("authorityInfoAccess must not be empty");
764
+ return accessDescriptions.map((element) => {
765
+ if (element.tag !== 48) throw new Error("authorityInfoAccess entry must use SEQUENCE");
766
+ const children = childrenOf(bytes, element);
767
+ if (children.length !== 2) throw new Error("authorityInfoAccess entry must contain method and location only");
768
+ const method = requireElement(children[0], "authorityInfoAccess method");
769
+ const location = requireElement(children[1], "authorityInfoAccess location");
770
+ if (method.tag !== 6) throw new Error("authorityInfoAccess method must use OBJECT IDENTIFIER");
771
+ if (location.tag !== 134) throw new Error(`Unsupported authorityInfoAccess location tag: ${location.tag}`);
772
+ return {
773
+ method: parseAuthorityInfoAccessMethodOid(decodeObjectIdentifier(method.value)),
774
+ uri: textDecoder.decode(location.value)
775
+ };
776
+ });
777
+ }
778
+ /** @internal Decode the CRL Distribution Points extension value. */
779
+ function parseCrlDistributionPoints(bytes) {
780
+ const sequenceElement = requireElement(readRootElement(bytes, { maxDepth: 64 }), "CRLDistributionPoints sequence");
781
+ if (sequenceElement.tag !== 48) throw new Error("CRLDistributionPoints must use SEQUENCE");
782
+ const elements = childrenOf(bytes, sequenceElement);
783
+ if (elements.length === 0) throw new Error("CRLDistributionPoints must not be empty");
784
+ const points = [];
785
+ for (const distributionPoint of elements) points.push(parseDistributionPoint(bytes, distributionPoint));
786
+ return points;
787
+ }
788
+ /** Decode a single DistributionPoint SEQUENCE. */
789
+ function parseDistributionPoint(source, element) {
790
+ if (element.tag !== 48) throw new Error("DistributionPoint must use SEQUENCE");
791
+ let distributionPoint;
792
+ let reasons;
793
+ let crlIssuer;
794
+ for (const child of childrenOf(source, element)) if (child.tag === 160) {
795
+ if (distributionPoint !== void 0) throw new Error("DistributionPoint distributionPoint must not repeat");
796
+ distributionPoint = parseDistributionPointName(source, child);
797
+ } else if (child.tag === 129) {
798
+ if (reasons !== void 0) throw new Error("DistributionPoint reasons must not repeat");
799
+ reasons = parseDistributionPointReasonFlagsContent(child.value);
800
+ } else if (child.tag === 162) {
801
+ if (crlIssuer !== void 0) throw new Error("DistributionPoint crlIssuer must not repeat");
802
+ crlIssuer = parseGeneralNames(source, child);
803
+ } else throw new Error(`Unsupported DistributionPoint field tag: ${String(child.tag)}`);
804
+ if (distributionPoint === void 0 && crlIssuer === void 0) throw new Error("DistributionPoint must include distributionPoint or crlIssuer");
805
+ return {
806
+ ...distributionPoint === void 0 ? {} : { distributionPoint },
807
+ ...reasons === void 0 ? {} : { reasons },
808
+ ...crlIssuer === void 0 ? {} : { crlIssuer }
809
+ };
810
+ }
811
+ /** Decode a DistributionPointName (fullName or relativeName). */
812
+ function parseDistributionPointName(source, element) {
813
+ const children = childrenOf(source, element);
814
+ if (children.length !== 1) throw new Error("distributionPointName must contain exactly one choice");
815
+ const distributionPointName = requireElement(children[0], "distributionPointName");
816
+ if (distributionPointName.tag === 160) {
817
+ const fullName = childrenOf(source, distributionPointName);
818
+ if (fullName.length === 0) throw new Error("distributionPointName fullName must not be empty");
819
+ for (const name of fullName) if ((name.tag & 192) !== 128) throw new Error("distributionPointName fullName must contain GeneralName entries");
820
+ return { fullName: fullName.map((name) => parseGeneralName(source, name)) };
821
+ }
822
+ if (distributionPointName.tag === 161) return { relativeName: parseRelativeDistinguishedName(source, distributionPointName) };
823
+ throw new Error(`Unsupported distributionPointName tag: ${distributionPointName.tag}`);
824
+ }
825
+ /** Decode a SEQUENCE OF GeneralName. */
826
+ function parseGeneralNames(source, element) {
827
+ const names = childrenOf(source, element);
828
+ if (names.length === 0) throw new Error("GeneralNames must not be empty");
829
+ for (const name of names) if ((name.tag & 192) !== 128) throw new Error("GeneralNames must contain GeneralName entries");
830
+ return names.map((name) => parseGeneralName(source, name));
831
+ }
832
+ /** Decode a single GeneralName from its implicit context tag. */
833
+ function parseGeneralName(source, element) {
834
+ switch (element.tag) {
835
+ case 160: {
836
+ const otherName = parseOtherName(source, element);
837
+ if (otherName !== void 0) return otherName;
838
+ return {
839
+ type: "unknown",
840
+ tag: element.tag,
841
+ value: source.slice(element.start, element.end)
842
+ };
843
+ }
844
+ case 129: return {
845
+ type: "email",
846
+ value: textDecoder.decode(element.value)
847
+ };
848
+ case 130: return {
849
+ type: "dns",
850
+ value: textDecoder.decode(element.value)
851
+ };
852
+ case 134: return {
853
+ type: "uri",
854
+ value: textDecoder.decode(element.value)
855
+ };
856
+ case 135: return {
857
+ type: "ip",
858
+ value: decodeIpAddress(element.value)
859
+ };
860
+ case 164: return {
861
+ type: "directoryName",
862
+ derHex: toHex(rebuildDirectoryNameFromImplicit(element, source))
863
+ };
864
+ default: return {
865
+ type: "unknown",
866
+ tag: element.tag,
867
+ value: source.slice(element.start, element.end)
868
+ };
869
+ }
870
+ }
871
+ /** Attempt to decode an otherName [0] as a known type (currently only SRV-ID). */
872
+ function parseOtherName(source, element) {
873
+ const otherNameElements = childrenOf(source, element);
874
+ if (otherNameElements.length !== 1) throw new Error("otherName must contain exactly one SEQUENCE");
875
+ const otherNameChildren = childrenOf(source, requireElement(otherNameElements[0], "otherName sequence"));
876
+ if (otherNameChildren.length !== 2) throw new Error("otherName must contain exactly type-id and value");
877
+ const typeId = requireElement(otherNameChildren[0], "otherName type-id");
878
+ const valueElement = requireElement(otherNameChildren[1], "otherName value");
879
+ if (decodeObjectIdentifier(typeId.value) !== OIDS.idOnDnsSrv) return;
880
+ if (valueElement.tag !== 160) throw new Error("SRV-ID otherName value must use explicit [0]");
881
+ const valueChildren = childrenOf(source, valueElement);
882
+ if (valueChildren.length !== 1) throw new Error("SRV-ID otherName value must contain exactly one IA5String");
883
+ const srvNameElement = requireElement(valueChildren[0], "SRV-ID IA5String");
884
+ if (srvNameElement.tag !== 22) throw new Error("SRV-ID otherName value must be an IA5String");
885
+ return {
886
+ type: "srv",
887
+ value: decodeString(srvNameElement.tag, srvNameElement.value)
888
+ };
889
+ }
890
+ /** @internal Decode the Name Constraints extension value. */
891
+ function parseNameConstraints(bytes) {
892
+ const sequenceElement = requireElement(readRootElement(bytes, {
893
+ maxDepth: 64,
894
+ allowOpaqueConstructedTags: [
895
+ 160,
896
+ 163,
897
+ 165
898
+ ]
899
+ }), "nameConstraints sequence");
900
+ if (sequenceElement.tag !== 48) throw new Error("nameConstraints must use SEQUENCE");
901
+ let permittedSubtrees;
902
+ let excludedSubtrees;
903
+ for (const child of childrenOf(bytes, sequenceElement)) if (child.tag === 160) {
904
+ if (permittedSubtrees !== void 0) throw new Error("nameConstraints permittedSubtrees must not repeat");
905
+ permittedSubtrees = parseGeneralSubtrees(bytes, child);
906
+ } else if (child.tag === 161) {
907
+ if (excludedSubtrees !== void 0) throw new Error("nameConstraints excludedSubtrees must not repeat");
908
+ excludedSubtrees = parseGeneralSubtrees(bytes, child);
909
+ } else throw new Error(`Unsupported nameConstraints field tag: ${String(child.tag)}`);
910
+ return {
911
+ ...permittedSubtrees !== void 0 ? { permittedSubtrees } : {},
912
+ ...excludedSubtrees !== void 0 ? { excludedSubtrees } : {}
913
+ };
914
+ }
915
+ /** Decode a SEQUENCE OF GeneralSubtree from a permittedSubtrees or excludedSubtrees wrapper. */
916
+ function parseGeneralSubtrees(source, container) {
917
+ const subtrees = [];
918
+ const subtreeElements = childrenOf(source, container);
919
+ if (subtreeElements.length === 0) throw new Error("name constraints GeneralSubtrees must not be empty");
920
+ for (const subtreeElement of subtreeElements) {
921
+ if (subtreeElement.tag !== 48) throw new Error("name constraints GeneralSubtree must use SEQUENCE");
922
+ const children = childrenOf(source, subtreeElement);
923
+ const baseElement = children[0];
924
+ if (baseElement === void 0) throw new Error("name constraints GeneralSubtree base is required");
925
+ let sawMinimum = false;
926
+ for (let i = 1; i < children.length; i += 1) {
927
+ const child = children[i];
928
+ if (child === void 0) continue;
929
+ if (child.tag === 128) {
930
+ if (sawMinimum) throw new Error("name constraints GeneralSubtree minimum must not repeat");
931
+ sawMinimum = true;
932
+ if (decodeNonNegativeIntegerNumber(child.value, "name constraints GeneralSubtree minimum") !== 0) throw new Error("name constraints GeneralSubtree minimum must be 0");
933
+ } else if (child.tag === 129) throw new Error("name constraints GeneralSubtree maximum is not supported");
934
+ else throw new Error(`Unsupported name constraints GeneralSubtree field tag: ${String(child.tag)}`);
935
+ }
936
+ const form = parseNameConstraintGeneralName(source, baseElement);
937
+ if (form !== void 0) subtrees.push({ base: form });
938
+ }
939
+ return subtrees;
940
+ }
941
+ /** Decode a GeneralName for use in name constraints (IP carries address+mask). */
942
+ function parseNameConstraintGeneralName(source, element) {
943
+ switch (element.tag) {
944
+ case 160: return {
945
+ type: "otherName",
946
+ value: new Uint8Array(element.value)
947
+ };
948
+ case 129: return {
949
+ type: "email",
950
+ value: textDecoder.decode(element.value)
951
+ };
952
+ case 130: return {
953
+ type: "dns",
954
+ value: textDecoder.decode(element.value)
955
+ };
956
+ case 163: return {
957
+ type: "x400Address",
958
+ value: new Uint8Array(element.value)
959
+ };
960
+ case 134: return {
961
+ type: "uri",
962
+ value: textDecoder.decode(element.value)
963
+ };
964
+ case 135:
965
+ if (element.value.length === 8) return {
966
+ type: "ip",
967
+ addressBytes: element.value.slice(0, 4),
968
+ maskBytes: element.value.slice(4, 8)
969
+ };
970
+ if (element.value.length === 32) return {
971
+ type: "ip",
972
+ addressBytes: element.value.slice(0, 16),
973
+ maskBytes: element.value.slice(16, 32)
974
+ };
975
+ throw new Error(`Invalid IP name constraint: expected 8 (IPv4) or 32 (IPv6) bytes, got ${String(element.value.length)}`);
976
+ case 164: return {
977
+ type: "directoryName",
978
+ derHex: toHex(rebuildDirectoryNameFromImplicit(element, source))
979
+ };
980
+ case 165: return {
981
+ type: "ediPartyName",
982
+ value: new Uint8Array(element.value)
983
+ };
984
+ case 136: return {
985
+ type: "registeredID",
986
+ value: decodeObjectIdentifier(element.value)
987
+ };
988
+ }
989
+ throw new Error(`Unsupported name constraint GeneralName tag: ${String(element.tag)}`);
990
+ }
991
+ /**
992
+ * Extracts the Name SEQUENCE from an implicitly-tagged directoryName [4].
993
+ *
994
+ * Handles two encoding styles found in the wild:
995
+ * - Proper implicit: [4] replaces SEQUENCE tag, content is RDN SETs directly → wrap with 0x30
996
+ * - Explicit-like: [4] wraps entire SEQUENCE, content starts with 0x30 → return content as-is
997
+ */
998
+ function rebuildDirectoryNameFromImplicit(element, _source) {
999
+ if (element.value.length > 0 && element.value[0] === 48) return new Uint8Array(element.value);
1000
+ const lengthEncoded = encodeLength(element.value.length);
1001
+ const result = new Uint8Array(1 + lengthEncoded.length + element.value.length);
1002
+ result[0] = 48;
1003
+ result.set(lengthEncoded, 1);
1004
+ result.set(element.value, 1 + lengthEncoded.length);
1005
+ return result;
1006
+ }
1007
+ /** Decode a DisplayText (UTF8String, IA5String, VisibleString, or BMPString). */
1008
+ function parseDisplayText(element) {
1009
+ switch (element.tag) {
1010
+ case 12:
1011
+ case 22:
1012
+ case 26: return textDecoder.decode(element.value);
1013
+ case 30: return decodeBmpString(element.value);
1014
+ default: throw new Error(`Unsupported DisplayText tag: ${element.tag}`);
1015
+ }
1016
+ }
1017
+ /** Decode a BMPString (UCS-2 big-endian) to a JS string. */
1018
+ function decodeBmpString(bytes) {
1019
+ if (bytes.length % 2 !== 0) throw new Error("Invalid BMPString length");
1020
+ let value = "";
1021
+ for (let index = 0; index < bytes.length; index += 2) {
1022
+ const left = bytes[index];
1023
+ const right = bytes[index + 1];
1024
+ if (left === void 0 || right === void 0) throw new Error("Invalid BMPString content");
1025
+ value += String.fromCharCode(left << 8 | right);
1026
+ }
1027
+ return value;
1028
+ }
1029
+ /** @internal Decode the Authority Key Identifier extension, returning the keyIdentifier hex or undefined. */
1030
+ function parseAuthorityKeyIdentifier(bytes) {
1031
+ const sequenceElement = requireElement(readElement(bytes, 0), "authorityKeyIdentifier sequence");
1032
+ if (sequenceElement.end !== bytes.length) throw new Error("Trailing data after DER element");
1033
+ let keyIdentifier;
1034
+ let sawAuthorityCertIssuer = false;
1035
+ let sawAuthorityCertSerialNumber = false;
1036
+ let lastFieldOrder = -1;
1037
+ let offset = sequenceElement.start;
1038
+ while (offset < sequenceElement.end) {
1039
+ const child = readElement(bytes, offset);
1040
+ if (child.end > sequenceElement.end) throw new Error("DER child exceeds parent length");
1041
+ if (child.tag === 128) {
1042
+ if (keyIdentifier !== void 0) throw new Error("authorityKeyIdentifier keyIdentifier must not repeat");
1043
+ if (lastFieldOrder >= 0) throw new Error("authorityKeyIdentifier fields must preserve DER order");
1044
+ keyIdentifier = toHex(child.value);
1045
+ lastFieldOrder = 0;
1046
+ } else if (child.tag === 161) {
1047
+ if (sawAuthorityCertIssuer) throw new Error("authorityKeyIdentifier authorityCertIssuer must not repeat");
1048
+ if (lastFieldOrder >= 1) throw new Error("authorityKeyIdentifier fields must preserve DER order");
1049
+ const issuerNames = childrenOf(bytes, child);
1050
+ if (issuerNames.length === 0) throw new Error("authorityKeyIdentifier authorityCertIssuer must contain GeneralName entries");
1051
+ for (const issuerName of issuerNames) {
1052
+ if ((issuerName.tag & 192) !== 128) throw new Error("authorityKeyIdentifier authorityCertIssuer must contain GeneralName entries");
1053
+ parseGeneralName(bytes, issuerName);
1054
+ }
1055
+ sawAuthorityCertIssuer = true;
1056
+ lastFieldOrder = 1;
1057
+ } else if (child.tag === 130) {
1058
+ if (sawAuthorityCertSerialNumber) throw new Error("authorityKeyIdentifier authorityCertSerialNumber must not repeat");
1059
+ if (lastFieldOrder >= 2 || !sawAuthorityCertIssuer) throw new Error("authorityKeyIdentifier fields must preserve DER order");
1060
+ validateImplicitSerialNumberEncoding(child.value, "authorityKeyIdentifier authorityCertSerialNumber");
1061
+ sawAuthorityCertSerialNumber = true;
1062
+ lastFieldOrder = 2;
1063
+ } else throw new Error(`Unsupported authorityKeyIdentifier field tag: ${String(child.tag)}`);
1064
+ offset = child.end;
1065
+ }
1066
+ if (offset !== sequenceElement.end) throw new Error("Malformed DER sequence");
1067
+ if (sawAuthorityCertIssuer !== sawAuthorityCertSerialNumber) throw new Error("authorityKeyIdentifier authorityCertIssuer and authorityCertSerialNumber must appear together");
1068
+ return keyIdentifier;
1069
+ }
1070
+ function validateImplicitSerialNumberEncoding(bytes, label) {
1071
+ const first = bytes[0];
1072
+ if (first === void 0) throw new Error(`${label} must not be empty`);
1073
+ if ((first & 128) !== 0) throw new Error(`${label} must be non-negative`);
1074
+ if (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 128) === 0) throw new Error(`${label} must use minimal encoding`);
1075
+ }
1076
+ function validateImplicitBitStringContent(bytes, label) {
1077
+ const unusedBits = bytes[0];
1078
+ if (unusedBits === void 0 || unusedBits > 7) throw new Error(`${label} must use BIT STRING encoding`);
1079
+ const bitStringBytes = bytes.slice(1);
1080
+ if (bitStringBytes.length === 0) {
1081
+ if (unusedBits !== 0) throw new Error(`${label} must use BIT STRING encoding`);
1082
+ return;
1083
+ }
1084
+ if (unusedBits === 0) return;
1085
+ const lastByte = bitStringBytes[bitStringBytes.length - 1];
1086
+ if (lastByte === void 0) throw new Error(`${label} must use BIT STRING encoding`);
1087
+ if ((lastByte & (1 << unusedBits) - 1) !== 0) throw new Error(`${label} BIT STRING must not set padding bits`);
1088
+ }
1089
+ //#endregion
1090
+ export { decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstraints, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificateFromSource, parseCertificatePem, parseCertificatePemOrThrow, parseCertificatePolicies, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow, parseCertificatesFromSource, parseCrlDistributionPoints, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames };