micro509 0.9.0 → 0.10.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 (107) hide show
  1. package/dist/index.d.ts +3 -3
  2. package/dist/index.js +15 -15
  3. package/dist/internal/asn1/asn1.js +145 -186
  4. package/dist/internal/asn1/asn1.js.map +1 -0
  5. package/dist/internal/asn1/der.js +210 -227
  6. package/dist/internal/asn1/der.js.map +1 -0
  7. package/dist/internal/asn1/oids.js +297 -101
  8. package/dist/internal/asn1/oids.js.map +1 -0
  9. package/dist/internal/asn1/oids2.js +69 -0
  10. package/dist/internal/asn1/oids2.js.map +1 -0
  11. package/dist/internal/crypto/algorithm-names.js +37 -35
  12. package/dist/internal/crypto/algorithm-names.js.map +1 -0
  13. package/dist/internal/crypto/ecdsa.js +25 -28
  14. package/dist/internal/crypto/ecdsa.js.map +1 -0
  15. package/dist/internal/crypto/hash.js +56 -117
  16. package/dist/internal/crypto/hash.js.map +1 -0
  17. package/dist/internal/crypto/pbes2.js +122 -133
  18. package/dist/internal/crypto/pbes2.js.map +1 -0
  19. package/dist/internal/crypto/rsa-pss.js +118 -124
  20. package/dist/internal/crypto/rsa-pss.js.map +1 -0
  21. package/dist/internal/crypto/sig-verify.js +87 -99
  22. package/dist/internal/crypto/sig-verify.js.map +1 -0
  23. package/dist/internal/crypto/signing.d.ts +12 -8
  24. package/dist/internal/crypto/signing.js +53 -55
  25. package/dist/internal/crypto/signing.js.map +1 -0
  26. package/dist/internal/crypto/webcrypto.js +5 -3
  27. package/dist/internal/crypto/webcrypto.js.map +1 -0
  28. package/dist/internal/shared/base64.js +10 -9
  29. package/dist/internal/shared/base64.js.map +1 -0
  30. package/dist/internal/shared/dn.js +50 -57
  31. package/dist/internal/shared/dn.js.map +1 -0
  32. package/dist/internal/shared/ip.js +43 -53
  33. package/dist/internal/shared/ip.js.map +1 -0
  34. package/dist/internal/verify/name-constraints-engine.js +211 -239
  35. package/dist/internal/verify/name-constraints-engine.js.map +1 -0
  36. package/dist/internal/verify/policy-engine.js +228 -247
  37. package/dist/internal/verify/policy-engine.js.map +1 -0
  38. package/dist/internal/verify/verify-path.js +213 -228
  39. package/dist/internal/verify/verify-path.js.map +1 -0
  40. package/dist/internal/x509/extension-bits.js +62 -59
  41. package/dist/internal/x509/extension-bits.js.map +1 -0
  42. package/dist/internal/x509/extension-registry.js +133 -164
  43. package/dist/internal/x509/extension-registry.js.map +1 -0
  44. package/dist/internal/x509/name-fields.js +35 -41
  45. package/dist/internal/x509/name-fields.js.map +1 -0
  46. package/dist/keys/keys.d.ts +583 -547
  47. package/dist/keys/keys.js +519 -431
  48. package/dist/keys/keys.js.map +1 -0
  49. package/dist/keys.js +2 -2
  50. package/dist/pem/pem.d.ts +46 -46
  51. package/dist/pem/pem.js +62 -81
  52. package/dist/pem/pem.js.map +1 -0
  53. package/dist/pem.js +2 -2
  54. package/dist/pkcs/pfx.d.ts +96 -80
  55. package/dist/pkcs/pfx.js +191 -231
  56. package/dist/pkcs/pfx.js.map +1 -0
  57. package/dist/pkcs/pkcs12-mac.d.ts +20 -18
  58. package/dist/pkcs/pkcs12-mac.js +90 -111
  59. package/dist/pkcs/pkcs12-mac.js.map +1 -0
  60. package/dist/pkcs/pkcs7.d.ts +118 -69
  61. package/dist/pkcs/pkcs7.js +401 -443
  62. package/dist/pkcs/pkcs7.js.map +1 -0
  63. package/dist/pkcs.d.ts +2 -2
  64. package/dist/pkcs.js +4 -4
  65. package/dist/result/result.d.ts +37 -32
  66. package/dist/result/result.js +46 -44
  67. package/dist/result/result.js.map +1 -0
  68. package/dist/result.js +2 -2
  69. package/dist/revocation/chain.d.ts +138 -119
  70. package/dist/revocation/chain.js +248 -281
  71. package/dist/revocation/chain.js.map +1 -0
  72. package/dist/revocation/crl.d.ts +125 -123
  73. package/dist/revocation/crl.js +653 -745
  74. package/dist/revocation/crl.js.map +1 -0
  75. package/dist/revocation/ocsp.d.ts +183 -177
  76. package/dist/revocation/ocsp.js +579 -636
  77. package/dist/revocation/ocsp.js.map +1 -0
  78. package/dist/revocation/revocation.d.ts +26 -26
  79. package/dist/revocation/revocation.js +104 -125
  80. package/dist/revocation/revocation.js.map +1 -0
  81. package/dist/revocation.js +5 -5
  82. package/dist/verify/identity.d.ts +42 -42
  83. package/dist/verify/identity.js +158 -167
  84. package/dist/verify/identity.js.map +1 -0
  85. package/dist/verify/name-constraints.d.ts +7 -7
  86. package/dist/verify/policy.d.ts +10 -10
  87. package/dist/verify/verify.d.ts +163 -163
  88. package/dist/verify/verify.js +396 -392
  89. package/dist/verify/verify.js.map +1 -0
  90. package/dist/verify.js +3 -3
  91. package/dist/x509/certificate.d.ts +117 -117
  92. package/dist/x509/certificate.js +51 -60
  93. package/dist/x509/certificate.js.map +1 -0
  94. package/dist/x509/csr.d.ts +25 -25
  95. package/dist/x509/csr.js +26 -30
  96. package/dist/x509/csr.js.map +1 -0
  97. package/dist/x509/extensions.d.ts +228 -184
  98. package/dist/x509/extensions.js +175 -200
  99. package/dist/x509/extensions.js.map +1 -0
  100. package/dist/x509/name.d.ts +94 -93
  101. package/dist/x509/name.js +30 -29
  102. package/dist/x509/name.js.map +1 -0
  103. package/dist/x509/parse.d.ts +185 -185
  104. package/dist/x509/parse.js +638 -676
  105. package/dist/x509/parse.js.map +1 -0
  106. package/dist/x509.js +6 -6
  107. package/package.json +79 -41
