micro509 0.9.0 → 0.11.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 (111) hide show
  1. package/dist/index.d.ts +5 -4
  2. package/dist/index.js +16 -15
  3. package/dist/internal/asn1/asn1.js +145 -186
  4. package/dist/internal/asn1/asn1.js.map +1 -0
  5. package/dist/internal/asn1/der.js +210 -227
  6. package/dist/internal/asn1/der.js.map +1 -0
  7. package/dist/internal/asn1/oids.js +297 -101
  8. package/dist/internal/asn1/oids.js.map +1 -0
  9. package/dist/internal/asn1/oids2.js +69 -0
  10. package/dist/internal/asn1/oids2.js.map +1 -0
  11. package/dist/internal/crypto/algorithm-names.js +37 -35
  12. package/dist/internal/crypto/algorithm-names.js.map +1 -0
  13. package/dist/internal/crypto/ecdsa.js +25 -28
  14. package/dist/internal/crypto/ecdsa.js.map +1 -0
  15. package/dist/internal/crypto/hash.js +56 -117
  16. package/dist/internal/crypto/hash.js.map +1 -0
  17. package/dist/internal/crypto/pbes2.js +122 -133
  18. package/dist/internal/crypto/pbes2.js.map +1 -0
  19. package/dist/internal/crypto/rsa-pss.js +118 -124
  20. package/dist/internal/crypto/rsa-pss.js.map +1 -0
  21. package/dist/internal/crypto/sig-verify.js +87 -99
  22. package/dist/internal/crypto/sig-verify.js.map +1 -0
  23. package/dist/internal/crypto/signing.d.ts +12 -8
  24. package/dist/internal/crypto/signing.js +53 -55
  25. package/dist/internal/crypto/signing.js.map +1 -0
  26. package/dist/internal/crypto/webcrypto.js +5 -3
  27. package/dist/internal/crypto/webcrypto.js.map +1 -0
  28. package/dist/internal/shared/base64.js +10 -9
  29. package/dist/internal/shared/base64.js.map +1 -0
  30. package/dist/internal/shared/dn.js +50 -57
  31. package/dist/internal/shared/dn.js.map +1 -0
  32. package/dist/internal/shared/ip.js +43 -53
  33. package/dist/internal/shared/ip.js.map +1 -0
  34. package/dist/internal/verify/name-constraints-engine.js +211 -239
  35. package/dist/internal/verify/name-constraints-engine.js.map +1 -0
  36. package/dist/internal/verify/policy-engine.js +228 -247
  37. package/dist/internal/verify/policy-engine.js.map +1 -0
  38. package/dist/internal/verify/verify-path.js +213 -228
  39. package/dist/internal/verify/verify-path.js.map +1 -0
  40. package/dist/internal/x509/extension-bits.js +62 -59
  41. package/dist/internal/x509/extension-bits.js.map +1 -0
  42. package/dist/internal/x509/extension-registry.js +133 -164
  43. package/dist/internal/x509/extension-registry.js.map +1 -0
  44. package/dist/internal/x509/name-fields.js +35 -41
  45. package/dist/internal/x509/name-fields.js.map +1 -0
  46. package/dist/keys/keys.d.ts +583 -547
  47. package/dist/keys/keys.js +519 -431
  48. package/dist/keys/keys.js.map +1 -0
  49. package/dist/keys.js +2 -2
  50. package/dist/pem/pem.d.ts +46 -46
  51. package/dist/pem/pem.js +62 -81
  52. package/dist/pem/pem.js.map +1 -0
  53. package/dist/pem.js +2 -2
  54. package/dist/pkcs/pfx.d.ts +96 -80
  55. package/dist/pkcs/pfx.js +191 -231
  56. package/dist/pkcs/pfx.js.map +1 -0
  57. package/dist/pkcs/pkcs12-mac.d.ts +20 -18
  58. package/dist/pkcs/pkcs12-mac.js +90 -111
  59. package/dist/pkcs/pkcs12-mac.js.map +1 -0
  60. package/dist/pkcs/pkcs7.d.ts +118 -69
  61. package/dist/pkcs/pkcs7.js +401 -443
  62. package/dist/pkcs/pkcs7.js.map +1 -0
  63. package/dist/pkcs.d.ts +2 -2
  64. package/dist/pkcs.js +4 -4
  65. package/dist/result/result.d.ts +37 -32
  66. package/dist/result/result.js +46 -44
  67. package/dist/result/result.js.map +1 -0
  68. package/dist/result.js +2 -2
  69. package/dist/revocation/chain.d.ts +138 -119
  70. package/dist/revocation/chain.js +248 -281
  71. package/dist/revocation/chain.js.map +1 -0
  72. package/dist/revocation/crl.d.ts +125 -123
  73. package/dist/revocation/crl.js +653 -745
  74. package/dist/revocation/crl.js.map +1 -0
  75. package/dist/revocation/ocsp.d.ts +183 -177
  76. package/dist/revocation/ocsp.js +579 -636
  77. package/dist/revocation/ocsp.js.map +1 -0
  78. package/dist/revocation/revocation.d.ts +26 -26
  79. package/dist/revocation/revocation.js +104 -125
  80. package/dist/revocation/revocation.js.map +1 -0
  81. package/dist/revocation.js +5 -5
  82. package/dist/verify/identity.d.ts +42 -42
  83. package/dist/verify/identity.js +158 -167
  84. package/dist/verify/identity.js.map +1 -0
  85. package/dist/verify/name-constraints.d.ts +7 -7
  86. package/dist/verify/policy.d.ts +10 -10
  87. package/dist/verify/verify.d.ts +163 -163
  88. package/dist/verify/verify.js +396 -392
  89. package/dist/verify/verify.js.map +1 -0
  90. package/dist/verify.js +3 -3
  91. package/dist/x509/certificate.d.ts +117 -117
  92. package/dist/x509/certificate.js +51 -60
  93. package/dist/x509/certificate.js.map +1 -0
  94. package/dist/x509/csr.d.ts +25 -25
  95. package/dist/x509/csr.js +26 -30
  96. package/dist/x509/csr.js.map +1 -0
  97. package/dist/x509/extensions.d.ts +228 -184
  98. package/dist/x509/extensions.js +175 -200
  99. package/dist/x509/extensions.js.map +1 -0
  100. package/dist/x509/fingerprint.d.ts +55 -0
  101. package/dist/x509/fingerprint.js +55 -0
  102. package/dist/x509/fingerprint.js.map +1 -0
  103. package/dist/x509/name.d.ts +94 -93
  104. package/dist/x509/name.js +30 -29
  105. package/dist/x509/name.js.map +1 -0
  106. package/dist/x509/parse.d.ts +288 -185
  107. package/dist/x509/parse.js +762 -677
  108. package/dist/x509/parse.js.map +1 -0
  109. package/dist/x509.d.ts +3 -2
  110. package/dist/x509.js +7 -6
  111. package/package.json +79 -41
@@ -1,15 +1,15 @@
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";
1
+ import { encodeLength as e, readElement as t, readRootElement as n, readSequenceChildren as r } from "../internal/asn1/der.js";
2
+ 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";
3
+ import { OIDS as m } from "../internal/asn1/oids2.js";
4
+ import { failureResult as h, rethrowIfInvariant as g, successResult as _ } from "../result/result.js";
5
+ import { pemDecodeOrThrow as v, splitPemBlocksOrThrow as y } from "../pem/pem.js";
6
+ import { derivePublicKey as b, exportSpkiDer as x, importSpkiDer as S, importSpkiDerOrThrow as C } from "../keys/keys.js";
7
+ import { describePublicKeyAlgorithm as w, describeSignatureAlgorithm as T } from "../internal/crypto/algorithm-names.js";
8
+ import { decodeIpAddress as E } from "../internal/shared/ip.js";
9
+ import { parseDistributionPointReasonFlagsContent as D, parseKeyUsageExtension as O } from "../internal/x509/extension-bits.js";
10
+ import { nameFieldKeyFromOid as k } from "../internal/x509/name-fields.js";
11
+ import { parseAuthorityInfoAccessMethodOid as A, parseExtendedKeyUsageOid as j } from "./extensions.js";
12
+ import { decodeAndApplyKnownExtension as M } from "../internal/x509/extension-registry.js";
13
13
  //#region src/x509/parse.ts
14
14
  /**
15
15
  * Certificate and CSR parse boundary.
@@ -22,15 +22,15 @@ import { decodeAndApplyKnownExtension } from "../internal/x509/extension-registr
22
22
  * @module
23
23
  */
24
24
  /** Shared UTF-8 decoder for IA5String / UTF8String values. */
25
- const textDecoder = new TextDecoder();
25
+ const N = new TextDecoder();
26
26
  /**
27
27
  * Identity helper that narrows the type of a custom {@linkcode ExtensionDecoder} literal.
28
28
  *
29
29
  * @param decoder Decoder definition to return unchanged.
30
30
  * @returns The same decoder, properly typed.
31
31
  */
