micro509 0.12.0 → 0.13.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 (36) hide show
  1. package/dist/der/der.d.ts +127 -0
  2. package/dist/der/der.js +171 -0
  3. package/dist/der/der.js.map +1 -0
  4. package/dist/der.d.ts +4 -0
  5. package/dist/der.js +4 -0
  6. package/dist/internal/asn1/asn1.d.ts +20 -0
  7. package/dist/internal/asn1/asn1.js +60 -28
  8. package/dist/internal/asn1/asn1.js.map +1 -1
  9. package/dist/internal/asn1/der.d.ts +171 -0
  10. package/dist/internal/asn1/der.js +101 -36
  11. package/dist/internal/asn1/der.js.map +1 -1
  12. package/dist/internal/asn1/oids2.js +9 -2
  13. package/dist/internal/asn1/oids2.js.map +1 -1
  14. package/dist/internal/shared/dn.js +142 -12
  15. package/dist/internal/shared/dn.js.map +1 -1
  16. package/dist/internal/shared/rfc3454-tables.js +1782 -0
  17. package/dist/internal/shared/rfc3454-tables.js.map +1 -0
  18. package/dist/internal/verify/name-constraints-engine.js +47 -15
  19. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  20. package/dist/internal/verify/policy-engine.js +85 -94
  21. package/dist/internal/verify/policy-engine.js.map +1 -1
  22. package/dist/internal/verify/verify-path.js +18 -14
  23. package/dist/internal/verify/verify-path.js.map +1 -1
  24. package/dist/internal/x509/extension-bits.js +1 -1
  25. package/dist/internal/x509/extension-bits.js.map +1 -1
  26. package/dist/revocation/chain.js +110 -55
  27. package/dist/revocation/chain.js.map +1 -1
  28. package/dist/revocation/crl.js.map +1 -1
  29. package/dist/revocation/ocsp.js +1 -1
  30. package/dist/revocation/ocsp.js.map +1 -1
  31. package/dist/verify/verify.d.ts +14 -1
  32. package/dist/verify/verify.js +39 -32
  33. package/dist/verify/verify.js.map +1 -1
  34. package/dist/x509/extensions.d.ts +1 -1
  35. package/dist/x509/extensions.js.map +1 -1
  36. package/package.json +32 -22