@@ -0,0 +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,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AAAI,MAAS,KAAA,KACZ,sBAAsB,GAAO,CAAO;CAEtC;CACA,iBAAiB,GAAO,IAAQ,CAAC;AAClC;;AAGA,SAAS,qBACR,GACA,GACA,GACO;CACP,IAAI,GAAQ;EACX,wBAAwB,GAAO,CAAW;EAC1C;CACD;CAIA,AAHK,aAAa,CAAW,KAC5B,wBAAwB,CAAK,GAE9B,4BAA4B,GAAO,CAAW;AAC/C;AAEA,SAAS,wBACR,GACA,GACO;CAEP,AADA,yBAAyB,GAAO,gBAAgB,GAC5C,EAAY,mBAAmB,0BAA0B,MAC5D,EAAM,iBAAiB;AAEzB;AAEA,SAAS,wBAAwB,GAAoC;CAGpE,AAFA,yBAAyB,GAAO,gBAAgB,GAChD,yBAAyB,GAAO,sBAAsB,GACtD,yBAAyB,GAAO,kBAAkB;AACnD;AAEA,SAAS,yBACR,GACA,GACO;CACP,AAAI,EAAM,KAAO,KAChB,IAAM;AAER;AAEA,SAAS,4BACR,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,7 +1,7 @@
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";
1
+ import { toHex as e } from "../asn1/asn1.js";
2
+ import { parseCertificatesFromSource as t } from "../../x509/parse.js";
3
+ import { verifySignedDataDetailed as n } from "../crypto/sig-verify.js";
4
+ import { canonicalDnKey as r, compareDistinguishedNames as i } from "../shared/dn.js";
5
5
  //#region src/internal/verify/verify-path.ts