32
- function defineExtensionDecoder(decoder) {
33
- return decoder;
32
+ function defineExtensionDecoder(e) {
33
+ return e;
34
34
  }
35
35
  /**
36
36
  * Identity helper that narrows the type of a custom {@linkcode ExtensionDecoderMap} literal.
@@ -38,8 +38,8 @@ function defineExtensionDecoder(decoder) {
38
38
  * @param decoderMap Map of named decoders to return unchanged.
39
39
  * @returns The same map, properly typed.
40
40
  */
41
- function defineExtensionDecoderMap(decoderMap) {
42
- return decoderMap;
41
+ function defineExtensionDecoderMap(e) {
42
+ return e;
43
43
  }
44
44
  /**
45
45
  * Throwing core for {@linkcode parseCertificateDer}.
@@ -52,94 +52,99 @@ function defineExtensionDecoderMap(decoderMap) {
52
52
  * @param der Raw DER bytes of an X.509 certificate.
53
53
  * @param options Custom extension decoders to apply during parsing.
54
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);
55
+ function parseCertificateDerOrThrow(e, t) {
56
+ let n = r(e, { maxDepth: 64 });
57
+ if (n.length !== 3) throw Error("Malformed Certificate");
58
+ let i = f(n[0], "TBSCertificate"), a = f(n[1], "signatureAlgorithm"), o = f(n[2], "signatureValue"), s = parseTbsCertificateFields(e, i), c = parseExtensionContainer(e, s.extensions), l = parseValidity(e, s.validity), d = parseSubjectPublicKeyInfo(e, s.subjectPublicKeyInfo), m = parseAlgorithmIdentifier(e, s.tbsSignatureAlgorithm), h = parseAlgorithmIdentifier(e, a);
59
+ assertMatchingCertificateSignatureAlgorithms(m, h);
60
+ let g = parseCustomExtensions(c.all, t);
107
61
  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 } : {}
62
+ der: new Uint8Array(e),
63
+ version: s.version,
64
+ serialNumberHex: p(s.serialNumber.value),
65
+ tbsCertificateDer: e.slice(i.start - i.headerLength, i.end),
66
+ subjectPublicKeyInfoDer: e.slice(s.subjectPublicKeyInfo.start - s.subjectPublicKeyInfo.headerLength, s.subjectPublicKeyInfo.end),
67
+ signatureValue: u(o),
68
+ issuer: parseName(e, s.issuer),
69
+ subject: parseName(e, s.subject),
70
+ notBefore: l.notBefore,
71
+ notAfter: l.notAfter,
72
+ signatureAlgorithmOid: h.oid,
73
+ signatureAlgorithmName: T(h.oid, h.parametersDer),
74
+ ...h.parametersDer === void 0 ? {} : { signatureAlgorithmParametersDer: h.parametersDer },
75
+ publicKeyAlgorithmOid: d.oid,
76
+ publicKeyAlgorithmName: w(d.oid, d.parametersOid),
77
+ ...d.parametersDer === void 0 ? {} : { publicKeyAlgorithmParametersDer: d.parametersDer },
78
+ ...d.parametersOid === void 0 ? {} : { publicKeyParametersOid: d.parametersOid },
79
+ extensions: c.all,
80
+ ...c.basicConstraints === void 0 ? {} : { basicConstraints: c.basicConstraints },
81
+ ...c.keyUsage === void 0 ? {} : { keyUsage: c.keyUsage },
82
+ ...c.extendedKeyUsage === void 0 ? {} : { extendedKeyUsage: c.extendedKeyUsage },
83
+ ...c.subjectAltNames === void 0 ? {} : { subjectAltNames: c.subjectAltNames },
84
+ ...c.nameConstraints === void 0 ? {} : { nameConstraints: c.nameConstraints },
85
+ ...c.certificatePolicies === void 0 ? {} : { certificatePolicies: c.certificatePolicies },
86
+ ...c.policyMappings === void 0 ? {} : { policyMappings: c.policyMappings },
87
+ ...c.policyConstraints === void 0 ? {} : { policyConstraints: c.policyConstraints },
88
+ ...c.inhibitAnyPolicy === void 0 ? {} : { inhibitAnyPolicy: c.inhibitAnyPolicy },
89
+ ...c.authorityInfoAccess === void 0 ? {} : { authorityInfoAccess: c.authorityInfoAccess },
90
+ ...c.crlDistributionPoints === void 0 ? {} : { crlDistributionPoints: c.crlDistributionPoints },
91
+ ...g.decodedExtensions === void 0 ? {} : { decodedExtensions: g.decodedExtensions },
92
+ ...g.decodedExtensionMap === void 0 ? {} : { decodedExtensionMap: g.decodedExtensionMap },
93
+ ...c.subjectKeyIdentifier === void 0 ? {} : { subjectKeyIdentifier: c.subjectKeyIdentifier },
94
+ ...c.authorityKeyIdentifier === void 0 ? {} : { authorityKeyIdentifier: c.authorityKeyIdentifier }
141
95
  };
142
96
  }
97
+ function parseCustomExtensions(e, t) {
98
+ return {
99
+ ...t?.decoders === void 0 ? {} : { decodedExtensions: decodeExtensions(e, t.decoders) },
100
+ ...t?.decoderMap === void 0 ? {} : { decodedExtensionMap: decodeExtensionMap(e, t.decoderMap) }
101
+ };
102
+ }
103
+ /** Extracts and validates the structural fields of a TBSCertificate sequence. */
104
+ function parseTbsCertificateFields(e, t) {
105
+ let n = i(e, t), r = parseCertificateVersionField(e, n), a = r.version, o = r.nextIndex, s = f(n[o], "serialNumber");
106
+ if (s.tag !== 2) throw Error("serialNumber must use INTEGER");
107
+ let c = validateOptionalTbsCertificateFields(n, o + 6, a);
108
+ return {
109
+ version: a,
110
+ serialNumber: s,
111
+ tbsSignatureAlgorithm: f(n[o + 1], "TBSCertificate signature"),
112
+ issuer: f(n[o + 2], "issuer"),
113
+ validity: f(n[o + 3], "validity"),
114
+ subject: f(n[o + 4], "subject"),
115
+ subjectPublicKeyInfo: f(n[o + 5], "subjectPublicKeyInfo"),
116
+ ...n[c - 1]?.tag === 163 ? { extensions: n[c - 1] } : {}
117
+ };
118
+ }
119
+ function parseCertificateVersionField(e, t) {
120
+ let n = t[0];
121
+ if (n?.tag !== 160) return {
122
+ version: 1,
123
+ nextIndex: 0
124
+ };
125
+ let r = i(e, n), a = f(r[0], "version INTEGER");
126
+ if (r.length !== 1 || a.tag !== 2) throw Error("version must use INTEGER");
127
+ let s = o(a.value) + 1;
128
+ if (s < 1 || s > 3) throw Error(`Unsupported certificate version: ${String(s)}`);
129
+ return {
130
+ version: s,
131
+ nextIndex: 1
132
+ };
133
+ }
134
+ function validateOptionalTbsCertificateFields(e, t, n) {
135
+ let r = t;
136
+ if (e[r]?.tag === 129 && (validateCertificateUniqueId(e[r], n, "issuerUniqueID"), r += 1), e[r]?.tag === 130 && (validateCertificateUniqueId(e[r], n, "subjectUniqueID"), r += 1), e[r]?.tag === 163) {
137
+ if (n !== 3) throw Error("extensions require certificate version 3");
138
+ r += 1;
139
+ }
140
+ if (r !== e.length) throw Error(`Unsupported TBSCertificate field tag: ${String(f(e[r], "TBSCertificate field").tag)}`);
141
+ return r;
142
+ }
143
+ function validateCertificateUniqueId(e, t, n) {
144
+ let r = f(e, n);
145
+ if (t < 2) throw Error(`${n} requires certificate version 2 or 3`);
146
+ validateImplicitBitStringContent(r.value, n);
147
+ }
143
148
  /**
144
149
  * Decode a DER-encoded X.509 certificate into a {@linkcode ParsedCertificate}.
145
150
  *
@@ -156,12 +161,11 @@ function parseCertificateDerOrThrow(der, options) {
156
161
  * @param der Raw DER bytes of an X.509 certificate.
157
162
  * @param options Custom extension decoders to apply during parsing.
158
163
  */
159
- function parseCertificateDer(der, options) {
164
+ function parseCertificateDer(e, t) {
160
165
  try {
161
- return successResult(parseCertificateDerOrThrow(der, options));
162
- } catch (error) {
163
- rethrowIfInvariant(error);
164
- return failureResult("malformed", error instanceof Error ? error.message : "Malformed certificate");
166
+ return _(parseCertificateDerOrThrow(e, t));
167
+ } catch (e) {
168
+ return g(e), h("malformed", e instanceof Error ? e.message : "Malformed certificate");
165
169
  }
166
170
  }
167
171
  /**
@@ -182,8 +186,8 @@ function parseCertificateDer(der, options) {
182
186
  * @param pem PEM string with a CERTIFICATE block.
183
187
  * @param options Custom extension decoders to apply during parsing.
184
188
  */
185
- function parseCertificatePemOrThrow(pem, options) {
186
- return parseCertificateDerOrThrow(pemDecodeOrThrow("CERTIFICATE", pem), options);
189
+ function parseCertificatePemOrThrow(e, t) {
190
+ return parseCertificateDerOrThrow(v("CERTIFICATE", e), t);
187
191
  }
188
192
  /**
189
193
  * Decode a PEM-encoded X.509 certificate into a {@linkcode ParsedCertificate}.
@@ -194,23 +198,20 @@ function parseCertificatePemOrThrow(pem, options) {
194
198
  * @param pem PEM string with a CERTIFICATE block.
195
199
  * @param options Custom extension decoders to apply during parsing.
196
200
  */
197
- function parseCertificatePem(pem, options) {
201
+ function parseCertificatePem(e, t) {
198
202
  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
+ return _(parseCertificatePemOrThrow(e, t));
204
+ } catch (e) {
205
+ return g(e), h("malformed", e instanceof Error ? e.message : "Malformed certificate");
203
206
  }
204
207
  }
205
208
  /** 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)];
209
+ function parseCertificatesFromSource(e, t) {
210
+ return typeof e == "string" ? parseCertificatesFromPemBlocks(e, t) : [parseCertificateDerOrThrow(new Uint8Array(e), t)];
208
211
  }
209
212
  /** 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);
213
+ function parseCertificateFromSource(e, t) {
214
+ return typeof e == "string" ? parseCertificatePemOrThrow(e, t) : hasParsedCertificateShape(e) ? e : parseCertificateDerOrThrow(new Uint8Array(e), t);
214
215
  }
215
216
  /**
216
217
  * Decode a PEM bundle containing one or more certificates.
@@ -220,8 +221,8 @@ function parseCertificateFromSource(source, options) {
220
221
  * @param pemBundle PEM text that may contain multiple CERTIFICATE blocks.
221
222
  * @param options Custom extension decoders to apply during parsing.
222
223
  */
223
- function parseCertificateChainPem(pemBundle, options) {
224
- return parseCertificatesFromPemBlocks(pemBundle, options);
224
+ function parseCertificateChainPem(e, t) {
225
+ return parseCertificatesFromPemBlocks(e, t);
225
226
  }
226
227
  /**
227
228
  * Decode a DER-encoded PKCS#10 CSR into a {@linkcode ParsedCertificateSigningRequest}.
@@ -229,54 +230,53 @@ function parseCertificateChainPem(pemBundle, options) {
229
230
  * @param der Raw DER bytes of a PKCS#10 certificate signing request.
230
231
  * @param options Custom extension decoders to apply during parsing.
231
232
  */
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);
233
+ function parseCertificateSigningRequestDerOrThrow(e, t) {
234
+ let n = r(e, { maxDepth: 64 });
235
+ if (n.length !== 3) throw Error("Malformed CertificationRequest");
236
+ let i = f(n[0], "CertificationRequestInfo"), a = f(n[1], "signatureAlgorithm"), o = f(n[2], "signatureValue"), s = parseCertificationRequestInfoFields(e, i), c = parseRequestedExtensions(e, s.attributes), l = parseSubjectPublicKeyInfo(e, s.subjectPublicKeyInfo), d = parseAlgorithmIdentifier(e, a), p = parseCustomExtensions(c.all, t);
253
237
  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 } : {}
238
+ version: s.version,
239
+ certificationRequestInfoDer: e.slice(i.start - i.headerLength, i.end),
240
+ subjectPublicKeyInfoDer: e.slice(s.subjectPublicKeyInfo.start - s.subjectPublicKeyInfo.headerLength, s.subjectPublicKeyInfo.end),
241
+ signatureValue: u(o),
242
+ subject: parseName(e, s.subject),
243
+ signatureAlgorithmOid: d.oid,
244
+ signatureAlgorithmName: T(d.oid, d.parametersDer),
245
+ ...d.parametersDer === void 0 ? {} : { signatureAlgorithmParametersDer: d.parametersDer },
246
+ publicKeyAlgorithmOid: l.oid,
247
+ publicKeyAlgorithmName: w(l.oid, l.parametersOid),
248
+ ...l.parametersDer === void 0 ? {} : { publicKeyAlgorithmParametersDer: l.parametersDer },
249
+ ...l.parametersOid === void 0 ? {} : { publicKeyParametersOid: l.parametersOid },
250
+ requestedExtensions: c.all,
251
+ ...c.basicConstraints === void 0 ? {} : { basicConstraints: c.basicConstraints },
252
+ ...c.keyUsage === void 0 ? {} : { keyUsage: c.keyUsage },
253
+ ...c.extendedKeyUsage === void 0 ? {} : { extendedKeyUsage: c.extendedKeyUsage },
254
+ ...c.subjectAltNames === void 0 ? {} : { subjectAltNames: c.subjectAltNames },
255
+ ...c.nameConstraints === void 0 ? {} : { nameConstraints: c.nameConstraints },
256
+ ...c.certificatePolicies === void 0 ? {} : { certificatePolicies: c.certificatePolicies },
257
+ ...c.policyMappings === void 0 ? {} : { policyMappings: c.policyMappings },
258
+ ...c.policyConstraints === void 0 ? {} : { policyConstraints: c.policyConstraints },
259
+ ...c.inhibitAnyPolicy === void 0 ? {} : { inhibitAnyPolicy: c.inhibitAnyPolicy },
260
+ ...c.authorityInfoAccess === void 0 ? {} : { authorityInfoAccess: c.authorityInfoAccess },
261
+ ...c.crlDistributionPoints === void 0 ? {} : { crlDistributionPoints: c.crlDistributionPoints },
262
+ ...p.decodedExtensions === void 0 ? {} : { decodedExtensions: p.decodedExtensions },
263
+ ...p.decodedExtensionMap === void 0 ? {} : { decodedExtensionMap: p.decodedExtensionMap }
264
+ };
265
+ }
266
+ function parseCertificationRequestInfoFields(e, t) {
267
+ let n = i(e, t);
268
+ if (n.length < 3 || n.length > 4) throw Error("Malformed CertificationRequestInfo");
269
+ let r = f(n[0], "version");
270
+ if (r.tag !== 2) throw Error("version must use INTEGER");
271
+ let a = o(r.value) + 1;
272
+ if (a !== 1) throw Error(`Unsupported CertificationRequestInfo version: ${String(a)}`);
273
+ let s = n[3];
274
+ if (s !== void 0 && s.tag !== 160) throw Error("CertificationRequestInfo attributes must use [0]");
275
+ return {
276
+ version: a,
277
+ subject: f(n[1], "subject"),
278
+ subjectPublicKeyInfo: f(n[2], "subjectPublicKeyInfo"),
279
+ ...s === void 0 ? {} : { attributes: s }
280
280
  };
281
281
  }
282
282
  /**
@@ -285,19 +285,18 @@ function parseCertificateSigningRequestDerOrThrow(der, options) {
285
285
  * @param der Raw DER bytes of a PKCS#10 certificate signing request.
286
286
  * @param options Custom extension decoders to apply during parsing.
287
287
  */
288
- function parseCertificateSigningRequestDer(der, options) {
288
+ function parseCertificateSigningRequestDer(e, t) {
289
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");
290
+ return _(parseCertificateSigningRequestDerOrThrow(e, t));
291
+ } catch (e) {
292
+ return g(e), h("malformed", e instanceof Error ? e.message : "Malformed certificate signing request");
294
293
  }
295
294
  }
296
- function parseCertificatesFromPemBlocks(pemBundle, options) {
297
- return splitPemBlocksOrThrow(pemBundle).filter((block) => block.label === "CERTIFICATE").map((block) => parseCertificateDerOrThrow(block.bytes, options));
295
+ function parseCertificatesFromPemBlocks(e, t) {
296
+ return y(e).filter((e) => e.label === "CERTIFICATE").map((e) => parseCertificateDerOrThrow(e.bytes, t));
298
297
  }
299
- function hasParsedCertificateShape(value) {
300
- return "subjectPublicKeyInfoDer" in value;
298
+ function hasParsedCertificateShape(e) {
299
+ return "subjectPublicKeyInfoDer" in e;
301
300
  }
302
301
  /**
303
302
  * Decode a PEM-encoded PKCS#10 CSR into a {@linkcode ParsedCertificateSigningRequest}.
@@ -305,8 +304,8 @@ function hasParsedCertificateShape(value) {
305
304
  * @param pem PEM string with a CERTIFICATE REQUEST block.
306
305
  * @param options Custom extension decoders to apply during parsing.
307
306
  */
308
- function parseCertificateSigningRequestPemOrThrow(pem, options) {
309
- return parseCertificateSigningRequestDerOrThrow(pemDecodeOrThrow("CERTIFICATE REQUEST", pem), options);
307
+ function parseCertificateSigningRequestPemOrThrow(e, t) {
308
+ return parseCertificateSigningRequestDerOrThrow(v("CERTIFICATE REQUEST", e), t);
310
309
  }
311
310
  /**
312
311
  * Decode a PEM-encoded PKCS#10 CSR into a {@linkcode ParsedCertificateSigningRequest}.
@@ -314,12 +313,11 @@ function parseCertificateSigningRequestPemOrThrow(pem, options) {
314
313
  * @param pem PEM string with a CERTIFICATE REQUEST block.
315
314
  * @param options Custom extension decoders to apply during parsing.
316
315
  */
317
- function parseCertificateSigningRequestPem(pem, options) {
316
+ function parseCertificateSigningRequestPem(e, t) {
318
317
  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");
318
+ return _(parseCertificateSigningRequestPemOrThrow(e, t));
319
+ } catch (e) {
320
+ return g(e), h("malformed", e instanceof Error ? e.message : "Malformed certificate signing request");
323
321
  }
324
322
  }
325
323
  /**
@@ -350,16 +348,139 @@ function parseCertificateSigningRequestPem(pem, options) {
350
348
  *
351
349
  * @see {@linkcode getSubjectPublicKey} for the non-throwing variant
352
350
  */
353
- function getSubjectPublicKeyOrThrow(parsed, algorithm) {
354
- return importSpkiDerOrThrow(parsed.subjectPublicKeyInfoDer, algorithm);
351
+ function getSubjectPublicKeyOrThrow(e, t) {
352
+ return C(e.subjectPublicKeyInfoDer, t);
355
353
  }
356
354
  /**
357
355
  * Import the subject public key of a parsed certificate or CSR as a WebCrypto `CryptoKey`.
358
356
  *
359
357
  * @see `getSubjectPublicKeyOrThrow` for the throwing variant
360
358
  */
361
- function getSubjectPublicKey(parsed, algorithm) {
362
- return importSpkiDer(parsed.subjectPublicKeyInfoDer, algorithm);
359
+ function getSubjectPublicKey(e, t) {
360
+ return S(e.subjectPublicKeyInfoDer, t);
361
+ }
362
+ /** Extract the AlgorithmIdentifier TLV from a SubjectPublicKeyInfo DER buffer. */
363
+ function subjectPublicKeyInfoAlgorithmDer(e) {
364
+ let t = f(r(e, { maxDepth: 64 })[0], "SubjectPublicKeyInfo algorithm");
365
+ return e.slice(t.start - t.headerLength, t.end);
366
+ }
367
+ /**
368
+ * Derive the public half of `privateKey`, export it as SPKI DER, and classify
369
+ * how it relates to a certificate's SubjectPublicKeyInfo. Single source of truth
370
+ * for {@linkcode certificateMatchesPrivateKey} and {@linkcode matchCertificatePrivateKey}.
371
+ *
372
+ * Equal SPKI bytes mean the key owns the certificate. When they differ, the
373
+ * AlgorithmIdentifier portions decide whether it is a same-algorithm key
374
+ * mismatch or a cross-algorithm (`key_type_mismatch`) one.
375
+ */
376
+ async function compareCertificateToPrivateKey(e, t) {
377
+ let n = await x(await b(t));
378
+ return optionalBytesEqual(n, e) ? "match" : optionalBytesEqual(subjectPublicKeyInfoAlgorithmDer(n), subjectPublicKeyInfoAlgorithmDer(e)) ? "key_mismatch" : "key_type_mismatch";
379
+ }
380
+ /**
381
+ * Check whether a certificate's subject public key belongs to a private key.
382
+ *
383
+ * Confirming that an uploaded private key actually matches the certificate it
384
+ * was submitted with is the first thing a key-intake or issuance endpoint must
385
+ * do. This derives the public half of `privateKey`, exports it as
386
+ * SubjectPublicKeyInfo DER, and compares those bytes against the certificate's
387
+ * own SubjectPublicKeyInfo — the canonical, algorithm-agnostic way to test key
388
+ * ownership. (Comparing JWKs field by field, or signing a probe and verifying
389
+ * it, are both more fragile.)
390
+ *
391
+ * A private key of a different type — e.g. an ECDSA key against an RSA
392
+ * certificate — simply produces different SPKI DER and returns `false`, so
393
+ * callers get a single boolean without branching on the kind of mismatch. Reach
394
+ * for {@linkcode matchCertificatePrivateKey} when you need the reason a match
395
+ * failed (or a typed failure instead of a thrown error) at a trust boundary.
396
+ *
397
+ * The comparison is over the exact DER encoding. A certificate whose
398
+ * SubjectPublicKeyInfo pins RSASSA-PSS parameters (rather than the plain
399
+ * `rsaEncryption` OID that WebCrypto emits) therefore will not match even for
400
+ * the same modulus; such certificates are rare in practice.
401
+ *
402
+ * @param certificate PEM string, DER bytes, or an already-parsed certificate.
403
+ * @param privateKey An extractable private `CryptoKey`.
404
+ * @returns `true` when the private key's public half matches the certificate's
405
+ * subject public key.
406
+ *
407
+ * @throws {Error} If `certificate` is malformed, or `privateKey` is not an
408
+ * extractable private key of a supported type (propagated from
409
+ * {@linkcode derivePublicKey}). Use {@linkcode matchCertificatePrivateKey} for a
410
+ * typed `Result` instead of thrown errors.
411
+ *
412
+ * @example
413
+ * ```ts
414
+ * const privateKey = await importPkcs8PemOrThrow(keyPem, { kind: 'ecdsa', curve: 'P-256' });
415
+ * if (!(await certificateMatchesPrivateKey(certificatePem, privateKey))) {
416
+ * throw new Error('uploaded key does not match the certificate');
417
+ * }
418
+ * ```
419
+ *
420
+ * @see {@linkcode matchCertificatePrivateKey} for the typed-`Result` variant with a mismatch reason
421
+ * @see {@linkcode getSubjectPublicKeyOrThrow} to obtain the certificate's public key directly
422
+ * @see {@linkcode derivePublicKey} for the private-to-public bridge this builds on
423
+ */
424
+ async function certificateMatchesPrivateKey(e, t) {
425
+ return await compareCertificateToPrivateKey(parseCertificateFromSource(e).subjectPublicKeyInfoDer, t) === "match";
426
+ }
427
+ /**
428
+ * Check whether a certificate's subject public key belongs to a private key,
429
+ * returning a typed {@linkcode MatchCertificatePrivateKeyResult}.
430
+ *
431
+ * The `Result`-returning companion to {@linkcode certificateMatchesPrivateKey}:
432
+ * where the boolean helper answers only "does it match?" (and throws on bad
433
+ * input), this surfaces the expected failures a key-intake or issuance endpoint
434
+ * meets on untrusted input as typed codes rather than exceptions — matching the
435
+ * house rule of returning `Result` for expected failures and throwing only for
436
+ * invariants. `ok: true` means the key owns the certificate; a failure carries
437
+ * one of:
438
+ *
439
+ * - `malformed_certificate` — `certificate` could not be parsed.
440
+ * - `unsupported_private_key` — `privateKey` is not an extractable private key
441
+ * of a supported type (from {@linkcode derivePublicKey}).
442
+ * - `key_type_mismatch` — the key is a different algorithm than the
443
+ * certificate's subject public key.
444
+ * - `key_mismatch` — the key is the right algorithm but a different key.
445
+ *
446
+ * As with {@linkcode certificateMatchesPrivateKey}, the comparison is over exact
447
+ * SPKI DER, so a certificate pinning RSASSA-PSS parameters reports
448
+ * `key_type_mismatch` against the `rsaEncryption` SPKI WebCrypto emits.
449
+ *
450
+ * @param certificate PEM string, DER bytes, or an already-parsed certificate.
451
+ * @param privateKey An extractable private `CryptoKey`.
452
+ * @returns A success when the key matches, or a typed failure otherwise.
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * const result = await matchCertificatePrivateKey(certificatePem, privateKey);
457
+ * if (!result.ok) {
458
+ * // result.code is 'malformed_certificate' | 'unsupported_private_key'
459
+ * // | 'key_type_mismatch' | 'key_mismatch'
460
+ * throw new Error(`key does not match certificate: ${result.code}`);
461
+ * }
462
+ * ```
463
+ *
464
+ * @see {@linkcode certificateMatchesPrivateKey} for the plain-boolean variant
465
+ */
466
+ async function matchCertificatePrivateKey(e, t) {
467
+ let n;
468
+ try {
469
+ n = parseCertificateFromSource(e);
470
+ } catch (e) {
471
+ return g(e), h("malformed_certificate", e instanceof Error ? e.message : "Malformed certificate");
472
+ }
473
+ let r;
474
+ try {
475
+ r = await compareCertificateToPrivateKey(n.subjectPublicKeyInfoDer, t);
476
+ } catch (e) {
477
+ return g(e), h("unsupported_private_key", e instanceof Error ? e.message : "Unsupported private key");
478
+ }
479
+ switch (r) {
480
+ case "match": return _(void 0);
481
+ case "key_mismatch": return h("key_mismatch", "Private key does not match the certificate's subject public key");
482
+ case "key_type_mismatch": return h("key_type_mismatch", "Private key algorithm does not match the certificate's subject public key algorithm");
483
+ }
363
484
  }
364
485
  /**
365
486
  * Find a raw extension by OID within a parsed extension list.
@@ -368,8 +489,8 @@ function getSubjectPublicKey(parsed, algorithm) {
368
489
  * @param oid Dotted-decimal OID to look up.
369
490
  * @returns The matching extension, or `undefined` if not present.
370
491
  */
371
- function findExtension(extensions, oid) {
372
- return extensions.find((extension) => extension.oid === oid);
492
+ function findExtension(e, t) {
493
+ return e.find((e) => e.oid === t);
373
494
  }
374
495
  /**
375
496
  * Decode a single extension using a custom {@linkcode ExtensionDecoder}.
@@ -378,10 +499,9 @@ function findExtension(extensions, oid) {
378
499
  * @param decoder Decoder whose OID will be matched.
379
500
  * @returns The decoded value, or `undefined` if the extension is absent.
380
501
  */
381
- function decodeExtension(extensions, decoder) {
382
- const extension = findExtension(extensions, decoder.oid);
383
- if (extension === void 0) return;
384
- return decoder.decode(extension);
502
+ function decodeExtension(e, t) {
503
+ let n = findExtension(e, t.oid);
504
+ if (n !== void 0) return t.decode(n);
385
505
  }
386
506
  /**
387
507
  * Decode all matching extensions using an array of {@linkcode ExtensionDecoder}s.
@@ -389,18 +509,17 @@ function decodeExtension(extensions, decoder) {
389
509
  * @param extensions Extension list to search.
390
510
  * @param decoders Decoders to apply. Only matching OIDs produce output.
391
511
  */
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)
512
+ function decodeExtensions(e, t) {
513
+ let n = [];
514
+ for (let r of t) {
515
+ let t = findExtension(e, r.oid);
516
+ t !== void 0 && n.push({
517
+ oid: t.oid,
518
+ critical: t.critical,
519
+ value: r.decode(t)
401
520
  });
402
521
  }
403
- return decoded;
522
+ return n;
404
523
  }
405
524
  /**
406
525
  * Decode all matching extensions using a named {@linkcode ExtensionDecoderMap}.
@@ -408,488 +527,446 @@ function decodeExtensions(extensions, decoders) {
408
527
  * @param extensions Extension list to search.
409
528
  * @param decoderMap Named decoders. Results are keyed by the same map keys.
410
529
  */
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)
530
+ function decodeExtensionMap(e, t) {
531
+ let n = {};
532
+ for (let r in t) {
533
+ let i = t[r];
534
+ if (i === void 0) continue;
535
+ let a = findExtension(e, i.oid);
536
+ a !== void 0 && (n = {
537
+ ...n,
538
+ [r]: {
539
+ oid: a.oid,
540
+ critical: a.critical,
541
+ value: i.decode(a)
424
542
  }
425
- };
543
+ });
426
544
  }
427
- return decoded;
545
+ return n;
428
546
  }
429
547
  /** 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");
548
+ function parseExtensionContainer(e, t) {
549
+ return t === void 0 ? { all: [] } : parseExtensionSequence(e, f(i(e, t)[0], "extensions sequence"), "certificate");
433
550
  }
434
551
  /** 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");
552
+ function parseRequestedExtensions(e, t) {
553
+ if (t === void 0) return { all: [] };
554
+ if (t.tag !== 160) throw Error("CertificationRequestInfo attributes must use [0]");
555
+ let n;
556
+ for (let r of i(e, t)) {
557
+ let t = i(e, r);
558
+ if (t.length !== 2) throw Error("Malformed CSR attribute");
559
+ if (c(f(t[0], "attribute OID").value) !== m.extensionRequest) continue;
560
+ if (n !== void 0) throw Error("extensionRequest attribute must not repeat");
561
+ let a = f(t[1], "attribute values");
562
+ if (a.tag !== 49) throw Error("extensionRequest attribute values must use SET");
563
+ let o = i(e, a);
564
+ if (o.length !== 1) throw Error("extensionRequest attribute must contain exactly one value");
565
+ n = parseExtensionSequence(e, f(o[0], "requested extensions"), "csr");
449
566
  }
450
- return requestedExtensions ?? { all: [] };
567
+ return n ?? { all: [] };
451
568
  }
452
569
  /** 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);
570
+ function parseExtensionSequence(e, t, n) {
571
+ let r = [], o = {}, s = /* @__PURE__ */ new Set();
572
+ for (let l of i(e, t)) {
573
+ let t = i(e, l);
574
+ if (t.length < 2 || t.length > 3) throw Error("Malformed Extension");
575
+ let u = c(f(t[0], "extension OID").value);
576
+ if (s.has(u)) throw Error(`Duplicate extension OID: ${u}`);
577
+ s.add(u);
578
+ let d = 1, m = !1, h = t[d];
579
+ h?.tag === 1 && (m = a(h.value), d += 1);
580
+ let g = f(t[d], "extension value");
581
+ if (g.tag !== 4 || d !== t.length - 1) throw Error("Extension value must use OCTET STRING");
582
+ r.push({
583
+ oid: u,
584
+ critical: m,
585
+ valueDer: new Uint8Array(g.value),
586
+ valueHex: p(g.value)
587
+ }), M(n, u, o, g.value);
479
588
  }
480
589
  return {
481
- all: parsed,
482
- ...knownParsed
590
+ all: r,
591
+ ...o
483
592
  };
484
593
  }
485
594
  /** 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
- }
595
+ function parseName(e, t) {
596
+ let n = [], r = [], a = {};
597
+ for (let o of i(e, t)) {
598
+ let t = parseNameAttributeSet(e, o);
599
+ n.push(t);
600
+ for (let e of t.attributes) r.push(e), e.key !== void 0 && a[e.key] === void 0 && (a[e.key] = e.value);
497
601
  }
498
602
  return {
499
- derHex: toHex(source.slice(element.start - element.headerLength, element.end)),
500
- rdns,
501
- attributes,
502
- values
603
+ derHex: p(e.slice(t.start - t.headerLength, t.end)),
604
+ rdns: n,
605
+ attributes: r,
606
+ values: a
503
607
  };
504
608
  }
505
609
  /** Decode a single RDN SET element. */
506
- function parseRelativeDistinguishedName(source, element) {
507
- return parseNameAttributeSet(source, element);
610
+ function parseRelativeDistinguishedName(e, t) {
611
+ return parseNameAttributeSet(e, t);
508
612
  }
509
613
  /** 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
614
+ function parseNameAttributeSet(e, t) {
615
+ let n = [], r = {};
616
+ for (let a of i(e, t)) {
617
+ let t = i(e, a), o = c(f(t[0], "name OID").value), s = f(t[1], "name value"), u = k(o), d = l(s.tag, s.value), p = u === void 0 ? {
618
+ oid: o,
619
+ valueTag: s.tag,
620
+ value: d
524
621
  } : {
525
- oid,
526
- valueTag: valueElement.tag,
527
- value: fieldValue
622
+ oid: o,
623
+ key: u,
624
+ valueTag: s.tag,
625
+ value: d
528
626
  };
529
- attributes.push(attribute);
530
- if (fieldKey !== void 0 && values[fieldKey] === void 0) values[fieldKey] = fieldValue;
627
+ n.push(p), u !== void 0 && r[u] === void 0 && (r[u] = d);
531
628
  }
532
629
  return {
533
- derHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),
534
- attributes,
535
- values
630
+ derHex: p(e.slice(t.start - t.headerLength, t.end)),
631
+ attributes: n,
632
+ values: r
536
633
  };
537
634
  }
538
635
  /** Decode the Validity SEQUENCE into notBefore / notAfter Dates. */
539
- function parseValidity(source, element) {
540
- const children = childrenOf(source, element);
636
+ function parseValidity(e, t) {
637
+ let n = i(e, t);
541
638
  return {
542
- notBefore: parseTime(requireElement(children[0], "notBefore")),
543
- notAfter: parseTime(requireElement(children[1], "notAfter"))
639
+ notBefore: d(f(n[0], "notBefore")),
640
+ notAfter: d(f(n[1], "notAfter"))
544
641
  };
545
642
  }
546
643
  /** 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;
644
+ function parseSubjectPublicKeyInfo(e, t) {
645
+ if (t.tag !== 48) throw Error("SubjectPublicKeyInfo must use SEQUENCE");
646
+ let n = i(e, t);
647
+ if (n.length !== 2) throw Error("SubjectPublicKeyInfo must contain algorithm and subjectPublicKey");
648
+ let r = f(n[0], "SPKI algorithm");
649
+ if (r.tag !== 48) throw Error("SubjectPublicKeyInfo algorithm must use SEQUENCE");
650
+ let a = parseAlgorithmIdentifier(e, r);
651
+ return u(f(n[1], "subjectPublicKey BIT STRING")), a;
556
652
  }
557
653
  /** 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
654
+ function parseAlgorithmIdentifier(e, t) {
655
+ let n = i(e, t);
656
+ if (n.length === 0 || n.length > 2) throw Error("Malformed AlgorithmIdentifier");
657
+ let r = c(f(n[0], "algorithm OID").value), a = n[1];
658
+ if (a === void 0) return { oid: r };
659
+ let o = e.slice(a.start - a.headerLength, a.end);
660
+ return a?.tag === 6 ? {
661
+ oid: r,
662
+ parametersDer: o,
663
+ parametersOid: c(a.value)
664
+ } : {
665
+ oid: r,
666
+ parametersDer: o
573
667
  };
574
668
  }
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");
669
+ function assertMatchingCertificateSignatureAlgorithms(e, t) {
670
+ if (e.oid !== t.oid || !optionalBytesEqual(e.parametersDer, t.parametersDer)) throw Error("Certificate signatureAlgorithm must match TBSCertificate signature");
577
671
  }
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;
672
+ function optionalBytesEqual(e, t) {
673
+ if (e === void 0 || t === void 0) return e === t;
674
+ if (e.length !== t.length) return !1;
675
+ for (let n = 0; n < e.length; n += 1) if (e[n] !== t[n]) return !1;
676
+ return !0;
583
677
  }
584
678
  /** @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);
679
+ function parseBasicConstraints(e) {
680
+ let t = n(e, { maxDepth: 64 });
681
+ if (t.tag !== 48) throw Error("basicConstraints must use SEQUENCE");
682
+ let r = i(e, t), o = !1, c, l = !1, u = !1;
683
+ for (let e of r) {
684
+ if (e.tag === 1) {
685
+ if (l) throw Error("basicConstraints cA must not repeat");
686
+ if (u) throw Error("basicConstraints cA must precede pathLength");
687
+ l = !0, o = a(e.value);
599
688
  continue;
600
689
  }
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");
690
+ if (e.tag === 2) {
691
+ if (u) throw Error("basicConstraints pathLength must not repeat");
692
+ u = !0, c = s(e.value, "basicConstraints pathLength");
605
693
  continue;
606
694
  }
607
- throw new Error(`Unsupported basicConstraints field tag: ${String(child.tag)}`);
695
+ throw Error(`Unsupported basicConstraints field tag: ${String(e.tag)}`);
608
696
  }
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 };
697
+ if (c !== void 0 && o !== !0) throw Error("basicConstraints pathLength requires cA = true");
698
+ return o ? c === void 0 ? { ca: !0 } : {
699
+ ca: !0,
700
+ pathLength: c
701
+ } : { ca: !1 };
615
702
  }
616
703
  /** @internal Decode the Key Usage BIT STRING extension value. */
617
- function parseKeyUsage(bytes) {
618
- return parseKeyUsageExtension(bytes);
704
+ function parseKeyUsage(e) {
705
+ return O(e);
619
706
  }
620
707
  /** @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)));
708
+ function parseExtendedKeyUsage(e) {
709
+ return i(e, f(n(e, { maxDepth: 64 }), "extendedKeyUsage sequence")).map((e) => j(c(e.value)));
623
710
  }
624
711
  /** @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));
712
+ function parseCertificatePolicies(e) {
713
+ let t = i(e, f(n(e, { maxDepth: 64 }), "certificatePolicies sequence"));
714
+ if (t.length === 0) throw Error("certificatePolicies must not be empty");
715
+ return t.map((t) => parsePolicyInformation(e, t));
629
716
  }
630
717
  /** 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");
718
+ function parsePolicyInformation(e, t) {
719
+ let n = i(e, t), r = c(f(n[0], "policyIdentifier").value), a = n[1];
720
+ if (n.length > 2) throw Error("policyInformation has unexpected trailing fields");
721
+ if (a === void 0) return { policyIdentifier: r };
722
+ let o = i(e, a);
723
+ if (o.length === 0) throw Error("policyQualifiers must not be empty");
639
724
  return {
640
- policyIdentifier,
641
- policyQualifiers: qualifiers.map((qualifierElement) => parsePolicyQualifierInfo(source, qualifierElement))
725
+ policyIdentifier: r,
726
+ policyQualifiers: o.map((t) => parsePolicyQualifierInfo(e, t))
642
727
  };
643
728
  }
644
729
  /** 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");
730
+ function parsePolicyQualifierInfo(e, t) {
731
+ let n = i(e, t), r = c(f(n[0], "policyQualifierId").value), a = f(n[1], "policyQualifier");
732
+ if (n.length > 2) throw Error("policyQualifierInfo has unexpected trailing fields");
733
+ if (r === m.cpsPolicyQualifier) {
734
+ if (a.tag !== 22) throw Error("cps policy qualifier must use IA5String");
652
735
  return {
653
736
  type: "cps",
654
- uri: decodeString(qualifierValue.tag, qualifierValue.value)
737
+ uri: l(a.tag, a.value)
655
738
  };
656
739
  }
657
- if (qualifierId === OIDS.userNoticePolicyQualifier) return {
740
+ return r === m.userNoticePolicyQualifier ? {
658
741
  type: "userNotice",
659
- ...parseUserNoticePolicyQualifierInfo(source, qualifierValue)
660
- };
661
- return {
742
+ ...parseUserNoticePolicyQualifierInfo(e, a)
743
+ } : {
662
744
  type: "oid",
663
- oid: qualifierId,
664
- qualifierDer: source.slice(qualifierValue.start - qualifierValue.headerLength, qualifierValue.end)
745
+ oid: r,
746
+ qualifierDer: e.slice(a.start - a.headerLength, a.end)
665
747
  };
666
748
  }
667
749
  /** 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);
750
+ function parseUserNoticePolicyQualifierInfo(e, t) {
751
+ let n = i(e, t), r, a;
752
+ for (let t of n) {
753
+ if (t.tag === 48) {
754
+ if (r !== void 0) throw Error("userNotice must not contain multiple noticeRef values");
755
+ r = parsePolicyNoticeReference(e, t);
676
756
  continue;
677
757
  }
678
- if (explicitText !== void 0) throw new Error("userNotice must not contain multiple explicitText values");
679
- explicitText = parseDisplayText(child);
758
+ if (a !== void 0) throw Error("userNotice must not contain multiple explicitText values");
759
+ a = parseDisplayText(t);
680
760
  }
681
761
  return {
682
- ...noticeRef === void 0 ? {} : { noticeRef },
683
- ...explicitText === void 0 ? {} : { explicitText }
762
+ ...r === void 0 ? {} : { noticeRef: r },
763
+ ...a === void 0 ? {} : { explicitText: a }
684
764
  };
685
765
  }
686
766
  /** 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");
767
+ function parsePolicyNoticeReference(e, t) {
768
+ if (t.tag !== 48) throw Error("noticeRef must use SEQUENCE");
769
+ let n = i(e, t), r = parseDisplayText(f(n[0], "noticeRef organization")), a = f(n[1], "noticeRef noticeNumbers");
770
+ if (n.length > 2) throw Error("noticeRef has unexpected trailing fields");
693
771
  return {
694
- organization,
695
- noticeNumbers: parsePolicyNoticeNumbers(source, noticeNumbersElement)
772
+ organization: r,
773
+ noticeNumbers: parsePolicyNoticeNumbers(e, a)
696
774
  };
697
775
  }
698
776
  /** 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");
777
+ function parsePolicyNoticeNumbers(e, t) {
778
+ if (t.tag !== 48) throw Error("noticeRef noticeNumbers must use SEQUENCE");
779
+ let n = i(e, t);
780
+ if (n.length === 0) throw Error("noticeRef noticeNumbers must not be empty");
781
+ return n.map((e) => {
782
+ if (e.tag !== 2) throw Error("noticeRef noticeNumber must use INTEGER");
783
+ return s(e.value, "noticeRef noticeNumber");
706
784
  });
707
785
  }
708
786
  /** @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");
787
+ function parsePolicyMappings(e) {
788
+ let t = i(e, f(n(e, { maxDepth: 64 }), "policyMappings sequence"));
789
+ if (t.length === 0) throw Error("policyMappings must not be empty");
790
+ return t.map((t) => {
791
+ let n = i(e, t), r = c(f(n[0], "policyMappings issuerDomainPolicy").value), a = c(f(n[1], "policyMappings subjectDomainPolicy").value);
792
+ if (n.length > 2) throw Error("policyMappings entry has unexpected trailing fields");
793
+ if (r === m.anyPolicy || a === m.anyPolicy) throw Error("policyMappings must not use anyPolicy");
718
794
  return {
719
- issuerDomainPolicy,
720
- subjectDomainPolicy
795
+ issuerDomainPolicy: r,
796
+ subjectDomainPolicy: a
721
797
  };
722
798
  });
723
799
  }
724
800
  /** @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");
801
+ function parsePolicyConstraints(e) {
802
+ let t = f(n(e, { maxDepth: 64 }), "policyConstraints sequence"), r, a;
803
+ for (let n of i(e, t)) {
804
+ if (n.tag === 128) {
805
+ if (r !== void 0) throw Error("policyConstraints must not repeat requireExplicitPolicy");
806
+ r = s(n.value, "policyConstraints requireExplicitPolicy");
733
807
  continue;
734
808
  }
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");
809
+ if (n.tag === 129) {
810
+ if (a !== void 0) throw Error("policyConstraints must not repeat inhibitPolicyMapping");
811
+ a = s(n.value, "policyConstraints inhibitPolicyMapping");
738
812
  continue;
739
813
  }
740
- throw new Error(`Unsupported policyConstraints field tag: ${child.tag}`);
814
+ throw Error(`Unsupported policyConstraints field tag: ${n.tag}`);
741
815
  }
742
- if (requireExplicitPolicy === void 0 && inhibitPolicyMapping === void 0) throw new Error("policyConstraints must set requireExplicitPolicy or inhibitPolicyMapping");
816
+ if (r === void 0 && a === void 0) throw Error("policyConstraints must set requireExplicitPolicy or inhibitPolicyMapping");
743
817
  return {
744
- ...requireExplicitPolicy === void 0 ? {} : { requireExplicitPolicy },
745
- ...inhibitPolicyMapping === void 0 ? {} : { inhibitPolicyMapping }
818
+ ...r === void 0 ? {} : { requireExplicitPolicy: r },
819
+ ...a === void 0 ? {} : { inhibitPolicyMapping: a }
746
820
  };
747
821
  }
748
822
  /** @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") };
823
+ function parseInhibitAnyPolicy(e) {
824
+ let t = f(n(e, { maxDepth: 64 }), "inhibitAnyPolicy integer");
825
+ if (t.tag !== 2) throw Error("inhibitAnyPolicy must be an INTEGER");
826
+ return { skipCerts: s(t.value, "inhibitAnyPolicy skipCerts") };
753
827
  }
754
828
  /** @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));
829
+ function parseSubjectAltNames(e) {
830
+ return i(e, f(n(e, { maxDepth: 64 }), "subjectAltName sequence")).map((t) => parseGeneralName(e, t));
757
831
  }
758
832
  /** @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}`);
833
+ function parseAuthorityInfoAccess(e) {
834
+ let t = f(n(e, { maxDepth: 64 }), "authorityInfoAccess sequence");
835
+ if (t.tag !== 48) throw Error("authorityInfoAccess must use SEQUENCE");
836
+ let r = i(e, t);
837
+ if (r.length === 0) throw Error("authorityInfoAccess must not be empty");
838
+ return r.map((t) => {
839
+ if (t.tag !== 48) throw Error("authorityInfoAccess entry must use SEQUENCE");
840
+ let n = i(e, t);
841
+ if (n.length !== 2) throw Error("authorityInfoAccess entry must contain method and location only");
842
+ let r = f(n[0], "authorityInfoAccess method"), a = f(n[1], "authorityInfoAccess location");
843
+ if (r.tag !== 6) throw Error("authorityInfoAccess method must use OBJECT IDENTIFIER");
844
+ if (a.tag !== 134) throw Error(`Unsupported authorityInfoAccess location tag: ${a.tag}`);
772
845
  return {
773
- method: parseAuthorityInfoAccessMethodOid(decodeObjectIdentifier(method.value)),
774
- uri: textDecoder.decode(location.value)
846
+ method: A(c(r.value)),
847
+ uri: N.decode(a.value)
775
848
  };
776
849
  });
777
850
  }
778
851
  /** @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;
852
+ function parseCrlDistributionPoints(e) {
853
+ let t = f(n(e, { maxDepth: 64 }), "CRLDistributionPoints sequence");
854
+ if (t.tag !== 48) throw Error("CRLDistributionPoints must use SEQUENCE");
855
+ let r = i(e, t);
856
+ if (r.length === 0) throw Error("CRLDistributionPoints must not be empty");
857
+ let a = [];
858
+ for (let t of r) a.push(parseDistributionPoint(e, t));
859
+ return a;
787
860
  }
788
861
  /** 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");
862
+ function parseDistributionPoint(e, t) {
863
+ if (t.tag !== 48) throw Error("DistributionPoint must use SEQUENCE");
864
+ let n = {};
865
+ for (let r of i(e, t)) parseDistributionPointField(e, r, n);
866
+ if (n.distributionPoint === void 0 && n.crlIssuer === void 0) throw Error("DistributionPoint must include distributionPoint or crlIssuer");
805
867
  return {
806
- ...distributionPoint === void 0 ? {} : { distributionPoint },
807
- ...reasons === void 0 ? {} : { reasons },
808
- ...crlIssuer === void 0 ? {} : { crlIssuer }
868
+ ...n.distributionPoint === void 0 ? {} : { distributionPoint: n.distributionPoint },
869
+ ...n.reasons === void 0 ? {} : { reasons: n.reasons },
870
+ ...n.crlIssuer === void 0 ? {} : { crlIssuer: n.crlIssuer }
809
871
  };
810
872
  }
873
+ function parseDistributionPointField(e, t, n) {
874
+ switch (t.tag) {
875
+ case 160:
876
+ if (n.distributionPoint !== void 0) throw Error("DistributionPoint distributionPoint must not repeat");
877
+ n.distributionPoint = parseDistributionPointName(e, t);
878
+ return;
879
+ case 129:
880
+ if (n.reasons !== void 0) throw Error("DistributionPoint reasons must not repeat");
881
+ n.reasons = D(t.value);
882
+ return;
883
+ case 162:
884
+ if (n.crlIssuer !== void 0) throw Error("DistributionPoint crlIssuer must not repeat");
885
+ n.crlIssuer = parseGeneralNames(e, t);
886
+ return;
887
+ default: throw Error(`Unsupported DistributionPoint field tag: ${String(t.tag)}`);
888
+ }
889
+ }
811
890
  /** 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)) };
891
+ function parseDistributionPointName(e, t) {
892
+ let n = i(e, t);
893
+ if (n.length !== 1) throw Error("distributionPointName must contain exactly one choice");
894
+ let r = f(n[0], "distributionPointName");
895
+ if (r.tag === 160) {
896
+ let t = i(e, r);
897
+ if (t.length === 0) throw Error("distributionPointName fullName must not be empty");
898
+ for (let e of t) if ((e.tag & 192) != 128) throw Error("distributionPointName fullName must contain GeneralName entries");
899
+ return { fullName: t.map((t) => parseGeneralName(e, t)) };
821
900
  }
822
- if (distributionPointName.tag === 161) return { relativeName: parseRelativeDistinguishedName(source, distributionPointName) };
823
- throw new Error(`Unsupported distributionPointName tag: ${distributionPointName.tag}`);
901
+ if (r.tag === 161) return { relativeName: parseRelativeDistinguishedName(e, r) };
902
+ throw Error(`Unsupported distributionPointName tag: ${r.tag}`);
824
903
  }
825
904
  /** 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));
905
+ function parseGeneralNames(e, t) {
906
+ let n = i(e, t);
907
+ if (n.length === 0) throw Error("GeneralNames must not be empty");
908
+ for (let e of n) if ((e.tag & 192) != 128) throw Error("GeneralNames must contain GeneralName entries");
909
+ return n.map((t) => parseGeneralName(e, t));
831
910
  }
832
911
  /** Decode a single GeneralName from its implicit context tag. */
833
- function parseGeneralName(source, element) {
834
- switch (element.tag) {
912
+ function parseGeneralName(e, t) {
913
+ switch (t.tag) {
835
914
  case 160: {
836
- const otherName = parseOtherName(source, element);
837
- if (otherName !== void 0) return otherName;
838
- return {
915
+ let n = parseOtherName(e, t);
916
+ return n === void 0 ? {
839
917
  type: "unknown",
840
- tag: element.tag,
841
- value: source.slice(element.start, element.end)
842
- };
918
+ tag: t.tag,
919
+ value: e.slice(t.start, t.end)
920
+ } : n;
843
921
  }
844
922
  case 129: return {
845
923
  type: "email",
846
- value: textDecoder.decode(element.value)
924
+ value: N.decode(t.value)
847
925
  };
848
926
  case 130: return {
849
927
  type: "dns",
850
- value: textDecoder.decode(element.value)
928
+ value: N.decode(t.value)
851
929
  };
852
930
  case 134: return {
853
931
  type: "uri",
854
- value: textDecoder.decode(element.value)
932
+ value: N.decode(t.value)
855
933
  };
856
934
  case 135: return {
857
935
  type: "ip",
858
- value: decodeIpAddress(element.value)
936
+ value: E(t.value)
859
937
  };
860
938
  case 164: return {
861
939
  type: "directoryName",
862
- derHex: toHex(rebuildDirectoryNameFromImplicit(element, source))
940
+ derHex: p(rebuildDirectoryNameFromImplicit(t, e))
863
941
  };
864
942
  default: return {
865
943
  type: "unknown",
866
- tag: element.tag,
867
- value: source.slice(element.start, element.end)
944
+ tag: t.tag,
945
+ value: e.slice(t.start, t.end)
868
946
  };
869
947
  }
870
948
  }
871
949
  /** 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");
950
+ function parseOtherName(e, t) {
951
+ let n = i(e, t);
952
+ if (n.length !== 1) throw Error("otherName must contain exactly one SEQUENCE");
953
+ let r = i(e, f(n[0], "otherName sequence"));
954
+ if (r.length !== 2) throw Error("otherName must contain exactly type-id and value");
955
+ let a = f(r[0], "otherName type-id"), o = f(r[1], "otherName value");
956
+ if (c(a.value) !== m.idOnDnsSrv) return;
957
+ if (o.tag !== 160) throw Error("SRV-ID otherName value must use explicit [0]");
958
+ let s = i(e, o);
959
+ if (s.length !== 1) throw Error("SRV-ID otherName value must contain exactly one IA5String");
960
+ let u = f(s[0], "SRV-ID IA5String");
961
+ if (u.tag !== 22) throw Error("SRV-ID otherName value must be an IA5String");
885
962
  return {
886
963
  type: "srv",
887
- value: decodeString(srvNameElement.tag, srvNameElement.value)
964
+ value: l(u.tag, u.value)
888
965
  };
889
966
  }
890
967
  /** @internal Decode the Name Constraints extension value. */
891
- function parseNameConstraints(bytes) {
892
- const sequenceElement = requireElement(readRootElement(bytes, {
968
+ function parseNameConstraints(e) {
969
+ let t = f(n(e, {
893
970
  maxDepth: 64,
894
971
  allowOpaqueConstructedTags: [
895
972
  160,
@@ -897,96 +974,96 @@ function parseNameConstraints(bytes) {
897
974
  165
898
975
  ]
899
976
  }), "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)}`);
977
+ if (t.tag !== 48) throw Error("nameConstraints must use SEQUENCE");
978
+ let r, a;
979
+ for (let n of i(e, t)) if (n.tag === 160) {
980
+ if (r !== void 0) throw Error("nameConstraints permittedSubtrees must not repeat");
981
+ r = parseGeneralSubtrees(e, n);
982
+ } else if (n.tag === 161) {
983
+ if (a !== void 0) throw Error("nameConstraints excludedSubtrees must not repeat");
984
+ a = parseGeneralSubtrees(e, n);
985
+ } else throw Error(`Unsupported nameConstraints field tag: ${String(n.tag)}`);
910
986
  return {
911
- ...permittedSubtrees !== void 0 ? { permittedSubtrees } : {},
912
- ...excludedSubtrees !== void 0 ? { excludedSubtrees } : {}
987
+ ...r === void 0 ? {} : { permittedSubtrees: r },
988
+ ...a === void 0 ? {} : { excludedSubtrees: a }
913
989
  };
914
990
  }
915
991
  /** 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)}`);
992
+ function parseGeneralSubtrees(e, t) {
993
+ let n = [], r = i(e, t);
994
+ if (r.length === 0) throw Error("name constraints GeneralSubtrees must not be empty");
995
+ for (let t of r) {
996
+ let r = parseGeneralSubtree(e, t);
997
+ r !== void 0 && n.push({ base: r });
998
+ }
999
+ return n;
1000
+ }
1001
+ function parseGeneralSubtree(e, t) {
1002
+ if (t.tag !== 48) throw Error("name constraints GeneralSubtree must use SEQUENCE");
1003
+ let n = i(e, t), r = n[0];
1004
+ if (r === void 0) throw Error("GeneralSubtree base is required");
1005
+ return validateGeneralSubtreeBounds(n.slice(1)), parseNameConstraintGeneralName(e, r);
1006
+ }
1007
+ function validateGeneralSubtreeBounds(e) {
1008
+ let t = !1;
1009
+ for (let n of e) {
1010
+ if (n.tag === 128) {
1011
+ if (t) throw Error("name constraints GeneralSubtree minimum must not repeat");
1012
+ if (t = !0, s(n.value, "name constraints GeneralSubtree minimum") !== 0) throw Error("name constraints GeneralSubtree minimum must be 0");
1013
+ continue;
935
1014
  }
936
- const form = parseNameConstraintGeneralName(source, baseElement);
937
- if (form !== void 0) subtrees.push({ base: form });
1015
+ throw n.tag === 129 ? Error("name constraints GeneralSubtree maximum is not supported") : Error(`Unsupported name constraints GeneralSubtree field tag: ${String(n.tag)}`);
938
1016
  }
939
- return subtrees;
940
1017
  }
941
1018
  /** Decode a GeneralName for use in name constraints (IP carries address+mask). */
942
- function parseNameConstraintGeneralName(source, element) {
943
- switch (element.tag) {
1019
+ function parseNameConstraintGeneralName(e, t) {
1020
+ switch (t.tag) {
944
1021
  case 160: return {
945
1022
  type: "otherName",
946
- value: new Uint8Array(element.value)
1023
+ value: new Uint8Array(t.value)
947
1024
  };
948
1025
  case 129: return {
949
1026
  type: "email",
950
- value: textDecoder.decode(element.value)
1027
+ value: N.decode(t.value)
951
1028
  };
952
1029
  case 130: return {
953
1030
  type: "dns",
954
- value: textDecoder.decode(element.value)
1031
+ value: N.decode(t.value)
955
1032
  };
956
1033
  case 163: return {
957
1034
  type: "x400Address",
958
- value: new Uint8Array(element.value)
1035
+ value: new Uint8Array(t.value)
959
1036
  };
960
1037
  case 134: return {
961
1038
  type: "uri",
962
- value: textDecoder.decode(element.value)
1039
+ value: N.decode(t.value)
963
1040
  };
964
1041
  case 135:
965
- if (element.value.length === 8) return {
1042
+ if (t.value.length === 8) return {
966
1043
  type: "ip",
967
- addressBytes: element.value.slice(0, 4),
968
- maskBytes: element.value.slice(4, 8)
1044
+ addressBytes: t.value.slice(0, 4),
1045
+ maskBytes: t.value.slice(4, 8)
969
1046
  };
970
- if (element.value.length === 32) return {
1047
+ if (t.value.length === 32) return {
971
1048
  type: "ip",
972
- addressBytes: element.value.slice(0, 16),
973
- maskBytes: element.value.slice(16, 32)
1049
+ addressBytes: t.value.slice(0, 16),
1050
+ maskBytes: t.value.slice(16, 32)
974
1051
  };
975
- throw new Error(`Invalid IP name constraint: expected 8 (IPv4) or 32 (IPv6) bytes, got ${String(element.value.length)}`);
1052
+ throw Error(`Invalid IP name constraint: expected 8 (IPv4) or 32 (IPv6) bytes, got ${String(t.value.length)}`);
976
1053
  case 164: return {
977
1054
  type: "directoryName",
978
- derHex: toHex(rebuildDirectoryNameFromImplicit(element, source))
1055
+ derHex: p(rebuildDirectoryNameFromImplicit(t, e))
979
1056
  };
980
1057
  case 165: return {
981
1058
  type: "ediPartyName",
982
- value: new Uint8Array(element.value)
1059
+ value: new Uint8Array(t.value)
983
1060
  };
984
1061
  case 136: return {
985
1062
  type: "registeredID",
986
- value: decodeObjectIdentifier(element.value)
1063
+ value: c(t.value)
987
1064
  };
988
1065
  }
989
- throw new Error(`Unsupported name constraint GeneralName tag: ${String(element.tag)}`);
1066
+ throw Error(`Unsupported name constraint GeneralName tag: ${String(t.tag)}`);
990
1067
  }
991
1068
  /**
992
1069
  * Extracts the Name SEQUENCE from an implicitly-tagged directoryName [4].
@@ -995,96 +1072,104 @@ function parseNameConstraintGeneralName(source, element) {
995
1072
  * - Proper implicit: [4] replaces SEQUENCE tag, content is RDN SETs directly → wrap with 0x30
996
1073
  * - Explicit-like: [4] wraps entire SEQUENCE, content starts with 0x30 → return content as-is
997
1074
  */
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;
1075
+ function rebuildDirectoryNameFromImplicit(t, n) {
1076
+ if (t.value.length > 0 && t.value[0] === 48) return new Uint8Array(t.value);
1077
+ let r = e(t.value.length), i = new Uint8Array(1 + r.length + t.value.length);
1078
+ return i[0] = 48, i.set(r, 1), i.set(t.value, 1 + r.length), i;
1006
1079
  }
1007
1080
  /** Decode a DisplayText (UTF8String, IA5String, VisibleString, or BMPString). */
1008
- function parseDisplayText(element) {
1009
- switch (element.tag) {
1081
+ function parseDisplayText(e) {
1082
+ switch (e.tag) {
1010
1083
  case 12:
1011
1084
  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}`);
1085
+ case 26: return N.decode(e.value);
1086
+ case 30: return decodeBmpString(e.value);
1087
+ default: throw Error(`Unsupported DisplayText tag: ${e.tag}`);
1015
1088
  }
1016
1089
  }
1017
1090
  /** 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);
1091
+ function decodeBmpString(e) {
1092
+ if (e.length % 2 != 0) throw Error("Invalid BMPString length");
1093
+ let t = "";
1094
+ for (let n = 0; n < e.length; n += 2) {
1095
+ let r = e[n], i = e[n + 1];
1096
+ if (r === void 0 || i === void 0) throw Error("Invalid BMPString content");
1097
+ t += String.fromCharCode(r << 8 | i);
1026
1098
  }
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;
1099
+ return t;
1100
+ }
1101
+ function parseAuthorityKeyIdentifier(e) {
1102
+ let n = f(t(e, 0), "authorityKeyIdentifier sequence");
1103
+ if (n.end !== e.length) throw Error("Trailing data after DER element");
1104
+ let r = {
1105
+ sawAuthorityCertIssuer: !1,
1106
+ sawAuthorityCertSerialNumber: !1,
1107
+ lastFieldOrder: -1
1108
+ }, i = n.start;
1109
+ for (; i < n.end;) {
1110
+ let a = t(e, i);
1111
+ if (a.end > n.end) throw Error("DER child exceeds parent length");
1112
+ parseAuthorityKeyIdentifierField(e, a, r), i = a.end;
1113
+ }
1114
+ if (i !== n.end) throw Error("Malformed DER sequence");
1115
+ if (r.sawAuthorityCertIssuer !== r.sawAuthorityCertSerialNumber) throw Error("authorityKeyIdentifier authorityCertIssuer and authorityCertSerialNumber must appear together");
1116
+ return r.keyIdentifier;
1117
+ }
1118
+ function parseAuthorityKeyIdentifierField(e, t, n) {
1119
+ switch (t.tag) {
1120
+ case 128:
1121
+ parseAuthorityKeyIdentifierKeyId(t, n);
1122
+ return;
1123
+ case 161:
1124
+ parseAuthorityKeyIdentifierIssuer(e, t, n);
1125
+ return;
1126
+ case 130:
1127
+ parseAuthorityKeyIdentifierSerial(t, n);
1128
+ return;
1129
+ default: throw Error(`Unsupported authorityKeyIdentifier field tag: ${String(t.tag)}`);
1130
+ }
1131
+ }
1132
+ function parseAuthorityKeyIdentifierKeyId(e, t) {
1133
+ if (t.keyIdentifier !== void 0) throw Error("authorityKeyIdentifier keyIdentifier must not repeat");
1134
+ if (t.lastFieldOrder >= 0) throw Error("authorityKeyIdentifier fields must preserve DER order");
1135
+ t.keyIdentifier = p(e.value), t.lastFieldOrder = 0;
1136
+ }
1137
+ function parseAuthorityKeyIdentifierIssuer(e, t, n) {
1138
+ if (n.sawAuthorityCertIssuer) throw Error("authorityKeyIdentifier authorityCertIssuer must not repeat");
1139
+ if (n.lastFieldOrder >= 1) throw Error("authorityKeyIdentifier fields must preserve DER order");
1140
+ let r = i(e, t);
1141
+ if (r.length === 0) throw Error("authorityKeyIdentifier authorityCertIssuer must contain GeneralName entries");
1142
+ for (let t of r) {
1143
+ if ((t.tag & 192) != 128) throw Error("authorityKeyIdentifier authorityCertIssuer must contain GeneralName entries");
1144
+ parseGeneralName(e, t);
1065
1145
  }
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`);
1146
+ n.sawAuthorityCertIssuer = !0, n.lastFieldOrder = 1;
1147
+ }
1148
+ function parseAuthorityKeyIdentifierSerial(e, t) {
1149
+ if (t.sawAuthorityCertSerialNumber) throw Error("authorityKeyIdentifier authorityCertSerialNumber must not repeat");
1150
+ if (t.lastFieldOrder >= 2 || !t.sawAuthorityCertIssuer) throw Error("authorityKeyIdentifier fields must preserve DER order");
1151
+ validateImplicitSerialNumberEncoding(e.value, "authorityKeyIdentifier authorityCertSerialNumber"), t.sawAuthorityCertSerialNumber = !0, t.lastFieldOrder = 2;
1152
+ }
1153
+ function validateImplicitSerialNumberEncoding(e, t) {
1154
+ let n = e[0];
1155
+ if (n === void 0) throw Error(`${t} must not be empty`);
1156
+ if (n & 128) throw Error(`${t} must be non-negative`);
1157
+ if (e.length > 1 && n === 0 && !((e[1] ?? 0) & 128)) throw Error(`${t} must use minimal encoding`);
1158
+ }
1159
+ function validateImplicitBitStringContent(e, t) {
1160
+ let n = e[0];
1161
+ if (n === void 0 || n > 7) throw Error(`${t} must use BIT STRING encoding`);
1162
+ let r = e.slice(1);
1163
+ if (r.length === 0) {
1164
+ if (n !== 0) throw Error(`${t} must use BIT STRING encoding`);
1082
1165
  return;
1083
1166
  }
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`);
1167
+ if (n === 0) return;
1168
+ let i = r[r.length - 1];
1169
+ if (i === void 0) throw Error(`${t} must use BIT STRING encoding`);
1170
+ if (i & (1 << n) - 1) throw Error(`${t} BIT STRING must not set padding bits`);
1088
1171
  }
1089
1172
  //#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 };
1173
+ export { certificateMatchesPrivateKey, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, matchCertificatePrivateKey, parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstraints, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificateFromSource, parseCertificatePem, parseCertificatePemOrThrow, parseCertificatePolicies, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow, parseCertificatesFromSource, parseCrlDistributionPoints, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames };
1174
+
1175
+ //# sourceMappingURL=parse.js.map