micro509 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +5 -5
  3. package/dist/index.js +15 -1
  4. package/dist/internal/asn1/asn1.js +280 -2
  5. package/dist/internal/asn1/der.js +378 -2
  6. package/dist/internal/asn1/oids.js +103 -2
  7. package/dist/internal/crypto/algorithm-names.js +58 -2
  8. package/dist/internal/crypto/ecdsa.js +68 -2
  9. package/dist/internal/crypto/hash.js +286 -2
  10. package/dist/internal/crypto/pbes2.js +213 -2
  11. package/dist/internal/crypto/rsa-pss.js +184 -2
  12. package/dist/internal/crypto/sig-verify.js +192 -2
  13. package/dist/internal/crypto/signing.d.ts +1 -2
  14. package/dist/internal/crypto/signing.js +123 -2
  15. package/dist/internal/crypto/webcrypto.js +14 -2
  16. package/dist/internal/shared/base64.js +16 -2
  17. package/dist/internal/shared/dn.js +84 -2
  18. package/dist/internal/shared/ip.js +164 -2
  19. package/dist/internal/verify/name-constraints-engine.js +450 -2
  20. package/dist/internal/verify/policy-engine.js +382 -2
  21. package/dist/internal/verify/verify-path.js +298 -2
  22. package/dist/internal/x509/extension-bits.js +132 -2
  23. package/dist/internal/x509/extension-registry.js +229 -2
  24. package/dist/internal/x509/name-fields.js +93 -2
  25. package/dist/keys/keys.d.ts +231 -7
  26. package/dist/keys/keys.js +1087 -5
  27. package/dist/keys.d.ts +2 -2
  28. package/dist/keys.js +2 -1
  29. package/dist/pem/pem.d.ts +2 -2
  30. package/dist/pem/pem.js +172 -6
  31. package/dist/pem.js +2 -1
  32. package/dist/pkcs/pfx.d.ts +4 -5
  33. package/dist/pkcs/pfx.js +395 -2
  34. package/dist/pkcs/pkcs12-mac.d.ts +2 -2
  35. package/dist/pkcs/pkcs12-mac.js +175 -2
  36. package/dist/pkcs/pkcs7.d.ts +1 -2
  37. package/dist/pkcs/pkcs7.js +653 -2
  38. package/dist/pkcs.d.ts +2 -2
  39. package/dist/pkcs.js +4 -1
  40. package/dist/result/result.d.ts +1 -2
  41. package/dist/result/result.js +111 -2
  42. package/dist/result.js +2 -1
  43. package/dist/revocation/chain.d.ts +4 -5
  44. package/dist/revocation/chain.js +536 -2
  45. package/dist/revocation/crl.d.ts +2 -2
  46. package/dist/revocation/crl.js +1119 -2
  47. package/dist/revocation/ocsp.d.ts +3 -2
  48. package/dist/revocation/ocsp.js +958 -2
  49. package/dist/revocation/revocation.d.ts +1 -2
  50. package/dist/revocation/revocation.js +261 -2
  51. package/dist/revocation.d.ts +2 -2
  52. package/dist/revocation.js +5 -1
  53. package/dist/verify/identity.d.ts +1 -2
  54. package/dist/verify/identity.js +270 -2
  55. package/dist/verify/name-constraints.d.ts +1 -2
  56. package/dist/verify/policy.d.ts +1 -2
  57. package/dist/verify/verify.d.ts +1 -2
  58. package/dist/verify/verify.js +764 -2
  59. package/dist/verify.js +3 -1
  60. package/dist/x509/certificate.d.ts +1 -2
  61. package/dist/x509/certificate.js +151 -2
  62. package/dist/x509/csr.d.ts +1 -2
  63. package/dist/x509/csr.js +71 -2
  64. package/dist/x509/extensions.d.ts +1 -2
  65. package/dist/x509/extensions.js +387 -2
  66. package/dist/x509/name.d.ts +1 -2
  67. package/dist/x509/name.js +173 -2
  68. package/dist/x509/parse.d.ts +84 -2
  69. package/dist/x509/parse.js +1090 -2
  70. package/dist/x509.d.ts +2 -2
  71. package/dist/x509.js +6 -1
  72. package/package.json +74 -34
  73. package/dist/internal/asn1/asn1.js.map +0 -1
  74. package/dist/internal/asn1/der.js.map +0 -1
  75. package/dist/internal/asn1/oids.js.map +0 -1
  76. package/dist/internal/crypto/algorithm-names.js.map +0 -1
  77. package/dist/internal/crypto/ecdsa.js.map +0 -1
  78. package/dist/internal/crypto/hash.js.map +0 -1
  79. package/dist/internal/crypto/pbes2.d.ts +0 -23
  80. package/dist/internal/crypto/pbes2.js.map +0 -1
  81. package/dist/internal/crypto/rsa-pss.js.map +0 -1
  82. package/dist/internal/crypto/sig-verify.js.map +0 -1
  83. package/dist/internal/crypto/signing.js.map +0 -1
  84. package/dist/internal/crypto/webcrypto.js.map +0 -1
  85. package/dist/internal/shared/base64.js.map +0 -1
  86. package/dist/internal/shared/dn.js.map +0 -1
  87. package/dist/internal/shared/ip.js.map +0 -1
  88. package/dist/internal/verify/name-constraints-engine.js.map +0 -1
  89. package/dist/internal/verify/policy-engine.js.map +0 -1
  90. package/dist/internal/verify/verify-path.js.map +0 -1
  91. package/dist/internal/x509/extension-bits.js.map +0 -1
  92. package/dist/internal/x509/extension-registry.js.map +0 -1
  93. package/dist/internal/x509/name-fields.js.map +0 -1
  94. package/dist/keys/keys.js.map +0 -1
  95. package/dist/pem/pem.js.map +0 -1
  96. package/dist/pkcs/pfx.js.map +0 -1
  97. package/dist/pkcs/pkcs12-mac.js.map +0 -1
  98. package/dist/pkcs/pkcs7.js.map +0 -1
  99. package/dist/result/result.js.map +0 -1
  100. package/dist/revocation/chain.js.map +0 -1
  101. package/dist/revocation/crl.js.map +0 -1
  102. package/dist/revocation/ocsp.js.map +0 -1
  103. package/dist/revocation/revocation.js.map +0 -1
  104. package/dist/verify/identity.js.map +0 -1
  105. package/dist/verify/verify.js.map +0 -1
  106. package/dist/x509/certificate.js.map +0 -1
  107. package/dist/x509/csr.js.map +0 -1
  108. package/dist/x509/extensions.js.map +0 -1
  109. package/dist/x509/name.js.map +0 -1
  110. package/dist/x509/parse.js.map +0 -1