6
6
  /**
7
7
  * Internal certificate path-building and signature-check helpers.
@@ -13,45 +13,43 @@ import { canonicalDnKey, compareDistinguishedNames } from "../shared/dn.js";
13
13
  * @module
14
14
  */
15
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();
16
+ function isWithinValidity(e, t) {
17
+ return e.notBefore.getTime() <= t.getTime() && t.getTime() <= e.notAfter.getTime();
18
18
  }
19
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);
20
+ function isSelfIssued(e) {
21
+ return i(e.subject, e.issuer);
22
22
  }
23
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;
24
+ function countCaCertificatesBelowParsed(e, t) {
25
+ let n = 0;
26
+ for (let r = 1; r < t; r += 1) {
27
+ let t = e[r];
28
+ t?.basicConstraints?.ca === !0 && !isSelfIssued(t) && (n += 1);
29
29
  }
30
- return total;
30
+ return n;
31
31
  }
32
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;
33
+ function loadCertificates(e) {
34
+ let t = [];
35
+ for (let n of e) t.push(...expandSource(n));
36
+ return t;
37
37
  }
38
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;
39
+ function loadSingleCertificate(e) {
40
+ let t = expandSource(e), n = t[0];
41
+ if (n === void 0) throw Error("No certificate found");
42
+ if (t.length !== 1) throw Error("Expected a single certificate source");
43
+ return n;
45
44
  }
46
45
  /** 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,
46
+ async function verifyCertificateSignature(e, t) {
47
+ let r = await n(e.signatureAlgorithmOid, e.signatureAlgorithmParametersDer, t.publicKeyAlgorithmOid, t.publicKeyParametersOid, t.subjectPublicKeyInfoDer, e.signatureValue, e.tbsCertificateDer);
48
+ return !r.ok && r.code === "verification_error" ? {
49
+ ok: !1,
51
50
  code: "signature_invalid",
52
- reason: result.reason
53
- };
54
- return result;
51
+ reason: r.reason
52
+ } : r;
55
53
  }
56
54
  /**
57
55
  * Depth-first chain search from leaf to root. Tries all issuer candidates,
@@ -59,240 +57,227 @@ async function verifyCertificateSignature(certificate, issuer) {
59
57
  * step. Returns the first fully anchored path or the deepest partial path
60
58
  * with the best failure encountered.
61
59
  */
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);
60
+ async function buildChainInternal(e, t, n, i, a, o) {
61
+ let s = [...t, ...n], c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), u = new Set(n.map((e) => fingerprint(e))), d = /* @__PURE__ */ new Map();
62
+ for (let e of i) {
63
+ let t = r(e.subject), n = d.get(t);
64
+ n === void 0 ? d.set(t, [e]) : n.push(e);
73
65
  }
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);
66
+ let f = !1, p = [e], m, h, g = /* @__PURE__ */ new Set();
67
+ s.forEach((e, t) => {
68
+ let n = r(e.subject), i = c.get(n);
69
+ i === void 0 ? c.set(n, [e]) : i.push(e), l.set(fingerprint(e), t);
85
70
  });
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
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
92
75
  };
