micro509 0.17.1 → 0.19.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.
- package/CHANGELOG.md +165 -6
- package/dist/crypto/crypto.d.ts +12 -4
- package/dist/crypto/crypto.js +30 -17
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +8 -2
- package/dist/der/der.d.ts +14 -4
- package/dist/der/der.js +19 -19
- package/dist/der/der.js.map +1 -1
- package/dist/der.d.ts +26 -2
- package/dist/der.js +4 -4
- package/dist/index.d.ts +84 -16
- package/dist/index.js +19 -19
- package/dist/internal/asn1/asn1.d.ts +1 -2
- package/dist/internal/asn1/asn1.js +10 -2
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js.map +1 -1
- package/dist/internal/asn1/decode-refusal.js.map +1 -1
- package/dist/internal/asn1/der.d.ts +1 -2
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +71 -353
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/asn1/oids.json.js +357 -0
- package/dist/internal/asn1/oids.json.js.map +1 -0
- package/dist/internal/crypto/algorithm-names.js +1 -1
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +1 -2
- package/dist/internal/crypto/pbes2.js +70 -70
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/prime-ec.js +37 -0
- package/dist/internal/crypto/prime-ec.js.map +1 -0
- package/dist/internal/crypto/rsa-pss.js +50 -50
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +41 -2
- package/dist/internal/crypto/sig-verify.js +125 -38
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.d.ts +1 -2
- package/dist/internal/crypto/signing.js +26 -26
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/jose/base64url.js.map +1 -1
- package/dist/internal/jose/json-data.js +108 -0
- package/dist/internal/jose/json-data.js.map +1 -0
- package/dist/internal/jose/strict-json.d.ts +1 -2
- package/dist/internal/jose/strict-json.js.map +1 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +1 -2
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna.js.map +1 -1
- package/dist/internal/shared/ip.d.ts +1 -2
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js.map +1 -1
- package/dist/internal/shared/punycode.js.map +1 -1
- package/dist/internal/shared/uri-host.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js +64 -64
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js.map +1 -1
- package/dist/internal/verify/verify-path.d.ts +1 -2
- package/dist/internal/verify/verify-path.js +234 -128
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js +10 -10
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +1 -2
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js +18 -18
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js +9 -9
- package/dist/internal/x509/general-name-profile.js.map +1 -1
- package/dist/internal/x509/general-name.js +32 -32
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js +1 -1
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js.map +1 -1
- package/dist/jose/base64url.d.ts +4 -0
- package/dist/jose/base64url.js +14 -0
- package/dist/jose/base64url.js.map +1 -0
- package/dist/jose/errors.d.ts +9 -3
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.d.ts +64 -0
- package/dist/jose/jwe.js +188 -0
- package/dist/jose/jwe.js.map +1 -0
- package/dist/jose/jwks.d.ts +38 -10
- package/dist/jose/jwks.js +156 -96
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.d.ts +8 -6
- package/dist/jose/jws.js +216 -170
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.d.ts +8 -2
- package/dist/jose/jwt.js +98 -98
- package/dist/jose/jwt.js.map +1 -1
- package/dist/jose/remote-jwks.d.ts +1 -2
- package/dist/jose/remote-jwks.js +106 -108
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/jose.d.ts +15 -4
- package/dist/jose.js +7 -5
- package/dist/kdf/argon2-arithmetic.js.map +1 -1
- package/dist/kdf/argon2-core.js.map +1 -1
- package/dist/kdf/argon2-memory.js.map +1 -1
- package/dist/kdf/argon2-portable.js.map +1 -1
- package/dist/kdf/argon2.d.ts +7 -2
- package/dist/kdf/argon2.js.map +1 -1
- package/dist/kdf.d.ts +6 -0
- package/dist/keys/keys.d.ts +31 -6
- package/dist/keys/keys.js +315 -233
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +11 -2
- package/dist/keys.js +2 -2
- package/dist/pem/pem.d.ts +1 -2
- package/dist/pem/pem.js +40 -25
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +6 -0
- package/dist/pkcs/pfx.d.ts +2 -3
- package/dist/pkcs/pfx.js +142 -142
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.d.ts +1 -2
- package/dist/pkcs/pkcs12-mac.js +122 -122
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +24 -3
- package/dist/pkcs/pkcs7.js +294 -256
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +10 -1
- package/dist/pkcs.js +4 -4
- package/dist/result/result.d.ts +1 -2
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +6 -0
- package/dist/revocation/chain.d.ts +69 -16
- package/dist/revocation/chain.js +431 -303
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +67 -14
- package/dist/revocation/crl.js +656 -366
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +78 -24
- package/dist/revocation/ocsp.js +622 -436
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +68 -14
- package/dist/revocation/revocation.js +195 -74
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +14 -5
- package/dist/revocation.js +4 -4
- package/dist/ssh/ssh.d.ts +2 -3
- package/dist/ssh/ssh.js +165 -170
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.d.ts +1 -2
- package/dist/ssh/wire.js +10 -10
- package/dist/ssh/wire.js.map +1 -1
- package/dist/ssh.d.ts +8 -0
- package/dist/verify/identity.d.ts +3 -4
- package/dist/verify/identity.js +33 -33
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/name-constraints.d.ts +9 -2
- package/dist/verify/policy.d.ts +9 -2
- package/dist/verify/verify.d.ts +85 -34
- package/dist/verify/verify.js +276 -226
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +12 -2
- package/dist/x509/certificate.d.ts +4 -5
- package/dist/x509/certificate.js +40 -40
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +3 -4
- package/dist/x509/csr.js +15 -15
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.d.ts +1 -2
- package/dist/x509/extensions.js +165 -165
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +1 -2
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.d.ts +1 -2
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +1 -2
- package/dist/x509/name.js +15 -15
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +9 -6
- package/dist/x509/parse.js +394 -394
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +17 -4
- package/dist/x509.js +8 -8
- package/package.json +32 -33
- package/dist/internal/asn1/oids2.js +0 -75
- package/dist/internal/asn1/oids2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"name-constraints-engine.js","names":["exhaustive","_exhaustive","details","input","compareDistinguishedNames","certificate","subtree","accumulated","state","root","chain","index","current","nameCheckResult","entry","OIDS","permittedLevels","constraints","excluded","unsupported","critical","form","subjectResult","sanResult","error","refusal","decodeRefusalOf","DECODE_REFUSAL_CODES","san","result","unsupportedForm","checkableResult","checkable","parsePresentedSrvName","mailbox","domain","presentedSmtpUtf8MailboxDomain","constraint","level","type","value","parseSrvNameRestriction","parseUriNameConstraint","label","domainToAscii","host","isMailboxDomain","constraintDomain","letter","c","typeId","tag","parseIpAddressToBytes","allOnesMaskForIpAddress","name","relevant","presented","restriction","lowerName","lowerConstraint","nameAt","constraintAt","atIndex","uri","parsed","uriAuthorityHost","nameBytes","constraintAddr","i","nameByte","addrByte","maskByte","constraintMask","subjectName","subjectDerHex","constraintName","constraintDerHex","directoryNameSubtreeMatch","derHex","bytes","hexToBytes","element","readRootElement","rdns","attributes","values","setElement","childrenOf","rdn","attribute","toHex","children","source","child","attributeSequence","parts","oidElement","valueElement","oid","decodeObjectIdentifier","requireElement","fieldValue","decodeString","fieldKey","nameFieldKeyFromOid","decodeIpAddress"],"sources":["../../../src/internal/verify/name-constraints-engine.ts"],"sourcesContent":["/**\n * Internal name-constraints evaluation engine.\n *\n * Accumulates and evaluates the shipped RFC 5280\n * [§4.2.1.10](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.10) / [§6.1](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1)\n * name-constraint subset during certificate path validation.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\thexToBytes,\n\trequireElement,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDECODE_REFUSAL_CODES,\n\tdecodeRefusalOf,\n\trethrowDecodeRefusal,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport { DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { NameMatch } from '#micro509/internal/shared/dn';\nimport { compareDistinguishedNames, directoryNameSubtreeMatch } from '#micro509/internal/shared/dn';\nimport { domainToAscii } from '#micro509/internal/shared/idna';\nimport {\n\tallOnesMaskForIpAddress,\n\tdecodeIpAddress,\n\tparseIpAddressToBytes,\n} from '#micro509/internal/shared/ip';\nimport { isMailboxDomain, presentedSmtpUtf8MailboxDomain } from '#micro509/internal/shared/mailbox';\nimport { uriAuthorityHost } from '#micro509/internal/shared/uri-host';\nimport {\n\tparsePresentedSrvName,\n\tparseSrvNameRestriction,\n\tparseUriNameConstraint,\n} from '#micro509/internal/x509/general-name-profile';\nimport type { DecodeRefusalCode, Micro509Error } from '#micro509/result/result';\nimport type { InitialNameConstraintsInput } from '#micro509/verify/name-constraints';\nimport type {\n\tNameConstraintForm,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tSubjectAltName,\n\tUnsupportedNameConstraintForm,\n} from '#micro509/x509/extensions';\nimport { nameFieldKeyFromOid } from '#micro509/x509/name';\nimport type {\n\tNameFieldKey,\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\n\n/**\n * Opaque state seeded from {@linkcode InitialNameConstraintsInput} and consumed\n * by {@linkcode evaluateNameConstraints}.\n */\nexport interface NameConstraintValidationState {\n\t/** Caller-supplied permitted subtree bases (pre-chain). */\n\treadonly initialPermittedSubtrees: readonly NameConstraintForm[];\n\t/** Caller-supplied excluded subtree bases (pre-chain). */\n\treadonly initialExcludedSubtrees: readonly NameConstraintForm[];\n}\n\n/** Discriminant codes for name-constraint validation failures. */\nexport type NameConstraintValidationFailureCode =\n\t| 'name_constraints_violated'\n\t| 'unsupported_name_constraints'\n\t| DecodeRefusalCode;\n\n/** Diagnostic context attached to a name-constraint validation failure. */\nexport interface NameConstraintValidationFailureDetails {\n\t/** CN of the certificate whose name violated constraints, if available. */\n\treadonly subjectCommonName?: string;\n\t/** The name or constraint-type string that caused the violation. */\n\treadonly actual?: string;\n}\n\n/** A name-constraint check that failed, with the offending certificate's chain index. */\nexport interface NameConstraintValidationFailure\n\textends Micro509Error<\n\t\tNameConstraintValidationFailureCode,\n\t\tNameConstraintValidationFailureDetails\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n\t/** Zero-based index into the chain of the certificate that violated constraints. */\n\treadonly index: number;\n}\n\n/** Success or failure outcome of name-constraint evaluation across a chain. */\nexport type NameConstraintValidationResult =\n\t| {\n\t\t\t/** All names in the chain satisfy accumulated constraints. */\n\t\t\treadonly ok: true;\n\t }\n\t| NameConstraintValidationFailure;\n\n/** Builder input for assembling optional failure detail fields. */\ninterface NameConstraintValidationFailureDetailsInput {\n\treadonly subjectCommonName?: string | undefined;\n\treadonly actual?: string | undefined;\n}\n\ntype SubjectAltNameCheckableResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value: NameConstraintForm | undefined;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly actual: string;\n\t };\n\n/** Constructs a {@linkcode NameConstraintValidationFailure} with optional details. */\nfunction nameConstraintFailure(\n\tcode: NameConstraintValidationFailureCode,\n\tmessage: string,\n\tindex: number,\n\tdetails?: NameConstraintValidationFailureDetails,\n): NameConstraintValidationFailure {\n\treturn {\n\t\tok: false,\n\t\tcode,\n\t\tmessage,\n\t\tindex,\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Strips undefined fields and returns `undefined` when all fields are empty. */\nfunction nameConstraintDetails(\n\tinput: NameConstraintValidationFailureDetailsInput,\n): NameConstraintValidationFailureDetails | undefined {\n\tconst details: NameConstraintValidationFailureDetails = {\n\t\t...(input.subjectCommonName === undefined\n\t\t\t? {}\n\t\t\t: { subjectCommonName: input.subjectCommonName }),\n\t\t...(input.actual === undefined ? {} : { actual: input.actual }),\n\t};\n\treturn Object.keys(details).length === 0 ? undefined : details;\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\n/**\n * Initializes validation state from caller-supplied initial constraints.\n *\n * Call once before {@linkcode evaluateNameConstraints}.\n */\nexport function createNameConstraintValidationState(\n\tinput: InitialNameConstraintsInput,\n): NameConstraintValidationState {\n\treturn {\n\t\tinitialPermittedSubtrees: input.permittedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t\tinitialExcludedSubtrees: input.excludedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t};\n}\n\n// Private: name constraint validation (RFC 5280 §4.2.1.10 / §6.1)\n\n/** Empty SEQUENCE DER hex — represents an empty subject DN. */\nconst EMPTY_SEQUENCE_HEX = '3000';\n\n/**\n * Accumulated name constraint state during root-to-leaf traversal.\n * - `permittedLevels`: each entry is one CA's permittedSubtrees. A name\n * must match at least one entry in *every* level (intersection semantics).\n * - `excluded`: flat list; a name must NOT match *any* entry.\n */\ninterface AccumulatedNameConstraints {\n\t/** One entry per CA that asserted permittedSubtrees; intersection semantics. */\n\treadonly permittedLevels: readonly (readonly NameConstraintForm[])[];\n\t/** Flat union of all excludedSubtrees seen so far. */\n\treadonly excluded: readonly NameConstraintForm[];\n\t/**\n\t * Name forms this engine cannot evaluate that were imposed by a\n\t * **critical** nameConstraints extension above. RFC 5280 §4.2.1.10:\n\t * a subsequent certificate carrying a name of such a form MUST be\n\t * rejected; certificates without one stay acceptable.\n\t */\n\treadonly unsupportedCriticalForms: ReadonlySet<UnsupportedDirectForm>;\n\t/** Type-ids of otherName forms imposed the same way; X.509 §9.4.2.2 makes each a distinct form. */\n\treadonly unsupportedCriticalOtherNames: ReadonlySet<string>;\n}\n\ntype UnsupportedDirectForm = Exclude<UnsupportedNameConstraintForm['type'], 'otherName'>;\n\n/**\n * Walks the chain root-to-leaf, accumulating nameConstraints from CA\n * certificates and checking each non-self-issued certificate's names\n * against the accumulated constraints.\n *\n * RFC 5280 §6.1.3(b)-(c) for name checks, §6.1.4(g) for constraint accumulation.\n */\n\nexport function evaluateNameConstraints(\n\tchain: readonly ParsedCertificate[],\n\tstate: NameConstraintValidationState,\n): NameConstraintValidationResult {\n\tlet accumulated = seedInitialNameConstraints(state);\n\n\t// Seed constraints from the root (trust anchor). The root's own\n\t// names are not checked, but its nameConstraints apply to all\n\t// certificates below it in the chain.\n\tconst root = chain[chain.length - 1];\n\tif (root?.nameConstraints !== undefined) {\n\t\taccumulated = accumulateConstraints(\n\t\t\taccumulated,\n\t\t\troot.nameConstraints,\n\t\t\thasCriticalNameConstraintsExtension(root),\n\t\t);\n\t}\n\n\t// Walk from just below root toward leaf.\n\tfor (let index = chain.length - 2; index >= 0; index -= 1) {\n\t\tconst current = chain[index];\n\t\tif (current === undefined) {\n\t\t\tthrow new Error(`Certificate chain contains undefined at index ${String(index)}`);\n\t\t}\n\n\t\t// RFC 5280 §6.1.3(b)-(c): check names against accumulated permitted (b)\n\t\t// and excluded (c) constraints. §4.2.1.10 exempts self-issued\n\t\t// certificates unless the certificate is the leaf.\n\t\tif (!isSelfIssued(current) || index === 0) {\n\t\t\tconst nameCheckResult = checkCertificateNames(current, accumulated, index);\n\t\t\tif (!nameCheckResult.ok) {\n\t\t\t\treturn nameCheckResult;\n\t\t\t}\n\t\t}\n\n\t\t// RFC 5280 §6.1.4(g): accumulate this certificate's nameConstraints,\n\t\t// intersecting permitted subtrees and unioning excluded subtrees.\n\t\tif (current.nameConstraints !== undefined) {\n\t\t\taccumulated = accumulateConstraints(\n\t\t\t\taccumulated,\n\t\t\t\tcurrent.nameConstraints,\n\t\t\t\thasCriticalNameConstraintsExtension(current),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when the certificate carries a critical nameConstraints extension. */\nfunction hasCriticalNameConstraintsExtension(certificate: ParsedCertificate): boolean {\n\treturn certificate.extensions.some(\n\t\t(entry) => entry.oid === OIDS.nameConstraints && entry.critical,\n\t);\n}\n\n/** Converts initial state into the starting accumulated-constraints snapshot. */\nfunction seedInitialNameConstraints(\n\tstate: NameConstraintValidationState,\n): AccumulatedNameConstraints {\n\treturn {\n\t\tpermittedLevels:\n\t\t\tstate.initialPermittedSubtrees.length > 0 ? [state.initialPermittedSubtrees] : [],\n\t\texcluded: state.initialExcludedSubtrees,\n\t\tunsupportedCriticalForms: new Set(),\n\t\tunsupportedCriticalOtherNames: new Set(),\n\t};\n}\n\n/**\n * Merges one certificate's nameConstraints extension into the running totals.\n *\n * Unsupported constraint forms from a critical extension are recorded so\n * subsequent certificates carrying a name of that form fail closed\n * (RFC 5280 §4.2.1.10). Unsupported forms in a non-critical extension are\n * dropped — the RFC's rejection requirement is scoped to critical\n * extensions (conforming CAs MUST mark nameConstraints critical anyway).\n */\nfunction accumulateConstraints(\n\tcurrent: AccumulatedNameConstraints,\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n\tcritical: boolean,\n): AccumulatedNameConstraints {\n\tconst permittedLevels =\n\t\tconstraints.permittedSubtrees !== undefined && constraints.permittedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.permittedLevels,\n\t\t\t\t\tconstraints.permittedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.permittedLevels;\n\tconst excluded =\n\t\tconstraints.excludedSubtrees !== undefined && constraints.excludedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.excluded,\n\t\t\t\t\t...constraints.excludedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.excluded;\n\tconst unsupported = critical ? listUnsupportedNameConstraintForms(constraints) : [];\n\treturn {\n\t\tpermittedLevels,\n\t\texcluded,\n\t\tunsupportedCriticalForms: new Set([\n\t\t\t...current.unsupportedCriticalForms,\n\t\t\t...unsupported.flatMap((form) => (form.type === 'otherName' ? [] : [form.type])),\n\t\t]),\n\t\tunsupportedCriticalOtherNames: new Set([\n\t\t\t...current.unsupportedCriticalOtherNames,\n\t\t\t...unsupported.flatMap((form) => (form.type === 'otherName' ? [form.typeId] : [])),\n\t\t]),\n\t};\n}\n\n/** Collects the unsupported GeneralName forms from a nameConstraints extension. */\nfunction listUnsupportedNameConstraintForms(\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n): readonly UnsupportedNameConstraintForm[] {\n\treturn [\n\t\t...(constraints.permittedSubtrees ?? []),\n\t\t...(constraints.excludedSubtrees ?? []),\n\t].flatMap((subtree) => (isSupportedNameConstraintForm(subtree.base) ? [] : [subtree.base]));\n}\n\n/** True for name forms this engine can evaluate: dns, email, uri, ip, directoryName, srv. */\nfunction isSupportedNameConstraintForm(form: ParsedNameConstraintForm): form is NameConstraintForm {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\tcase 'email':\n\t\tcase 'uri':\n\t\tcase 'ip':\n\t\tcase 'directoryName':\n\t\tcase 'srv':\n\t\t\treturn true;\n\t\tcase 'otherName':\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn false;\n\t\tdefault: {\n\t\t\tconst exhaustive: never = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks a certificate's subject DN and SANs against accumulated\n * name constraints. Returns a failure if any name violates constraints.\n */\nfunction checkCertificateNames(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\ttry {\n\t\tconst subjectResult = checkCertificateSubjectName(certificate, accumulated, index);\n\t\tif (!subjectResult.ok) return subjectResult;\n\t\tconst sanResult = checkCertificateSubjectAltNames(certificate, accumulated, index);\n\t\tif (!sanResult.ok) return sanResult;\n\t\treturn checkCertificateSubjectEmailFallback(certificate, accumulated, index);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\tif (refusal === undefined) throw error;\n\t\treturn nameConstraintFailure(\n\t\t\trefusal.code,\n\t\t\trefusal.message,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: refusal.message,\n\t\t\t}),\n\t\t);\n\t}\n}\n\n/** Checks a certificate subject DN against the accumulated directory-name constraints. */\nfunction checkCertificateSubjectName(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\tif (certificate.subject.derHex === EMPTY_SEQUENCE_HEX) return { ok: true };\n\tconst dnResult = isNamePermitted(\n\t\t{ type: 'directoryName', derHex: certificate.subject.derHex },\n\t\taccumulated,\n\t);\n\treturn dnResult\n\t\t? { ok: true }\n\t\t: nameConstraintFailure(\n\t\t\t\t'name_constraints_violated',\n\t\t\t\t'subject distinguished name violates name constraints',\n\t\t\t\tindex,\n\t\t\t\tnameConstraintDetails({ subjectCommonName: certificate.subject.values.commonName }),\n\t\t\t);\n}\n\nfunction checkCertificateSubjectAltNames(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\tfor (const san of certificate.subjectAltNames ?? []) {\n\t\tconst result = checkCertificateSubjectAltName(certificate, accumulated, san, index);\n\t\tif (!result.ok) return result;\n\t}\n\treturn { ok: true };\n}\n\nfunction checkCertificateSubjectAltName(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tsan: SubjectAltName,\n\tindex: number,\n): NameConstraintValidationResult {\n\tconst unsupportedForm = unprocessableConstraintFormOf(san, accumulated);\n\tif (unsupportedForm !== undefined) {\n\t\treturn nameConstraintFailure(\n\t\t\t'unsupported_name_constraints',\n\t\t\t`critical name constraints impose ${unsupportedForm} constraints that cannot be processed, and the certificate contains a ${unsupportedForm} subject alternative name`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: unsupportedForm,\n\t\t\t}),\n\t\t);\n\t}\n\tif (san.type === 'smtpUtf8Mailbox') {\n\t\treturn checkSmtpUtf8Mailbox(certificate, accumulated, san.value, index);\n\t}\n\tconst checkableResult = sanToConstraintCheckable(san);\n\tif (!checkableResult.ok) {\n\t\treturn nameConstraintFailure(\n\t\t\t'name_constraints_violated',\n\t\t\t`SAN ${checkableResult.actual} is malformed and cannot be checked against name constraints`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: checkableResult.actual,\n\t\t\t}),\n\t\t);\n\t}\n\tconst checkable = checkableResult.value;\n\tif (\n\t\tcheckable?.type === 'srv' &&\n\t\taccumulatedHasConstraintsOfType('srv', accumulated) &&\n\t\tparsePresentedSrvName(asciiLowercase(checkable.value)) === undefined\n\t) {\n\t\treturn nameConstraintFailure(\n\t\t\t'name_constraints_violated',\n\t\t\t`SAN srv:${checkable.value} is not _Service.Name and cannot be evaluated against SRVName constraints`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: `srv:${checkable.value}`,\n\t\t\t}),\n\t\t);\n\t}\n\tif (\n\t\tcheckable?.type === 'uri' &&\n\t\taccumulatedHasConstraintsOfType('uri', accumulated) &&\n\t\turiConstraintHost(checkable.value) === undefined\n\t) {\n\t\treturn nameConstraintFailure(\n\t\t\t'name_constraints_violated',\n\t\t\t`SAN uri:${checkable.value} has no FQDN authority host and cannot be evaluated against URI name constraints`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: `uri:${checkable.value}`,\n\t\t\t}),\n\t\t);\n\t}\n\tif (checkable === undefined || isNamePermitted(checkable, accumulated)) return { ok: true };\n\treturn nameConstraintFailure(\n\t\t'name_constraints_violated',\n\t\t`SAN ${formatConstraintForm(checkable)} violates name constraints`,\n\t\tindex,\n\t\tnameConstraintDetails({\n\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\tactual: formatConstraintForm(checkable),\n\t\t}),\n\t);\n}\n\n/**\n * RFC 9598 §6 applies rfc822Name constraints to a SmtpUTF8Mailbox by its domain\n * alone: the Local-part and \"@\" are stripped from the name and the constraint,\n * and the remaining domains compare octet for octet after lowercasing, as a\n * suffix when the constraint starts with \".\". A mailbox that breaks the §3\n * syntax cannot be compared, so it fails whenever rfc822Name constraints are\n * in force.\n */\nfunction checkSmtpUtf8Mailbox(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tmailbox: string,\n\tindex: number,\n): NameConstraintValidationResult {\n\tconst permitted = accumulatedHasEmailConstraints(accumulated)\n\t\t? isSmtpUtf8MailboxDomainPermitted(mailbox, accumulated)\n\t\t: true;\n\tif (permitted) return { ok: true };\n\treturn nameConstraintFailure(\n\t\t'name_constraints_violated',\n\t\t`SAN smtpUtf8Mailbox:${mailbox} violates name constraints`,\n\t\tindex,\n\t\tnameConstraintDetails({\n\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\tactual: `smtpUtf8Mailbox:${mailbox}`,\n\t\t}),\n\t);\n}\n\n/** RFC 9598 §5: a presented SmtpUTF8Mailbox whose domain the email constraints permit. */\nfunction isSmtpUtf8MailboxDomainPermitted(\n\tmailbox: string,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\tconst domain = presentedSmtpUtf8MailboxDomain(mailbox);\n\treturn domain !== undefined && isMailboxDomainPermitted(domain, accumulated);\n}\n\nfunction isMailboxDomainPermitted(\n\tdomain: string,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\tif (hasMalformedConstraint('email', accumulated)) return false;\n\tconst matches = (constraint: NameConstraintForm): boolean =>\n\t\tconstraint.type === 'email' && matchesMailboxDomainConstraint(domain, constraint.value);\n\tif (accumulated.excluded.some(matches)) return false;\n\treturn accumulated.permittedLevels.every(\n\t\t(level) => !level.some((constraint) => constraint.type === 'email') || level.some(matches),\n\t);\n}\n\n/**\n * A dNSName or rfc822Name constraint whose domain is not a well-formed name\n * cannot be compared, so no name of its type is permitted while one is in force.\n */\nfunction hasMalformedConstraint(\n\ttype: NameConstraintForm['type'],\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\treturn [...accumulated.excluded, ...accumulated.permittedLevels.flat()].some(\n\t\t(constraint) => constraint.type === type && !isWellFormedConstraint(constraint),\n\t);\n}\n\nfunction isWellFormedConstraint(constraint: NameConstraintForm): boolean {\n\tswitch (constraint.type) {\n\t\tcase 'dns': {\n\t\t\tconst value = asciiLowercase(constraint.value);\n\t\t\treturn (\n\t\t\t\tvalue.length === 0 || isComparableDomain(value.startsWith('.') ? value.slice(1) : value)\n\t\t\t);\n\t\t}\n\t\tcase 'email':\n\t\t\treturn constraintMailboxDomain(constraint.value) !== undefined;\n\t\tcase 'srv':\n\t\t\treturn parseSrvNameRestriction(asciiLowercase(constraint.value)) !== undefined;\n\t\tcase 'directoryName':\n\t\t\treturn parseDirectoryNameDerHex(constraint.derHex) !== undefined;\n\t\tcase 'uri':\n\t\t\treturn parseUriNameConstraint(constraint.value) !== undefined;\n\t\tcase 'ip':\n\t\t\treturn true;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = constraint;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Labels of 1 to 63 letters, digits, hyphens or underscores, with each `xn--` label an A-label. */\nfunction isComparableDomain(domain: string): boolean {\n\treturn (\n\t\tdomain.length <= 253 &&\n\t\tdomain.split('.').every((label) => /^[a-z0-9_-]{1,63}$/.test(label)) &&\n\t\tdomainToAscii(domain, 'lookup').ok\n\t);\n}\n\n/** RFC 9598 §6: the lowercased domain of an rfc822Name constraint, keeping a leading \".\". */\nfunction constraintMailboxDomain(constraint: string): string | undefined {\n\tconst domain = asciiLowercase(constraint.slice(constraint.lastIndexOf('@') + 1));\n\tconst host = domain.startsWith('.') ? domain.slice(1) : domain;\n\treturn isMailboxDomain(host, 'lookup') ? domain : undefined;\n}\n\nfunction matchesMailboxDomainConstraint(domain: string, constraint: string): boolean {\n\tconst constraintDomain = constraintMailboxDomain(constraint);\n\treturn constraintDomain?.startsWith('.') === true\n\t\t? domain.endsWith(constraintDomain)\n\t\t: domain === constraintDomain;\n}\n\nfunction asciiLowercase(value: string): string {\n\treturn value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());\n}\n\nfunction checkCertificateSubjectEmailFallback(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\t// RFC 5280 §4.2.1.10 applies rfc822Name constraints to the subject DN\n\t// emailAddress when the certificate has no subjectAltName extension. This\n\t// implementation applies it whenever the SAN carries no rfc822Name.\n\tconst hasEmailConstraints = accumulatedHasEmailConstraints(accumulated);\n\tif (hasEmailConstraints) {\n\t\tconst hasSanEmail = certificate.subjectAltNames?.some((san) => san.type === 'email') ?? false;\n\t\tif (!hasSanEmail && certificate.subject.values.emailAddress !== undefined) {\n\t\t\tconst emailForm: NameConstraintForm = {\n\t\t\t\ttype: 'email',\n\t\t\t\tvalue: certificate.subject.values.emailAddress,\n\t\t\t};\n\t\t\tif (!isNamePermitted(emailForm, accumulated)) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`subject emailAddress ${certificate.subject.values.emailAddress} violates name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: certificate.subject.values.emailAddress,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when any level of accumulated constraints addresses the email name form. */\nfunction accumulatedHasEmailConstraints(accumulated: AccumulatedNameConstraints): boolean {\n\tfor (const level of accumulated.permittedLevels) {\n\t\tif (level.some((c) => c.type === 'email')) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn accumulated.excluded.some((c) => c.type === 'email');\n}\n\n/** True when any level of accumulated constraints addresses the given name form. */\nfunction accumulatedHasConstraintsOfType(\n\ttype: NameConstraintForm['type'],\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\treturn [...accumulated.excluded, ...accumulated.permittedLevels.flat()].some(\n\t\t(constraint) => constraint.type === type,\n\t);\n}\n\n/**\n * The unprocessable critical constraint form a SAN instantiates, if one is in\n * force. An otherName is its own form per type-id. Raw `unknown` input carries\n * the DER tag byte, and an unknown otherName meets every otherName type-id.\n */\nfunction unprocessableConstraintFormOf(\n\tsan: SubjectAltName,\n\taccumulated: AccumulatedNameConstraints,\n): string | undefined {\n\tconst otherName = (typeId: string): string | undefined =>\n\t\taccumulated.unsupportedCriticalOtherNames.has(typeId) ? `otherName ${typeId}` : undefined;\n\tconst direct = (form: UnsupportedDirectForm): string | undefined =>\n\t\taccumulated.unsupportedCriticalForms.has(form) ? form : undefined;\n\tswitch (san.type) {\n\t\tcase 'otherName':\n\t\t\treturn otherName(san.typeId);\n\t\tcase 'smtpUtf8Mailbox':\n\t\t\treturn otherName(OIDS.idOnSmtpUtf8Mailbox);\n\t\tcase 'upn':\n\t\t\treturn otherName(OIDS.ntPrincipalName);\n\t\tcase 'krb5PrincipalName':\n\t\t\treturn otherName(OIDS.idPkinitSan);\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn direct(san.type);\n\t\tcase 'unknown':\n\t\t\treturn unknownTagForm(san.tag, accumulated);\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction unknownTagForm(tag: number, accumulated: AccumulatedNameConstraints): string | undefined {\n\tlet form: UnsupportedDirectForm;\n\n\tswitch (tag) {\n\t\tcase 0xa3:\n\t\t\tform = 'x400Address';\n\t\t\tbreak;\n\t\tcase 0xa5:\n\t\t\tform = 'ediPartyName';\n\t\t\tbreak;\n\t\tcase 0x88:\n\t\t\tform = 'registeredID';\n\t\t\tbreak;\n\t\tcase 0xa0:\n\t\t\treturn accumulated.unsupportedCriticalOtherNames.size > 0 ? 'otherName' : undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n\n\treturn accumulated.unsupportedCriticalForms.has(form) ? form : undefined;\n}\n\n/**\n * Converts a SubjectAltName to a NameConstraintForm for checking.\n * Returns `undefined` for name forms that don't participate in\n * constraint checking (unknown tags).\n */\nfunction sanToConstraintCheckable(san: SubjectAltName): SubjectAltNameCheckableResult {\n\tswitch (san.type) {\n\t\tcase 'dns':\n\t\t\treturn { ok: true, value: { type: 'dns', value: san.value } };\n\t\tcase 'email':\n\t\t\treturn { ok: true, value: { type: 'email', value: san.value } };\n\t\tcase 'uri':\n\t\t\treturn { ok: true, value: { type: 'uri', value: san.value } };\n\t\tcase 'srv':\n\t\t\treturn { ok: true, value: { type: 'srv', value: san.value } };\n\t\tcase 'smtpUtf8Mailbox':\n\t\tcase 'upn':\n\t\tcase 'krb5PrincipalName':\n\t\tcase 'otherName':\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn { ok: true, value: undefined };\n\t\tcase 'ip':\n\t\t\ttry {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\ttype: 'ip',\n\t\t\t\t\t\taddressBytes: parseIpAddressToBytes(san.value),\n\t\t\t\t\t\tmaskBytes: allOnesMaskForIpAddress(san.value),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tactual: `ip:${san.value}`,\n\t\t\t\t};\n\t\t\t}\n\t\tcase 'directoryName':\n\t\t\treturn { ok: true, value: { type: 'directoryName', derHex: san.derHex } };\n\t\tcase 'unknown':\n\t\t\treturn { ok: true, value: undefined };\n\t\tdefault: {\n\t\t\tconst exhaustive: never = san;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks whether a name is permitted by the accumulated constraints.\n * A name is permitted if:\n * 1. It does NOT match any excluded constraint, AND\n * 2. For every permitted level that contains constraints of the same\n * name form, it matches at least one.\n */\nfunction isNamePermitted(\n\tname: NameConstraintForm,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\tif (\n\t\thasMalformedConstraint(name.type, accumulated) ||\n\t\t(endsInRootDot(name) && accumulatedHasConstraintsOfType(name.type, accumulated))\n\t) {\n\t\treturn false;\n\t}\n\t// Check excluded — if any match, reject.\n\tfor (const constraint of accumulated.excluded) {\n\t\tif (nameConstraintMatch(name, constraint) !== 'mismatch') {\n\t\t\treturn false;\n\t\t}\n\t}\n\t// Check permitted — for each level with relevant constraints,\n\t// the name must match at least one.\n\tfor (const level of accumulated.permittedLevels) {\n\t\tconst relevant = level.filter((constraint) => constraint.type === name.type);\n\t\tif (relevant.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!relevant.some((constraint) => nameConstraintMatch(name, constraint) === 'match')) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** RFC 5280 §4.2.1.6: a dNSName or rfc822Name host in RFC 1034 §3.5 preferred name syntax has no trailing root dot. */\nfunction endsInRootDot(name: NameConstraintForm): boolean {\n\treturn (name.type === 'dns' || name.type === 'email') && name.value.endsWith('.');\n}\n\n/** RFC 4518 §2: a comparison that string preparation cannot perform is Undefined. */\nfunction nameConstraintMatch(name: NameConstraintForm, constraint: NameConstraintForm): NameMatch {\n\tif (name.type === 'directoryName' && constraint.type === 'directoryName') {\n\t\treturn matchesDnConstraint(name.derHex, constraint.derHex);\n\t}\n\treturn nameMatchesConstraint(name, constraint) ? 'match' : 'mismatch';\n}\n\n/** Dispatches to the type-specific matching function for the name form. */\nfunction nameMatchesConstraint(name: NameConstraintForm, constraint: NameConstraintForm): boolean {\n\tif (name.type === 'dns' && constraint.type === 'dns') {\n\t\treturn matchesDnsConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'email' && constraint.type === 'email') {\n\t\treturn matchesEmailConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'uri' && constraint.type === 'uri') {\n\t\treturn matchesUriConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'ip' && constraint.type === 'ip') {\n\t\treturn matchesIpConstraint(name.addressBytes, constraint.addressBytes, constraint.maskBytes);\n\t}\n\tif (name.type === 'srv' && constraint.type === 'srv') {\n\t\treturn matchesSrvConstraint(name.value, constraint.value);\n\t}\n\treturn false;\n}\n\n/**\n * RFC 4985 §4: a restriction's service, when present, must equal the SRVName's\n * service case-insensitively (§2), and its Name, when present, is satisfied by\n * that domain or any subdomain added to the left.\n */\nfunction matchesSrvConstraint(name: string, constraint: string): boolean {\n\tconst presented = parsePresentedSrvName(asciiLowercase(name));\n\tconst restriction = parseSrvNameRestriction(asciiLowercase(constraint));\n\treturn (\n\t\tpresented !== undefined &&\n\t\trestriction !== undefined &&\n\t\t(restriction.service.length === 0 || presented.service === restriction.service) &&\n\t\t(restriction.name.length === 0 ||\n\t\t\tpresented.name === restriction.name ||\n\t\t\tpresented.name.endsWith(`.${restriction.name}`))\n\t);\n}\n\n/**\n * DNS name constraint matching. RFC 5280 §4.2.1.10 adds zero or more labels on\n * the left; §7.2 compares label by label case-insensitively. Constraint\n * \"example.com\" matches \"example.com\" and any subdomain. RFC 5280 defines no\n * leading-period dNSName form; \".example.com\" matches subdomains only, as in\n * OpenSSL, BoringSSL, Go, NSS, mozilla::pkix and rustls-webpki (RFC 5280\n * erratum 5997).\n */\nfunction matchesDnsConstraint(name: string, constraint: string): boolean {\n\tconst lowerName = name.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.length === 0) {\n\t\treturn true;\n\t}\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn lowerName.endsWith(lowerConstraint);\n\t}\n\treturn lowerName === lowerConstraint || lowerName.endsWith(`.${lowerConstraint}`);\n}\n\n/**\n * RFC 5280 §4.2.1.10 email constraint matching, deferring to §7.5 (as\n * replaced by RFC 9549 §7.5.1): the local part matches exactly, the host part\n * case-insensitively.\n * - \"user@example.com\" constrains the local part exactly and the host case-insensitively.\n * - \"example.com\" matches any address whose host is example.com.\n * - \".example.com\" matches any address under a subdomain of example.com.\n */\nfunction matchesEmailConstraint(name: string, constraint: string): boolean {\n\tif (constraint.includes('@')) {\n\t\tconst nameAt = name.lastIndexOf('@');\n\t\tconst constraintAt = constraint.lastIndexOf('@');\n\t\tif (nameAt < 0 || constraintAt < 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif (name.slice(0, nameAt) !== constraint.slice(0, constraintAt)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (\n\t\t\tname.slice(nameAt + 1).toLowerCase() === constraint.slice(constraintAt + 1).toLowerCase()\n\t\t);\n\t}\n\tconst atIndex = name.lastIndexOf('@');\n\tif (atIndex < 0) {\n\t\treturn false;\n\t}\n\tconst host = name.slice(atIndex + 1).toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn host.endsWith(lowerConstraint);\n\t}\n\treturn host === lowerConstraint;\n}\n\n/**\n * RFC 5280 §4.2.1.10: a URI constraint applies to the host part, a constraint\n * without a leading period names one host, and \".example.com\" is satisfied by\n * its subdomains only.\n */\nfunction matchesUriConstraint(uri: string, constraint: string): boolean {\n\tconst host = uriConstraintHost(uri);\n\tconst parsed = parseUriNameConstraint(constraint);\n\tif (host === undefined || parsed === undefined) {\n\t\treturn false;\n\t}\n\tswitch (parsed.type) {\n\t\tcase 'any':\n\t\t\treturn true;\n\t\tcase 'host':\n\t\t\treturn host === parsed.name;\n\t\tcase 'subdomains':\n\t\t\treturn host.endsWith(`.${parsed.name}`);\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = parsed;\n\t\t\tthrow new Error(`Unhandled UriNameConstraint type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * RFC 5280 §4.2.1.10: the domain name of a URI's authority host, which a URI\n * constraint in force requires. `undefined` for no authority, an IP address, a\n * reg-name that is not a domain name, or a single-label host.\n */\nfunction uriConstraintHost(uri: string): string | undefined {\n\tconst host = uriAuthorityHost(uri, 'presented');\n\treturn host.type === 'dns' && host.name.includes('.') ? host.name : undefined;\n}\n\n/**\n * RFC 5280 §4.2.1.10: IP constraint matching.\n * (nameiP & mask) == (constraintiP & mask)\n */\nfunction matchesIpConstraint(\n\tnameBytes: Uint8Array,\n\tconstraintAddr: Uint8Array,\n\tconstraintMask: Uint8Array,\n): boolean {\n\tif (nameBytes.length !== constraintAddr.length) {\n\t\treturn false;\n\t}\n\tfor (let i = 0; i < nameBytes.length; i += 1) {\n\t\tconst nameByte = nameBytes[i] ?? 0;\n\t\tconst addrByte = constraintAddr[i] ?? 0;\n\t\tconst maskByte = constraintMask[i] ?? 0;\n\t\tif ((nameByte & maskByte) !== (addrByte & maskByte)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * RFC 5280 §4.2.1.10: DirectoryName constraint matching.\n * The subject DN must equal or be subordinate to the constraint DN,\n * using RFC 5280 section 7.1 name comparison semantics.\n */\nfunction matchesDnConstraint(subjectDerHex: string, constraintDerHex: string): NameMatch {\n\tconst subjectName = parseDirectoryNameDerHex(subjectDerHex);\n\tconst constraintName = parseDirectoryNameDerHex(constraintDerHex);\n\tif (subjectName === undefined || constraintName === undefined) {\n\t\treturn 'mismatch';\n\t}\n\treturn directoryNameSubtreeMatch(subjectName, constraintName);\n}\n\n/** Re-parses a hex-encoded DER Name for RDN-by-RDN comparison. Returns `undefined` on malformed input. */\nfunction parseDirectoryNameDerHex(derHex: string): ParsedName | undefined {\n\tif (!/^(?:[0-9a-fA-F]{2})+$/.test(derHex)) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\tconst bytes = hexToBytes(derHex);\n\t\tconst root = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tconst element = unwrapDirectoryNameElement(bytes, root);\n\t\tif (element.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\t\tconst attributes: ParsedNameAttribute[] = [];\n\t\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\t\tfor (const setElement of childrenOf(bytes, element)) {\n\t\t\tconst rdn = parseDirectoryNameRdn(bytes, setElement);\n\t\t\tif (rdn === undefined) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\trdns.push(rdn);\n\t\t\tfor (const attribute of rdn.attributes) {\n\t\t\t\tattributes.push(attribute);\n\t\t\t\tif (attribute.key !== undefined && values[attribute.key] === undefined) {\n\t\t\t\t\tvalues[attribute.key] = attribute.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tderHex: toHex(bytes),\n\t\t\trdns,\n\t\t\tattributes,\n\t\t\tvalues,\n\t\t};\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Unwraps doubly-nested directoryName SEQUENCE encoding.\n *\n * Some encoders produce `[4] { SEQ { SEQ { SET... } } }` instead of `[4] { SEQ { SET... } }`.\n * A single SEQUENCE child indicates the extra wrapper (valid Names have SET children).\n */\nfunction unwrapDirectoryNameElement(source: Uint8Array, element: DerElement): DerElement {\n\tif (element.tag !== 0x30) {\n\t\treturn element;\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length === 1 && child?.tag === 0x30) {\n\t\treturn child;\n\t}\n\treturn element;\n}\n\n/** Parses one SET element (a single RDN) from the DER Name SEQUENCE. */\nfunction parseDirectoryNameRdn(\n\tsource: Uint8Array,\n\tsetElement: DerElement,\n): ParsedRelativeDistinguishedName | undefined {\n\tif (setElement.tag !== 0x31) {\n\t\treturn undefined;\n\t}\n\tconst children = childrenOf(source, setElement);\n\tif (children.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const attributeSequence of children) {\n\t\tif (attributeSequence.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parts = childrenOf(source, attributeSequence);\n\t\tconst oidElement = parts[0];\n\t\tconst valueElement = parts[1];\n\t\tif (oidElement === undefined || valueElement === undefined || parts.length !== 2) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (oidElement.tag !== 0x06) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst oid = decodeObjectIdentifier(requireElement(oidElement, 'directoryName OID').value);\n\t\tlet fieldValue: string;\n\t\ttry {\n\t\t\tfieldValue = decodeString(\n\t\t\t\tvalueElement.tag,\n\t\t\t\trequireElement(valueElement, 'directoryName value').value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tfieldKey !== undefined\n\t\t\t\t? { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t: { oid, valueTag: valueElement.tag, value: fieldValue };\n\t\tattributes.push(attribute);\n\t\tif (fieldKey !== undefined && values[fieldKey] === undefined) {\n\t\t\tvalues[fieldKey] = fieldValue;\n\t\t}\n\t}\n\tif (attributes.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Human-readable label for a constraint form, used in error messages. */\nfunction formatConstraintForm(form: NameConstraintForm): string {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\t\treturn `dns:${form.value}`;\n\t\tcase 'email':\n\t\t\treturn `email:${form.value}`;\n\t\tcase 'uri':\n\t\t\treturn `uri:${form.value}`;\n\t\tcase 'ip':\n\t\t\treturn `ip:${decodeIpAddress(form.addressBytes)}`;\n\t\tcase 'directoryName':\n\t\t\treturn `dn:${form.derHex.slice(0, 20)}${form.derHex.length > 20 ? '...' : ''}`;\n\t\tcase 'srv':\n\t\t\treturn `srv:${form.value}`;\n\t\tdefault: {\n\t\t\tconst exhaustive = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyHA,SAAS,sBACR,GACA,GACA,GACA,GACkC;CAClC,OAAO;EACN,IAAI;EACJ;EACA;EACA;EACA,GAAIE,MAAY,KAAA,IAAY,CAAC,IAAI,EAAE,WAAQ;CAC5C;AACD;;AAGA,SAAS,sBACR,GACqD;CACrD,IAAMA,IAAkD;EACvD,GAAIC,EAAM,sBAAsB,KAAA,IAC7B,CAAC,IACD,EAAE,mBAAmBA,EAAM,kBAAkB;EAChD,GAAIA,EAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQA,EAAM,OAAO;CAC9D;CACA,OAAO,OAAO,KAAKD,CAAO,CAAC,CAA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;GAAK,OAAOI;EAAW;EAGxE,AADAjB,EAAW,KAAKK,CAAS,GACrBc,MAAa,KAAA,KAAalB,EAAOkB,OAAc,KAAA,MAClD,EAAOA,KAAYF;CAErB;CACA,IAAIjB,EAAW,WAAW,GAG1B,OAAO;EACN,QAAQM,EAAME,EAAO,MAAMN,EAAW,QAAQA,EAAW,cAAcA,EAAW,GAAG,CAAC;EACtF;EACA;CACD;AACD;;AAGA,SAAS,qBAAqB,GAAkC;CAC/D,QAAQjE,EAAK,MAAb;EACC,KAAK,OACJ,OAAO,OAAOA,EAAK;EACpB,KAAK,SACJ,OAAO,SAASA,EAAK;EACtB,KAAK,OACJ,OAAO,OAAOA,EAAK;EACpB,KAAK,MACJ,OAAO,MAAMoF,EAAgBpF,EAAK,YAAY;EAC/C,KAAK,iBACJ,OAAO,MAAMA,EAAK,OAAO,MAAM,GAAG,EAAE,IAAIA,EAAK,OAAO,SAAS,KAAK,QAAQ;EAC3E,KAAK,OACJ,OAAO,OAAOA,EAAK;EACpB,SAEC,MAAU,MAAM,sCAAsC,OAAOrB,CAAU,GAAG;CAE5E;AACD"}
|
|
1
|
+
{"version":3,"file":"name-constraints-engine.js","names":["exhaustive","_exhaustive","DECODE_REFUSAL_CODES","childrenOf","decodeObjectIdentifier","decodeString","hexToBytes","requireElement","toHex","decodeRefusalOf","rethrowDecodeRefusal","readRootElement","OIDS","compareDistinguishedNames","directoryNameSubtreeMatch","domainToAscii","allOnesMaskForIpAddress","decodeIpAddress","parseIpAddressToBytes","isMailboxDomain","presentedSmtpUtf8MailboxDomain","uriAuthorityHost","parsePresentedSrvName","parseSrvNameRestriction","parseUriNameConstraint","nameFieldKeyFromOid","code","message","index","details","input","certificate","subtree","chain","state","accumulated","root","current","nameCheckResult","entry","constraints","critical","permittedLevels","excluded","unsupported","form","subjectResult","sanResult","error","refusal","san","result","unsupportedForm","checkableResult","checkable","mailbox","domain","constraint","level","type","value","label","host","constraintDomain","letter","c","typeId","tag","name","relevant","presented","restriction","lowerName","lowerConstraint","nameAt","constraintAt","atIndex","uri","parsed","nameBytes","constraintAddr","constraintMask","i","nameByte","addrByte","maskByte","subjectDerHex","constraintDerHex","subjectName","constraintName","derHex","bytes","element","rdns","attributes","values","setElement","rdn","attribute","source","children","child","attributeSequence","parts","oidElement","valueElement","oid","fieldValue","fieldKey"],"sources":["../../../src/internal/verify/name-constraints-engine.ts"],"sourcesContent":["/**\n * Internal name-constraints evaluation engine.\n *\n * Accumulates and evaluates the shipped RFC 5280\n * [§4.2.1.10](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.10) / [§6.1](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1)\n * name-constraint subset during certificate path validation.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\thexToBytes,\n\trequireElement,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDECODE_REFUSAL_CODES,\n\tdecodeRefusalOf,\n\trethrowDecodeRefusal,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport { DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { NameMatch } from '#micro509/internal/shared/dn';\nimport { compareDistinguishedNames, directoryNameSubtreeMatch } from '#micro509/internal/shared/dn';\nimport { domainToAscii } from '#micro509/internal/shared/idna';\nimport {\n\tallOnesMaskForIpAddress,\n\tdecodeIpAddress,\n\tparseIpAddressToBytes,\n} from '#micro509/internal/shared/ip';\nimport { isMailboxDomain, presentedSmtpUtf8MailboxDomain } from '#micro509/internal/shared/mailbox';\nimport { uriAuthorityHost } from '#micro509/internal/shared/uri-host';\nimport {\n\tparsePresentedSrvName,\n\tparseSrvNameRestriction,\n\tparseUriNameConstraint,\n} from '#micro509/internal/x509/general-name-profile';\nimport type { DecodeRefusalCode, Micro509Error } from '#micro509/result/result';\nimport type { InitialNameConstraintsInput } from '#micro509/verify/name-constraints';\nimport type {\n\tNameConstraintForm,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tSubjectAltName,\n\tUnsupportedNameConstraintForm,\n} from '#micro509/x509/extensions';\nimport { nameFieldKeyFromOid } from '#micro509/x509/name';\nimport type {\n\tNameFieldKey,\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\n\n/**\n * Opaque state seeded from {@linkcode InitialNameConstraintsInput} and consumed\n * by {@linkcode evaluateNameConstraints}.\n */\nexport interface NameConstraintValidationState {\n\t/** Caller-supplied permitted subtree bases (pre-chain). */\n\treadonly initialPermittedSubtrees: readonly NameConstraintForm[];\n\t/** Caller-supplied excluded subtree bases (pre-chain). */\n\treadonly initialExcludedSubtrees: readonly NameConstraintForm[];\n}\n\n/** Discriminant codes for name-constraint validation failures. */\nexport type NameConstraintValidationFailureCode =\n\t| 'name_constraints_violated'\n\t| 'unsupported_name_constraints'\n\t| DecodeRefusalCode;\n\n/** Diagnostic context attached to a name-constraint validation failure. */\nexport interface NameConstraintValidationFailureDetails {\n\t/** CN of the certificate whose name violated constraints, if available. */\n\treadonly subjectCommonName?: string;\n\t/** The name or constraint-type string that caused the violation. */\n\treadonly actual?: string;\n}\n\n/** A name-constraint check that failed, with the offending certificate's chain index. */\nexport interface NameConstraintValidationFailure\n\textends Micro509Error<\n\t\tNameConstraintValidationFailureCode,\n\t\tNameConstraintValidationFailureDetails\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n\t/** Zero-based index into the chain of the certificate that violated constraints. */\n\treadonly index: number;\n}\n\n/** Success or failure outcome of name-constraint evaluation across a chain. */\nexport type NameConstraintValidationResult =\n\t| {\n\t\t\t/** All names in the chain satisfy accumulated constraints. */\n\t\t\treadonly ok: true;\n\t }\n\t| NameConstraintValidationFailure;\n\n/** Builder input for assembling optional failure detail fields. */\ninterface NameConstraintValidationFailureDetailsInput {\n\treadonly subjectCommonName?: string | undefined;\n\treadonly actual?: string | undefined;\n}\n\ntype SubjectAltNameCheckableResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value: NameConstraintForm | undefined;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly actual: string;\n\t };\n\n/** Constructs a {@linkcode NameConstraintValidationFailure} with optional details. */\nfunction nameConstraintFailure(\n\tcode: NameConstraintValidationFailureCode,\n\tmessage: string,\n\tindex: number,\n\tdetails?: NameConstraintValidationFailureDetails,\n): NameConstraintValidationFailure {\n\treturn {\n\t\tok: false,\n\t\tcode,\n\t\tmessage,\n\t\tindex,\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Strips undefined fields and returns `undefined` when all fields are empty. */\nfunction nameConstraintDetails(\n\tinput: NameConstraintValidationFailureDetailsInput,\n): NameConstraintValidationFailureDetails | undefined {\n\tconst details: NameConstraintValidationFailureDetails = {\n\t\t...(input.subjectCommonName === undefined\n\t\t\t? {}\n\t\t\t: { subjectCommonName: input.subjectCommonName }),\n\t\t...(input.actual === undefined ? {} : { actual: input.actual }),\n\t};\n\treturn Object.keys(details).length === 0 ? undefined : details;\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\n/**\n * Initializes validation state from caller-supplied initial constraints.\n *\n * Call once before {@linkcode evaluateNameConstraints}.\n */\nexport function createNameConstraintValidationState(\n\tinput: InitialNameConstraintsInput,\n): NameConstraintValidationState {\n\treturn {\n\t\tinitialPermittedSubtrees: input.permittedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t\tinitialExcludedSubtrees: input.excludedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t};\n}\n\n// Private: name constraint validation (RFC 5280 §4.2.1.10 / §6.1)\n\n/** Empty SEQUENCE DER hex — represents an empty subject DN. */\nconst EMPTY_SEQUENCE_HEX = '3000';\n\n/**\n * Accumulated name constraint state during root-to-leaf traversal.\n * - `permittedLevels`: each entry is one CA's permittedSubtrees. A name\n * must match at least one entry in *every* level (intersection semantics).\n * - `excluded`: flat list; a name must NOT match *any* entry.\n */\ninterface AccumulatedNameConstraints {\n\t/** One entry per CA that asserted permittedSubtrees; intersection semantics. */\n\treadonly permittedLevels: readonly (readonly NameConstraintForm[])[];\n\t/** Flat union of all excludedSubtrees seen so far. */\n\treadonly excluded: readonly NameConstraintForm[];\n\t/**\n\t * Name forms this engine cannot evaluate that were imposed by a\n\t * **critical** nameConstraints extension above. RFC 5280 §4.2.1.10:\n\t * a subsequent certificate carrying a name of such a form MUST be\n\t * rejected; certificates without one stay acceptable.\n\t */\n\treadonly unsupportedCriticalForms: ReadonlySet<UnsupportedDirectForm>;\n\t/** Type-ids of otherName forms imposed the same way; X.509 §9.4.2.2 makes each a distinct form. */\n\treadonly unsupportedCriticalOtherNames: ReadonlySet<string>;\n}\n\ntype UnsupportedDirectForm = Exclude<UnsupportedNameConstraintForm['type'], 'otherName'>;\n\n/**\n * Walks the chain root-to-leaf, accumulating nameConstraints from CA\n * certificates and checking each non-self-issued certificate's names\n * against the accumulated constraints.\n *\n * RFC 5280 §6.1.3(b)-(c) for name checks, §6.1.4(g) for constraint accumulation.\n */\n\nexport function evaluateNameConstraints(\n\tchain: readonly ParsedCertificate[],\n\tstate: NameConstraintValidationState,\n): NameConstraintValidationResult {\n\tlet accumulated = seedInitialNameConstraints(state);\n\n\t// Seed constraints from the root (trust anchor). The root's own\n\t// names are not checked, but its nameConstraints apply to all\n\t// certificates below it in the chain.\n\tconst root = chain[chain.length - 1];\n\tif (root?.nameConstraints !== undefined) {\n\t\taccumulated = accumulateConstraints(\n\t\t\taccumulated,\n\t\t\troot.nameConstraints,\n\t\t\thasCriticalNameConstraintsExtension(root),\n\t\t);\n\t}\n\n\t// Walk from just below root toward leaf.\n\tfor (let index = chain.length - 2; index >= 0; index -= 1) {\n\t\tconst current = chain[index];\n\t\tif (current === undefined) {\n\t\t\tthrow new Error(`Certificate chain contains undefined at index ${String(index)}`);\n\t\t}\n\n\t\t// RFC 5280 §6.1.3(b)-(c): check names against accumulated permitted (b)\n\t\t// and excluded (c) constraints. §4.2.1.10 exempts self-issued\n\t\t// certificates unless the certificate is the leaf.\n\t\tif (!isSelfIssued(current) || index === 0) {\n\t\t\tconst nameCheckResult = checkCertificateNames(current, accumulated, index);\n\t\t\tif (!nameCheckResult.ok) {\n\t\t\t\treturn nameCheckResult;\n\t\t\t}\n\t\t}\n\n\t\t// RFC 5280 §6.1.4(g): accumulate this certificate's nameConstraints,\n\t\t// intersecting permitted subtrees and unioning excluded subtrees.\n\t\tif (current.nameConstraints !== undefined) {\n\t\t\taccumulated = accumulateConstraints(\n\t\t\t\taccumulated,\n\t\t\t\tcurrent.nameConstraints,\n\t\t\t\thasCriticalNameConstraintsExtension(current),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when the certificate carries a critical nameConstraints extension. */\nfunction hasCriticalNameConstraintsExtension(certificate: ParsedCertificate): boolean {\n\treturn certificate.extensions.some(\n\t\t(entry) => entry.oid === OIDS.nameConstraints && entry.critical,\n\t);\n}\n\n/** Converts initial state into the starting accumulated-constraints snapshot. */\nfunction seedInitialNameConstraints(\n\tstate: NameConstraintValidationState,\n): AccumulatedNameConstraints {\n\treturn {\n\t\tpermittedLevels:\n\t\t\tstate.initialPermittedSubtrees.length > 0 ? [state.initialPermittedSubtrees] : [],\n\t\texcluded: state.initialExcludedSubtrees,\n\t\tunsupportedCriticalForms: new Set(),\n\t\tunsupportedCriticalOtherNames: new Set(),\n\t};\n}\n\n/**\n * Merges one certificate's nameConstraints extension into the running totals.\n *\n * Unsupported constraint forms from a critical extension are recorded so\n * subsequent certificates carrying a name of that form fail closed\n * (RFC 5280 §4.2.1.10). Unsupported forms in a non-critical extension are\n * dropped — the RFC's rejection requirement is scoped to critical\n * extensions (conforming CAs MUST mark nameConstraints critical anyway).\n */\nfunction accumulateConstraints(\n\tcurrent: AccumulatedNameConstraints,\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n\tcritical: boolean,\n): AccumulatedNameConstraints {\n\tconst permittedLevels =\n\t\tconstraints.permittedSubtrees !== undefined && constraints.permittedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.permittedLevels,\n\t\t\t\t\tconstraints.permittedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.permittedLevels;\n\tconst excluded =\n\t\tconstraints.excludedSubtrees !== undefined && constraints.excludedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.excluded,\n\t\t\t\t\t...constraints.excludedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.excluded;\n\tconst unsupported = critical ? listUnsupportedNameConstraintForms(constraints) : [];\n\treturn {\n\t\tpermittedLevels,\n\t\texcluded,\n\t\tunsupportedCriticalForms: new Set([\n\t\t\t...current.unsupportedCriticalForms,\n\t\t\t...unsupported.flatMap((form) => (form.type === 'otherName' ? [] : [form.type])),\n\t\t]),\n\t\tunsupportedCriticalOtherNames: new Set([\n\t\t\t...current.unsupportedCriticalOtherNames,\n\t\t\t...unsupported.flatMap((form) => (form.type === 'otherName' ? [form.typeId] : [])),\n\t\t]),\n\t};\n}\n\n/** Collects the unsupported GeneralName forms from a nameConstraints extension. */\nfunction listUnsupportedNameConstraintForms(\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n): readonly UnsupportedNameConstraintForm[] {\n\treturn [\n\t\t...(constraints.permittedSubtrees ?? []),\n\t\t...(constraints.excludedSubtrees ?? []),\n\t].flatMap((subtree) => (isSupportedNameConstraintForm(subtree.base) ? [] : [subtree.base]));\n}\n\n/** True for name forms this engine can evaluate: dns, email, uri, ip, directoryName, srv. */\nfunction isSupportedNameConstraintForm(form: ParsedNameConstraintForm): form is NameConstraintForm {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\tcase 'email':\n\t\tcase 'uri':\n\t\tcase 'ip':\n\t\tcase 'directoryName':\n\t\tcase 'srv':\n\t\t\treturn true;\n\t\tcase 'otherName':\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn false;\n\t\tdefault: {\n\t\t\tconst exhaustive: never = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks a certificate's subject DN and SANs against accumulated\n * name constraints. Returns a failure if any name violates constraints.\n */\nfunction checkCertificateNames(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\ttry {\n\t\tconst subjectResult = checkCertificateSubjectName(certificate, accumulated, index);\n\t\tif (!subjectResult.ok) return subjectResult;\n\t\tconst sanResult = checkCertificateSubjectAltNames(certificate, accumulated, index);\n\t\tif (!sanResult.ok) return sanResult;\n\t\treturn checkCertificateSubjectEmailFallback(certificate, accumulated, index);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\tif (refusal === undefined) throw error;\n\t\treturn nameConstraintFailure(\n\t\t\trefusal.code,\n\t\t\trefusal.message,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: refusal.message,\n\t\t\t}),\n\t\t);\n\t}\n}\n\n/** Checks a certificate subject DN against the accumulated directory-name constraints. */\nfunction checkCertificateSubjectName(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\tif (certificate.subject.derHex === EMPTY_SEQUENCE_HEX) return { ok: true };\n\tconst dnResult = isNamePermitted(\n\t\t{ type: 'directoryName', derHex: certificate.subject.derHex },\n\t\taccumulated,\n\t);\n\treturn dnResult\n\t\t? { ok: true }\n\t\t: nameConstraintFailure(\n\t\t\t\t'name_constraints_violated',\n\t\t\t\t'subject distinguished name violates name constraints',\n\t\t\t\tindex,\n\t\t\t\tnameConstraintDetails({ subjectCommonName: certificate.subject.values.commonName }),\n\t\t\t);\n}\n\nfunction checkCertificateSubjectAltNames(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\tfor (const san of certificate.subjectAltNames ?? []) {\n\t\tconst result = checkCertificateSubjectAltName(certificate, accumulated, san, index);\n\t\tif (!result.ok) return result;\n\t}\n\treturn { ok: true };\n}\n\nfunction checkCertificateSubjectAltName(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tsan: SubjectAltName,\n\tindex: number,\n): NameConstraintValidationResult {\n\tconst unsupportedForm = unprocessableConstraintFormOf(san, accumulated);\n\tif (unsupportedForm !== undefined) {\n\t\treturn nameConstraintFailure(\n\t\t\t'unsupported_name_constraints',\n\t\t\t`critical name constraints impose ${unsupportedForm} constraints that cannot be processed, and the certificate contains a ${unsupportedForm} subject alternative name`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: unsupportedForm,\n\t\t\t}),\n\t\t);\n\t}\n\tif (san.type === 'smtpUtf8Mailbox') {\n\t\treturn checkSmtpUtf8Mailbox(certificate, accumulated, san.value, index);\n\t}\n\tconst checkableResult = sanToConstraintCheckable(san);\n\tif (!checkableResult.ok) {\n\t\treturn nameConstraintFailure(\n\t\t\t'name_constraints_violated',\n\t\t\t`SAN ${checkableResult.actual} is malformed and cannot be checked against name constraints`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: checkableResult.actual,\n\t\t\t}),\n\t\t);\n\t}\n\tconst checkable = checkableResult.value;\n\tif (\n\t\tcheckable?.type === 'srv' &&\n\t\taccumulatedHasConstraintsOfType('srv', accumulated) &&\n\t\tparsePresentedSrvName(asciiLowercase(checkable.value)) === undefined\n\t) {\n\t\treturn nameConstraintFailure(\n\t\t\t'name_constraints_violated',\n\t\t\t`SAN srv:${checkable.value} is not _Service.Name and cannot be evaluated against SRVName constraints`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: `srv:${checkable.value}`,\n\t\t\t}),\n\t\t);\n\t}\n\tif (\n\t\tcheckable?.type === 'uri' &&\n\t\taccumulatedHasConstraintsOfType('uri', accumulated) &&\n\t\turiConstraintHost(checkable.value) === undefined\n\t) {\n\t\treturn nameConstraintFailure(\n\t\t\t'name_constraints_violated',\n\t\t\t`SAN uri:${checkable.value} has no FQDN authority host and cannot be evaluated against URI name constraints`,\n\t\t\tindex,\n\t\t\tnameConstraintDetails({\n\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\tactual: `uri:${checkable.value}`,\n\t\t\t}),\n\t\t);\n\t}\n\tif (checkable === undefined || isNamePermitted(checkable, accumulated)) return { ok: true };\n\treturn nameConstraintFailure(\n\t\t'name_constraints_violated',\n\t\t`SAN ${formatConstraintForm(checkable)} violates name constraints`,\n\t\tindex,\n\t\tnameConstraintDetails({\n\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\tactual: formatConstraintForm(checkable),\n\t\t}),\n\t);\n}\n\n/**\n * RFC 9598 §6 applies rfc822Name constraints to a SmtpUTF8Mailbox by its domain\n * alone: the Local-part and \"@\" are stripped from the name and the constraint,\n * and the remaining domains compare octet for octet after lowercasing, as a\n * suffix when the constraint starts with \".\". A mailbox that breaks the §3\n * syntax cannot be compared, so it fails whenever rfc822Name constraints are\n * in force.\n */\nfunction checkSmtpUtf8Mailbox(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tmailbox: string,\n\tindex: number,\n): NameConstraintValidationResult {\n\tconst permitted = accumulatedHasEmailConstraints(accumulated)\n\t\t? isSmtpUtf8MailboxDomainPermitted(mailbox, accumulated)\n\t\t: true;\n\tif (permitted) return { ok: true };\n\treturn nameConstraintFailure(\n\t\t'name_constraints_violated',\n\t\t`SAN smtpUtf8Mailbox:${mailbox} violates name constraints`,\n\t\tindex,\n\t\tnameConstraintDetails({\n\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\tactual: `smtpUtf8Mailbox:${mailbox}`,\n\t\t}),\n\t);\n}\n\n/** RFC 9598 §5: a presented SmtpUTF8Mailbox whose domain the email constraints permit. */\nfunction isSmtpUtf8MailboxDomainPermitted(\n\tmailbox: string,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\tconst domain = presentedSmtpUtf8MailboxDomain(mailbox);\n\treturn domain !== undefined && isMailboxDomainPermitted(domain, accumulated);\n}\n\nfunction isMailboxDomainPermitted(\n\tdomain: string,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\tif (hasMalformedConstraint('email', accumulated)) return false;\n\tconst matches = (constraint: NameConstraintForm): boolean =>\n\t\tconstraint.type === 'email' && matchesMailboxDomainConstraint(domain, constraint.value);\n\tif (accumulated.excluded.some(matches)) return false;\n\treturn accumulated.permittedLevels.every(\n\t\t(level) => !level.some((constraint) => constraint.type === 'email') || level.some(matches),\n\t);\n}\n\n/**\n * A dNSName or rfc822Name constraint whose domain is not a well-formed name\n * cannot be compared, so no name of its type is permitted while one is in force.\n */\nfunction hasMalformedConstraint(\n\ttype: NameConstraintForm['type'],\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\treturn [...accumulated.excluded, ...accumulated.permittedLevels.flat()].some(\n\t\t(constraint) => constraint.type === type && !isWellFormedConstraint(constraint),\n\t);\n}\n\nfunction isWellFormedConstraint(constraint: NameConstraintForm): boolean {\n\tswitch (constraint.type) {\n\t\tcase 'dns': {\n\t\t\tconst value = asciiLowercase(constraint.value);\n\t\t\treturn (\n\t\t\t\tvalue.length === 0 || isComparableDomain(value.startsWith('.') ? value.slice(1) : value)\n\t\t\t);\n\t\t}\n\t\tcase 'email':\n\t\t\treturn constraintMailboxDomain(constraint.value) !== undefined;\n\t\tcase 'srv':\n\t\t\treturn parseSrvNameRestriction(asciiLowercase(constraint.value)) !== undefined;\n\t\tcase 'directoryName':\n\t\t\treturn parseDirectoryNameDerHex(constraint.derHex) !== undefined;\n\t\tcase 'uri':\n\t\t\treturn parseUriNameConstraint(constraint.value) !== undefined;\n\t\tcase 'ip':\n\t\t\treturn true;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = constraint;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Labels of 1 to 63 letters, digits, hyphens or underscores, with each `xn--` label an A-label. */\nfunction isComparableDomain(domain: string): boolean {\n\treturn (\n\t\tdomain.length <= 253 &&\n\t\tdomain.split('.').every((label) => /^[a-z0-9_-]{1,63}$/.test(label)) &&\n\t\tdomainToAscii(domain, 'lookup').ok\n\t);\n}\n\n/** RFC 9598 §6: the lowercased domain of an rfc822Name constraint, keeping a leading \".\". */\nfunction constraintMailboxDomain(constraint: string): string | undefined {\n\tconst domain = asciiLowercase(constraint.slice(constraint.lastIndexOf('@') + 1));\n\tconst host = domain.startsWith('.') ? domain.slice(1) : domain;\n\treturn isMailboxDomain(host, 'lookup') ? domain : undefined;\n}\n\nfunction matchesMailboxDomainConstraint(domain: string, constraint: string): boolean {\n\tconst constraintDomain = constraintMailboxDomain(constraint);\n\treturn constraintDomain?.startsWith('.') === true\n\t\t? domain.endsWith(constraintDomain)\n\t\t: domain === constraintDomain;\n}\n\nfunction asciiLowercase(value: string): string {\n\treturn value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());\n}\n\nfunction checkCertificateSubjectEmailFallback(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\t// RFC 5280 §4.2.1.10 applies rfc822Name constraints to the subject DN\n\t// emailAddress when the certificate has no subjectAltName extension. This\n\t// implementation applies it whenever the SAN carries no rfc822Name.\n\tconst hasEmailConstraints = accumulatedHasEmailConstraints(accumulated);\n\tif (hasEmailConstraints) {\n\t\tconst hasSanEmail = certificate.subjectAltNames?.some((san) => san.type === 'email') ?? false;\n\t\tif (!hasSanEmail && certificate.subject.values.emailAddress !== undefined) {\n\t\t\tconst emailForm: NameConstraintForm = {\n\t\t\t\ttype: 'email',\n\t\t\t\tvalue: certificate.subject.values.emailAddress,\n\t\t\t};\n\t\t\tif (!isNamePermitted(emailForm, accumulated)) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`subject emailAddress ${certificate.subject.values.emailAddress} violates name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: certificate.subject.values.emailAddress,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when any level of accumulated constraints addresses the email name form. */\nfunction accumulatedHasEmailConstraints(accumulated: AccumulatedNameConstraints): boolean {\n\tfor (const level of accumulated.permittedLevels) {\n\t\tif (level.some((c) => c.type === 'email')) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn accumulated.excluded.some((c) => c.type === 'email');\n}\n\n/** True when any level of accumulated constraints addresses the given name form. */\nfunction accumulatedHasConstraintsOfType(\n\ttype: NameConstraintForm['type'],\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\treturn [...accumulated.excluded, ...accumulated.permittedLevels.flat()].some(\n\t\t(constraint) => constraint.type === type,\n\t);\n}\n\n/**\n * The unprocessable critical constraint form a SAN instantiates, if one is in\n * force. An otherName is its own form per type-id. Raw `unknown` input carries\n * the DER tag byte, and an unknown otherName meets every otherName type-id.\n */\nfunction unprocessableConstraintFormOf(\n\tsan: SubjectAltName,\n\taccumulated: AccumulatedNameConstraints,\n): string | undefined {\n\tconst otherName = (typeId: string): string | undefined =>\n\t\taccumulated.unsupportedCriticalOtherNames.has(typeId) ? `otherName ${typeId}` : undefined;\n\tconst direct = (form: UnsupportedDirectForm): string | undefined =>\n\t\taccumulated.unsupportedCriticalForms.has(form) ? form : undefined;\n\tswitch (san.type) {\n\t\tcase 'otherName':\n\t\t\treturn otherName(san.typeId);\n\t\tcase 'smtpUtf8Mailbox':\n\t\t\treturn otherName(OIDS.idOnSmtpUtf8Mailbox);\n\t\tcase 'upn':\n\t\t\treturn otherName(OIDS.ntPrincipalName);\n\t\tcase 'krb5PrincipalName':\n\t\t\treturn otherName(OIDS.idPkinitSan);\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn direct(san.type);\n\t\tcase 'unknown':\n\t\t\treturn unknownTagForm(san.tag, accumulated);\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction unknownTagForm(tag: number, accumulated: AccumulatedNameConstraints): string | undefined {\n\tlet form: UnsupportedDirectForm;\n\n\tswitch (tag) {\n\t\tcase 0xa3:\n\t\t\tform = 'x400Address';\n\t\t\tbreak;\n\t\tcase 0xa5:\n\t\t\tform = 'ediPartyName';\n\t\t\tbreak;\n\t\tcase 0x88:\n\t\t\tform = 'registeredID';\n\t\t\tbreak;\n\t\tcase 0xa0:\n\t\t\treturn accumulated.unsupportedCriticalOtherNames.size > 0 ? 'otherName' : undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n\n\treturn accumulated.unsupportedCriticalForms.has(form) ? form : undefined;\n}\n\n/**\n * Converts a SubjectAltName to a NameConstraintForm for checking.\n * Returns `undefined` for name forms that don't participate in\n * constraint checking (unknown tags).\n */\nfunction sanToConstraintCheckable(san: SubjectAltName): SubjectAltNameCheckableResult {\n\tswitch (san.type) {\n\t\tcase 'dns':\n\t\t\treturn { ok: true, value: { type: 'dns', value: san.value } };\n\t\tcase 'email':\n\t\t\treturn { ok: true, value: { type: 'email', value: san.value } };\n\t\tcase 'uri':\n\t\t\treturn { ok: true, value: { type: 'uri', value: san.value } };\n\t\tcase 'srv':\n\t\t\treturn { ok: true, value: { type: 'srv', value: san.value } };\n\t\tcase 'smtpUtf8Mailbox':\n\t\tcase 'upn':\n\t\tcase 'krb5PrincipalName':\n\t\tcase 'otherName':\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn { ok: true, value: undefined };\n\t\tcase 'ip':\n\t\t\ttry {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\ttype: 'ip',\n\t\t\t\t\t\taddressBytes: parseIpAddressToBytes(san.value),\n\t\t\t\t\t\tmaskBytes: allOnesMaskForIpAddress(san.value),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tactual: `ip:${san.value}`,\n\t\t\t\t};\n\t\t\t}\n\t\tcase 'directoryName':\n\t\t\treturn { ok: true, value: { type: 'directoryName', derHex: san.derHex } };\n\t\tcase 'unknown':\n\t\t\treturn { ok: true, value: undefined };\n\t\tdefault: {\n\t\t\tconst exhaustive: never = san;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks whether a name is permitted by the accumulated constraints.\n * A name is permitted if:\n * 1. It does NOT match any excluded constraint, AND\n * 2. For every permitted level that contains constraints of the same\n * name form, it matches at least one.\n */\nfunction isNamePermitted(\n\tname: NameConstraintForm,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\tif (\n\t\thasMalformedConstraint(name.type, accumulated) ||\n\t\t(endsInRootDot(name) && accumulatedHasConstraintsOfType(name.type, accumulated))\n\t) {\n\t\treturn false;\n\t}\n\t// Check excluded — if any match, reject.\n\tfor (const constraint of accumulated.excluded) {\n\t\tif (nameConstraintMatch(name, constraint) !== 'mismatch') {\n\t\t\treturn false;\n\t\t}\n\t}\n\t// Check permitted — for each level with relevant constraints,\n\t// the name must match at least one.\n\tfor (const level of accumulated.permittedLevels) {\n\t\tconst relevant = level.filter((constraint) => constraint.type === name.type);\n\t\tif (relevant.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!relevant.some((constraint) => nameConstraintMatch(name, constraint) === 'match')) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** RFC 5280 §4.2.1.6: a dNSName or rfc822Name host in RFC 1034 §3.5 preferred name syntax has no trailing root dot. */\nfunction endsInRootDot(name: NameConstraintForm): boolean {\n\treturn (name.type === 'dns' || name.type === 'email') && name.value.endsWith('.');\n}\n\n/** RFC 4518 §2: a comparison that string preparation cannot perform is Undefined. */\nfunction nameConstraintMatch(name: NameConstraintForm, constraint: NameConstraintForm): NameMatch {\n\tif (name.type === 'directoryName' && constraint.type === 'directoryName') {\n\t\treturn matchesDnConstraint(name.derHex, constraint.derHex);\n\t}\n\treturn nameMatchesConstraint(name, constraint) ? 'match' : 'mismatch';\n}\n\n/** Dispatches to the type-specific matching function for the name form. */\nfunction nameMatchesConstraint(name: NameConstraintForm, constraint: NameConstraintForm): boolean {\n\tif (name.type === 'dns' && constraint.type === 'dns') {\n\t\treturn matchesDnsConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'email' && constraint.type === 'email') {\n\t\treturn matchesEmailConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'uri' && constraint.type === 'uri') {\n\t\treturn matchesUriConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'ip' && constraint.type === 'ip') {\n\t\treturn matchesIpConstraint(name.addressBytes, constraint.addressBytes, constraint.maskBytes);\n\t}\n\tif (name.type === 'srv' && constraint.type === 'srv') {\n\t\treturn matchesSrvConstraint(name.value, constraint.value);\n\t}\n\treturn false;\n}\n\n/**\n * RFC 4985 §4: a restriction's service, when present, must equal the SRVName's\n * service case-insensitively (§2), and its Name, when present, is satisfied by\n * that domain or any subdomain added to the left.\n */\nfunction matchesSrvConstraint(name: string, constraint: string): boolean {\n\tconst presented = parsePresentedSrvName(asciiLowercase(name));\n\tconst restriction = parseSrvNameRestriction(asciiLowercase(constraint));\n\treturn (\n\t\tpresented !== undefined &&\n\t\trestriction !== undefined &&\n\t\t(restriction.service.length === 0 || presented.service === restriction.service) &&\n\t\t(restriction.name.length === 0 ||\n\t\t\tpresented.name === restriction.name ||\n\t\t\tpresented.name.endsWith(`.${restriction.name}`))\n\t);\n}\n\n/**\n * DNS name constraint matching. RFC 5280 §4.2.1.10 adds zero or more labels on\n * the left; §7.2 compares label by label case-insensitively. Constraint\n * \"example.com\" matches \"example.com\" and any subdomain. RFC 5280 defines no\n * leading-period dNSName form; \".example.com\" matches subdomains only, as in\n * OpenSSL, BoringSSL, Go, NSS, mozilla::pkix and rustls-webpki (RFC 5280\n * erratum 5997).\n */\nfunction matchesDnsConstraint(name: string, constraint: string): boolean {\n\tconst lowerName = name.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.length === 0) {\n\t\treturn true;\n\t}\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn lowerName.endsWith(lowerConstraint);\n\t}\n\treturn lowerName === lowerConstraint || lowerName.endsWith(`.${lowerConstraint}`);\n}\n\n/**\n * RFC 5280 §4.2.1.10 email constraint matching, deferring to §7.5 (as\n * replaced by RFC 9549 §7.5.1): the local part matches exactly, the host part\n * case-insensitively.\n * - \"user@example.com\" constrains the local part exactly and the host case-insensitively.\n * - \"example.com\" matches any address whose host is example.com.\n * - \".example.com\" matches any address under a subdomain of example.com.\n */\nfunction matchesEmailConstraint(name: string, constraint: string): boolean {\n\tif (constraint.includes('@')) {\n\t\tconst nameAt = name.lastIndexOf('@');\n\t\tconst constraintAt = constraint.lastIndexOf('@');\n\t\tif (nameAt < 0 || constraintAt < 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif (name.slice(0, nameAt) !== constraint.slice(0, constraintAt)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (\n\t\t\tname.slice(nameAt + 1).toLowerCase() === constraint.slice(constraintAt + 1).toLowerCase()\n\t\t);\n\t}\n\tconst atIndex = name.lastIndexOf('@');\n\tif (atIndex < 0) {\n\t\treturn false;\n\t}\n\tconst host = name.slice(atIndex + 1).toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn host.endsWith(lowerConstraint);\n\t}\n\treturn host === lowerConstraint;\n}\n\n/**\n * RFC 5280 §4.2.1.10: a URI constraint applies to the host part, a constraint\n * without a leading period names one host, and \".example.com\" is satisfied by\n * its subdomains only.\n */\nfunction matchesUriConstraint(uri: string, constraint: string): boolean {\n\tconst host = uriConstraintHost(uri);\n\tconst parsed = parseUriNameConstraint(constraint);\n\tif (host === undefined || parsed === undefined) {\n\t\treturn false;\n\t}\n\tswitch (parsed.type) {\n\t\tcase 'any':\n\t\t\treturn true;\n\t\tcase 'host':\n\t\t\treturn host === parsed.name;\n\t\tcase 'subdomains':\n\t\t\treturn host.endsWith(`.${parsed.name}`);\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = parsed;\n\t\t\tthrow new Error(`Unhandled UriNameConstraint type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * RFC 5280 §4.2.1.10: the domain name of a URI's authority host, which a URI\n * constraint in force requires. `undefined` for no authority, an IP address, a\n * reg-name that is not a domain name, or a single-label host.\n */\nfunction uriConstraintHost(uri: string): string | undefined {\n\tconst host = uriAuthorityHost(uri, 'presented');\n\treturn host.type === 'dns' && host.name.includes('.') ? host.name : undefined;\n}\n\n/**\n * RFC 5280 §4.2.1.10: IP constraint matching.\n * (nameiP & mask) == (constraintiP & mask)\n */\nfunction matchesIpConstraint(\n\tnameBytes: Uint8Array,\n\tconstraintAddr: Uint8Array,\n\tconstraintMask: Uint8Array,\n): boolean {\n\tif (nameBytes.length !== constraintAddr.length) {\n\t\treturn false;\n\t}\n\tfor (let i = 0; i < nameBytes.length; i += 1) {\n\t\tconst nameByte = nameBytes[i] ?? 0;\n\t\tconst addrByte = constraintAddr[i] ?? 0;\n\t\tconst maskByte = constraintMask[i] ?? 0;\n\t\tif ((nameByte & maskByte) !== (addrByte & maskByte)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * RFC 5280 §4.2.1.10: DirectoryName constraint matching.\n * The subject DN must equal or be subordinate to the constraint DN,\n * using RFC 5280 section 7.1 name comparison semantics.\n */\nfunction matchesDnConstraint(subjectDerHex: string, constraintDerHex: string): NameMatch {\n\tconst subjectName = parseDirectoryNameDerHex(subjectDerHex);\n\tconst constraintName = parseDirectoryNameDerHex(constraintDerHex);\n\tif (subjectName === undefined || constraintName === undefined) {\n\t\treturn 'mismatch';\n\t}\n\treturn directoryNameSubtreeMatch(subjectName, constraintName);\n}\n\n/** Re-parses a hex-encoded DER Name for RDN-by-RDN comparison. Returns `undefined` on malformed input. */\nfunction parseDirectoryNameDerHex(derHex: string): ParsedName | undefined {\n\tif (!/^(?:[0-9a-fA-F]{2})+$/.test(derHex)) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\tconst bytes = hexToBytes(derHex);\n\t\tconst root = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tconst element = unwrapDirectoryNameElement(bytes, root);\n\t\tif (element.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\t\tconst attributes: ParsedNameAttribute[] = [];\n\t\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\t\tfor (const setElement of childrenOf(bytes, element)) {\n\t\t\tconst rdn = parseDirectoryNameRdn(bytes, setElement);\n\t\t\tif (rdn === undefined) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\trdns.push(rdn);\n\t\t\tfor (const attribute of rdn.attributes) {\n\t\t\t\tattributes.push(attribute);\n\t\t\t\tif (attribute.key !== undefined && values[attribute.key] === undefined) {\n\t\t\t\t\tvalues[attribute.key] = attribute.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tderHex: toHex(bytes),\n\t\t\trdns,\n\t\t\tattributes,\n\t\t\tvalues,\n\t\t};\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Unwraps doubly-nested directoryName SEQUENCE encoding.\n *\n * Some encoders produce `[4] { SEQ { SEQ { SET... } } }` instead of `[4] { SEQ { SET... } }`.\n * A single SEQUENCE child indicates the extra wrapper (valid Names have SET children).\n */\nfunction unwrapDirectoryNameElement(source: Uint8Array, element: DerElement): DerElement {\n\tif (element.tag !== 0x30) {\n\t\treturn element;\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length === 1 && child?.tag === 0x30) {\n\t\treturn child;\n\t}\n\treturn element;\n}\n\n/** Parses one SET element (a single RDN) from the DER Name SEQUENCE. */\nfunction parseDirectoryNameRdn(\n\tsource: Uint8Array,\n\tsetElement: DerElement,\n): ParsedRelativeDistinguishedName | undefined {\n\tif (setElement.tag !== 0x31) {\n\t\treturn undefined;\n\t}\n\tconst children = childrenOf(source, setElement);\n\tif (children.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const attributeSequence of children) {\n\t\tif (attributeSequence.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parts = childrenOf(source, attributeSequence);\n\t\tconst oidElement = parts[0];\n\t\tconst valueElement = parts[1];\n\t\tif (oidElement === undefined || valueElement === undefined || parts.length !== 2) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (oidElement.tag !== 0x06) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst oid = decodeObjectIdentifier(requireElement(oidElement, 'directoryName OID').value);\n\t\tlet fieldValue: string;\n\t\ttry {\n\t\t\tfieldValue = decodeString(\n\t\t\t\tvalueElement.tag,\n\t\t\t\trequireElement(valueElement, 'directoryName value').value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tfieldKey !== undefined\n\t\t\t\t? { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t: { oid, valueTag: valueElement.tag, value: fieldValue };\n\t\tattributes.push(attribute);\n\t\tif (fieldKey !== undefined && values[fieldKey] === undefined) {\n\t\t\tvalues[fieldKey] = fieldValue;\n\t\t}\n\t}\n\tif (attributes.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Human-readable label for a constraint form, used in error messages. */\nfunction formatConstraintForm(form: NameConstraintForm): string {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\t\treturn `dns:${form.value}`;\n\t\tcase 'email':\n\t\t\treturn `email:${form.value}`;\n\t\tcase 'uri':\n\t\t\treturn `uri:${form.value}`;\n\t\tcase 'ip':\n\t\t\treturn `ip:${decodeIpAddress(form.addressBytes)}`;\n\t\tcase 'directoryName':\n\t\t\treturn `dn:${form.derHex.slice(0, 20)}${form.derHex.length > 20 ? '...' : ''}`;\n\t\tcase 'srv':\n\t\t\treturn `srv:${form.value}`;\n\t\tdefault: {\n\t\t\tconst exhaustive = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\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CAAU,GAAG;CAE5E;AACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy-engine.js","names":["disabledCounter","chainLength","input","chain","state","anchorInChain","outcome","rootNode","OIDS","qualifierSet","expectedPolicySet","parentKeys","depth","validPolicy","certificate","leafDepth","index","authority","graph","qualifiersByOid","collected","node","depthNodes","leafAnyPolicy","oid","qualifiers","parentKey","visited","stack","startKeys","key","out","nextKey","next","seen","unique","qualifier","value","initialPolicySet","constrained","policyIdentifier","policy","anyPolicy","policyQualifiers","left","right","policies","certificatePolicies","isLeaf","byOid","previousDepth","currentDepth","anyPolicyInfo","previousAnyPolicy","previousAnyPolicyKey","allowAnyPolicyExpansion","matchingParents","expansionParents","hasPreviousAnyPolicy","parents","nodes","parentsByPolicy","expectedPolicy","existing","separator","depthString","maxDepth","parent","groupedMappings","mapping","mappings","subjectPolicies","anyPolicyNode","issuerDomainPolicy","subjectDomainPolicies","nodeKey","mappingAllowed","policyConstraints","compareDistinguishedNames"],"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 (!isLeaf && 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,IAAMA,IAAkBC,IAAc;CACtC,OAAO;EACN,kBAAkBC,EAAM,oBAAoB;EAC5C,gBAAgBA,EAAM,0BAA0B,KAAO,IAAIF;EAC3D,sBAAsBE,EAAM,yBAAyB,KAAO,IAAIF;EAChE,kBAAkBE,EAAM,qBAAqB,KAAO,IAAIF;EACxD,kBAAkB,yBAAyB;CAC5C;AACD;;;;;AAMA,SAAgB,oBACf,GACA,GACA,IAAgB,IACS;CACzB,IAAIG,EAAM,WAAW,GACpB,MAAU,WAAW,qDAAqD;CAE3E,mBAAmBA,GAAOC,GAAOC,CAAa;CAC9C,IAAMC,IAAU,8BAA8BF,CAAK;CA4BnD,OA3BIA,EAAM,mBAAmB,KAAKE,EAAQ,wBAAwB,WAAW,IACrE;EACN,IAAI;EACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,SAAS;IACR,UACCF,EAAM,qBAAqB,QAAQ,oBAAoBA,EAAM,iBAAiB,KAAK,GAAG;IACvF,QAAQ,sBAAsBE,EAAQ,uBAAuB;GAC9D;EACD;CACD,IAEGF,EAAM,qBAAqB,SAASE,EAAQ,wBAAwB,WAAW,IAC3E;EACN,IAAI;EACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,SAAS;IACR,UAAUF,EAAM,iBAAiB,KAAK,GAAG;IACzC,QAAQ,sBAAsBE,EAAQ,uBAAuB;GAC9D;EACD;CACD,IAEM;EAAE,IAAI;EAAM,OAAOA;CAAQ;AACnC;;AAGA,SAAS,2BAAwC;CAChD,IAAMC,IAAW,sBAAsB,GAAGC,EAAK,WAAW,KAAA,GAAW,CAACA,EAAK,SAAS,GAAG,CAAC,CAAC;CACzF,OAAO,EACN,cAAc,iBAAC,IAAI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BAA0B,MAC5D,EAAM,iBAAiB;AAEzB;AAEA,SAAS,wBAAwB,GAAoC;CAGpE,AAFA,yBAAyBV,GAAO,gBAAgB,GAChD,yBAAyBA,GAAO,sBAAsB,GACtD,yBAAyBA,GAAO,kBAAkB;AACnD;AAEA,SAAS,yBACR,GACA,GACO;CACP,AAAIA,EAAM0B,KAAO,KAChB,IAAMA;AAER;AAEA,SAAS,4BACR,GACA,GACO;CACP,IAAM+C,IAAoB/D,EAAY;CAatC,AAXC,qBAAqB+D,GAAmB,qBAAqB,KAC7DA,EAAkB,wBAAwBzE,EAAM,mBAEhD,EAAM,iBAAiByE,EAAkB,wBAGzC,qBAAqBA,GAAmB,oBAAoB,KAC5DA,EAAkB,uBAAuBzE,EAAM,yBAE/C,EAAM,uBAAuByE,EAAkB,uBAG/C,qBAAqB/D,EAAY,kBAAkB,SAAS,KAC5DA,EAAY,iBAAiB,YAAYV,EAAM,qBAE/C,EAAM,mBAAmBU,EAAY,iBAAiB;AAExD;AAEA,SAAS,qBAAqB,GAA4C;CACzE,OAAOuB,MAAU,KAAA,KAAa,OAAO,UAAUA,CAAK,KAAKA,KAAS;AACnE;;AAGA,SAAS,aAAa,GAAyC;CAC9D,OAAOyC,EAA0BhE,EAAY,SAASA,EAAY,MAAM;AACzE"}
|
|
1
|
+
{"version":3,"file":"policy-engine.js","names":["OIDS","compareDistinguishedNames","input","chainLength","disabledCounter","chain","state","anchorInChain","outcome","rootNode","depth","validPolicy","qualifierSet","expectedPolicySet","parentKeys","certificate","leafDepth","index","authority","graph","qualifiersByOid","node","collected","depthNodes","leafAnyPolicy","oid","qualifiers","parentKey","visited","startKeys","next","out","stack","key","nextKey","seen","unique","qualifier","_field","value","initialPolicySet","constrained","policyIdentifier","policy","anyPolicy","policyQualifiers","left","right","policies","isLeaf","certificatePolicies","byOid","allowAnyPolicyExpansion","previousDepth","currentDepth","anyPolicyInfo","previousAnyPolicy","previousAnyPolicyKey","matchingParents","hasPreviousAnyPolicy","expansionParents","nodes","parents","parentsByPolicy","expectedPolicy","existing","separator","depthString","maxDepth","parent","mappings","mappingAllowed","groupedMappings","mapping","subjectPolicies","anyPolicyNode","issuerDomainPolicy","subjectDomainPolicies","nodeKey","policyConstraints"],"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 (!isLeaf && 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,4BACfE,GACAC,GACwB;CACxB,IAAMC,IAAkBD,IAAc;CACtC,OAAO;EACN,kBAAkBD,EAAM,oBAAoB;EAC5C,gBAAgBA,EAAM,0BAA0B,KAAO,IAAIE;EAC3D,sBAAsBF,EAAM,yBAAyB,KAAO,IAAIE;EAChE,kBAAkBF,EAAM,qBAAqB,KAAO,IAAIE;EACxD,kBAAkB,yBAAyB;CAC5C;AACD;;;;;AAMA,SAAgB,oBACfC,GACAC,GACAC,IAAgB,IACS;CACzB,IAAIF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AAoB,KAC5DA,EAAkB,uBAAuBzE,EAAM,yBAE/CA,EAAM,uBAAuByE,EAAkB,uBAG/C,qBAAqBhE,EAAY,kBAAkB,SAAS,KAC5DA,EAAY,iBAAiB,YAAYT,EAAM,qBAE/CA,EAAM,mBAAmBS,EAAY,iBAAiB;AAExD;AAEA,SAAS,qBAAqBwB,GAA4C;CACzE,OAAOA,MAAU,KAAA,KAAa,OAAO,UAAUA,CAAK,KAAKA,KAAS;AACnE;;AAGA,SAAS,aAAaxB,GAAyC;CAC9D,OAAOd,EAA0Bc,EAAY,SAASA,EAAY,MAAM;AACzE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spki-distrust.js","names":["
|
|
1
|
+
{"version":3,"file":"spki-distrust.js","names":["toArrayBuffer","toHex","getCrypto","hashes","blocked","hash","digests","spki","key","digest","bytes"],"sources":["../../../src/internal/verify/spki-distrust.ts"],"sourcesContent":["/** Caller-supplied SHA-256 SPKI distrust, scoped to one verification operation. */\nimport { toArrayBuffer, toHex } from '#micro509/internal/asn1/asn1';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\n\n/** Validates and snapshots the caller's hashes before any asynchronous work. */\nexport function createSpkiDistrustCheck(\n\thashes: readonly string[] | undefined,\n): (spki: Uint8Array) => Promise<string | undefined> {\n\tconst blocked = new Set<string>();\n\tfor (const hash of hashes ?? []) {\n\t\tif (typeof hash !== 'string' || !/^[0-9a-fA-F]{64}$/.test(hash)) {\n\t\t\tthrow new RangeError('distrustedSpkiSha256 entries must be 64 hexadecimal characters');\n\t\t}\n\t\tblocked.add(hash.toLowerCase());\n\t}\n\tconst digests = new Map<string, Promise<string>>();\n\treturn async (spki) => {\n\t\tif (blocked.size === 0) return undefined;\n\t\tconst key = toHex(spki);\n\t\tlet digest = digests.get(key);\n\t\tif (digest === undefined) {\n\t\t\tdigest = getCrypto()\n\t\t\t\t.subtle.digest('SHA-256', toArrayBuffer(spki))\n\t\t\t\t.then((bytes) => toHex(new Uint8Array(bytes)));\n\t\t\tdigests.set(key, digest);\n\t\t}\n\t\tconst hash = await digest;\n\t\treturn blocked.has(hash) ? hash : undefined;\n\t};\n}\n"],"mappings":";;;;;AAKA,SAAgB,wBACfG,GACoD;CACpD,IAAMC,oBAAU,IAAI,IAAY;CAChC,KAAK,IAAMC,KAAQF,KAAU,CAAC,GAAG;EAChC,IAAI,OAAOE,KAAS,YAAY,CAAC,oBAAoB,KAAKA,CAAI,GAC7D,MAAU,WAAW,gEAAgE;EAEtFD,EAAQ,IAAIC,EAAK,YAAY,CAAC;CAC/B;CACA,IAAMC,oBAAU,IAAI,IAA6B;CACjD,OAAO,OAAOC,MAAS;EACtB,IAAIH,EAAQ,SAAS,GAAG;EACxB,IAAMI,IAAMP,EAAMM,CAAI,GAClBE,IAASH,EAAQ,IAAIE,CAAG;EACxBC,MAAW,KAAA,MACdA,IAASP,EAAU,CAAC,CAClB,OAAO,OAAO,WAAWF,EAAcO,CAAI,CAAC,CAAC,CAC7C,MAAMG,MAAUT,EAAM,IAAI,WAAWS,CAAK,CAAC,CAAC,GAC9CJ,EAAQ,IAAIE,GAAKC,CAAM;EAExB,IAAMJ,IAAO,MAAMI;EACnB,OAAOL,EAAQ,IAAIC,CAAI,IAAIA,IAAO,KAAA;CACnC;AACD"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
import { ParsedCertificate } from "../../x509/parse.js";
|
|
2
2
|
/** Returns `true` if the certificate's subject and issuer DNs are semantically equal (RFC 5280 §7.1). */
|
|
3
|
-
export declare function isSelfIssued(certificate: ParsedCertificate): boolean;
|
|
4
|
-
//# sourceMappingURL=verify-path.d.ts.map
|
|
3
|
+
export declare function isSelfIssued(certificate: ParsedCertificate): boolean;
|