@@ -1,2 +1,298 @@
1
- import{toHex as e}from"../asn1/asn1.js";import{parseCertificatesFromSource as t}from"../../x509/parse.js";import{verifySignedDataDetailed as n}from"../crypto/sig-verify.js";import{canonicalDnKey as r,compareDistinguishedNames as i}from"../shared/dn.js";function a(e,t){return e.notBefore.getTime()<=t.getTime()&&t.getTime()<=e.notAfter.getTime()}function o(e){return i(e.subject,e.issuer)}function s(e,t){let n=0;for(let r=1;r<t;r+=1){let t=e[r];t?.basicConstraints?.ca===!0&&!o(t)&&(n+=1)}return n}function c(e){let t=[];for(let n of e)t.push(...f(n));return t}function l(e){let t=f(e),n=t[0];if(n===void 0)throw Error(`No certificate found`);if(t.length!==1)throw Error(`Expected a single certificate source`);return n}async function u(e,t){let r=await n(e.signatureAlgorithmOid,e.signatureAlgorithmParametersDer,t.publicKeyAlgorithmOid,t.publicKeyParametersOid,t.subjectPublicKeyInfoDer,e.signatureValue,e.tbsCertificateDer);return!r.ok&&r.code===`verification_error`?{ok:!1,code:`signature_invalid`,reason:r.reason}:r}async function d(e,t,n,i,s,c){let l=[...t,...n],d=new Map,f=new Map,m=new Set(n.map(e=>x(e))),h=new Map;for(let e of i){let t=r(e.subject),n=h.get(t);n===void 0?h.set(t,[e]):n.push(e)}let g=!1,b=[e],S,C,w=new Set;l.forEach((e,t)=>{let n=r(e.subject),i=d.get(n);i===void 0?d.set(n,[e]):i.push(e),f.set(x(e),t)});let T=l.length+1,E=x(e),D=await O(e,[e],new Set([E]),0);if(D!==void 0)return{chain:D,foundTrustedRoot:!0};if(C!==void 0)return{chain:b,foundTrustedRoot:!1,failure:C};if(g)return{chain:b,foundTrustedRoot:!1};return S===void 0?{chain:b,foundTrustedRoot:!1}:{chain:b,foundTrustedRoot:!1,missingIssuerAt:S};async function O(e,t,n,i){if(m.has(x(e)))return t;let l=await _(e,h,c,t.length-1);if(l.failure!==void 0&&A(l.failure,t),l.matched)return t;if(t.length>T)return;let C=[...n].sort().join(`,`),E=`${x(e)}:${i}:${C}`;if(w.has(E))return;let D=p(e,d.get(r(e.issuer))??[],f,m);if(D.length===0){let n=t.length>b.length;k(t),o(e)?g=!0:n&&(S=t.length-1),w.add(E);return}for(let r of D){let l=x(r);if(n.has(l))continue;if(!a(r,s)){A(c.failure(`certificate_expired`,`certificate not valid at requested time`,t.length,c.detail({subjectCommonName:r.subject.values.commonName,expected:v(s),actual:`${v(r.notBefore)}..${v(r.notAfter)}`})),t);continue}if(r.basicConstraints?.ca!==!0){A(c.failure(`ca_required`,`issuer must be a CA certificate`,t.length,c.detail({subjectCommonName:r.subject.values.commonName})),t);continue}if(r.keyUsage!==void 0&&!r.keyUsage.flags.includes(`keyCertSign`)){A(c.failure(`key_cert_sign_required`,`issuer missing keyCertSign`,t.length,c.detail({subjectCommonName:r.subject.values.commonName})),t);continue}if(e.authorityKeyIdentifier!==void 0&&r.subjectKeyIdentifier!==void 0&&e.authorityKeyIdentifier!==r.subjectKeyIdentifier){A(c.failure(`authority_key_identifier_mismatch`,`authorityKeyIdentifier does not match issuer subjectKeyIdentifier`,t.length-1,c.detail({subjectCommonName:e.subject.values.commonName,issuerCommonName:r.subject.values.commonName,expected:r.subjectKeyIdentifier,actual:e.authorityKeyIdentifier})),t);continue}let d=i+ +(e.basicConstraints?.ca===!0&&!o(e)&&t.length>1),f=r.basicConstraints?.pathLength;if(y(f)&&d>f){A(c.failure(`path_length_exceeded`,`path length constraint exceeded`,t.length,c.detail({subjectCommonName:r.subject.values.commonName,expected:String(f),actual:String(d)})),t);continue}let p=await u(e,r);if(!p.ok){A(c.failure(p.code,p.reason,t.length-1,c.detail({subjectCommonName:e.subject.values.commonName,issuerCommonName:r.subject.values.commonName,actual:p.reason})),t);continue}if(!p.valid){A(c.failure(`signature_invalid`,`certificate signature does not verify`,t.length-1,c.detail({subjectCommonName:e.subject.values.commonName,issuerCommonName:r.subject.values.commonName})),t);continue}let m=new Set(n);m.add(l);let h=await O(r,[...t,r],m,d);if(h!==void 0)return h}w.add(E),k(t)}function k(e){return e.length>b.length?(b=e,!0):!1}function A(e,t){(C===void 0||t.length>b.length)&&(C=e,b=t)}}function f(e){return t(e)}function p(e,t,n,r){let i=e.authorityKeyIdentifier,a=[...t].filter(t=>g(t,e)),o=new Map;for(let e of a)o.set(e,x(e));return a.sort((e,t)=>{let a=h(m(e,i),m(t,i));if(a!==0)return a;let s=o.get(e)??``,c=o.get(t)??``,l=h(r.has(s),r.has(c));return l===0?(n.get(s)??2**53-1)-(n.get(c)??2**53-1):l})}function m(e,t){return t!==void 0&&e.subjectKeyIdentifier!==void 0&&e.subjectKeyIdentifier===t}function h(e,t){return e===t?0:e?-1:1}function g(e,t){return i(t.issuer,e.subject)}async function _(e,t,i,a){let o=t.get(r(e.issuer));if(o===void 0)return{matched:!1};let s;for(let t of o){if(t.subjectKeyIdentifier!==void 0&&e.authorityKeyIdentifier!==void 0&&t.subjectKeyIdentifier!==e.authorityKeyIdentifier)continue;let r;try{let i=await n(e.signatureAlgorithmOid,e.signatureAlgorithmParametersDer,t.publicKeyAlgorithmOid,t.publicKeyParametersOid,t.subjectPublicKeyInfoDer,e.signatureValue,e.tbsCertificateDer);r=!i.ok&&i.code===`verification_error`?{ok:!1,code:`signature_invalid`,reason:i.reason}:i}catch(t){s===void 0&&(s=i.failure(`signature_invalid`,`certificate signature does not verify`,a,i.detail({subjectCommonName:e.subject.values.commonName,actual:t instanceof Error?t.message:`trust anchor key is malformed`})));continue}if(!r.ok){s===void 0&&(s=i.failure(r.code,r.reason,a,i.detail({subjectCommonName:e.subject.values.commonName,actual:r.reason})));continue}if(!r.valid){s===void 0&&(s=i.failure(`signature_invalid`,`certificate signature does not verify`,a,i.detail({subjectCommonName:e.subject.values.commonName,actual:`certificate signature does not verify`})));continue}return{matched:!0}}return s===void 0?{matched:!1}:{matched:!1,failure:s}}function v(e){return Number.isNaN(e.getTime())?`<invalid date>`:e.toISOString()}function y(e){return e!==void 0&&Number.isInteger(e)&&e>=0}const b=new WeakMap;function x(t){let n=b.get(t);return n===void 0&&(n=e(t.der),b.set(t,n)),n}export{d as buildChainInternal,s as countCaCertificatesBelowParsed,o as isSelfIssued,a as isWithinValidity,c as loadCertificates,l as loadSingleCertificate,u as verifyCertificateSignature};
2
- //# sourceMappingURL=verify-path.js.map
1
+ import { toHex } from "../asn1/asn1.js";
2
+ import { parseCertificatesFromSource } from "../../x509/parse.js";
3
+ import { verifySignedDataDetailed } from "../crypto/sig-verify.js";
4
+ import { canonicalDnKey, compareDistinguishedNames } from "../shared/dn.js";
5
+ //#region src/internal/verify/verify-path.ts
6
+ /**
7
+ * Internal certificate path-building and signature-check helpers.
8
+ *
9
+ * Loads and parses candidate certificates, ranks issuer candidates by AKI/root
10
+ * affinity, matches against bare {@linkcode TrustAnchor}s, and performs the
11
+ * depth-first chain search used by the public verify APIs in `verify.ts`.
12
+ *
13
+ * @module
14
+ */
15
+ /** Returns `true` if `at` falls within the certificate's notBefore/notAfter window (inclusive). */
16
+ function isWithinValidity(certificate, at) {
17
+ return certificate.notBefore.getTime() <= at.getTime() && at.getTime() <= certificate.notAfter.getTime();
18
+ }
19
+ /** Returns `true` if the certificate's subject and issuer DNs are semantically equal (RFC 5280 §7.1). */
20
+ function isSelfIssued(certificate) {
21
+ return compareDistinguishedNames(certificate.subject, certificate.issuer);
22
+ }
23
+ /** Counts non-self-issued CA certificates in positions 0..(index-1) for pathLength checking. */
24
+ function countCaCertificatesBelowParsed(chain, index) {
25
+ let total = 0;
26
+ for (let cursor = 1; cursor < index; cursor += 1) {
27
+ const certificate = chain[cursor];
28
+ if (certificate?.basicConstraints?.ca === true && !isSelfIssued(certificate)) total += 1;
29
+ }
30
+ return total;
31
+ }
32
+ /** Parses an array of PEM/DER sources into parsed certificates, expanding multi-block PEM. */
33
+ function loadCertificates(sources) {
34
+ const loaded = [];
35
+ for (const source of sources) loaded.push(...expandSource(source));
36
+ return loaded;
37
+ }
38
+ /** Parses exactly one certificate from a PEM/DER source. Throws if the source contains zero or multiple certificates. */
39
+ function loadSingleCertificate(source) {
40
+ const loaded = expandSource(source);
41
+ const first = loaded[0];
42
+ if (first === void 0) throw new Error("No certificate found");
43
+ if (loaded.length !== 1) throw new Error("Expected a single certificate source");
44
+ return first;
45
+ }
46
+ /** Verifies that `certificate` was signed by `issuer`'s public key. */
47
+ async function verifyCertificateSignature(certificate, issuer) {
48
+ const result = await verifySignedDataDetailed(certificate.signatureAlgorithmOid, certificate.signatureAlgorithmParametersDer, issuer.publicKeyAlgorithmOid, issuer.publicKeyParametersOid, issuer.subjectPublicKeyInfoDer, certificate.signatureValue, certificate.tbsCertificateDer);
49
+ if (!result.ok && result.code === "verification_error") return {
50
+ ok: false,
51
+ code: "signature_invalid",
52
+ reason: result.reason
53
+ };
54
+ return result;
55
+ }
56
+ /**
57
+ * Depth-first chain search from leaf to root. Tries all issuer candidates,
58
+ * checking validity, CA constraints, AKI, pathLength, and signatures at each
59
+ * step. Returns the first fully anchored path or the deepest partial path
60
+ * with the best failure encountered.
61
+ */
62
+ async function buildChainInternal(leaf, intermediates, roots, trustAnchors, at, callbacks) {
63
+ const candidates = [...intermediates, ...roots];
64
+ const subjectIndex = /* @__PURE__ */ new Map();
65
+ const order = /* @__PURE__ */ new Map();
66
+ const rootFingerprints = new Set(roots.map((candidate) => fingerprint(candidate)));
67
+ const anchorIndex = /* @__PURE__ */ new Map();
68
+ for (const anchor of trustAnchors) {
69
+ const key = canonicalDnKey(anchor.subject);
70
+ const existing = anchorIndex.get(key);
71
+ if (existing === void 0) anchorIndex.set(key, [anchor]);
72
+ else existing.push(anchor);
73
+ }
74
+ let sawUntrustedAnchor = false;
75
+ let deepestPath = [leaf];
76
+ let deepestMissingIssuerAt;
77
+ let preferredFailure;
78
+ const deadEnds = /* @__PURE__ */ new Set();
79
+ candidates.forEach((candidate, index) => {
80
+ const key = canonicalDnKey(candidate.subject);
81
+ const existing = subjectIndex.get(key);
82
+ if (existing === void 0) subjectIndex.set(key, [candidate]);
83
+ else existing.push(candidate);
84
+ order.set(fingerprint(candidate), index);
85
+ });
86
+ const maxDepth = candidates.length + 1;
87
+ const startFingerprint = fingerprint(leaf);
88
+ const success = await search(leaf, [leaf], /* @__PURE__ */ new Set([startFingerprint]), 0);
89
+ if (success !== void 0) return {
90
+ chain: success,
91
+ foundTrustedRoot: true
92
+ };
93
+ if (preferredFailure !== void 0) return {
94
+ chain: deepestPath,
95
+ foundTrustedRoot: false,
96
+ failure: preferredFailure
97
+ };
98
+ if (sawUntrustedAnchor) return {
99
+ chain: deepestPath,
100
+ foundTrustedRoot: false
101
+ };
102
+ return deepestMissingIssuerAt === void 0 ? {
103
+ chain: deepestPath,
104
+ foundTrustedRoot: false
105
+ } : {
106
+ chain: deepestPath,
107
+ foundTrustedRoot: false,
108
+ missingIssuerAt: deepestMissingIssuerAt
109
+ };
110
+ async function search(current, path, visited, caBelowCount) {
111
+ if (rootFingerprints.has(fingerprint(current))) return path;
112
+ const matchedAnchor = await matchTrustAnchor(current, anchorIndex, callbacks, path.length - 1);
113
+ if (matchedAnchor.failure !== void 0) recordFailure(matchedAnchor.failure, path);
114
+ if (matchedAnchor.matched) return path;
115
+ if (path.length > maxDepth) return;
116
+ const visitedKey = [...visited].sort().join(",");
117
+ const memoKey = `${fingerprint(current)}:${caBelowCount}:${visitedKey}`;
118
+ if (deadEnds.has(memoKey)) return;
119
+ const issuers = rankIssuerCandidates(current, subjectIndex.get(canonicalDnKey(current.issuer)) ?? [], order, rootFingerprints);
120
+ if (issuers.length === 0) {
121
+ const wasDeepest = path.length > deepestPath.length;
122
+ updateDeepest(path);
123
+ if (isSelfIssued(current)) sawUntrustedAnchor = true;
124
+ else if (wasDeepest) deepestMissingIssuerAt = path.length - 1;
125
+ deadEnds.add(memoKey);
126
+ return;
127
+ }
128
+ for (const issuer of issuers) {
129
+ const issuerFingerprint = fingerprint(issuer);
130
+ if (visited.has(issuerFingerprint)) continue;
131
+ if (!isWithinValidity(issuer, at)) {
132
+ recordFailure(callbacks.failure("certificate_expired", "certificate not valid at requested time", path.length, callbacks.detail({
133
+ subjectCommonName: issuer.subject.values.commonName,
134
+ expected: describeDateTime(at),
135
+ actual: `${describeDateTime(issuer.notBefore)}..${describeDateTime(issuer.notAfter)}`
136
+ })), path);
137
+ continue;
138
+ }
139
+ if (issuer.basicConstraints?.ca !== true) {
140
+ recordFailure(callbacks.failure("ca_required", "issuer must be a CA certificate", path.length, callbacks.detail({ subjectCommonName: issuer.subject.values.commonName })), path);
141
+ continue;
142
+ }
143
+ if (issuer.keyUsage !== void 0 && !issuer.keyUsage.flags.includes("keyCertSign")) {
144
+ recordFailure(callbacks.failure("key_cert_sign_required", "issuer missing keyCertSign", path.length, callbacks.detail({ subjectCommonName: issuer.subject.values.commonName })), path);
145
+ continue;
146
+ }
147
+ if (current.authorityKeyIdentifier !== void 0 && issuer.subjectKeyIdentifier !== void 0 && current.authorityKeyIdentifier !== issuer.subjectKeyIdentifier) {
148
+ recordFailure(callbacks.failure("authority_key_identifier_mismatch", "authorityKeyIdentifier does not match issuer subjectKeyIdentifier", path.length - 1, callbacks.detail({
149
+ subjectCommonName: current.subject.values.commonName,
150
+ issuerCommonName: issuer.subject.values.commonName,
151
+ expected: issuer.subjectKeyIdentifier,
152
+ actual: current.authorityKeyIdentifier
153
+ })), path);
154
+ continue;
155
+ }
156
+ const nextCaBelowCount = caBelowCount + (current.basicConstraints?.ca === true && !isSelfIssued(current) && path.length > 1 ? 1 : 0);
157
+ const pathLength = issuer.basicConstraints?.pathLength;
158
+ if (isNonNegativeInteger(pathLength) && nextCaBelowCount > pathLength) {
159
+ recordFailure(callbacks.failure("path_length_exceeded", "path length constraint exceeded", path.length, callbacks.detail({
160
+ subjectCommonName: issuer.subject.values.commonName,
161
+ expected: String(pathLength),
162
+ actual: String(nextCaBelowCount)
163
+ })), path);
164
+ continue;
165
+ }
166
+ const signatureResult = await verifyCertificateSignature(current, issuer);
167
+ if (!signatureResult.ok) {
168
+ recordFailure(callbacks.failure(signatureResult.code, signatureResult.reason, path.length - 1, callbacks.detail({
169
+ subjectCommonName: current.subject.values.commonName,
170
+ issuerCommonName: issuer.subject.values.commonName,
171
+ actual: signatureResult.reason
172
+ })), path);
173
+ continue;
174
+ }
175
+ if (!signatureResult.valid) {
176
+ recordFailure(callbacks.failure("signature_invalid", "certificate signature does not verify", path.length - 1, callbacks.detail({
177
+ subjectCommonName: current.subject.values.commonName,
178
+ issuerCommonName: issuer.subject.values.commonName
179
+ })), path);
180
+ continue;
181
+ }
182
+ const nextVisited = new Set(visited);
183
+ nextVisited.add(issuerFingerprint);
184
+ const result = await search(issuer, [...path, issuer], nextVisited, nextCaBelowCount);
185
+ if (result !== void 0) return result;
186
+ }
187
+ deadEnds.add(memoKey);
188
+ updateDeepest(path);
189
+ }
190
+ function updateDeepest(path) {
191
+ if (path.length > deepestPath.length) {
192
+ deepestPath = path;
193
+ return true;
194
+ }
195
+ return false;
196
+ }
197
+ function recordFailure(candidateFailure, path) {
198
+ if (preferredFailure === void 0 || path.length > deepestPath.length) {
199
+ preferredFailure = candidateFailure;
200
+ deepestPath = path;
201
+ }
202
+ }
203
+ }
204
+ /** Expands a PEM (possibly multi-block) or DER source into parsed certificates. */
205
+ function expandSource(source) {
206
+ return parseCertificatesFromSource(source);
207
+ }
208
+ /** Filters and sorts issuer candidates: AKI match first, then roots, then input order. */
209
+ function rankIssuerCandidates(current, candidates, order, rootFingerprints) {
210
+ const aki = current.authorityKeyIdentifier;
211
+ const filtered = [...candidates].filter((candidate) => isIssuerOf(candidate, current));
212
+ const fps = /* @__PURE__ */ new Map();
213
+ for (const candidate of filtered) fps.set(candidate, fingerprint(candidate));
214
+ return filtered.sort((left, right) => {
215
+ const akiScore = compareBooleans(matchesAki(left, aki), matchesAki(right, aki));
216
+ if (akiScore !== 0) return akiScore;
217
+ const leftFp = fps.get(left) ?? "";
218
+ const rightFp = fps.get(right) ?? "";
219
+ const rootScore = compareBooleans(rootFingerprints.has(leftFp), rootFingerprints.has(rightFp));
220
+ if (rootScore !== 0) return rootScore;
221
+ return (order.get(leftFp) ?? Number.MAX_SAFE_INTEGER) - (order.get(rightFp) ?? Number.MAX_SAFE_INTEGER);
222
+ });
223
+ }
224
+ /** Returns `true` if the candidate's SKI matches the given authority key identifier. */
225
+ function matchesAki(candidate, aki) {
226
+ return aki !== void 0 && candidate.subjectKeyIdentifier !== void 0 && candidate.subjectKeyIdentifier === aki;
227
+ }
228
+ /** Sort comparator: `true` sorts before `false`. Returns -1, 0, or 1. */
229
+ function compareBooleans(left, right) {
230
+ if (left === right) return 0;
231
+ return left ? -1 : 1;
232
+ }
233
+ /** Returns `true` if `issuer`'s subject DN semantically matches `child`'s issuer DN (RFC 5280 §7.1). */
234
+ function isIssuerOf(issuer, child) {
235
+ return compareDistinguishedNames(child.issuer, issuer.subject);
236
+ }
237
+ /** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */
238
+ async function matchTrustAnchor(certificate, anchorIndex, callbacks, index) {
239
+ const anchors = anchorIndex.get(canonicalDnKey(certificate.issuer));
240
+ if (anchors === void 0) return { matched: false };
241
+ let firstFailure;
242
+ for (const anchor of anchors) {
243
+ if (anchor.subjectKeyIdentifier !== void 0 && certificate.authorityKeyIdentifier !== void 0 && anchor.subjectKeyIdentifier !== certificate.authorityKeyIdentifier) continue;
244
+ let verified;
245
+ try {
246
+ const verificationResult = await verifySignedDataDetailed(certificate.signatureAlgorithmOid, certificate.signatureAlgorithmParametersDer, anchor.publicKeyAlgorithmOid, anchor.publicKeyParametersOid, anchor.subjectPublicKeyInfoDer, certificate.signatureValue, certificate.tbsCertificateDer);
247
+ verified = !verificationResult.ok && verificationResult.code === "verification_error" ? {
248
+ ok: false,
249
+ code: "signature_invalid",
250
+ reason: verificationResult.reason
251
+ } : verificationResult;
252
+ } catch (error) {
253
+ if (firstFailure === void 0) firstFailure = callbacks.failure("signature_invalid", "certificate signature does not verify", index, callbacks.detail({
254
+ subjectCommonName: certificate.subject.values.commonName,
255
+ actual: error instanceof Error ? error.message : "trust anchor key is malformed"
256
+ }));
257
+ continue;
258
+ }
259
+ if (!verified.ok) {
260
+ if (firstFailure === void 0) firstFailure = callbacks.failure(verified.code, verified.reason, index, callbacks.detail({
261
+ subjectCommonName: certificate.subject.values.commonName,
262
+ actual: verified.reason
263
+ }));
264
+ continue;
265
+ }
266
+ if (!verified.valid) {
267
+ if (firstFailure === void 0) firstFailure = callbacks.failure("signature_invalid", "certificate signature does not verify", index, callbacks.detail({
268
+ subjectCommonName: certificate.subject.values.commonName,
269
+ actual: "certificate signature does not verify"
270
+ }));
271
+ continue;
272
+ }
273
+ return { matched: true };
274
+ }
275
+ return firstFailure !== void 0 ? {
276
+ matched: false,
277
+ failure: firstFailure
278
+ } : { matched: false };
279
+ }
280
+ function describeDateTime(value) {
281
+ return Number.isNaN(value.getTime()) ? "<invalid date>" : value.toISOString();
282
+ }
283
+ function isNonNegativeInteger(value) {
284
+ return value !== void 0 && Number.isInteger(value) && value >= 0;
285
+ }
286
+ /** Cache for computed fingerprints to avoid repeated toHex() calls. */
287
+ const fingerprintCache = /* @__PURE__ */ new WeakMap();
288
+ /** Returns a hex fingerprint of the certificate's raw DER, used for cycle detection and dedup. */
289
+ function fingerprint(certificate) {
290
+ let cached = fingerprintCache.get(certificate);
291
+ if (cached === void 0) {
292
+ cached = toHex(certificate.der);
293
+ fingerprintCache.set(certificate, cached);
294
+ }
295
+ return cached;
296
+ }
297
+ //#endregion
298
+ export { buildChainInternal, countCaCertificatesBelowParsed, isSelfIssued, isWithinValidity, loadCertificates, loadSingleCertificate, verifyCertificateSignature };
@@ -1,2 +1,132 @@
1
- import{bitString as e,readRootElement as t}from"../asn1/der.js";const n=[`digitalSignature`,`nonRepudiation`,`keyEncipherment`,`dataEncipherment`,`keyAgreement`,`keyCertSign`,`cRLSign`,`encipherOnly`,`decipherOnly`],r=[`keyCompromise`,`cACompromise`,`affiliationChanged`,`superseded`,`cessationOfOperation`,`certificateHold`,`privilegeWithdrawn`,`aACompromise`];function i(t){let r=c(t,e=>d(n,e,`key usage`));return e(r.bytes,r.unusedBits)}function a(e){let r=t(e,{maxDepth:64});if(r.tag!==3)throw Error(`keyUsage must be a BIT STRING`);return u(l(r.value,n,0),`keyUsage`)}function o(e){let t=c(e,e=>d(r,e,`distribution point reason`)+1);return Uint8Array.of(t.unusedBits,...t.bytes)}function s(e){return u(l(e,r,1),`DistributionPoint reasons`)}function c(e,t){if(e.length===0)return{bytes:new Uint8Array,unusedBits:0};let n=-1,r=[];for(let i of e){let e=t(i);r.push(e),e>n&&(n=e)}let i=Math.floor(n/8)+1,a=new Uint8Array(i);for(let e of r){let t=Math.floor(e/8),n=e%8;a[t]=(a[t]??0)|1<<7-n}return{bytes:a,unusedBits:(8-(n+1)%8)%8}}function l(e,t,n){if(e.length===0)throw Error(`Empty BIT STRING`);let r=e[0]??0;if(r>7)throw Error(`Invalid BIT STRING`);let i=e.slice(1);if(i.length===0&&r!==0)throw Error(`Invalid BIT STRING`);let a=!1;r>0&&i.length>0&&(a=((i[i.length-1]??0)&(1<<r)-1)!=0);let o=[];for(let e=0;e<t.length;e+=1){let r=e+n,a=Math.floor(r/8);if(a>=i.length)break;if((i[a]??0)&1<<7-r%8){let n=t[e];n!==void 0&&o.push(n)}}return{flags:o,nonZeroPadding:a}}function u(e,t){if(e.nonZeroPadding)throw Error(`${t} BIT STRING must not set padding bits`);return e}function d(e,t,n){let r=e.indexOf(t);if(r<0)throw Error(`Unsupported ${n}: ${t}`);return r}export{o as encodeDistributionPointReasonFlagsContent,i as encodeKeyUsageExtension,s as parseDistributionPointReasonFlagsContent,a as parseKeyUsageExtension};
2
- //# sourceMappingURL=extension-bits.js.map
1
+ import { bitString, readRootElement } from "../asn1/der.js";
2
+ //#region src/internal/x509/extension-bits.ts
3
+ /**
4
+ * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.
5
+ *
6
+ * Centralizes the bit-position ordering so certificate builders and parsers
7
+ * produce identical wire encodings.
8
+ *
9
+ * @module
10
+ */
11
+ /** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */
12
+ const KEY_USAGE_ORDER = [
13
+ "digitalSignature",
14
+ "nonRepudiation",
15
+ "keyEncipherment",
16
+ "dataEncipherment",
17
+ "keyAgreement",
18
+ "keyCertSign",
19
+ "cRLSign",
20
+ "encipherOnly",
21
+ "decipherOnly"
22
+ ];
23
+ /** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */
24
+ const DISTRIBUTION_POINT_REASON_ORDER = [
25
+ "keyCompromise",
26
+ "cACompromise",
27
+ "affiliationChanged",
28
+ "superseded",
29
+ "cessationOfOperation",
30
+ "certificateHold",
31
+ "privilegeWithdrawn",
32
+ "aACompromise"
33
+ ];
34
+ /**
35
+ * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.
36
+ *
37
+ * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.
38
+ */
39
+ function encodeKeyUsageExtension(usages) {
40
+ const encoded = encodeBitFlags(usages, (usage) => indexInOrder(KEY_USAGE_ORDER, usage, "key usage"));
41
+ return bitString(encoded.bytes, encoded.unusedBits);
42
+ }
43
+ /**
44
+ * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.
45
+ *
46
+ * @param bytes DER of the keyUsage extension value (BIT STRING).
47
+ */
48
+ function parseKeyUsageExtension(bytes) {
49
+ const bitStringElement = readRootElement(bytes, { maxDepth: 64 });
50
+ if (bitStringElement.tag !== 3) throw new Error("keyUsage must be a BIT STRING");
51
+ return requireCanonicalBitFlags(decodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0), "keyUsage");
52
+ }
53
+ /**
54
+ * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes
55
+ * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.
56
+ *
57
+ * @param reasons Reason flags to encode.
58
+ */
59
+ function encodeDistributionPointReasonFlagsContent(reasons) {
60
+ const encoded = encodeBitFlags(reasons, (reason) => indexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, "distribution point reason") + 1);
61
+ return Uint8Array.of(encoded.unusedBits, ...encoded.bytes);
62
+ }
63
+ /**
64
+ * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.
65
+ *
66
+ * @param value Raw content bytes (unusedBits prefix + flag bytes).
67
+ * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.
68
+ */
69
+ function parseDistributionPointReasonFlagsContent(value) {
70
+ return requireCanonicalBitFlags(decodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1), "DistributionPoint reasons");
71
+ }
72
+ /** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */
73
+ function encodeBitFlags(values, bitForValue) {
74
+ if (values.length === 0) return {
75
+ bytes: /* @__PURE__ */ new Uint8Array(0),
76
+ unusedBits: 0
77
+ };
78
+ let highestBit = -1;
79
+ const bits = [];
80
+ for (const value of values) {
81
+ const bit = bitForValue(value);
82
+ bits.push(bit);
83
+ if (bit > highestBit) highestBit = bit;
84
+ }
85
+ const byteLength = Math.floor(highestBit / 8) + 1;
86
+ const bytes = new Uint8Array(byteLength);
87
+ for (const bit of bits) {
88
+ const byteIndex = Math.floor(bit / 8);
89
+ const bitIndex = bit % 8;
90
+ bytes[byteIndex] = (bytes[byteIndex] ?? 0) | 1 << 7 - bitIndex;
91
+ }
92
+ return {
93
+ bytes,
94
+ unusedBits: (8 - (highestBit + 1) % 8) % 8
95
+ };
96
+ }
97
+ /** Unpack set bits from a BIT STRING content into named flags from a candidate list. */
98
+ function decodeBitFlags(value, candidates, bitOffset) {
99
+ if (value.length === 0) throw new Error("Empty BIT STRING");
100
+ const unusedBits = value[0] ?? 0;
101
+ if (unusedBits > 7) throw new Error("Invalid BIT STRING");
102
+ const bytes = value.slice(1);
103
+ if (bytes.length === 0 && unusedBits !== 0) throw new Error("Invalid BIT STRING");
104
+ let nonZeroPadding = false;
105
+ if (unusedBits > 0 && bytes.length > 0) nonZeroPadding = ((bytes[bytes.length - 1] ?? 0) & (1 << unusedBits) - 1) !== 0;
106
+ const flags = [];
107
+ for (let index = 0; index < candidates.length; index += 1) {
108
+ const bit = index + bitOffset;
109
+ const byteIndex = Math.floor(bit / 8);
110
+ if (byteIndex >= bytes.length) break;
111
+ if (((bytes[byteIndex] ?? 0) & 1 << 7 - bit % 8) !== 0) {
112
+ const candidate = candidates[index];
113
+ if (candidate !== void 0) flags.push(candidate);
114
+ }
115
+ }
116
+ return {
117
+ flags,
118
+ nonZeroPadding
119
+ };
120
+ }
121
+ function requireCanonicalBitFlags(parsed, label) {
122
+ if (parsed.nonZeroPadding) throw new Error(`${label} BIT STRING must not set padding bits`);
123
+ return parsed;
124
+ }
125
+ /** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */
126
+ function indexInOrder(order, value, label) {
127
+ const index = order.indexOf(value);
128
+ if (index < 0) throw new Error(`Unsupported ${label}: ${value}`);
129
+ return index;
130
+ }
131
+ //#endregion
132
+ export { encodeDistributionPointReasonFlagsContent, encodeKeyUsageExtension, parseDistributionPointReasonFlagsContent, parseKeyUsageExtension };