@@ -29,33 +29,33 @@ function createPolicyValidationState(e, t) {
29
29
  * Walks the chain root-to-leaf, updating policy state per certificate,
30
30
  * then checks whether the resulting policy set satisfies caller requirements.
31
31
  */
32
- function evaluatePolicyChain(e, t) {
32
+ function evaluatePolicyChain(e, t, n = !0) {
33
33
  if (e.length === 0) throw RangeError("policy validation requires at least one certificate");
34
- processPolicyState(e, t);
35
- let n = derivePolicyValidationOutcome(e, t);
36
- return t.explicitPolicy === 0 && n.userConstrainedPolicies.length === 0 ? {
34
+ processPolicyState(e, t, n);
35
+ let r = derivePolicyValidationOutcome(t);
36
+ return t.explicitPolicy === 0 && r.userConstrainedPolicies.length === 0 ? {
37
37
  ok: !1,
38
38
  error: {
39
39
  code: "explicit_policy_required",
40
40
  message: "policy validation requires an explicit permitted policy",
41
41
  details: {
42
42
  expected: t.initialPolicySet === "any" ? "explicit policy" : t.initialPolicySet.join(","),
43
- actual: describeFinalPolicies(n.userConstrainedPolicies)
43
+ actual: describeFinalPolicies(r.userConstrainedPolicies)
44
44
  }
45
45
  }
46
- } : t.initialPolicySet !== "any" && n.userConstrainedPolicies.length === 0 ? {
46
+ } : t.initialPolicySet !== "any" && r.userConstrainedPolicies.length === 0 ? {
47
47
  ok: !1,
48
48
  error: {
49
49
  code: "initial_policy_set_not_satisfied",
50
50
  message: "certificate chain does not satisfy the requested initial policy set",
51
51
  details: {
52
52
  expected: t.initialPolicySet.join(","),
53
- actual: describeFinalPolicies(n.userConstrainedPolicies)
53
+ actual: describeFinalPolicies(r.userConstrainedPolicies)
54
54
  }
55
55
  }
56
56
  } : {
57
57
  ok: !0,
58
- value: n
58
+ value: r
59
59
  };
60
60
  }
61
61
  /** Builds the depth-0 graph with a single anyPolicy root node. */
@@ -78,111 +78,102 @@ function createPolicyGraphNode(e, t, n, r, i) {
78
78
  function policyNodeKey(e, t) {
79
79
  return `${String(e)}:${t}`;
80
80
  }
81
- /** Iterates root-to-leaf (skipping root), applying each certificate's policies to the state. */
82
- function processPolicyState(e, t) {
81
+ /**
82
+ * Applies each path certificate's policies to the state, top CA first. When
83
+ * `anchorInChain` is true the terminal certificate is the trust anchor and is
84
+ * excluded; a bare anchor leaves the terminal certificate a path certificate
85
+ * that must be processed.
86
+ */
87
+ function processPolicyState(e, t, n) {
83
88
  if (e.length === 1) {
84
89
  let n = e[0];
85
90
  if (n === void 0) throw Error(`missing certificate at chain index 0 (chain length ${String(e.length)})`);
86
91
  processPolicyCertificate(t, n, 1, !0);
87
92
  return;
88
93
  }
89
- let n = e.length - 1;
90
- for (let r = e.length - 2; r >= 0; --r) {
91
- let i = e[r];
92
- if (i === void 0) throw Error(`missing certificate at chain index ${String(r)} (chain length ${String(e.length)})`);
93
- let a = n - r;
94
- processPolicyCertificate(t, i, a, a === n);
94
+ let r = n ? e.length - 1 : e.length;
95
+ for (let n = r - 1; n >= 0; --n) {
96
+ let i = e[n];
97
+ if (i === void 0) throw Error(`missing certificate at chain index ${String(n)} (chain length ${String(e.length)})`);
98
+ let a = r - n;
99
+ processPolicyCertificate(t, i, a, a === r);
95
100
  }
96
101
  }
97
- /** Extracts the final authority- and user-constrained policy sets from the completed graph. */
98
- function derivePolicyValidationOutcome(e, t) {
99
- let n = collectAuthorityConstrainedPolicies(e, t.validPolicyGraph), r = collectRootDomainPolicies(e, t.validPolicyGraph);
102
+ /** Extracts the authority- and user-constrained policy sets from the completed graph (RFC 9618 §5.5 step (g)). */
103
+ function derivePolicyValidationOutcome(e) {
104
+ let t = collectAuthorityConstrainedPolicies(e.validPolicyGraph);
100
105
  return {
101
- authorityConstrainedPolicies: [...n.values()].sort(comparePolicies),
102
- userConstrainedPolicies: deriveUserConstrainedPolicies(n, r, t.initialPolicySet)
106
+ authorityConstrainedPolicies: [...t.values()].sort(comparePolicies),
107
+ userConstrainedPolicies: deriveUserConstrainedPolicies(t, e.initialPolicySet)
103
108
  };
104
109
  }
105
- /** Collects leaf-depth policies whose graph paths trace back to the anyPolicy root. */
106
- function collectAuthorityConstrainedPolicies(t, n) {
107
- if (n === null) return /* @__PURE__ */ new Map();
108
- let r = Math.max(1, t.length - 1), i = n.nodesByDepth[r];
109
- if (i === void 0) return /* @__PURE__ */ new Map();
110
+ /**
111
+ * RFC 9618 §5.5 (g)(2)-(4) authority_constrained_policy_set. The
112
+ * valid_policy_node_set is every graph node, at any depth, whose valid_policy is
113
+ * not anyPolicy and whose single parent is an anyPolicy node, plus a depth-n
114
+ * anyPolicy node when present. Pruning has already removed nodes with no path to
115
+ * the leaf, so the whole graph is the final tree.
116
+ */
117
+ function collectAuthorityConstrainedPolicies(t) {
118
+ if (t === null) return /* @__PURE__ */ new Map();
119
+ let n = /* @__PURE__ */ new Map(), record = (e) => {
120
+ let r = n.get(e.validPolicy) ?? [];
121
+ r.push(...gatherLineageQualifiers(t, e)), n.set(e.validPolicy, r);
122
+ };
123
+ for (let n of t.nodesByDepth) for (let r of n.values()) r.validPolicy !== e.anyPolicy && r.parentKeys.size === 1 && getSingleParent(t, r)?.validPolicy === e.anyPolicy && record(r);
124
+ let r = t.nodesByDepth.length - 1, i = t.nodesByDepth[r]?.get(policyNodeKey(r, e.anyPolicy));
125
+ i !== void 0 && record(i);
110
126
  let a = /* @__PURE__ */ new Map();
111
- for (let [t, r] of i) {
112
- if (r.validPolicy === e.anyPolicy) {
113
- a.set(e.anyPolicy, buildConstrainedPolicy(e.anyPolicy, r.qualifierSet));
114
- continue;
115
- }
116
- reachesAuthorityRoot(n, t) && a.set(r.validPolicy, buildConstrainedPolicy(r.validPolicy, r.qualifierSet));
117
- }
127
+ for (let [e, t] of n) a.set(e, buildConstrainedPolicy(e, dedupeQualifiers(t)));
118
128
  return a;
119
129
  }
120
- /** DFS upward through parent links to check if the node ultimately connects to the depth-0 anyPolicy root. */
121
- function reachesAuthorityRoot(t, n) {
122
- let r = [n], i = /* @__PURE__ */ new Set();
123
- for (; r.length > 0;) {
124
- let n = r.pop();
125
- if (n === void 0 || i.has(n)) continue;
126
- i.add(n);
127
- let a = getPolicyGraphNode(t, n);
128
- if (a !== void 0) for (let n of a.parentKeys) {
129
- let i = getPolicyGraphNode(t, n);
130
- if (i !== void 0) {
131
- if (i.depth === 0 && i.validPolicy === e.anyPolicy) return !0;
132
- r.push(n);
133
- }
130
+ /** Returns the sole parent of a node whose parent list has exactly one entry. */
131
+ function getSingleParent(e, t) {
132
+ let n = [...t.parentKeys][0];
133
+ return n === void 0 ? void 0 : getPolicyGraphNode(e, n);
134
+ }
135
+ /** RFC 9618 §5.5 (g)(4)(ii): qualifiers from a node, its ancestors, and its descendants. */
136
+ function gatherLineageQualifiers(e, t) {
137
+ let n = [...t.qualifierSet ?? []];
138
+ return collectDirectionalQualifiers(e, t.parentKeys, (e) => e.parentKeys, n), collectDirectionalQualifiers(e, t.childKeys, (e) => e.childKeys, n), n;
139
+ }
140
+ /** Follows one edge direction transitively, appending each visited node's qualifiers. */
141
+ function collectDirectionalQualifiers(e, t, n, r) {
142
+ let i = /* @__PURE__ */ new Set(), a = [...t];
143
+ for (; a.length > 0;) {
144
+ let t = a.pop();
145
+ if (t === void 0 || i.has(t)) continue;
146
+ i.add(t);
147
+ let o = getPolicyGraphNode(e, t);
148
+ if (o !== void 0) {
149
+ o.qualifierSet !== void 0 && r.push(...o.qualifierSet);
150
+ for (let e of n(o)) a.push(e);
134
151
  }
135
152
  }
136
- return !1;
137
153
  }
138
- /** Like authority-constrained, but records the OID at the depth-1 node that connects to root. */
139
- function collectRootDomainPolicies(t, n) {
140
- if (n === null) return /* @__PURE__ */ new Map();
141
- let r = Math.max(1, t.length - 1), i = n.nodesByDepth[r];
142
- if (i === void 0) return /* @__PURE__ */ new Map();
143
- let a = /* @__PURE__ */ new Map();
144
- for (let [t, r] of i) {
145
- if (r.validPolicy === e.anyPolicy) {
146
- a.set(e.anyPolicy, buildConstrainedPolicy(e.anyPolicy, r.qualifierSet));
147
- continue;
148
- }
149
- collectAuthorityConstrainedPolicyRoots(n, t, a);
150
- }
151
- return a;
152
- }
153
- /** Walks parent links upward, collecting the depth-1 OID that first connects to the root anyPolicy. */
154
- function collectAuthorityConstrainedPolicyRoots(t, n, r) {
155
- let i = [n], a = /* @__PURE__ */ new Set();
156
- for (; i.length > 0;) {
157
- let o = i.pop();
158
- if (o === void 0 || a.has(o)) continue;
159
- a.add(o);
160
- let s = getPolicyGraphNode(t, o);
161
- if (s !== void 0) for (let a of s.parentKeys) {
162
- let c = getPolicyGraphNode(t, a);
163
- if (c !== void 0) {
164
- if (c.depth === 0 && c.validPolicy === e.anyPolicy) {
165
- r.set(s.validPolicy, buildConstrainedPolicy(s.validPolicy, o === n ? s.qualifierSet : void 0));
166
- continue;
167
- }
168
- i.push(a);
169
- }
170
- }
154
+ /** Deduplicates qualifiers by value, returning `undefined` when none remain. */
155
+ function dedupeQualifiers(e) {
156
+ let t = /* @__PURE__ */ new Set(), n = [];
157
+ for (let r of e) {
158
+ let e = JSON.stringify(r, (e, t) => t instanceof Uint8Array ? Array.from(t) : t);
159
+ t.has(e) || (t.add(e), n.push(r));
171
160
  }
161
+ return n.length === 0 ? void 0 : n;
172
162
  }
173
- /** Intersects root-domain policies with the caller's initial-policy-set. */
174
- function deriveUserConstrainedPolicies(t, n, r) {
175
- if (r === "any") return [...t.values()].sort(comparePolicies);
176
- let i = n.get(e.anyPolicy), a = t.has(e.anyPolicy), o = /* @__PURE__ */ new Map();
177
- for (let e of r) {
178
- let r = n.get(e);
179
- if (r !== void 0) {
180
- o.set(e, r);
181
- continue;
182
- }
183
- i !== void 0 && (t.has(e) || a) && o.set(e, buildConstrainedPolicy(e, i.policyQualifiers));
184
- }
185
- return [...o.values()].sort(comparePolicies);
163
+ /**
164
+ * RFC 9618 §5.5 (g)(5)-(6) user_constrained_policy_set. It equals the
165
+ * authority-constrained set when the initial-policy-set is anyPolicy. Otherwise
166
+ * it keeps the members named in the initial-policy-set, and, when the authority
167
+ * set holds anyPolicy, adds the remaining requested OIDs with anyPolicy's
168
+ * qualifiers.
169
+ */
170
+ function deriveUserConstrainedPolicies(t, n) {
171
+ if (n === "any") return [...t.values()].sort(comparePolicies);
172
+ let r = /* @__PURE__ */ new Map();
173
+ for (let [e, i] of t) n.includes(e) && r.set(e, i);
174
+ let i = t.get(e.anyPolicy);
175
+ if (i !== void 0) for (let e of n) r.has(e) || r.set(e, buildConstrainedPolicy(e, i.policyQualifiers));
176
+ return [...r.values()].sort(comparePolicies);
186
177
  }
187
178
  /** Constructs a {@linkcode ConstrainedPolicy}, omitting qualifiers when absent. */
188
179
  function buildConstrainedPolicy(e, t) {
@@ -1 +1 @@
1
- {"version":3,"file":"policy-engine.js","names":[],"sources":["../../../src/internal/verify/policy-engine.ts"],"sourcesContent":["/**\n * Internal RFC 9618 policy-validation engine.\n *\n * Tracks the policy graph and counter state through each certificate in a\n * chain, then derives the {@linkcode PolicyValidationOutcome}.\n *\n * @module\n */\n\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport type { Micro509Error, Result } from '#micro509/result/result';\nimport type {\n\tConstrainedPolicy,\n\tPolicyValidationInput,\n\tPolicyValidationOutcome,\n} from '#micro509/verify/policy';\nimport type { PolicyInformation, PolicyQualifierInfo } from '#micro509/x509/extensions';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\n\n/**\n * Mutable state threaded through each step of the policy-validation walk.\n *\n * Created by {@linkcode createPolicyValidationState}, consumed by\n * {@linkcode evaluatePolicyChain}.\n */\nexport interface PolicyValidationState {\n\t/** Caller-requested acceptable policies, or `'any'`. */\n\treadonly initialPolicySet: readonly string[] | 'any';\n\t/** Remaining certificates before explicit-policy enforcement kicks in. */\n\texplicitPolicy: number;\n\t/** Remaining certificates before policy mappings are disallowed. */\n\tinhibitPolicyMapping: number;\n\t/** Remaining certificates before anyPolicy expansion stops. */\n\tinhibitAnyPolicy: number;\n\t/** The RFC 9618 policy graph; `null` when the graph has been emptied. */\n\tvalidPolicyGraph: PolicyGraph | null;\n}\n\n/** Discriminant codes for policy-validation failures. */\nexport type PolicyValidationFailureCode =\n\t| 'explicit_policy_required'\n\t| 'initial_policy_set_not_satisfied';\n\n/** Diagnostic context for a policy-validation failure. */\nexport interface PolicyValidationFailureDetails {\n\t/** Description of the policies the caller expected. */\n\treadonly expected: string;\n\t/** Comma-joined OIDs (or `\"<none>\"`) that actually survived processing. */\n\treadonly actual: string;\n}\n\n/** A policy-validation failure with structured diagnostic details. */\nexport interface PolicyValidationFailure\n\textends Micro509Error<PolicyValidationFailureCode, PolicyValidationFailureDetails> {}\n\n/** Success with {@linkcode PolicyValidationOutcome}, or a {@linkcode PolicyValidationFailure}. */\nexport type PolicyValidationResult = Result<PolicyValidationOutcome, PolicyValidationFailure>;\n\n/** One node in the RFC 9618 policy graph, keyed by `depth:policyOID`. */\nexport interface PolicyGraphNode {\n\t/** Graph depth (0 = root anyPolicy node). */\n\tdepth: number;\n\t/** The policy OID this node represents at its depth. */\n\tvalidPolicy: string;\n\t/** Policy qualifiers inherited from the certificate that created this node. */\n\tqualifierSet?: readonly PolicyQualifierInfo[];\n\t/** OIDs this node expects to see in the next certificate's policies. */\n\texpectedPolicySet: Set<string>;\n\t/** Keys of parent nodes in the previous depth level. */\n\tparentKeys: Set<string>;\n\t/** Keys of child nodes in the next depth level. */\n\tchildKeys: Set<string>;\n}\n\n/** The full RFC 9618 valid-policy graph, indexed by depth level. */\nexport interface PolicyGraph {\n\t/** Each index `i` holds the nodes at depth `i`, keyed by `\"depth:oid\"`. */\n\tnodesByDepth: Map<string, PolicyGraphNode>[];\n}\n\n/**\n * Initializes mutable policy state from caller options.\n *\n * Counter values default to `chainLength + 1` (effectively disabled) unless\n * the corresponding input flag is `true`.\n */\nexport function createPolicyValidationState(\n\tinput: PolicyValidationInput,\n\tchainLength: number,\n): PolicyValidationState {\n\tconst disabledCounter = chainLength + 1;\n\treturn {\n\t\tinitialPolicySet: input.initialPolicySet ?? 'any',\n\t\texplicitPolicy: input.requireExplicitPolicy === true ? 0 : disabledCounter,\n\t\tinhibitPolicyMapping: input.inhibitPolicyMapping === true ? 0 : disabledCounter,\n\t\tinhibitAnyPolicy: input.inhibitAnyPolicy === true ? 0 : disabledCounter,\n\t\tvalidPolicyGraph: createInitialPolicyGraph(),\n\t};\n}\n\n/**\n * Walks the chain root-to-leaf, updating policy state per certificate,\n * then checks whether the resulting policy set satisfies caller requirements.\n */\nexport function evaluatePolicyChain(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n): PolicyValidationResult {\n\tif (chain.length === 0) {\n\t\tthrow new RangeError('policy validation requires at least one certificate');\n\t}\n\tprocessPolicyState(chain, state);\n\tconst outcome = derivePolicyValidationOutcome(chain, state);\n\tif (state.explicitPolicy === 0 && outcome.userConstrainedPolicies.length === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: 'explicit_policy_required',\n\t\t\t\tmessage: 'policy validation requires an explicit permitted policy',\n\t\t\t\tdetails: {\n\t\t\t\t\texpected:\n\t\t\t\t\t\tstate.initialPolicySet === 'any' ? 'explicit policy' : state.initialPolicySet.join(','),\n\t\t\t\t\tactual: describeFinalPolicies(outcome.userConstrainedPolicies),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\tif (state.initialPolicySet !== 'any' && outcome.userConstrainedPolicies.length === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: 'initial_policy_set_not_satisfied',\n\t\t\t\tmessage: 'certificate chain does not satisfy the requested initial policy set',\n\t\t\t\tdetails: {\n\t\t\t\t\texpected: state.initialPolicySet.join(','),\n\t\t\t\t\tactual: describeFinalPolicies(outcome.userConstrainedPolicies),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn { ok: true, value: outcome };\n}\n\n/** Builds the depth-0 graph with a single anyPolicy root node. */\nfunction createInitialPolicyGraph(): PolicyGraph {\n\tconst rootNode = createPolicyGraphNode(0, OIDS.anyPolicy, undefined, [OIDS.anyPolicy], []);\n\treturn {\n\t\tnodesByDepth: [new Map([[policyNodeKey(0, OIDS.anyPolicy), rootNode]])],\n\t};\n}\n\n/** Constructs a new {@linkcode PolicyGraphNode} with empty child-key set. */\nfunction createPolicyGraphNode(\n\tdepth: number,\n\tvalidPolicy: string,\n\tqualifierSet: readonly PolicyQualifierInfo[] | undefined,\n\texpectedPolicySet: readonly string[],\n\tparentKeys: readonly string[],\n): PolicyGraphNode {\n\treturn {\n\t\tdepth,\n\t\tvalidPolicy,\n\t\t...(qualifierSet === undefined ? {} : { qualifierSet }),\n\t\texpectedPolicySet: new Set(expectedPolicySet),\n\t\tparentKeys: new Set(parentKeys),\n\t\tchildKeys: new Set<string>(),\n\t};\n}\n\n/** Canonical map key for a graph node: `\"depth:policyOID\"`. */\nfunction policyNodeKey(depth: number, validPolicy: string): string {\n\treturn `${String(depth)}:${validPolicy}`;\n}\n\n/** Iterates root-to-leaf (skipping root), applying each certificate's policies to the state. */\nfunction processPolicyState(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n): void {\n\tif (chain.length === 1) {\n\t\tconst certificate = chain[0];\n\t\tif (certificate === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`missing certificate at chain index 0 (chain length ${String(chain.length)})`,\n\t\t\t);\n\t\t}\n\t\tprocessPolicyCertificate(state, certificate, 1, true);\n\t\treturn;\n\t}\n\tconst leafDepth = chain.length - 1;\n\tfor (let index = chain.length - 2; index >= 0; index -= 1) {\n\t\tconst certificate = chain[index];\n\t\tif (certificate === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`missing certificate at chain index ${String(index)} (chain length ${String(chain.length)})`,\n\t\t\t);\n\t\t}\n\t\tconst depth = leafDepth - index;\n\t\tprocessPolicyCertificate(state, certificate, depth, depth === leafDepth);\n\t}\n}\n\n/** Extracts the final authority- and user-constrained policy sets from the completed graph. */\nfunction derivePolicyValidationOutcome(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n): PolicyValidationOutcome {\n\tconst authorityConstrainedPolicies = collectAuthorityConstrainedPolicies(\n\t\tchain,\n\t\tstate.validPolicyGraph,\n\t);\n\tconst rootDomainPolicies = collectRootDomainPolicies(chain, state.validPolicyGraph);\n\treturn {\n\t\tauthorityConstrainedPolicies: [...authorityConstrainedPolicies.values()].sort(comparePolicies),\n\t\tuserConstrainedPolicies: deriveUserConstrainedPolicies(\n\t\t\tauthorityConstrainedPolicies,\n\t\t\trootDomainPolicies,\n\t\t\tstate.initialPolicySet,\n\t\t),\n\t};\n}\n\n/** Collects leaf-depth policies whose graph paths trace back to the anyPolicy root. */\nfunction collectAuthorityConstrainedPolicies(\n\tchain: readonly ParsedCertificate[],\n\tgraph: PolicyGraph | null,\n): ReadonlyMap<string, ConstrainedPolicy> {\n\tif (graph === null) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst leafDepth = Math.max(1, chain.length - 1);\n\tconst finalDepth = graph.nodesByDepth[leafDepth];\n\tif (finalDepth === undefined) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst authorityPolicies = new Map<string, ConstrainedPolicy>();\n\tfor (const [key, node] of finalDepth) {\n\t\tif (node.validPolicy === OIDS.anyPolicy) {\n\t\t\tauthorityPolicies.set(\n\t\t\t\tOIDS.anyPolicy,\n\t\t\t\tbuildConstrainedPolicy(OIDS.anyPolicy, node.qualifierSet),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (reachesAuthorityRoot(graph, key)) {\n\t\t\tauthorityPolicies.set(\n\t\t\t\tnode.validPolicy,\n\t\t\t\tbuildConstrainedPolicy(node.validPolicy, node.qualifierSet),\n\t\t\t);\n\t\t}\n\t}\n\treturn authorityPolicies;\n}\n\n/** DFS upward through parent links to check if the node ultimately connects to the depth-0 anyPolicy root. */\nfunction reachesAuthorityRoot(graph: PolicyGraph, nodeKey: string): boolean {\n\tconst pending = [nodeKey];\n\tconst visited = new Set<string>();\n\twhile (pending.length > 0) {\n\t\tconst currentKey = pending.pop();\n\t\tif (currentKey === undefined || visited.has(currentKey)) {\n\t\t\tcontinue;\n\t\t}\n\t\tvisited.add(currentKey);\n\t\tconst node = getPolicyGraphNode(graph, currentKey);\n\t\tif (node === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const parentKey of node.parentKeys) {\n\t\t\tconst parent = getPolicyGraphNode(graph, parentKey);\n\t\t\tif (parent === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (parent.depth === 0 && parent.validPolicy === OIDS.anyPolicy) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpending.push(parentKey);\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Like authority-constrained, but records the OID at the depth-1 node that connects to root. */\nfunction collectRootDomainPolicies(\n\tchain: readonly ParsedCertificate[],\n\tgraph: PolicyGraph | null,\n): ReadonlyMap<string, ConstrainedPolicy> {\n\tif (graph === null) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst leafDepth = Math.max(1, chain.length - 1);\n\tconst finalDepth = graph.nodesByDepth[leafDepth];\n\tif (finalDepth === undefined) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst rootPolicies = new Map<string, ConstrainedPolicy>();\n\tfor (const [key, node] of finalDepth) {\n\t\tif (node.validPolicy === OIDS.anyPolicy) {\n\t\t\trootPolicies.set(OIDS.anyPolicy, buildConstrainedPolicy(OIDS.anyPolicy, node.qualifierSet));\n\t\t\tcontinue;\n\t\t}\n\t\tcollectAuthorityConstrainedPolicyRoots(graph, key, rootPolicies);\n\t}\n\treturn rootPolicies;\n}\n\n/** Walks parent links upward, collecting the depth-1 OID that first connects to the root anyPolicy. */\nfunction collectAuthorityConstrainedPolicyRoots(\n\tgraph: PolicyGraph,\n\tnodeKey: string,\n\tauthorityPolicies: Map<string, ConstrainedPolicy>,\n): void {\n\tconst pending = [nodeKey];\n\tconst visited = new Set<string>();\n\twhile (pending.length > 0) {\n\t\tconst currentKey = pending.pop();\n\t\tif (currentKey === undefined || visited.has(currentKey)) {\n\t\t\tcontinue;\n\t\t}\n\t\tvisited.add(currentKey);\n\t\tconst node = getPolicyGraphNode(graph, currentKey);\n\t\tif (node === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const parentKey of node.parentKeys) {\n\t\t\tconst parent = getPolicyGraphNode(graph, parentKey);\n\t\t\tif (parent === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (parent.depth === 0 && parent.validPolicy === OIDS.anyPolicy) {\n\t\t\t\t// Record the depth-1 policy that connects to root\n\t\t\t\t// If the depth-1 node is anyPolicy itself, record anyPolicy so it can satisfy\n\t\t\t\t// any policy in the initial-policy-set via deriveUserConstrainedPolicies\n\t\t\t\tauthorityPolicies.set(\n\t\t\t\t\tnode.validPolicy,\n\t\t\t\t\tbuildConstrainedPolicy(\n\t\t\t\t\t\tnode.validPolicy,\n\t\t\t\t\t\tcurrentKey === nodeKey ? node.qualifierSet : undefined,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpending.push(parentKey);\n\t\t}\n\t}\n}\n\n/** Intersects root-domain policies with the caller's initial-policy-set. */\nfunction deriveUserConstrainedPolicies(\n\tfinalAuthorityConstrainedPolicies: ReadonlyMap<string, ConstrainedPolicy>,\n\trootDomainPolicies: ReadonlyMap<string, ConstrainedPolicy>,\n\tinitialPolicySet: readonly string[] | 'any',\n): readonly ConstrainedPolicy[] {\n\tif (initialPolicySet === 'any') {\n\t\treturn [...finalAuthorityConstrainedPolicies.values()].sort(comparePolicies);\n\t}\n\tconst anyPolicy = rootDomainPolicies.get(OIDS.anyPolicy);\n\t// If the EE asserts anyPolicy, it satisfies any policy in initial-policy-set\n\tconst eeHasAnyPolicy = finalAuthorityConstrainedPolicies.has(OIDS.anyPolicy);\n\tconst constrained = new Map<string, ConstrainedPolicy>();\n\tfor (const policyIdentifier of initialPolicySet) {\n\t\tconst direct = rootDomainPolicies.get(policyIdentifier);\n\t\tif (direct !== undefined) {\n\t\t\tconstrained.set(policyIdentifier, direct);\n\t\t\tcontinue;\n\t\t}\n\t\t// anyPolicy can satisfy a requested policy if:\n\t\t// 1. The EE asserts the specific policy (finalAuthorityConstrainedPolicies.has), OR\n\t\t// 2. The EE itself asserts anyPolicy (eeHasAnyPolicy)\n\t\tif (\n\t\t\tanyPolicy !== undefined &&\n\t\t\t(finalAuthorityConstrainedPolicies.has(policyIdentifier) || eeHasAnyPolicy)\n\t\t) {\n\t\t\tconstrained.set(\n\t\t\t\tpolicyIdentifier,\n\t\t\t\tbuildConstrainedPolicy(policyIdentifier, anyPolicy.policyQualifiers),\n\t\t\t);\n\t\t}\n\t}\n\treturn [...constrained.values()].sort(comparePolicies);\n}\n\n/** Constructs a {@linkcode ConstrainedPolicy}, omitting qualifiers when absent. */\nfunction buildConstrainedPolicy(\n\tpolicyIdentifier: string,\n\tpolicyQualifiers: readonly PolicyQualifierInfo[] | undefined,\n): ConstrainedPolicy {\n\treturn {\n\t\tpolicyIdentifier,\n\t\t...(policyQualifiers === undefined ? {} : { policyQualifiers }),\n\t};\n}\n\n/** Lexicographic comparator for sorting policies by OID string. */\nfunction comparePolicies(left: ConstrainedPolicy, right: ConstrainedPolicy): number {\n\treturn left.policyIdentifier.localeCompare(right.policyIdentifier);\n}\n\n/** Human-readable comma-joined OID list for error messages; `\"<none>\"` when empty. */\nfunction describeFinalPolicies(policies: readonly ConstrainedPolicy[]): string {\n\treturn policies.length === 0\n\t\t? '<none>'\n\t\t: policies.map((policy) => policy.policyIdentifier).join(',');\n}\n\n/** Applies one certificate's policies, mappings, and constraints to the running state. */\nfunction processPolicyCertificate(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n\tdepth: number,\n\tisLeaf: boolean,\n): void {\n\tconst certificatePolicies = normalizeCertificatePolicies(certificate.certificatePolicies);\n\tif (state.validPolicyGraph !== null && certificatePolicies === undefined) {\n\t\tstate.validPolicyGraph = null;\n\t} else if (state.validPolicyGraph !== null && certificatePolicies !== undefined) {\n\t\tapplyCertificatePolicyStep(\n\t\t\tstate.validPolicyGraph,\n\t\t\tcertificatePolicies,\n\t\t\tdepth,\n\t\t\tstate.inhibitAnyPolicy > 0 || (!isLeaf && isSelfIssued(certificate)),\n\t\t);\n\t\tif (certificate.policyMappings !== undefined) {\n\t\t\tapplyPolicyMappingsStep(\n\t\t\t\tstate.validPolicyGraph,\n\t\t\t\tdepth,\n\t\t\t\tcertificate.policyMappings,\n\t\t\t\tstate.inhibitPolicyMapping > 0,\n\t\t\t);\n\t\t}\n\t}\n\tupdatePolicyCounters(state, certificate, isLeaf);\n}\n\n/** Deduplicates certificate policies by OID, keeping the first occurrence. */\nfunction normalizeCertificatePolicies(\n\tpolicies: readonly PolicyInformation[] | undefined,\n): Map<string, PolicyInformation> | undefined {\n\tif (policies === undefined) {\n\t\treturn undefined;\n\t}\n\tconst byOid = new Map<string, PolicyInformation>();\n\tfor (const policy of policies) {\n\t\tif (!byOid.has(policy.policyIdentifier)) {\n\t\t\tbyOid.set(policy.policyIdentifier, policy);\n\t\t}\n\t}\n\treturn byOid;\n}\n\n/** Extends the policy graph by one depth level using a certificate's policy extension. */\nfunction applyCertificatePolicyStep(\n\tgraph: PolicyGraph,\n\tcertificatePolicies: ReadonlyMap<string, PolicyInformation>,\n\tdepth: number,\n\tallowAnyPolicyExpansion: boolean,\n): void {\n\tconst previousDepth = graph.nodesByDepth[depth - 1] ?? new Map<string, PolicyGraphNode>();\n\tconst currentDepth = new Map<string, PolicyGraphNode>();\n\tgraph.nodesByDepth[depth] = currentDepth;\n\tconst anyPolicyInfo = certificatePolicies.get(OIDS.anyPolicy);\n\tconst previousAnyPolicy = previousDepth.get(policyNodeKey(depth - 1, OIDS.anyPolicy));\n\tconst previousAnyPolicyKey = policyNodeKey(depth - 1, OIDS.anyPolicy);\n\n\taddPolicyNodesFromExpectedParents(graph, currentDepth, previousDepth, certificatePolicies, depth);\n\n\tif (previousAnyPolicy !== undefined) {\n\t\taddPolicyNodesFromPreviousAnyPolicy(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tcertificatePolicies,\n\t\t\tdepth,\n\t\t\tpreviousAnyPolicyKey,\n\t\t);\n\t}\n\n\tif (anyPolicyInfo !== undefined && allowAnyPolicyExpansion) {\n\t\taddAnyPolicyExpansionNodes(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tpreviousDepth,\n\t\t\tdepth,\n\t\t\tanyPolicyInfo,\n\t\t\tpreviousAnyPolicyKey,\n\t\t\tpreviousAnyPolicy !== undefined,\n\t\t);\n\t}\n\n\tprunePolicyGraph(graph, depth - 1);\n}\n\n/** Adds explicit certificate-policy nodes whose expected policies match parent nodes. */\nfunction addPolicyNodesFromExpectedParents(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tpreviousDepth: ReadonlyMap<string, PolicyGraphNode>,\n\tcertificatePolicies: ReadonlyMap<string, PolicyInformation>,\n\tdepth: number,\n): void {\n\tfor (const policy of certificatePolicies.values()) {\n\t\tif (policy.policyIdentifier === OIDS.anyPolicy) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst matchingParents = collectParentsForExpectedPolicy(previousDepth, policy.policyIdentifier);\n\t\tif (matchingParents.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\taddOrMergePolicyNode(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tdepth,\n\t\t\tpolicy.policyIdentifier,\n\t\t\tpolicy.policyQualifiers,\n\t\t\tmatchingParents,\n\t\t\t[policy.policyIdentifier],\n\t\t);\n\t}\n}\n\nfunction addPolicyNodesFromPreviousAnyPolicy(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tcertificatePolicies: ReadonlyMap<string, PolicyInformation>,\n\tdepth: number,\n\tpreviousAnyPolicyKey: string,\n): void {\n\tfor (const policy of certificatePolicies.values()) {\n\t\tif (policy.policyIdentifier === OIDS.anyPolicy) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (currentDepth.has(policyNodeKey(depth, policy.policyIdentifier))) {\n\t\t\tcontinue;\n\t\t}\n\t\taddOrMergePolicyNode(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tdepth,\n\t\t\tpolicy.policyIdentifier,\n\t\t\tpolicy.policyQualifiers,\n\t\t\t[previousAnyPolicyKey],\n\t\t\t[policy.policyIdentifier],\n\t\t);\n\t}\n}\n\n/** Expands an accepted anyPolicy entry into the policies expected by the previous depth. */\nfunction addAnyPolicyExpansionNodes(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tpreviousDepth: ReadonlyMap<string, PolicyGraphNode>,\n\tdepth: number,\n\tanyPolicyInfo: PolicyInformation,\n\tpreviousAnyPolicyKey: string,\n\thasPreviousAnyPolicy: boolean,\n): void {\n\tfor (const [validPolicy, parentKeys] of collectExpectedPolicyParents(previousDepth)) {\n\t\tif (currentDepth.has(policyNodeKey(depth, validPolicy))) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst expansionParents = collectAnyPolicyExpansionParents(\n\t\t\tvalidPolicy,\n\t\t\tparentKeys,\n\t\t\tpreviousAnyPolicyKey,\n\t\t\thasPreviousAnyPolicy,\n\t\t);\n\t\tif (expansionParents.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\taddOrMergePolicyNode(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tdepth,\n\t\t\tvalidPolicy,\n\t\t\tanyPolicyInfo.policyQualifiers,\n\t\t\texpansionParents,\n\t\t\t[validPolicy],\n\t\t);\n\t}\n}\n\nfunction collectAnyPolicyExpansionParents(\n\tvalidPolicy: string,\n\tparentKeys: readonly string[],\n\tpreviousAnyPolicyKey: string,\n\thasPreviousAnyPolicy: boolean,\n): readonly string[] {\n\tif (validPolicy !== OIDS.anyPolicy) {\n\t\treturn parentKeys;\n\t}\n\treturn hasPreviousAnyPolicy ? [previousAnyPolicyKey] : [];\n}\n\n/** Finds all previous-depth nodes whose expectedPolicySet contains the given OID. */\nfunction collectParentsForExpectedPolicy(\n\tnodes: ReadonlyMap<string, PolicyGraphNode>,\n\tpolicyIdentifier: string,\n): string[] {\n\tconst parents: string[] = [];\n\tfor (const [key, node] of nodes) {\n\t\tif (node.expectedPolicySet.has(policyIdentifier)) {\n\t\t\tparents.push(key);\n\t\t}\n\t}\n\treturn parents;\n}\n\n/** Groups all previous-depth nodes by each OID in their expectedPolicySet. */\nfunction collectExpectedPolicyParents(\n\tnodes: ReadonlyMap<string, PolicyGraphNode>,\n): Map<string, string[]> {\n\tconst parentsByPolicy = new Map<string, string[]>();\n\tfor (const [key, node] of nodes) {\n\t\tfor (const expectedPolicy of node.expectedPolicySet) {\n\t\t\tconst parents = parentsByPolicy.get(expectedPolicy);\n\t\t\tif (parents === undefined) {\n\t\t\t\tparentsByPolicy.set(expectedPolicy, [key]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparents.push(key);\n\t\t}\n\t}\n\treturn parentsByPolicy;\n}\n\n/** Inserts a node at the current depth, or merges parents/expected-policies into an existing one. */\nfunction addOrMergePolicyNode(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tdepth: number,\n\tvalidPolicy: string,\n\tqualifierSet: readonly PolicyQualifierInfo[] | undefined,\n\tparentKeys: readonly string[],\n\texpectedPolicySet: readonly string[],\n): void {\n\tconst key = policyNodeKey(depth, validPolicy);\n\tconst existing = currentDepth.get(key);\n\tif (existing !== undefined) {\n\t\tfor (const parentKey of parentKeys) {\n\t\t\texisting.parentKeys.add(parentKey);\n\t\t\tgetPolicyGraphNode(graph, parentKey)?.childKeys.add(key);\n\t\t}\n\t\tfor (const expectedPolicy of expectedPolicySet) {\n\t\t\texisting.expectedPolicySet.add(expectedPolicy);\n\t\t}\n\t\tif (existing.qualifierSet === undefined && qualifierSet !== undefined) {\n\t\t\texisting.qualifierSet = qualifierSet;\n\t\t}\n\t\treturn;\n\t}\n\tconst node = createPolicyGraphNode(\n\t\tdepth,\n\t\tvalidPolicy,\n\t\tqualifierSet,\n\t\texpectedPolicySet,\n\t\tparentKeys,\n\t);\n\tcurrentDepth.set(key, node);\n\tfor (const parentKey of parentKeys) {\n\t\tgetPolicyGraphNode(graph, parentKey)?.childKeys.add(key);\n\t}\n}\n\n/** Looks up a node by its `\"depth:oid\"` key, parsing the depth prefix. */\nfunction getPolicyGraphNode(graph: PolicyGraph, key: string): PolicyGraphNode | undefined {\n\tconst separator = key.indexOf(':');\n\tif (separator <= 0) {\n\t\treturn undefined;\n\t}\n\tconst depthString = key.slice(0, separator);\n\tconst depth = Number.parseInt(depthString, 10);\n\tif (Number.isNaN(depth)) {\n\t\treturn undefined;\n\t}\n\treturn graph.nodesByDepth[depth]?.get(key);\n}\n\n/** Removes childless leaf nodes bottom-up, cascading deletions through parent links. */\nfunction prunePolicyGraph(graph: PolicyGraph, maxDepth: number): void {\n\tfor (let depth = maxDepth; depth >= 0; depth -= 1) {\n\t\tconst nodes = graph.nodesByDepth[depth];\n\t\tif (nodes === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of nodes.keys()) {\n\t\t\tconst node = nodes.get(key);\n\t\t\tif (node === undefined || node.childKeys.size > 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdeletePolicyGraphNode(graph, key);\n\t\t}\n\t}\n}\n\n/** Removes a node and recursively prunes its parents if they become childless. */\nfunction deletePolicyGraphNode(graph: PolicyGraph, key: string): void {\n\tconst node = getPolicyGraphNode(graph, key);\n\tif (node === undefined) {\n\t\treturn;\n\t}\n\tgraph.nodesByDepth[node.depth]?.delete(key);\n\tfor (const parentKey of node.parentKeys) {\n\t\tconst parent = getPolicyGraphNode(graph, parentKey);\n\t\tif (parent === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tparent.childKeys.delete(key);\n\t\tif (parent.childKeys.size === 0) {\n\t\t\tdeletePolicyGraphNode(graph, parentKey);\n\t\t}\n\t}\n}\n\n/** Applies issuer→subject policy mappings at the current depth, or deletes mapped nodes when disallowed. */\nfunction applyPolicyMappingsStep(\n\tgraph: PolicyGraph,\n\tdepth: number,\n\tmappings: readonly {\n\t\treadonly issuerDomainPolicy: string;\n\t\treadonly subjectDomainPolicy: string;\n\t}[],\n\tmappingAllowed: boolean,\n): void {\n\tconst currentDepth = graph.nodesByDepth[depth];\n\tif (currentDepth === undefined) {\n\t\treturn;\n\t}\n\tconst groupedMappings = new Map<string, string[]>();\n\tfor (const mapping of mappings) {\n\t\tif (\n\t\t\tmapping.issuerDomainPolicy === OIDS.anyPolicy ||\n\t\t\tmapping.subjectDomainPolicy === OIDS.anyPolicy\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst subjectPolicies = groupedMappings.get(mapping.issuerDomainPolicy);\n\t\tif (subjectPolicies === undefined) {\n\t\t\tgroupedMappings.set(mapping.issuerDomainPolicy, [mapping.subjectDomainPolicy]);\n\t\t\tcontinue;\n\t\t}\n\t\tsubjectPolicies.push(mapping.subjectDomainPolicy);\n\t}\n\tconst anyPolicyNode = currentDepth.get(policyNodeKey(depth, OIDS.anyPolicy));\n\tfor (const [issuerDomainPolicy, subjectDomainPolicies] of groupedMappings) {\n\t\tconst nodeKey = policyNodeKey(depth, issuerDomainPolicy);\n\t\tconst node = currentDepth.get(nodeKey);\n\t\tif (mappingAllowed) {\n\t\t\tif (node !== undefined) {\n\t\t\t\tnode.expectedPolicySet = new Set(subjectDomainPolicies);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (anyPolicyNode !== undefined) {\n\t\t\t\taddOrMergePolicyNode(\n\t\t\t\t\tgraph,\n\t\t\t\t\tcurrentDepth,\n\t\t\t\t\tdepth,\n\t\t\t\t\tissuerDomainPolicy,\n\t\t\t\t\tanyPolicyNode.qualifierSet,\n\t\t\t\t\t[...anyPolicyNode.parentKeys],\n\t\t\t\t\tsubjectDomainPolicies,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (node !== undefined) {\n\t\t\tdeletePolicyGraphNode(graph, nodeKey);\n\t\t}\n\t}\n\tprunePolicyGraph(graph, depth - 1);\n}\n\n/** Decrements explicitPolicy / inhibitPolicyMapping / inhibitAnyPolicy and applies policyConstraints overrides. */\nfunction updatePolicyCounters(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n\tisLeaf: boolean,\n): void {\n\tif (isLeaf) {\n\t\tupdateLeafPolicyCounter(state, certificate);\n\t\treturn;\n\t}\n\tif (!isSelfIssued(certificate)) {\n\t\tdecrementPolicyCounters(state);\n\t}\n\tapplyPolicyCounterOverrides(state, certificate);\n}\n\nfunction updateLeafPolicyCounter(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n): void {\n\tdecrementPositiveCounter(state, 'explicitPolicy');\n\tif (certificate.policyConstraints?.requireExplicitPolicy === 0) {\n\t\tstate.explicitPolicy = 0;\n\t}\n}\n\nfunction decrementPolicyCounters(state: PolicyValidationState): void {\n\tdecrementPositiveCounter(state, 'explicitPolicy');\n\tdecrementPositiveCounter(state, 'inhibitPolicyMapping');\n\tdecrementPositiveCounter(state, 'inhibitAnyPolicy');\n}\n\nfunction decrementPositiveCounter(\n\tstate: PolicyValidationState,\n\tkey: 'explicitPolicy' | 'inhibitPolicyMapping' | 'inhibitAnyPolicy',\n): void {\n\tif (state[key] > 0) {\n\t\tstate[key] -= 1;\n\t}\n}\n\nfunction applyPolicyCounterOverrides(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n): void {\n\tconst policyConstraints = certificate.policyConstraints;\n\tif (\n\t\tisNonNegativeInteger(policyConstraints?.requireExplicitPolicy) &&\n\t\tpolicyConstraints.requireExplicitPolicy < state.explicitPolicy\n\t) {\n\t\tstate.explicitPolicy = policyConstraints.requireExplicitPolicy;\n\t}\n\tif (\n\t\tisNonNegativeInteger(policyConstraints?.inhibitPolicyMapping) &&\n\t\tpolicyConstraints.inhibitPolicyMapping < state.inhibitPolicyMapping\n\t) {\n\t\tstate.inhibitPolicyMapping = policyConstraints.inhibitPolicyMapping;\n\t}\n\tif (\n\t\tisNonNegativeInteger(certificate.inhibitAnyPolicy?.skipCerts) &&\n\t\tcertificate.inhibitAnyPolicy.skipCerts < state.inhibitAnyPolicy\n\t) {\n\t\tstate.inhibitAnyPolicy = certificate.inhibitAnyPolicy.skipCerts;\n\t}\n}\n\nfunction isNonNegativeInteger(value: number | undefined): value is number {\n\treturn value !== undefined && Number.isInteger(value) && value >= 0;\n}\n\n/** A certificate is self-issued when subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nfunction isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuFA,SAAgB,4BACf,GACA,GACwB;CACxB,IAAM,IAAkB,IAAc;CACtC,OAAO;EACN,kBAAkB,EAAM,oBAAoB;EAC5C,gBAAgB,EAAM,0BAA0B,KAAO,IAAI;EAC3D,sBAAsB,EAAM,yBAAyB,KAAO,IAAI;EAChE,kBAAkB,EAAM,qBAAqB,KAAO,IAAI;EACxD,kBAAkB,yBAAyB;CAC5C;AACD;;;;;AAMA,SAAgB,oBACf,GACA,GACyB;CACzB,IAAI,EAAM,WAAW,GACpB,MAAU,WAAW,qDAAqD;CAE3E,mBAAmB,GAAO,CAAK;CAC/B,IAAM,IAAU,8BAA8B,GAAO,CAAK;CA4B1D,OA3BI,EAAM,mBAAmB,KAAK,EAAQ,wBAAwB,WAAW,IACrE;EACN,IAAI;EACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,SAAS;IACR,UACC,EAAM,qBAAqB,QAAQ,oBAAoB,EAAM,iBAAiB,KAAK,GAAG;IACvF,QAAQ,sBAAsB,EAAQ,uBAAuB;GAC9D;EACD;CACD,IAEG,EAAM,qBAAqB,SAAS,EAAQ,wBAAwB,WAAW,IAC3E;EACN,IAAI;EACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,SAAS;IACR,UAAU,EAAM,iBAAiB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R,GACA,GACO;CACP,IAAM,IAAoB,EAAY;CAatC,AAXC,qBAAqB,GAAmB,qBAAqB,KAC7D,EAAkB,wBAAwB,EAAM,mBAEhD,EAAM,iBAAiB,EAAkB,wBAGzC,qBAAqB,GAAmB,oBAAoB,KAC5D,EAAkB,uBAAuB,EAAM,yBAE/C,EAAM,uBAAuB,EAAkB,uBAG/C,qBAAqB,EAAY,kBAAkB,SAAS,KAC5D,EAAY,iBAAiB,YAAY,EAAM,qBAE/C,EAAM,mBAAmB,EAAY,iBAAiB;AAExD;AAEA,SAAS,qBAAqB,GAA4C;CACzE,OAAO,MAAU,KAAA,KAAa,OAAO,UAAU,CAAK,KAAK,KAAS;AACnE;;AAGA,SAAS,aAAa,GAAyC;CAC9D,OAAO,EAA0B,EAAY,SAAS,EAAY,MAAM;AACzE"}
1
+ {"version":3,"file":"policy-engine.js","names":[],"sources":["../../../src/internal/verify/policy-engine.ts"],"sourcesContent":["/**\n * Internal RFC 9618 policy-validation engine.\n *\n * Tracks the policy graph and counter state through each certificate in a\n * chain, then derives the {@linkcode PolicyValidationOutcome}.\n *\n * @module\n */\n\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport type { Micro509Error, Result } from '#micro509/result/result';\nimport type {\n\tConstrainedPolicy,\n\tPolicyValidationInput,\n\tPolicyValidationOutcome,\n} from '#micro509/verify/policy';\nimport type { PolicyInformation, PolicyQualifierInfo } from '#micro509/x509/extensions';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\n\n/**\n * Mutable state threaded through each step of the policy-validation walk.\n *\n * Created by {@linkcode createPolicyValidationState}, consumed by\n * {@linkcode evaluatePolicyChain}.\n */\nexport interface PolicyValidationState {\n\t/** Caller-requested acceptable policies, or `'any'`. */\n\treadonly initialPolicySet: readonly string[] | 'any';\n\t/** Remaining certificates before explicit-policy enforcement kicks in. */\n\texplicitPolicy: number;\n\t/** Remaining certificates before policy mappings are disallowed. */\n\tinhibitPolicyMapping: number;\n\t/** Remaining certificates before anyPolicy expansion stops. */\n\tinhibitAnyPolicy: number;\n\t/** The RFC 9618 policy graph; `null` when the graph has been emptied. */\n\tvalidPolicyGraph: PolicyGraph | null;\n}\n\n/** Discriminant codes for policy-validation failures. */\nexport type PolicyValidationFailureCode =\n\t| 'explicit_policy_required'\n\t| 'initial_policy_set_not_satisfied';\n\n/** Diagnostic context for a policy-validation failure. */\nexport interface PolicyValidationFailureDetails {\n\t/** Description of the policies the caller expected. */\n\treadonly expected: string;\n\t/** Comma-joined OIDs (or `\"<none>\"`) that actually survived processing. */\n\treadonly actual: string;\n}\n\n/** A policy-validation failure with structured diagnostic details. */\nexport interface PolicyValidationFailure\n\textends Micro509Error<PolicyValidationFailureCode, PolicyValidationFailureDetails> {}\n\n/** Success with {@linkcode PolicyValidationOutcome}, or a {@linkcode PolicyValidationFailure}. */\nexport type PolicyValidationResult = Result<PolicyValidationOutcome, PolicyValidationFailure>;\n\n/** One node in the RFC 9618 policy graph, keyed by `depth:policyOID`. */\nexport interface PolicyGraphNode {\n\t/** Graph depth (0 = root anyPolicy node). */\n\tdepth: number;\n\t/** The policy OID this node represents at its depth. */\n\tvalidPolicy: string;\n\t/** Policy qualifiers inherited from the certificate that created this node. */\n\tqualifierSet?: readonly PolicyQualifierInfo[];\n\t/** OIDs this node expects to see in the next certificate's policies. */\n\texpectedPolicySet: Set<string>;\n\t/** Keys of parent nodes in the previous depth level. */\n\tparentKeys: Set<string>;\n\t/** Keys of child nodes in the next depth level. */\n\tchildKeys: Set<string>;\n}\n\n/** The full RFC 9618 valid-policy graph, indexed by depth level. */\nexport interface PolicyGraph {\n\t/** Each index `i` holds the nodes at depth `i`, keyed by `\"depth:oid\"`. */\n\tnodesByDepth: Map<string, PolicyGraphNode>[];\n}\n\n/**\n * Initializes mutable policy state from caller options.\n *\n * Counter values default to `chainLength + 1` (effectively disabled) unless\n * the corresponding input flag is `true`.\n */\nexport function createPolicyValidationState(\n\tinput: PolicyValidationInput,\n\tchainLength: number,\n): PolicyValidationState {\n\tconst disabledCounter = chainLength + 1;\n\treturn {\n\t\tinitialPolicySet: input.initialPolicySet ?? 'any',\n\t\texplicitPolicy: input.requireExplicitPolicy === true ? 0 : disabledCounter,\n\t\tinhibitPolicyMapping: input.inhibitPolicyMapping === true ? 0 : disabledCounter,\n\t\tinhibitAnyPolicy: input.inhibitAnyPolicy === true ? 0 : disabledCounter,\n\t\tvalidPolicyGraph: createInitialPolicyGraph(),\n\t};\n}\n\n/**\n * Walks the chain root-to-leaf, updating policy state per certificate,\n * then checks whether the resulting policy set satisfies caller requirements.\n */\nexport function evaluatePolicyChain(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n\tanchorInChain = true,\n): PolicyValidationResult {\n\tif (chain.length === 0) {\n\t\tthrow new RangeError('policy validation requires at least one certificate');\n\t}\n\tprocessPolicyState(chain, state, anchorInChain);\n\tconst outcome = derivePolicyValidationOutcome(state);\n\tif (state.explicitPolicy === 0 && outcome.userConstrainedPolicies.length === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: 'explicit_policy_required',\n\t\t\t\tmessage: 'policy validation requires an explicit permitted policy',\n\t\t\t\tdetails: {\n\t\t\t\t\texpected:\n\t\t\t\t\t\tstate.initialPolicySet === 'any' ? 'explicit policy' : state.initialPolicySet.join(','),\n\t\t\t\t\tactual: describeFinalPolicies(outcome.userConstrainedPolicies),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\tif (state.initialPolicySet !== 'any' && outcome.userConstrainedPolicies.length === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: 'initial_policy_set_not_satisfied',\n\t\t\t\tmessage: 'certificate chain does not satisfy the requested initial policy set',\n\t\t\t\tdetails: {\n\t\t\t\t\texpected: state.initialPolicySet.join(','),\n\t\t\t\t\tactual: describeFinalPolicies(outcome.userConstrainedPolicies),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn { ok: true, value: outcome };\n}\n\n/** Builds the depth-0 graph with a single anyPolicy root node. */\nfunction createInitialPolicyGraph(): PolicyGraph {\n\tconst rootNode = createPolicyGraphNode(0, OIDS.anyPolicy, undefined, [OIDS.anyPolicy], []);\n\treturn {\n\t\tnodesByDepth: [new Map([[policyNodeKey(0, OIDS.anyPolicy), rootNode]])],\n\t};\n}\n\n/** Constructs a new {@linkcode PolicyGraphNode} with empty child-key set. */\nfunction createPolicyGraphNode(\n\tdepth: number,\n\tvalidPolicy: string,\n\tqualifierSet: readonly PolicyQualifierInfo[] | undefined,\n\texpectedPolicySet: readonly string[],\n\tparentKeys: readonly string[],\n): PolicyGraphNode {\n\treturn {\n\t\tdepth,\n\t\tvalidPolicy,\n\t\t...(qualifierSet === undefined ? {} : { qualifierSet }),\n\t\texpectedPolicySet: new Set(expectedPolicySet),\n\t\tparentKeys: new Set(parentKeys),\n\t\tchildKeys: new Set<string>(),\n\t};\n}\n\n/** Canonical map key for a graph node: `\"depth:policyOID\"`. */\nfunction policyNodeKey(depth: number, validPolicy: string): string {\n\treturn `${String(depth)}:${validPolicy}`;\n}\n\n/**\n * Applies each path certificate's policies to the state, top CA first. When\n * `anchorInChain` is true the terminal certificate is the trust anchor and is\n * excluded; a bare anchor leaves the terminal certificate a path certificate\n * that must be processed.\n */\nfunction processPolicyState(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n\tanchorInChain: boolean,\n): void {\n\tif (chain.length === 1) {\n\t\tconst certificate = chain[0];\n\t\tif (certificate === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`missing certificate at chain index 0 (chain length ${String(chain.length)})`,\n\t\t\t);\n\t\t}\n\t\tprocessPolicyCertificate(state, certificate, 1, true);\n\t\treturn;\n\t}\n\tconst leafDepth = anchorInChain ? chain.length - 1 : chain.length;\n\tfor (let index = leafDepth - 1; index >= 0; index -= 1) {\n\t\tconst certificate = chain[index];\n\t\tif (certificate === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`missing certificate at chain index ${String(index)} (chain length ${String(chain.length)})`,\n\t\t\t);\n\t\t}\n\t\tconst depth = leafDepth - index;\n\t\tprocessPolicyCertificate(state, certificate, depth, depth === leafDepth);\n\t}\n}\n\n/** Extracts the authority- and user-constrained policy sets from the completed graph (RFC 9618 §5.5 step (g)). */\nfunction derivePolicyValidationOutcome(state: PolicyValidationState): PolicyValidationOutcome {\n\tconst authority = collectAuthorityConstrainedPolicies(state.validPolicyGraph);\n\treturn {\n\t\tauthorityConstrainedPolicies: [...authority.values()].sort(comparePolicies),\n\t\tuserConstrainedPolicies: deriveUserConstrainedPolicies(authority, state.initialPolicySet),\n\t};\n}\n\n/**\n * RFC 9618 §5.5 (g)(2)-(4) authority_constrained_policy_set. The\n * valid_policy_node_set is every graph node, at any depth, whose valid_policy is\n * not anyPolicy and whose single parent is an anyPolicy node, plus a depth-n\n * anyPolicy node when present. Pruning has already removed nodes with no path to\n * the leaf, so the whole graph is the final tree.\n */\nfunction collectAuthorityConstrainedPolicies(\n\tgraph: PolicyGraph | null,\n): ReadonlyMap<string, ConstrainedPolicy> {\n\tif (graph === null) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst qualifiersByOid = new Map<string, PolicyQualifierInfo[]>();\n\tconst record = (node: PolicyGraphNode): void => {\n\t\tconst collected = qualifiersByOid.get(node.validPolicy) ?? [];\n\t\tcollected.push(...gatherLineageQualifiers(graph, node));\n\t\tqualifiersByOid.set(node.validPolicy, collected);\n\t};\n\tfor (const depthNodes of graph.nodesByDepth) {\n\t\tfor (const node of depthNodes.values()) {\n\t\t\tif (node.validPolicy === OIDS.anyPolicy || node.parentKeys.size !== 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (getSingleParent(graph, node)?.validPolicy === OIDS.anyPolicy) {\n\t\t\t\trecord(node);\n\t\t\t}\n\t\t}\n\t}\n\tconst leafDepth = graph.nodesByDepth.length - 1;\n\tconst leafAnyPolicy = graph.nodesByDepth[leafDepth]?.get(\n\t\tpolicyNodeKey(leafDepth, OIDS.anyPolicy),\n\t);\n\tif (leafAnyPolicy !== undefined) {\n\t\trecord(leafAnyPolicy);\n\t}\n\tconst authority = new Map<string, ConstrainedPolicy>();\n\tfor (const [oid, qualifiers] of qualifiersByOid) {\n\t\tauthority.set(oid, buildConstrainedPolicy(oid, dedupeQualifiers(qualifiers)));\n\t}\n\treturn authority;\n}\n\n/** Returns the sole parent of a node whose parent list has exactly one entry. */\nfunction getSingleParent(graph: PolicyGraph, node: PolicyGraphNode): PolicyGraphNode | undefined {\n\tconst parentKey = [...node.parentKeys][0];\n\treturn parentKey === undefined ? undefined : getPolicyGraphNode(graph, parentKey);\n}\n\n/** RFC 9618 §5.5 (g)(4)(ii): qualifiers from a node, its ancestors, and its descendants. */\nfunction gatherLineageQualifiers(\n\tgraph: PolicyGraph,\n\tnode: PolicyGraphNode,\n): readonly PolicyQualifierInfo[] {\n\tconst qualifiers: PolicyQualifierInfo[] = [...(node.qualifierSet ?? [])];\n\tcollectDirectionalQualifiers(graph, node.parentKeys, (visited) => visited.parentKeys, qualifiers);\n\tcollectDirectionalQualifiers(graph, node.childKeys, (visited) => visited.childKeys, qualifiers);\n\treturn qualifiers;\n}\n\n/** Follows one edge direction transitively, appending each visited node's qualifiers. */\nfunction collectDirectionalQualifiers(\n\tgraph: PolicyGraph,\n\tstartKeys: ReadonlySet<string>,\n\tnext: (node: PolicyGraphNode) => ReadonlySet<string>,\n\tout: PolicyQualifierInfo[],\n): void {\n\tconst visited = new Set<string>();\n\tconst stack = [...startKeys];\n\twhile (stack.length > 0) {\n\t\tconst key = stack.pop();\n\t\tif (key === undefined || visited.has(key)) {\n\t\t\tcontinue;\n\t\t}\n\t\tvisited.add(key);\n\t\tconst node = getPolicyGraphNode(graph, key);\n\t\tif (node === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (node.qualifierSet !== undefined) {\n\t\t\tout.push(...node.qualifierSet);\n\t\t}\n\t\tfor (const nextKey of next(node)) {\n\t\t\tstack.push(nextKey);\n\t\t}\n\t}\n}\n\n/** Deduplicates qualifiers by value, returning `undefined` when none remain. */\nfunction dedupeQualifiers(\n\tqualifiers: readonly PolicyQualifierInfo[],\n): readonly PolicyQualifierInfo[] | undefined {\n\tconst seen = new Set<string>();\n\tconst unique: PolicyQualifierInfo[] = [];\n\tfor (const qualifier of qualifiers) {\n\t\tconst key = JSON.stringify(qualifier, (_field, value) =>\n\t\t\tvalue instanceof Uint8Array ? Array.from(value) : value,\n\t\t);\n\t\tif (!seen.has(key)) {\n\t\t\tseen.add(key);\n\t\t\tunique.push(qualifier);\n\t\t}\n\t}\n\treturn unique.length === 0 ? undefined : unique;\n}\n\n/**\n * RFC 9618 §5.5 (g)(5)-(6) user_constrained_policy_set. It equals the\n * authority-constrained set when the initial-policy-set is anyPolicy. Otherwise\n * it keeps the members named in the initial-policy-set, and, when the authority\n * set holds anyPolicy, adds the remaining requested OIDs with anyPolicy's\n * qualifiers.\n */\nfunction deriveUserConstrainedPolicies(\n\tauthority: ReadonlyMap<string, ConstrainedPolicy>,\n\tinitialPolicySet: readonly string[] | 'any',\n): readonly ConstrainedPolicy[] {\n\tif (initialPolicySet === 'any') {\n\t\treturn [...authority.values()].sort(comparePolicies);\n\t}\n\tconst constrained = new Map<string, ConstrainedPolicy>();\n\tfor (const [policyIdentifier, policy] of authority) {\n\t\tif (initialPolicySet.includes(policyIdentifier)) {\n\t\t\tconstrained.set(policyIdentifier, policy);\n\t\t}\n\t}\n\tconst anyPolicy = authority.get(OIDS.anyPolicy);\n\tif (anyPolicy !== undefined) {\n\t\tfor (const policyIdentifier of initialPolicySet) {\n\t\t\tif (!constrained.has(policyIdentifier)) {\n\t\t\t\tconstrained.set(\n\t\t\t\t\tpolicyIdentifier,\n\t\t\t\t\tbuildConstrainedPolicy(policyIdentifier, anyPolicy.policyQualifiers),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn [...constrained.values()].sort(comparePolicies);\n}\n\n/** Constructs a {@linkcode ConstrainedPolicy}, omitting qualifiers when absent. */\nfunction buildConstrainedPolicy(\n\tpolicyIdentifier: string,\n\tpolicyQualifiers: readonly PolicyQualifierInfo[] | undefined,\n): ConstrainedPolicy {\n\treturn {\n\t\tpolicyIdentifier,\n\t\t...(policyQualifiers === undefined ? {} : { policyQualifiers }),\n\t};\n}\n\n/** Lexicographic comparator for sorting policies by OID string. */\nfunction comparePolicies(left: ConstrainedPolicy, right: ConstrainedPolicy): number {\n\treturn left.policyIdentifier.localeCompare(right.policyIdentifier);\n}\n\n/** Human-readable comma-joined OID list for error messages; `\"<none>\"` when empty. */\nfunction describeFinalPolicies(policies: readonly ConstrainedPolicy[]): string {\n\treturn policies.length === 0\n\t\t? '<none>'\n\t\t: policies.map((policy) => policy.policyIdentifier).join(',');\n}\n\n/** Applies one certificate's policies, mappings, and constraints to the running state. */\nfunction processPolicyCertificate(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n\tdepth: number,\n\tisLeaf: boolean,\n): void {\n\tconst certificatePolicies = normalizeCertificatePolicies(certificate.certificatePolicies);\n\tif (state.validPolicyGraph !== null && certificatePolicies === undefined) {\n\t\tstate.validPolicyGraph = null;\n\t} else if (state.validPolicyGraph !== null && certificatePolicies !== undefined) {\n\t\tapplyCertificatePolicyStep(\n\t\t\tstate.validPolicyGraph,\n\t\t\tcertificatePolicies,\n\t\t\tdepth,\n\t\t\tstate.inhibitAnyPolicy > 0 || (!isLeaf && isSelfIssued(certificate)),\n\t\t);\n\t\tif (certificate.policyMappings !== undefined) {\n\t\t\tapplyPolicyMappingsStep(\n\t\t\t\tstate.validPolicyGraph,\n\t\t\t\tdepth,\n\t\t\t\tcertificate.policyMappings,\n\t\t\t\tstate.inhibitPolicyMapping > 0,\n\t\t\t);\n\t\t}\n\t}\n\tupdatePolicyCounters(state, certificate, isLeaf);\n}\n\n/** Deduplicates certificate policies by OID, keeping the first occurrence. */\nfunction normalizeCertificatePolicies(\n\tpolicies: readonly PolicyInformation[] | undefined,\n): Map<string, PolicyInformation> | undefined {\n\tif (policies === undefined) {\n\t\treturn undefined;\n\t}\n\tconst byOid = new Map<string, PolicyInformation>();\n\tfor (const policy of policies) {\n\t\tif (!byOid.has(policy.policyIdentifier)) {\n\t\t\tbyOid.set(policy.policyIdentifier, policy);\n\t\t}\n\t}\n\treturn byOid;\n}\n\n/** Extends the policy graph by one depth level using a certificate's policy extension. */\nfunction applyCertificatePolicyStep(\n\tgraph: PolicyGraph,\n\tcertificatePolicies: ReadonlyMap<string, PolicyInformation>,\n\tdepth: number,\n\tallowAnyPolicyExpansion: boolean,\n): void {\n\tconst previousDepth = graph.nodesByDepth[depth - 1] ?? new Map<string, PolicyGraphNode>();\n\tconst currentDepth = new Map<string, PolicyGraphNode>();\n\tgraph.nodesByDepth[depth] = currentDepth;\n\tconst anyPolicyInfo = certificatePolicies.get(OIDS.anyPolicy);\n\tconst previousAnyPolicy = previousDepth.get(policyNodeKey(depth - 1, OIDS.anyPolicy));\n\tconst previousAnyPolicyKey = policyNodeKey(depth - 1, OIDS.anyPolicy);\n\n\taddPolicyNodesFromExpectedParents(graph, currentDepth, previousDepth, certificatePolicies, depth);\n\n\tif (previousAnyPolicy !== undefined) {\n\t\taddPolicyNodesFromPreviousAnyPolicy(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tcertificatePolicies,\n\t\t\tdepth,\n\t\t\tpreviousAnyPolicyKey,\n\t\t);\n\t}\n\n\tif (anyPolicyInfo !== undefined && allowAnyPolicyExpansion) {\n\t\taddAnyPolicyExpansionNodes(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tpreviousDepth,\n\t\t\tdepth,\n\t\t\tanyPolicyInfo,\n\t\t\tpreviousAnyPolicyKey,\n\t\t\tpreviousAnyPolicy !== undefined,\n\t\t);\n\t}\n\n\tprunePolicyGraph(graph, depth - 1);\n}\n\n/** Adds explicit certificate-policy nodes whose expected policies match parent nodes. */\nfunction addPolicyNodesFromExpectedParents(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tpreviousDepth: ReadonlyMap<string, PolicyGraphNode>,\n\tcertificatePolicies: ReadonlyMap<string, PolicyInformation>,\n\tdepth: number,\n): void {\n\tfor (const policy of certificatePolicies.values()) {\n\t\tif (policy.policyIdentifier === OIDS.anyPolicy) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst matchingParents = collectParentsForExpectedPolicy(previousDepth, policy.policyIdentifier);\n\t\tif (matchingParents.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\taddOrMergePolicyNode(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tdepth,\n\t\t\tpolicy.policyIdentifier,\n\t\t\tpolicy.policyQualifiers,\n\t\t\tmatchingParents,\n\t\t\t[policy.policyIdentifier],\n\t\t);\n\t}\n}\n\nfunction addPolicyNodesFromPreviousAnyPolicy(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tcertificatePolicies: ReadonlyMap<string, PolicyInformation>,\n\tdepth: number,\n\tpreviousAnyPolicyKey: string,\n): void {\n\tfor (const policy of certificatePolicies.values()) {\n\t\tif (policy.policyIdentifier === OIDS.anyPolicy) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (currentDepth.has(policyNodeKey(depth, policy.policyIdentifier))) {\n\t\t\tcontinue;\n\t\t}\n\t\taddOrMergePolicyNode(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tdepth,\n\t\t\tpolicy.policyIdentifier,\n\t\t\tpolicy.policyQualifiers,\n\t\t\t[previousAnyPolicyKey],\n\t\t\t[policy.policyIdentifier],\n\t\t);\n\t}\n}\n\n/** Expands an accepted anyPolicy entry into the policies expected by the previous depth. */\nfunction addAnyPolicyExpansionNodes(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tpreviousDepth: ReadonlyMap<string, PolicyGraphNode>,\n\tdepth: number,\n\tanyPolicyInfo: PolicyInformation,\n\tpreviousAnyPolicyKey: string,\n\thasPreviousAnyPolicy: boolean,\n): void {\n\tfor (const [validPolicy, parentKeys] of collectExpectedPolicyParents(previousDepth)) {\n\t\tif (currentDepth.has(policyNodeKey(depth, validPolicy))) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst expansionParents = collectAnyPolicyExpansionParents(\n\t\t\tvalidPolicy,\n\t\t\tparentKeys,\n\t\t\tpreviousAnyPolicyKey,\n\t\t\thasPreviousAnyPolicy,\n\t\t);\n\t\tif (expansionParents.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\taddOrMergePolicyNode(\n\t\t\tgraph,\n\t\t\tcurrentDepth,\n\t\t\tdepth,\n\t\t\tvalidPolicy,\n\t\t\tanyPolicyInfo.policyQualifiers,\n\t\t\texpansionParents,\n\t\t\t[validPolicy],\n\t\t);\n\t}\n}\n\nfunction collectAnyPolicyExpansionParents(\n\tvalidPolicy: string,\n\tparentKeys: readonly string[],\n\tpreviousAnyPolicyKey: string,\n\thasPreviousAnyPolicy: boolean,\n): readonly string[] {\n\tif (validPolicy !== OIDS.anyPolicy) {\n\t\treturn parentKeys;\n\t}\n\treturn hasPreviousAnyPolicy ? [previousAnyPolicyKey] : [];\n}\n\n/** Finds all previous-depth nodes whose expectedPolicySet contains the given OID. */\nfunction collectParentsForExpectedPolicy(\n\tnodes: ReadonlyMap<string, PolicyGraphNode>,\n\tpolicyIdentifier: string,\n): string[] {\n\tconst parents: string[] = [];\n\tfor (const [key, node] of nodes) {\n\t\tif (node.expectedPolicySet.has(policyIdentifier)) {\n\t\t\tparents.push(key);\n\t\t}\n\t}\n\treturn parents;\n}\n\n/** Groups all previous-depth nodes by each OID in their expectedPolicySet. */\nfunction collectExpectedPolicyParents(\n\tnodes: ReadonlyMap<string, PolicyGraphNode>,\n): Map<string, string[]> {\n\tconst parentsByPolicy = new Map<string, string[]>();\n\tfor (const [key, node] of nodes) {\n\t\tfor (const expectedPolicy of node.expectedPolicySet) {\n\t\t\tconst parents = parentsByPolicy.get(expectedPolicy);\n\t\t\tif (parents === undefined) {\n\t\t\t\tparentsByPolicy.set(expectedPolicy, [key]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparents.push(key);\n\t\t}\n\t}\n\treturn parentsByPolicy;\n}\n\n/** Inserts a node at the current depth, or merges parents/expected-policies into an existing one. */\nfunction addOrMergePolicyNode(\n\tgraph: PolicyGraph,\n\tcurrentDepth: Map<string, PolicyGraphNode>,\n\tdepth: number,\n\tvalidPolicy: string,\n\tqualifierSet: readonly PolicyQualifierInfo[] | undefined,\n\tparentKeys: readonly string[],\n\texpectedPolicySet: readonly string[],\n): void {\n\tconst key = policyNodeKey(depth, validPolicy);\n\tconst existing = currentDepth.get(key);\n\tif (existing !== undefined) {\n\t\tfor (const parentKey of parentKeys) {\n\t\t\texisting.parentKeys.add(parentKey);\n\t\t\tgetPolicyGraphNode(graph, parentKey)?.childKeys.add(key);\n\t\t}\n\t\tfor (const expectedPolicy of expectedPolicySet) {\n\t\t\texisting.expectedPolicySet.add(expectedPolicy);\n\t\t}\n\t\tif (existing.qualifierSet === undefined && qualifierSet !== undefined) {\n\t\t\texisting.qualifierSet = qualifierSet;\n\t\t}\n\t\treturn;\n\t}\n\tconst node = createPolicyGraphNode(\n\t\tdepth,\n\t\tvalidPolicy,\n\t\tqualifierSet,\n\t\texpectedPolicySet,\n\t\tparentKeys,\n\t);\n\tcurrentDepth.set(key, node);\n\tfor (const parentKey of parentKeys) {\n\t\tgetPolicyGraphNode(graph, parentKey)?.childKeys.add(key);\n\t}\n}\n\n/** Looks up a node by its `\"depth:oid\"` key, parsing the depth prefix. */\nfunction getPolicyGraphNode(graph: PolicyGraph, key: string): PolicyGraphNode | undefined {\n\tconst separator = key.indexOf(':');\n\tif (separator <= 0) {\n\t\treturn undefined;\n\t}\n\tconst depthString = key.slice(0, separator);\n\tconst depth = Number.parseInt(depthString, 10);\n\tif (Number.isNaN(depth)) {\n\t\treturn undefined;\n\t}\n\treturn graph.nodesByDepth[depth]?.get(key);\n}\n\n/** Removes childless leaf nodes bottom-up, cascading deletions through parent links. */\nfunction prunePolicyGraph(graph: PolicyGraph, maxDepth: number): void {\n\tfor (let depth = maxDepth; depth >= 0; depth -= 1) {\n\t\tconst nodes = graph.nodesByDepth[depth];\n\t\tif (nodes === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of nodes.keys()) {\n\t\t\tconst node = nodes.get(key);\n\t\t\tif (node === undefined || node.childKeys.size > 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdeletePolicyGraphNode(graph, key);\n\t\t}\n\t}\n}\n\n/** Removes a node and recursively prunes its parents if they become childless. */\nfunction deletePolicyGraphNode(graph: PolicyGraph, key: string): void {\n\tconst node = getPolicyGraphNode(graph, key);\n\tif (node === undefined) {\n\t\treturn;\n\t}\n\tgraph.nodesByDepth[node.depth]?.delete(key);\n\tfor (const parentKey of node.parentKeys) {\n\t\tconst parent = getPolicyGraphNode(graph, parentKey);\n\t\tif (parent === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tparent.childKeys.delete(key);\n\t\tif (parent.childKeys.size === 0) {\n\t\t\tdeletePolicyGraphNode(graph, parentKey);\n\t\t}\n\t}\n}\n\n/** Applies issuer→subject policy mappings at the current depth, or deletes mapped nodes when disallowed. */\nfunction applyPolicyMappingsStep(\n\tgraph: PolicyGraph,\n\tdepth: number,\n\tmappings: readonly {\n\t\treadonly issuerDomainPolicy: string;\n\t\treadonly subjectDomainPolicy: string;\n\t}[],\n\tmappingAllowed: boolean,\n): void {\n\tconst currentDepth = graph.nodesByDepth[depth];\n\tif (currentDepth === undefined) {\n\t\treturn;\n\t}\n\tconst groupedMappings = new Map<string, string[]>();\n\tfor (const mapping of mappings) {\n\t\tif (\n\t\t\tmapping.issuerDomainPolicy === OIDS.anyPolicy ||\n\t\t\tmapping.subjectDomainPolicy === OIDS.anyPolicy\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst subjectPolicies = groupedMappings.get(mapping.issuerDomainPolicy);\n\t\tif (subjectPolicies === undefined) {\n\t\t\tgroupedMappings.set(mapping.issuerDomainPolicy, [mapping.subjectDomainPolicy]);\n\t\t\tcontinue;\n\t\t}\n\t\tsubjectPolicies.push(mapping.subjectDomainPolicy);\n\t}\n\tconst anyPolicyNode = currentDepth.get(policyNodeKey(depth, OIDS.anyPolicy));\n\tfor (const [issuerDomainPolicy, subjectDomainPolicies] of groupedMappings) {\n\t\tconst nodeKey = policyNodeKey(depth, issuerDomainPolicy);\n\t\tconst node = currentDepth.get(nodeKey);\n\t\tif (mappingAllowed) {\n\t\t\tif (node !== undefined) {\n\t\t\t\tnode.expectedPolicySet = new Set(subjectDomainPolicies);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (anyPolicyNode !== undefined) {\n\t\t\t\taddOrMergePolicyNode(\n\t\t\t\t\tgraph,\n\t\t\t\t\tcurrentDepth,\n\t\t\t\t\tdepth,\n\t\t\t\t\tissuerDomainPolicy,\n\t\t\t\t\tanyPolicyNode.qualifierSet,\n\t\t\t\t\t[...anyPolicyNode.parentKeys],\n\t\t\t\t\tsubjectDomainPolicies,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (node !== undefined) {\n\t\t\tdeletePolicyGraphNode(graph, nodeKey);\n\t\t}\n\t}\n\tprunePolicyGraph(graph, depth - 1);\n}\n\n/** Decrements explicitPolicy / inhibitPolicyMapping / inhibitAnyPolicy and applies policyConstraints overrides. */\nfunction updatePolicyCounters(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n\tisLeaf: boolean,\n): void {\n\tif (isLeaf) {\n\t\tupdateLeafPolicyCounter(state, certificate);\n\t\treturn;\n\t}\n\tif (!isSelfIssued(certificate)) {\n\t\tdecrementPolicyCounters(state);\n\t}\n\tapplyPolicyCounterOverrides(state, certificate);\n}\n\nfunction updateLeafPolicyCounter(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n): void {\n\tdecrementPositiveCounter(state, 'explicitPolicy');\n\tif (certificate.policyConstraints?.requireExplicitPolicy === 0) {\n\t\tstate.explicitPolicy = 0;\n\t}\n}\n\nfunction decrementPolicyCounters(state: PolicyValidationState): void {\n\tdecrementPositiveCounter(state, 'explicitPolicy');\n\tdecrementPositiveCounter(state, 'inhibitPolicyMapping');\n\tdecrementPositiveCounter(state, 'inhibitAnyPolicy');\n}\n\nfunction decrementPositiveCounter(\n\tstate: PolicyValidationState,\n\tkey: 'explicitPolicy' | 'inhibitPolicyMapping' | 'inhibitAnyPolicy',\n): void {\n\tif (state[key] > 0) {\n\t\tstate[key] -= 1;\n\t}\n}\n\nfunction applyPolicyCounterOverrides(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n): void {\n\tconst policyConstraints = certificate.policyConstraints;\n\tif (\n\t\tisNonNegativeInteger(policyConstraints?.requireExplicitPolicy) &&\n\t\tpolicyConstraints.requireExplicitPolicy < state.explicitPolicy\n\t) {\n\t\tstate.explicitPolicy = policyConstraints.requireExplicitPolicy;\n\t}\n\tif (\n\t\tisNonNegativeInteger(policyConstraints?.inhibitPolicyMapping) &&\n\t\tpolicyConstraints.inhibitPolicyMapping < state.inhibitPolicyMapping\n\t) {\n\t\tstate.inhibitPolicyMapping = policyConstraints.inhibitPolicyMapping;\n\t}\n\tif (\n\t\tisNonNegativeInteger(certificate.inhibitAnyPolicy?.skipCerts) &&\n\t\tcertificate.inhibitAnyPolicy.skipCerts < state.inhibitAnyPolicy\n\t) {\n\t\tstate.inhibitAnyPolicy = certificate.inhibitAnyPolicy.skipCerts;\n\t}\n}\n\nfunction isNonNegativeInteger(value: number | undefined): value is number {\n\treturn value !== undefined && Number.isInteger(value) && value >= 0;\n}\n\n/** A certificate is self-issued when subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nfunction isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistingu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.set(n, [e]) : i.push(e), l.set(fingerprint(e), t);
70
70
  });
71
71
  let _ = s.length + 1, v = fingerprint(e), y = await search(e, [e], /* @__PURE__ */ new Set([v]), 0);
72
- if (y !== void 0) return {
73
- chain: y,
74
- foundTrustedRoot: !0
75
- };
72
+ if (y !== void 0) {
73
+ let e = y[y.length - 1];
74
+ return {
75
+ chain: y,
76
+ foundTrustedRoot: !0,
77
+ anchorCertificateInChain: e !== void 0 && u.has(fingerprint(e))
78
+ };
79
+ }
76
80
  if (h !== void 0) return {
77
81
  chain: p,
78
82
  foundTrustedRoot: !1,
@@ -225,22 +229,22 @@ function isIssuerOf(e, t) {
225
229
  return i(t.issuer, e.subject);
226
230
  }
227
231
  /** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */
228
- async function matchTrustAnchor(e, t, n, i) {
229
- let a = t.get(r(e.issuer));
230
- if (a === void 0) return { matched: !1 };
231
- let o;
232
- for (let t of a) {
233
- if (trustAnchorAkiMismatch(e, t)) continue;
232
+ async function matchTrustAnchor(e, t, n, a) {
233
+ let o = t.get(r(e.issuer));
234
+ if (o === void 0) return { matched: !1 };
235
+ let s;
236
+ for (let t of o) {
237
+ if (trustAnchorAkiMismatch(e, t) || !i(e.issuer, t.subject)) continue;
234
238
  let r = await verifyTrustAnchorSignature(e, t);
235
239
  if (!r.ok) {
236
- o === void 0 && (o = n.failure(r.code, r.reason, i, n.detail({
240
+ s === void 0 && (s = n.failure(r.code, r.reason, a, n.detail({
237
241
  subjectCommonName: e.subject.values.commonName,
238
242
  actual: r.reason
239
243
  })));
240
244
  continue;
241
245
  }
242
246
  if (!r.valid) {
243
- o === void 0 && (o = n.failure("signature_invalid", "certificate signature does not verify", i, n.detail({
247
+ s === void 0 && (s = n.failure("signature_invalid", "certificate signature does not verify", a, n.detail({
244
248
  subjectCommonName: e.subject.values.commonName,
245
249
  actual: "certificate signature does not verify"
246
250
  })));
@@ -248,9 +252,9 @@ async function matchTrustAnchor(e, t, n, i) {
248
252
  }
249
253
  return { matched: !0 };
250
254
  }
251
- return o === void 0 ? { matched: !1 } : {
255
+ return s === void 0 ? { matched: !1 } : {
252
256
  matched: !1,
253
- failure: o
257
+ failure: s
254
258
  };
255
259
  }
256
260
  function trustAnchorAkiMismatch(e, t) {