93
- if (preferredFailure !== void 0) return {
94
- chain: deepestPath,
95
- foundTrustedRoot: false,
96
- failure: preferredFailure
76
+ if (h !== void 0) return {
77
+ chain: p,
78
+ foundTrustedRoot: !1,
79
+ failure: h
97
80
  };
98
- if (sawUntrustedAnchor) return {
99
- chain: deepestPath,
100
- foundTrustedRoot: false
81
+ if (f) return {
82
+ chain: p,
83
+ foundTrustedRoot: !1
101
84
  };
102
- return deepestMissingIssuerAt === void 0 ? {
103
- chain: deepestPath,
104
- foundTrustedRoot: false
85
+ return m === void 0 ? {
86
+ chain: p,
87
+ foundTrustedRoot: !1
105
88
  } : {
106
- chain: deepestPath,
107
- foundTrustedRoot: false,
108
- missingIssuerAt: deepestMissingIssuerAt
89
+ chain: p,
90
+ foundTrustedRoot: !1,
91
+ missingIssuerAt: m
109
92
  };
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);
93
+ async function search(e, t, n, i) {
94
+ if (u.has(fingerprint(e))) return t;
95
+ let a = await matchTrustAnchor(e, d, o, t.length - 1);
96
+ if (a.failure !== void 0 && recordFailure(a.failure, t), a.matched) return t;
97
+ if (t.length > _) return;
98
+ let s = [...n].sort().join(","), f = `${fingerprint(e)}:${i}:${s}`;
99
+ if (g.has(f)) return;
100
+ let p = rankIssuerCandidates(e, c.get(r(e.issuer)) ?? [], l, u);
101
+ if (p.length === 0) {
102
+ recordMissingIssuers(e, t), g.add(f);
126
103
  return;
127
104
  }
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);
105
+ let m = await searchIssuerCandidates(e, p, t, n, i);
106
+ if (m !== void 0) return m;
107
+ g.add(f), updateDeepest(t);
189
108
  }
190
- function updateDeepest(path) {
191
- if (path.length > deepestPath.length) {
192
- deepestPath = path;
193
- return true;
109
+ function recordMissingIssuers(e, t) {
110
+ isSelfIssued(e) ? (updateDeepest(t), f = !0) : updateDeepest(t) && (m = t.length - 1);
111
+ }
112
+ /** Searches ranked issuer candidates until one produces a trusted path. */
113
+ async function searchIssuerCandidates(e, t, n, r, i) {
114
+ for (let a of t) {
115
+ let t = await searchIssuerCandidate(e, a, n, r, i);
116
+ if (t !== void 0) return t;
194
117
  }
195
- return false;
196
118
  }
197
- function recordFailure(candidateFailure, path) {
198
- if (preferredFailure === void 0 || path.length > deepestPath.length) {
199
- preferredFailure = candidateFailure;
200
- deepestPath = path;
119
+ async function searchIssuerCandidate(e, t, n, r, i) {
120
+ let s = fingerprint(t);
121
+ if (r.has(s)) return;
122
+ let c = await evaluateIssuerCandidate(e, t, n, i, a, o);
123
+ if (!c.ok) {
124
+ recordFailure(c.failure, n);
125
+ return;
201
126
  }
127
+ let l = new Set(r);
128
+ return l.add(s), await search(t, [...n, t], l, c.nextCaBelowCount);
129
+ }
130
+ function updateDeepest(e) {
131
+ return e.length > p.length ? (p = e, !0) : !1;
132
+ }
133
+ function recordFailure(e, t) {
134
+ (h === void 0 || t.length > p.length) && (h = e, p = t);
202
135
  }
203
136
  }
137
+ /** Applies issuer constraints and signature verification to one path candidate. */
138
+ async function evaluateIssuerCandidate(e, t, n, r, i, a) {
139
+ let o = evaluateIssuerConstraints(e, t, n, r, i, a);
140
+ if (!o.ok) return o;
141
+ let s = await verifyCertificateSignature(e, t);
142
+ return s.ok ? s.valid ? o : {
143
+ ok: !1,
144
+ failure: a.failure("signature_invalid", "certificate signature does not verify", n.length - 1, a.detail({
145
+ subjectCommonName: e.subject.values.commonName,
146
+ issuerCommonName: t.subject.values.commonName
147
+ }))
148
+ } : {
149
+ ok: !1,
150
+ failure: a.failure(s.code, s.reason, n.length - 1, a.detail({
151
+ subjectCommonName: e.subject.values.commonName,
152
+ issuerCommonName: t.subject.values.commonName,
153
+ actual: s.reason
154
+ }))
155
+ };
156
+ }
157
+ function evaluateIssuerConstraints(e, t, n, r, i, a) {
158
+ return isWithinValidity(t, i) ? t.basicConstraints?.ca === !0 ? evaluateIssuerKeyConstraints(e, t, n, r, a) : {
159
+ ok: !1,
160
+ failure: a.failure("ca_required", "issuer must be a CA certificate", n.length, a.detail({ subjectCommonName: t.subject.values.commonName }))
161
+ } : {
162
+ ok: !1,
163
+ failure: a.failure("certificate_expired", "certificate not valid at requested time", n.length, a.detail({
164
+ subjectCommonName: t.subject.values.commonName,
165
+ expected: describeDateTime(i),
166
+ actual: `${describeDateTime(t.notBefore)}..${describeDateTime(t.notAfter)}`
167
+ }))
168
+ };
169
+ }
170
+ function evaluateIssuerKeyConstraints(e, t, n, r, i) {
171
+ if (t.keyUsage !== void 0 && !t.keyUsage.flags.includes("keyCertSign")) return {
172
+ ok: !1,
173
+ failure: i.failure("key_cert_sign_required", "issuer missing keyCertSign", n.length, i.detail({ subjectCommonName: t.subject.values.commonName }))
174
+ };
175
+ if (authorityKeyIdentifierMismatch(e, t)) return {
176
+ ok: !1,
177
+ failure: i.failure("authority_key_identifier_mismatch", "authorityKeyIdentifier does not match issuer subjectKeyIdentifier", n.length - 1, i.detail({
178
+ subjectCommonName: e.subject.values.commonName,
179
+ issuerCommonName: t.subject.values.commonName,
180
+ expected: t.subjectKeyIdentifier,
181
+ actual: e.authorityKeyIdentifier
182
+ }))
183
+ };
184
+ let a = r + +(e.basicConstraints?.ca === !0 && !isSelfIssued(e) && n.length > 1), o = t.basicConstraints?.pathLength;
185
+ return isNonNegativeInteger(o) && a > o ? {
186
+ ok: !1,
187
+ failure: i.failure("path_length_exceeded", "path length constraint exceeded", n.length, i.detail({
188
+ subjectCommonName: t.subject.values.commonName,
189
+ expected: String(o),
190
+ actual: String(a)
191
+ }))
192
+ } : {
193
+ ok: !0,
194
+ nextCaBelowCount: a
195
+ };
196
+ }
197
+ function authorityKeyIdentifierMismatch(e, t) {
198
+ return e.authorityKeyIdentifier !== void 0 && t.subjectKeyIdentifier !== void 0 && e.authorityKeyIdentifier !== t.subjectKeyIdentifier;
199
+ }
204
200
  /** Expands a PEM (possibly multi-block) or DER source into parsed certificates. */
205
- function expandSource(source) {
206
- return parseCertificatesFromSource(source);
201
+ function expandSource(e) {
202
+ return t(e);
207
203
  }
208
204
  /** 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);
205
+ function rankIssuerCandidates(e, t, n, r) {
206
+ let i = e.authorityKeyIdentifier, a = [...t].filter((t) => isIssuerOf(t, e)), o = /* @__PURE__ */ new Map();
207
+ for (let e of a) o.set(e, fingerprint(e));
208
+ return a.sort((e, t) => {
209
+ let a = compareBooleans(matchesAki(e, i), matchesAki(t, i));
210
+ if (a !== 0) return a;
211
+ let s = o.get(e) ?? "", c = o.get(t) ?? "", l = compareBooleans(r.has(s), r.has(c));
212
+ return l === 0 ? (n.get(s) ?? 2 ** 53 - 1) - (n.get(c) ?? 2 ** 53 - 1) : l;
222
213
  });
223
214
  }
224
215
  /** 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;
216
+ function matchesAki(e, t) {
217
+ return t !== void 0 && e.subjectKeyIdentifier !== void 0 && e.subjectKeyIdentifier === t;
227
218
  }
228
219
  /** 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;
220
+ function compareBooleans(e, t) {
221
+ return e === t ? 0 : e ? -1 : 1;
232
222
  }
233
223
  /** 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);
224
+ function isIssuerOf(e, t) {
225
+ return i(t.issuer, e.subject);
236
226
  }
237
227
  /** 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
- }));
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;
234
+ let r = await verifyTrustAnchorSignature(e, t);
235
+ if (!r.ok) {
236
+ o === void 0 && (o = n.failure(r.code, r.reason, i, n.detail({
237
+ subjectCommonName: e.subject.values.commonName,
238
+ actual: r.reason
239
+ })));
264
240
  continue;
265
241
  }
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,
242
+ if (!r.valid) {
243
+ o === void 0 && (o = n.failure("signature_invalid", "certificate signature does not verify", i, n.detail({
244
+ subjectCommonName: e.subject.values.commonName,
269
245
  actual: "certificate signature does not verify"
270
- }));
246
+ })));
271
247
  continue;
272
248
  }
273
- return { matched: true };
249
+ return { matched: !0 };
274
250
  }
275
- return firstFailure !== void 0 ? {
276
- matched: false,
277
- failure: firstFailure
278
- } : { matched: false };
251
+ return o === void 0 ? { matched: !1 } : {
252
+ matched: !1,
253
+ failure: o
254
+ };
255
+ }
256
+ function trustAnchorAkiMismatch(e, t) {
257
+ return t.subjectKeyIdentifier !== void 0 && e.authorityKeyIdentifier !== void 0 && t.subjectKeyIdentifier !== e.authorityKeyIdentifier;
279
258
  }
280
- function describeDateTime(value) {
281
- return Number.isNaN(value.getTime()) ? "<invalid date>" : value.toISOString();
259
+ async function verifyTrustAnchorSignature(e, t) {
260
+ let r = await n(e.signatureAlgorithmOid, e.signatureAlgorithmParametersDer, t.publicKeyAlgorithmOid, t.publicKeyParametersOid, t.subjectPublicKeyInfoDer, e.signatureValue, e.tbsCertificateDer);
261
+ return !r.ok && r.code === "verification_error" ? {
262
+ ok: !1,
263
+ code: "signature_invalid",
264
+ reason: r.reason
265
+ } : r;
266
+ }
267
+ function describeDateTime(e) {
268
+ return Number.isNaN(e.getTime()) ? "<invalid date>" : e.toISOString();
282
269
  }
283
- function isNonNegativeInteger(value) {
284
- return value !== void 0 && Number.isInteger(value) && value >= 0;
270
+ function isNonNegativeInteger(e) {
271
+ return e !== void 0 && Number.isInteger(e) && e >= 0;
285
272
  }
286
273
  /** Cache for computed fingerprints to avoid repeated toHex() calls. */
287
- const fingerprintCache = /* @__PURE__ */ new WeakMap();
274
+ const a = /* @__PURE__ */ new WeakMap();
288
275
  /** 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;
276
+ function fingerprint(t) {
277
+ let n = a.get(t);
278
+ return n === void 0 && (n = e(t.der), a.set(t, n)), n;
296
279
  }
297
280
  //#endregion
298
- export { buildChainInternal, countCaCertificatesBelowParsed, isSelfIssued, isWithinValidity, loadCertificates, loadSingleCertificate, verifyCertificateSignature };
281
+ export { authorityKeyIdentifierMismatch, buildChainInternal, countCaCertificatesBelowParsed, isSelfIssued, isWithinValidity, loadCertificates, loadSingleCertificate, verifyCertificateSignature };
282
+
283
+ //# sourceMappingURL=verify-path.js.map