micro509 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +5 -5
  3. package/dist/index.js +15 -1
  4. package/dist/internal/asn1/asn1.js +280 -2
  5. package/dist/internal/asn1/der.js +378 -2
  6. package/dist/internal/asn1/oids.js +103 -2
  7. package/dist/internal/crypto/algorithm-names.js +58 -2
  8. package/dist/internal/crypto/ecdsa.js +68 -2
  9. package/dist/internal/crypto/hash.js +286 -2
  10. package/dist/internal/crypto/pbes2.js +213 -2
  11. package/dist/internal/crypto/rsa-pss.js +184 -2
  12. package/dist/internal/crypto/sig-verify.js +192 -2
  13. package/dist/internal/crypto/signing.d.ts +1 -2
  14. package/dist/internal/crypto/signing.js +123 -2
  15. package/dist/internal/crypto/webcrypto.js +14 -2
  16. package/dist/internal/shared/base64.js +16 -2
  17. package/dist/internal/shared/dn.js +84 -2
  18. package/dist/internal/shared/ip.js +164 -2
  19. package/dist/internal/verify/name-constraints-engine.js +450 -2
  20. package/dist/internal/verify/policy-engine.js +382 -2
  21. package/dist/internal/verify/verify-path.js +298 -2
  22. package/dist/internal/x509/extension-bits.js +132 -2
  23. package/dist/internal/x509/extension-registry.js +229 -2
  24. package/dist/internal/x509/name-fields.js +93 -2
  25. package/dist/keys/keys.d.ts +231 -7
  26. package/dist/keys/keys.js +1087 -5
  27. package/dist/keys.d.ts +2 -2
  28. package/dist/keys.js +2 -1
  29. package/dist/pem/pem.d.ts +2 -2
  30. package/dist/pem/pem.js +172 -6
  31. package/dist/pem.js +2 -1
  32. package/dist/pkcs/pfx.d.ts +4 -5
  33. package/dist/pkcs/pfx.js +395 -2
  34. package/dist/pkcs/pkcs12-mac.d.ts +2 -2
  35. package/dist/pkcs/pkcs12-mac.js +175 -2
  36. package/dist/pkcs/pkcs7.d.ts +1 -2
  37. package/dist/pkcs/pkcs7.js +653 -2
  38. package/dist/pkcs.d.ts +2 -2
  39. package/dist/pkcs.js +4 -1
  40. package/dist/result/result.d.ts +1 -2
  41. package/dist/result/result.js +111 -2
  42. package/dist/result.js +2 -1
  43. package/dist/revocation/chain.d.ts +4 -5
  44. package/dist/revocation/chain.js +536 -2
  45. package/dist/revocation/crl.d.ts +2 -2
  46. package/dist/revocation/crl.js +1119 -2
  47. package/dist/revocation/ocsp.d.ts +3 -2
  48. package/dist/revocation/ocsp.js +958 -2
  49. package/dist/revocation/revocation.d.ts +1 -2
  50. package/dist/revocation/revocation.js +261 -2
  51. package/dist/revocation.d.ts +2 -2
  52. package/dist/revocation.js +5 -1
  53. package/dist/verify/identity.d.ts +1 -2
  54. package/dist/verify/identity.js +270 -2
  55. package/dist/verify/name-constraints.d.ts +1 -2
  56. package/dist/verify/policy.d.ts +1 -2
  57. package/dist/verify/verify.d.ts +1 -2
  58. package/dist/verify/verify.js +764 -2
  59. package/dist/verify.js +3 -1
  60. package/dist/x509/certificate.d.ts +1 -2
  61. package/dist/x509/certificate.js +151 -2
  62. package/dist/x509/csr.d.ts +1 -2
  63. package/dist/x509/csr.js +71 -2
  64. package/dist/x509/extensions.d.ts +1 -2
  65. package/dist/x509/extensions.js +387 -2
  66. package/dist/x509/name.d.ts +1 -2
  67. package/dist/x509/name.js +173 -2
  68. package/dist/x509/parse.d.ts +84 -2
  69. package/dist/x509/parse.js +1090 -2
  70. package/dist/x509.d.ts +2 -2
  71. package/dist/x509.js +6 -1
  72. package/package.json +74 -34
  73. package/dist/internal/asn1/asn1.js.map +0 -1
  74. package/dist/internal/asn1/der.js.map +0 -1
  75. package/dist/internal/asn1/oids.js.map +0 -1
  76. package/dist/internal/crypto/algorithm-names.js.map +0 -1
  77. package/dist/internal/crypto/ecdsa.js.map +0 -1
  78. package/dist/internal/crypto/hash.js.map +0 -1
  79. package/dist/internal/crypto/pbes2.d.ts +0 -23
  80. package/dist/internal/crypto/pbes2.js.map +0 -1
  81. package/dist/internal/crypto/rsa-pss.js.map +0 -1
  82. package/dist/internal/crypto/sig-verify.js.map +0 -1
  83. package/dist/internal/crypto/signing.js.map +0 -1
  84. package/dist/internal/crypto/webcrypto.js.map +0 -1
  85. package/dist/internal/shared/base64.js.map +0 -1
  86. package/dist/internal/shared/dn.js.map +0 -1
  87. package/dist/internal/shared/ip.js.map +0 -1
  88. package/dist/internal/verify/name-constraints-engine.js.map +0 -1
  89. package/dist/internal/verify/policy-engine.js.map +0 -1
  90. package/dist/internal/verify/verify-path.js.map +0 -1
  91. package/dist/internal/x509/extension-bits.js.map +0 -1
  92. package/dist/internal/x509/extension-registry.js.map +0 -1
  93. package/dist/internal/x509/name-fields.js.map +0 -1
  94. package/dist/keys/keys.js.map +0 -1
  95. package/dist/pem/pem.js.map +0 -1
  96. package/dist/pkcs/pfx.js.map +0 -1
  97. package/dist/pkcs/pkcs12-mac.js.map +0 -1
  98. package/dist/pkcs/pkcs7.js.map +0 -1
  99. package/dist/result/result.js.map +0 -1
  100. package/dist/revocation/chain.js.map +0 -1
  101. package/dist/revocation/crl.js.map +0 -1
  102. package/dist/revocation/ocsp.js.map +0 -1
  103. package/dist/revocation/revocation.js.map +0 -1
  104. package/dist/verify/identity.js.map +0 -1
  105. package/dist/verify/verify.js.map +0 -1
  106. package/dist/x509/certificate.js.map +0 -1
  107. package/dist/x509/csr.js.map +0 -1
  108. package/dist/x509/extensions.js.map +0 -1
  109. package/dist/x509/name.js.map +0 -1
  110. package/dist/x509/parse.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"dn.js","names":[],"sources":["../../../src/internal/shared/dn.ts"],"sourcesContent":["/**\n * RFC 5280 §7.1 distinguished name comparison utilities.\n *\n * Provides semantic DN equality (case-folding, NFKC normalization,\n * whitespace collapse) and a canonical string key for O(1) Map lookups.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-7.1 | RFC 5280 §7.1}. Internationalized Names in Distinguished Names\n * @module\n */\n\nimport type {\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse.ts';\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** RFC 5280 §7.1 semantic equality: same RDN count, each pair matches attribute-by-attribute. */\nexport function compareDistinguishedNames(left: ParsedName, right: ParsedName): boolean {\n\tif (left.rdns.length !== right.rdns.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < left.rdns.length; index += 1) {\n\t\tconst leftRdn = left.rdns[index];\n\t\tconst rightRdn = right.rdns[index];\n\t\tif (leftRdn === undefined || rightRdn === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!compareRelativeDistinguishedNames(leftRdn, rightRdn)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * Produces a deterministic string key for a parsed DN, suitable as a Map key.\n * Semantically equal DNs (per RFC 5280 §7.1) produce identical keys.\n *\n * Format: RDNs joined by `,`, attributes within each RDN sorted by OID then\n * by prepared value, joined by `+`.\n */\nexport function canonicalDnKey(name: ParsedName): string {\n\treturn name.rdns.map(canonicalRdnKey).join(',');\n}\n\n/** True when `subject` equals or is subordinate to `constraint` (RDN prefix match). */\nexport function isWithinDirectoryNameSubtree(subject: ParsedName, constraint: ParsedName): boolean {\n\tif (constraint.rdns.length > subject.rdns.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < constraint.rdns.length; index += 1) {\n\t\tconst subjectRdn = subject.rdns[index];\n\t\tconst constraintRdn = constraint.rdns[index];\n\t\tif (subjectRdn === undefined || constraintRdn === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!compareRelativeDistinguishedNames(subjectRdn, constraintRdn)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n// ---------------------------------------------------------------------------\n// RDN / attribute comparison\n// ---------------------------------------------------------------------------\n\n/** Order-independent RDN equality: same attribute count, each pair matched exactly once. */\nexport function compareRelativeDistinguishedNames(\n\tleft: ParsedRelativeDistinguishedName,\n\tright: ParsedRelativeDistinguishedName,\n): boolean {\n\tif (left.attributes.length !== right.attributes.length) {\n\t\treturn false;\n\t}\n\tconst matched = new Array<boolean>(right.attributes.length).fill(false);\n\tfor (const leftAttribute of left.attributes) {\n\t\tlet found = false;\n\t\tfor (let index = 0; index < right.attributes.length; index += 1) {\n\t\t\tconst rightAttribute = right.attributes[index];\n\t\t\tif (rightAttribute === undefined || matched[index]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!compareNameAttributeValue(leftAttribute, rightAttribute)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmatched[index] = true;\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (!found) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Compares two AttributeTypeAndValue pairs using RFC 5280 §7.1 string-prep for DirectoryString tags. */\nexport function compareNameAttributeValue(\n\tleft: ParsedNameAttribute,\n\tright: ParsedNameAttribute,\n): boolean {\n\tif (left.oid !== right.oid) {\n\t\treturn false;\n\t}\n\tif (isDirectoryStringTag(left.valueTag) && isDirectoryStringTag(right.valueTag)) {\n\t\tconst preparedLeft = prepareNameCompareString(left.value);\n\t\tconst preparedRight = prepareNameCompareString(right.value);\n\t\tif (preparedLeft === undefined || preparedRight === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn preparedLeft === preparedRight;\n\t}\n\treturn left.valueTag === right.valueTag && left.value === right.value;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** True for UTF8String (0x0C) and PrintableString (0x13) — the DirectoryString types we normalize. */\nexport function isDirectoryStringTag(tag: number): boolean {\n\treturn tag === 0x0c || tag === 0x13;\n}\n\n/** NFKC-normalizes, lowercases, trims, and collapses whitespace for RFC 5280 §7.1 comparison. */\nexport function prepareNameCompareString(value: string): string | undefined {\n\tconst normalized = value.normalize('NFKC');\n\tif (/[^\\P{Cc}\\t\\n\\r]/u.test(normalized)) {\n\t\treturn undefined;\n\t}\n\treturn normalized.toLowerCase().trim().replace(/\\s+/gu, ' ');\n}\n\n/** Canonical string for a single RDN: attributes sorted, values prepared. */\nfunction canonicalRdnKey(rdn: ParsedRelativeDistinguishedName): string {\n\treturn rdn.attributes\n\t\t.map((attr) => {\n\t\t\tconst val = isDirectoryStringTag(attr.valueTag)\n\t\t\t\t? (prepareNameCompareString(attr.value) ?? `[raw:${attr.valueTag}]${attr.value}`)\n\t\t\t\t: `[${String(attr.valueTag)}]${attr.value}`;\n\t\t\treturn `${attr.oid}=${escapeCanonicalDnValue(val)}`;\n\t\t})\n\t\t.sort()\n\t\t.join('+');\n}\n\nfunction escapeCanonicalDnValue(value: string): string {\n\treturn value\n\t\t.replaceAll('\\\\', '\\\\\\\\')\n\t\t.replaceAll(',', '\\\\,')\n\t\t.replaceAll('+', '\\\\+')\n\t\t.replaceAll('=', '\\\\=');\n}\n"],"mappings":"AAqBA,SAAgB,EAA0B,EAAkB,EAA4B,CACvF,GAAI,EAAK,KAAK,SAAW,EAAM,KAAK,OACnC,MAAO,GAER,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAK,KAAK,OAAQ,GAAS,EAAG,CACzD,IAAM,EAAU,EAAK,KAAK,GACpB,EAAW,EAAM,KAAK,GAI5B,GAHI,IAAY,IAAA,IAAa,IAAa,IAAA,IAGtC,CAAC,EAAkC,EAAS,CAAQ,EACvD,MAAO,EAET,CACA,MAAO,EACR,CASA,SAAgB,EAAe,EAA0B,CACxD,OAAO,EAAK,KAAK,IAAI,CAAe,CAAC,CAAC,KAAK,GAAG,CAC/C,CAGA,SAAgB,EAA6B,EAAqB,EAAiC,CAClG,GAAI,EAAW,KAAK,OAAS,EAAQ,KAAK,OACzC,MAAO,GAER,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAW,KAAK,OAAQ,GAAS,EAAG,CAC/D,IAAM,EAAa,EAAQ,KAAK,GAC1B,EAAgB,EAAW,KAAK,GAItC,GAHI,IAAe,IA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AC1C,EAAyB,EAAK,KAAK,GAAK,QAAQ,EAAK,SAAS,GAAG,EAAK,QACvE,IAAI,OAAO,EAAK,QAAQ,EAAE,GAAG,EAAK,QACrC,MAAO,GAAG,EAAK,IAAI,GAAG,EAAuB,CAAG,GACjD,CAAC,CAAC,CACD,KAAK,CAAC,CACN,KAAK,GAAG,CACX,CAEA,SAAS,EAAuB,EAAuB,CACtD,OAAO,EACL,WAAW,KAAM,MAAM,CAAC,CACxB,WAAW,IAAK,KAAK,CAAC,CACtB,WAAW,IAAK,KAAK,CAAC,CACtB,WAAW,IAAK,KAAK,CACxB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ip.js","names":[],"sources":["../../../src/internal/shared/ip.ts"],"sourcesContent":["/**\n * IP address parsing and normalization helpers shared by parsing,\n * validation, and identity matching flows.\n *\n * These utilities keep IPv4 and IPv6 handling consistent for SAN\n * matching and name constraint evaluation.\n *\n * @example\n * ```ts\n * import {\n * \tallOnesMaskForIpAddress,\n * \tdecodeIpAddress,\n * \texpandIpv6,\n * \tnormalizeIpAddress,\n * \tparseIpAddressToBytes,\n * } from './ip.ts';\n *\n * normalizeIpAddress('::1');\n * // '0000:0000:0000:0000:0000:0000:0000:0001'\n *\n * expandIpv6('2001:db8::1');\n * // ['2001', '0db8', '0000', '0000', '0000', '0000', '0000', '0001']\n *\n * Array.from(parseIpAddressToBytes('127.0.0.1'));\n * // [127, 0, 0, 1]\n *\n * decodeIpAddress(Uint8Array.of(127, 0, 0, 1));\n * // '127.0.0.1'\n *\n * Array.from(allOnesMaskForIpAddress('127.0.0.1'));\n * // [255, 255, 255, 255]\n * ```\n *\n * @module\n */\n\n/** Matches a single valid IPv6 hex segment (1–4 hex digits). */\nconst IPV6_SEGMENT = /^[0-9a-f]{1,4}$/;\n\n/**\n * Normalizes an IP address string for comparison.\\\n * IPv4 addresses pass through unchanged; IPv6 addresses expand to 8\n * colon-separated zero-padded groups.\n *\n * @example\n * ```ts\n * normalizeIpAddress('::1');\n * // '0000:0000:0000:0000:0000:0000:0000:0001'\n * ```\n *\n * @param value IPv4 or IPv6 address string to normalize.\n * @returns The normalized address string.\n */\nexport function normalizeIpAddress(value: string): string {\n\tif (!value.includes(':')) {\n\t\treturn value;\n\t}\n\treturn expandIpv6(value).join(':');\n}\n\n/**\n * Expands an IPv6 address, including `::` shorthand, into exactly 8\n * zero-padded four-character hex segments.\\\n * Throws on malformed input.\n *\n * @example\n * ```ts\n * expandIpv6('2001:db8::1');\n * // ['2001', '0db8', '0000', '0000', '0000', '0000', '0000', '0001']\n * ```\n *\n * @param value IPv6 address string to expand.\n * @returns The 8 normalized IPv6 segments.\n */\nexport function expandIpv6(value: string): readonly string[] {\n\tconst normalized = value.toLowerCase();\n\tconst pieces = normalized.split('::');\n\tconst head = pieces[0] ?? '';\n\tconst tail = pieces[1];\n\tif (tail !== undefined && normalized.indexOf('::') !== normalized.lastIndexOf('::')) {\n\t\tthrow new Error(`Invalid IPv6 address: ${value}`);\n\t}\n\tconst headParts = head.length > 0 ? head.split(':') : [];\n\tconst tailParts = tail !== undefined && tail.length > 0 ? tail.split(':') : [];\n\tconst missing = 8 - (headParts.length + tailParts.length);\n\tif ((tail === undefined && headParts.length !== 8) || missing < 0) {\n\t\tthrow new Error(`Invalid IPv6 address: ${value}`);\n\t}\n\tconst zeroes = Array.from({ length: missing }, () => '0');\n\tconst parts = tail === undefined ? headParts : [...headParts, ...zeroes, ...tailParts];\n\tif (parts.length !== 8) {\n\t\tthrow new Error(`Invalid IPv6 address: ${value}`);\n\t}\n\treturn parts.map((segment) => {\n\t\tif (!IPV6_SEGMENT.test(segment)) {\n\t\t\tthrow new Error(`Invalid IPv6 address: ${value}`);\n\t\t}\n\t\treturn segment.padStart(4, '0');\n\t});\n}\n\n/**\n * Parses an IPv4 or IPv6 address string into raw bytes.\\\n * Returns 4 bytes for IPv4 and 16 bytes for IPv6.\n *\n * Suitable for encoding into SAN iPAddress octets or name-constraint ranges.\n *\n * @example\n * ```ts\n * Array.from(parseIpAddressToBytes('127.0.0.1'));\n * // [127, 0, 0, 1]\n * ```\n *\n * @param value IPv4 or IPv6 address string to parse.\n * @returns The raw address bytes.\n */\nexport function parseIpAddressToBytes(value: string): Uint8Array {\n\tif (value.includes(':')) {\n\t\treturn parseIpv6ToBytes(value);\n\t}\n\tconst segments = value.split('.');\n\tif (segments.length !== 4) {\n\t\tthrow new Error(`Invalid IPv4 address: ${value}`);\n\t}\n\treturn Uint8Array.from(\n\t\tsegments.map((segment) => {\n\t\t\tif (segment.length === 0) {\n\t\t\t\tthrow new Error(`Invalid IPv4 address: ${value}`);\n\t\t\t}\n\t\t\tconst parsed = Number(segment);\n\t\t\tif (!Number.isInteger(parsed) || parsed < 0 || parsed > 255) {\n\t\t\t\tthrow new Error(`Invalid IPv4 address: ${value}`);\n\t\t\t}\n\t\t\treturn parsed;\n\t\t}),\n\t);\n}\n\n/**\n * Converts raw IP address bytes back to a human-readable string.\\\n * Returns dotted-decimal IPv4 for 4-byte input and colon-separated hex\n * IPv6 for 16-byte input.\n *\n * Throws on any other length.\n *\n * @example\n * ```ts\n * decodeIpAddress(Uint8Array.of(127, 0, 0, 1));\n * // '127.0.0.1'\n * ```\n *\n * @param bytes Raw IPv4 or IPv6 address bytes.\n * @returns The decoded address string.\n */\nexport function decodeIpAddress(bytes: Uint8Array): string {\n\tif (bytes.length === 4) {\n\t\treturn Array.from(bytes, (value) => String(value)).join('.');\n\t}\n\tif (bytes.length === 16) {\n\t\tconst groups: string[] = [];\n\t\tfor (let index = 0; index < bytes.length; index += 2) {\n\t\t\tconst left = bytes[index] ?? 0;\n\t\t\tconst right = bytes[index + 1] ?? 0;\n\t\t\tgroups.push(((left << 8) | right).toString(16));\n\t\t}\n\t\treturn groups.join(':');\n\t}\n\tthrow new Error(`Unsupported IP address length: ${bytes.length}`);\n}\n\n/**\n * Returns an all-ones (`0xff`) mask of the appropriate length for the\n * given IP address string.\\\n * Returns 4 bytes for IPv4 and 16 bytes for IPv6.\n *\n * Used to build name-constraint subnet masks that match a single host.\n *\n * @example\n * ```ts\n * Array.from(allOnesMaskForIpAddress('127.0.0.1'));\n * // [255, 255, 255, 255]\n * ```\n *\n * @param value IPv4 or IPv6 address string used to choose mask length.\n * @returns An all-ones mask for the same address family.\n */\nexport function allOnesMaskForIpAddress(value: string): Uint8Array {\n\t// Validate and parse the IP address to determine its type\n\tconst parsed = parseIpAddressToBytes(value);\n\tconst mask = new Uint8Array(parsed.length);\n\tmask.fill(0xff);\n\treturn mask;\n}\n\n/** Parses an IPv6 address string into a 16-byte `Uint8Array`. */\nfunction parseIpv6ToBytes(value: string): Uint8Array {\n\tconst expanded = expandIpv6(value);\n\tconst bytes = new Uint8Array(16);\n\texpanded.forEach((segment, index) => {\n\t\tconst parsed = Number.parseInt(segment, 16);\n\t\tbytes[index * 2] = parsed >> 8;\n\t\tbytes[index * 2 + 1] = parsed & 0xff;\n\t});\n\treturn bytes;\n}\n"],"mappings":"AAqCA,MAAM,EAAe,kBAqCrB,SAAgB,EAAW,EAAkC,CAC5D,IAAM,EAAa,EAAM,YAAY,EAC/B,EAAS,EAAW,MAAM,IAAI,EAC9B,EAAO,EAAO,IAAM,GACpB,EAAO,EAAO,GACpB,GAAI,IAAS,IAAA,IAAa,EAAW,QAAQ,IAAI,IAAM,EAAW,YAAY,IAAI,EACjF,MAAU,MAAM,yBAAyB,GAAO,EAEjD,IAAM,EAAY,EAAK,OAAS,EAAI,EAAK,MAAM,GAAG,EAAI,CAAC,EACjD,EAAY,IAAS,IAAA,IAAa,EAAK,OAAS,EAAI,EAAK,MAAM,GAAG,EAAI,CAAC,EACvE,EAAU,GAAK,EAAU,OAAS,EAAU,QAClD,GAAK,IAAS,IAAA,IAAa,EAAU,SAAW,GAAM,EAAU,EAC/D,MAAU,MAAM,yBAAyB,GAAO,EAEjD,IAAM,EAAS,MAAM,KAAK,CAAE,OAAQ,CAAQ,MAAS,GAAG,EAClD,EAAQ,IAAS,IAAA,GAAY,EAAY,CAAC,GAAG,EAAW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AO,MAAM,EAEzC,OADA,EAAK,KAAK,GAAI,EACP,CACR,CAGA,SAAS,EAAiB,EAA2B,CACpD,IAAM,EAAW,EAAW,CAAK,EAC3B,EAAQ,IAAI,WAAW,EAAE,EAM/B,OALA,EAAS,SAAS,EAAS,IAAU,CACpC,IAAM,EAAS,OAAO,SAAS,EAAS,EAAE,EAC1C,EAAM,EAAQ,GAAK,GAAU,EAC7B,EAAM,EAAQ,EAAI,GAAK,EAAS,GACjC,CAAC,EACM,CACR"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"name-constraints-engine.js","names":["exhaustive"],"sources":["../../../src/internal/verify/name-constraints-engine.ts"],"sourcesContent":["/**\n * Internal name-constraints evaluation engine.\n *\n * Accumulates and evaluates the shipped RFC 5280 §4.2.1.10 / §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.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\ttype DerElement,\n\treadRootElement,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tcompareDistinguishedNames,\n\tisWithinDirectoryNameSubtree,\n} from '#micro509/internal/shared/dn.ts';\nimport {\n\tallOnesMaskForIpAddress,\n\tdecodeIpAddress,\n\tparseIpAddressToBytes,\n} from '#micro509/internal/shared/ip.ts';\nimport type { Micro509Error } from '#micro509/result/result.ts';\nimport type { InitialNameConstraintsInput } from '#micro509/verify/name-constraints.ts';\nimport type {\n\tNameConstraintForm,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tSubjectAltName,\n\tUnsupportedNameConstraintForm,\n} from '#micro509/x509/extensions.ts';\nimport { nameFieldKeyFromOid } from '#micro509/x509/name.ts';\nimport type {\n\tNameFieldKey,\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse.ts';\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\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// ---------------------------------------------------------------------------\n// Private: name constraint validation (RFC 5280 §4.2.1.10 / §6.1)\n// ---------------------------------------------------------------------------\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<UnsupportedNameConstraintForm['type']>;\n}\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 intermediates, §6.1.5(g) for the leaf.\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// (b) If not self-issued, check names against accumulated constraints.\n\t\t// RFC 5280 §4.2.1.10: self-issued certificates are exempt UNLESS\n\t\t// they are the final certificate (leaf) in the path.\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// (c) If this cert has nameConstraints, accumulate them.\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};\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 newUnsupported = critical ? listUnsupportedNameConstraintTypes(constraints) : [];\n\tconst unsupportedCriticalForms =\n\t\tnewUnsupported.length > 0\n\t\t\t? new Set([...current.unsupportedCriticalForms, ...newUnsupported])\n\t\t\t: current.unsupportedCriticalForms;\n\treturn { permittedLevels, excluded, unsupportedCriticalForms };\n}\n\n/** Collects the distinct unsupported GeneralName form types from a nameConstraints extension. */\nfunction listUnsupportedNameConstraintTypes(\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n): readonly UnsupportedNameConstraintForm['type'][] {\n\tconst unsupportedTypes = new Set<UnsupportedNameConstraintForm['type']>();\n\tfor (const subtree of constraints.permittedSubtrees ?? []) {\n\t\tif (!isSupportedNameConstraintForm(subtree.base)) {\n\t\t\tunsupportedTypes.add(subtree.base.type);\n\t\t}\n\t}\n\tfor (const subtree of constraints.excludedSubtrees ?? []) {\n\t\tif (!isSupportedNameConstraintForm(subtree.base)) {\n\t\t\tunsupportedTypes.add(subtree.base.type);\n\t\t}\n\t}\n\treturn [...unsupportedTypes];\n}\n\n/** True for name forms this engine can evaluate: dns, email, uri, ip, directoryName. */\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\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\t// Check subject DN as directoryName (if non-empty).\n\tif (certificate.subject.derHex !== EMPTY_SEQUENCE_HEX) {\n\t\tconst dnResult = isNamePermitted(\n\t\t\t{ type: 'directoryName', derHex: certificate.subject.derHex },\n\t\t\taccumulated,\n\t\t);\n\t\tif (!dnResult) {\n\t\t\treturn 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({\n\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Check each SAN.\n\tif (certificate.subjectAltNames !== undefined) {\n\t\tfor (const san of certificate.subjectAltNames) {\n\t\t\t// RFC 5280 §4.2.1.10: a critical nameConstraints extension imposing\n\t\t\t// constraints on a name form this engine cannot process forces\n\t\t\t// rejection of any subsequent certificate carrying that form.\n\t\t\tconst unsupportedForm = sanUnsupportedFormType(san);\n\t\t\tif (\n\t\t\t\tunsupportedForm !== undefined &&\n\t\t\t\taccumulated.unsupportedCriticalForms.has(unsupportedForm)\n\t\t\t) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'unsupported_name_constraints',\n\t\t\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\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: unsupportedForm,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst checkableResult = sanToConstraintCheckable(san);\n\t\t\tif (!checkableResult.ok) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`SAN ${checkableResult.actual} is malformed and cannot be checked against 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: checkableResult.actual,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst checkable = checkableResult.value;\n\t\t\tif (checkable === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isNamePermitted(checkable, accumulated)) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`SAN ${formatConstraintForm(checkable)} 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: formatConstraintForm(checkable),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// RFC 5280 §4.2.1.10: When constraints are imposed on the rfc822Name\n\t// name form, but the certificate does not include a SAN email, the\n\t// constraint MUST be applied to the emailAddress attribute in the\n\t// subject DN.\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/**\n * Maps a SAN to the unsupported constraint form it instantiates, if any.\n *\n * SRV-ID SANs are otherName [0] instances. Unknown SANs carry the full DER\n * tag byte: 0xa0 otherName [0], 0xa3 x400Address [3], 0xa5 ediPartyName [5],\n * 0x88 registeredID [8].\n */\nfunction sanUnsupportedFormType(\n\tsan: SubjectAltName,\n): UnsupportedNameConstraintForm['type'] | undefined {\n\tif (san.type === 'srv') {\n\t\treturn 'otherName';\n\t}\n\tif (san.type !== 'unknown') {\n\t\treturn undefined;\n\t}\n\tswitch (san.tag) {\n\t\tcase 0xa0:\n\t\t\treturn 'otherName';\n\t\tcase 0xa3:\n\t\t\treturn 'x400Address';\n\t\tcase 0xa5:\n\t\t\treturn 'ediPartyName';\n\t\tcase 0x88:\n\t\t\treturn 'registeredID';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\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: 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\t// Check excluded — if any match, reject.\n\tfor (const constraint of accumulated.excluded) {\n\t\tif (nameMatchesConstraint(name, constraint)) {\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) => nameMatchesConstraint(name, constraint))) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\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 === 'directoryName' && constraint.type === 'directoryName') {\n\t\treturn matchesDnConstraint(name.derHex, constraint.derHex);\n\t}\n\treturn false;\n}\n\n/**\n * RFC 5280 §4.2.1.10: DNS name constraint matching.\n * Constraint \"example.com\" matches \"example.com\" and any subdomain.\n * Constraint \".example.com\" matches only subdomains, not \"example.com\" itself.\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.\n * - \"user@example.com\" matches only that exact address.\n * - \"example.com\" matches any address @example.com.\n * - \".example.com\" matches any address @subdomain.example.com.\n */\nfunction matchesEmailConstraint(name: string, constraint: string): boolean {\n\tconst lowerName = name.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.includes('@')) {\n\t\treturn lowerName === lowerConstraint;\n\t}\n\tconst atIndex = lowerName.indexOf('@');\n\tif (atIndex < 0) {\n\t\treturn false;\n\t}\n\tconst host = lowerName.slice(atIndex + 1);\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: URI constraint matching.\n * Applied to the host part of the URI.\n * - Constraint \".example.com\" matches subdomains only.\n * - Constraint \"example.com\" matches ONLY that exact host (no subdomain\n * expansion, unlike DNS constraints).\n */\nfunction matchesUriConstraint(uri: string, constraint: string): boolean {\n\tconst host = extractUriHost(uri);\n\tif (host === undefined) {\n\t\treturn false;\n\t}\n\tconst lowerHost = host.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.length === 0) {\n\t\treturn true;\n\t}\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn lowerHost.endsWith(lowerConstraint);\n\t}\n\t// Non-period constraint: exact host match only (RFC 5280 §4.2.1.10).\n\treturn lowerHost === lowerConstraint;\n}\n\n/** Extracts the host (reg-name) portion of a URI, stripping scheme, userinfo, port, and path. */\nfunction extractUriHost(uri: string): string | undefined {\n\ttry {\n\t\tconst url = new URL(uri);\n\t\treturn url.hostname;\n\t} catch {\n\t\treturn undefined;\n\t}\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): boolean {\n\tconst subjectName = parseDirectoryNameDerHex(subjectDerHex);\n\tconst constraintName = parseDirectoryNameDerHex(constraintDerHex);\n\tif (subjectName === undefined || constraintName === undefined) {\n\t\treturn false;\n\t}\n\treturn isWithinDirectoryNameSubtree(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 {\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 {\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\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":"ueA+GA,SAAS,EACR,EACA,EACA,EACA,EACkC,CAClC,MAAO,CACN,GAAI,GACJ,OACA,UACA,QACA,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,CAC5C,CACD,CAGA,SAAS,EACR,EACqD,CACrD,IAAM,EAAkD,CACvD,GAAI,EAAM,oBAAsB,IAAA,GAC7B,CAAC,EACD,CAAE,kBAAmB,EAAM,iBAAkB,EAChD,GAAI,EAAM,SAAW,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQ,EAAM,MAAO,CAC9D,EACA,OAAO,OAAO,KAAK,CAAO,CAAC,CAAC,SAAW,EAAI,IAAA,GAAY,CACxD,CAGA,SAAS,EAAa,EAAyC,CAC9D,OAAO,EAA0B,EAAY,QAAS,EAAY,MAAM,CACzE,CAOA,SAAgB,EACf,EACgC,CAChC,MAAO,CACN,yBAA0B,EAAM,mBAAmB,IAAK,GAAY,EAAQ,IAAI,GAAK,CAAC,EACtF,wBAAyB,EAAM,kBAAkB,IAAK,GAAY,EAAQ,IAAI,GAAK,CAAC,CACrF,CACD,CAqCA,SAAgB,EACf,EACA,EACiC,CACjC,IAAI,EAAc,EA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,YAAY,IAC/C,IAAK,gBACJ,MAAO,MAAM,EAAK,OAAO,MAAM,EAAG,EAAE,IAAI,EAAK,OAAO,OAAS,GAAK,MAAQ,KAC3E,QAEC,MAAU,MAAM,sCAAsC,OAAOA,CAAU,GAAG,CAE5E,CACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"policy-engine.js","names":[],"sources":["../../../src/internal/verify/policy-engine.ts"],"sourcesContent":["/**\n * Internal RFC 9618 policy-validation engine.\n *\n * Tracks the policy graph and counter state through each certificate in a\n * chain, then derives the {@linkcode PolicyValidationOutcome}.\n *\n * @module\n */\n\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn.ts';\nimport type { Micro509Error, Result } from '#micro509/result/result.ts';\nimport type {\n\tConstrainedPolicy,\n\tPolicyValidationInput,\n\tPolicyValidationOutcome,\n} from '#micro509/verify/policy.ts';\nimport type { PolicyInformation, PolicyQualifierInfo } from '#micro509/x509/extensions.ts';\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\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`. */\ninterface 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. */\ninterface PolicyGraph {\n\t/** Each index `i` holds the nodes at depth `i`, keyed by `\"depth:oid\"`. */\n\tnodesByDepth: Map<string, PolicyGraphNode>[];\n}\n\n/**\n * Initializes mutable policy state from caller options.\n *\n * Counter values default to `chainLength + 1` (effectively disabled) unless\n * the corresponding input flag is `true`.\n */\nexport function createPolicyValidationState(\n\tinput: PolicyValidationInput,\n\tchainLength: number,\n): PolicyValidationState {\n\tconst disabledCounter = chainLength + 1;\n\treturn {\n\t\tinitialPolicySet: input.initialPolicySet ?? 'any',\n\t\texplicitPolicy: input.requireExplicitPolicy === true ? 0 : disabledCounter,\n\t\tinhibitPolicyMapping: input.inhibitPolicyMapping === true ? 0 : disabledCounter,\n\t\tinhibitAnyPolicy: input.inhibitAnyPolicy === true ? 0 : disabledCounter,\n\t\tvalidPolicyGraph: createInitialPolicyGraph(),\n\t};\n}\n\n/**\n * Walks the chain root-to-leaf, updating policy state per certificate,\n * then checks whether the resulting policy set satisfies caller requirements.\n */\nexport function evaluatePolicyChain(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n): PolicyValidationResult {\n\tif (chain.length === 0) {\n\t\tthrow new RangeError('policy validation requires at least one certificate');\n\t}\n\tprocessPolicyState(chain, state);\n\tconst outcome = derivePolicyValidationOutcome(chain, state);\n\tif (state.explicitPolicy === 0 && outcome.userConstrainedPolicies.length === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: 'explicit_policy_required',\n\t\t\t\tmessage: 'policy validation requires an explicit permitted policy',\n\t\t\t\tdetails: {\n\t\t\t\t\texpected:\n\t\t\t\t\t\tstate.initialPolicySet === 'any' ? 'explicit policy' : state.initialPolicySet.join(','),\n\t\t\t\t\tactual: describeFinalPolicies(outcome.userConstrainedPolicies),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\tif (state.initialPolicySet !== 'any' && outcome.userConstrainedPolicies.length === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tcode: 'initial_policy_set_not_satisfied',\n\t\t\t\tmessage: 'certificate chain does not satisfy the requested initial policy set',\n\t\t\t\tdetails: {\n\t\t\t\t\texpected: state.initialPolicySet.join(','),\n\t\t\t\t\tactual: describeFinalPolicies(outcome.userConstrainedPolicies),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn { ok: true, value: outcome };\n}\n\n/** Builds the depth-0 graph with a single anyPolicy root node. */\nfunction createInitialPolicyGraph(): PolicyGraph {\n\tconst rootNode = createPolicyGraphNode(0, OIDS.anyPolicy, undefined, [OIDS.anyPolicy], []);\n\treturn {\n\t\tnodesByDepth: [new Map([[policyNodeKey(0, OIDS.anyPolicy), rootNode]])],\n\t};\n}\n\n/** Constructs a new {@linkcode PolicyGraphNode} with empty child-key set. */\nfunction createPolicyGraphNode(\n\tdepth: number,\n\tvalidPolicy: string,\n\tqualifierSet: readonly PolicyQualifierInfo[] | undefined,\n\texpectedPolicySet: readonly string[],\n\tparentKeys: readonly string[],\n): PolicyGraphNode {\n\treturn {\n\t\tdepth,\n\t\tvalidPolicy,\n\t\t...(qualifierSet === undefined ? {} : { qualifierSet }),\n\t\texpectedPolicySet: new Set(expectedPolicySet),\n\t\tparentKeys: new Set(parentKeys),\n\t\tchildKeys: new Set<string>(),\n\t};\n}\n\n/** Canonical map key for a graph node: `\"depth:policyOID\"`. */\nfunction policyNodeKey(depth: number, validPolicy: string): string {\n\treturn `${String(depth)}:${validPolicy}`;\n}\n\n/** Iterates root-to-leaf (skipping root), applying each certificate's policies to the state. */\nfunction processPolicyState(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n): void {\n\tif (chain.length === 1) {\n\t\tconst certificate = chain[0];\n\t\tif (certificate === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`missing certificate at chain index 0 (chain length ${String(chain.length)})`,\n\t\t\t);\n\t\t}\n\t\tprocessPolicyCertificate(state, certificate, 1, true);\n\t\treturn;\n\t}\n\tconst leafDepth = chain.length - 1;\n\tfor (let index = chain.length - 2; index >= 0; index -= 1) {\n\t\tconst certificate = chain[index];\n\t\tif (certificate === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`missing certificate at chain index ${String(index)} (chain length ${String(chain.length)})`,\n\t\t\t);\n\t\t}\n\t\tconst depth = leafDepth - index;\n\t\tprocessPolicyCertificate(state, certificate, depth, depth === leafDepth);\n\t}\n}\n\n/** Extracts the final authority- and user-constrained policy sets from the completed graph. */\nfunction derivePolicyValidationOutcome(\n\tchain: readonly ParsedCertificate[],\n\tstate: PolicyValidationState,\n): PolicyValidationOutcome {\n\tconst authorityConstrainedPolicies = collectAuthorityConstrainedPolicies(\n\t\tchain,\n\t\tstate.validPolicyGraph,\n\t);\n\tconst rootDomainPolicies = collectRootDomainPolicies(chain, state.validPolicyGraph);\n\treturn {\n\t\tauthorityConstrainedPolicies: [...authorityConstrainedPolicies.values()].sort(comparePolicies),\n\t\tuserConstrainedPolicies: deriveUserConstrainedPolicies(\n\t\t\tauthorityConstrainedPolicies,\n\t\t\trootDomainPolicies,\n\t\t\tstate.initialPolicySet,\n\t\t),\n\t};\n}\n\n/** Collects leaf-depth policies whose graph paths trace back to the anyPolicy root. */\nfunction collectAuthorityConstrainedPolicies(\n\tchain: readonly ParsedCertificate[],\n\tgraph: PolicyGraph | null,\n): ReadonlyMap<string, ConstrainedPolicy> {\n\tif (graph === null) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst leafDepth = Math.max(1, chain.length - 1);\n\tconst finalDepth = graph.nodesByDepth[leafDepth];\n\tif (finalDepth === undefined) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst authorityPolicies = new Map<string, ConstrainedPolicy>();\n\tfor (const [key, node] of finalDepth) {\n\t\tif (node.validPolicy === OIDS.anyPolicy) {\n\t\t\tauthorityPolicies.set(\n\t\t\t\tOIDS.anyPolicy,\n\t\t\t\tbuildConstrainedPolicy(OIDS.anyPolicy, node.qualifierSet),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (reachesAuthorityRoot(graph, key)) {\n\t\t\tauthorityPolicies.set(\n\t\t\t\tnode.validPolicy,\n\t\t\t\tbuildConstrainedPolicy(node.validPolicy, node.qualifierSet),\n\t\t\t);\n\t\t}\n\t}\n\treturn authorityPolicies;\n}\n\n/** DFS upward through parent links to check if the node ultimately connects to the depth-0 anyPolicy root. */\nfunction reachesAuthorityRoot(graph: PolicyGraph, nodeKey: string): boolean {\n\tconst pending = [nodeKey];\n\tconst visited = new Set<string>();\n\twhile (pending.length > 0) {\n\t\tconst currentKey = pending.pop();\n\t\tif (currentKey === undefined || visited.has(currentKey)) {\n\t\t\tcontinue;\n\t\t}\n\t\tvisited.add(currentKey);\n\t\tconst node = getPolicyGraphNode(graph, currentKey);\n\t\tif (node === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const parentKey of node.parentKeys) {\n\t\t\tconst parent = getPolicyGraphNode(graph, parentKey);\n\t\t\tif (parent === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (parent.depth === 0 && parent.validPolicy === OIDS.anyPolicy) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpending.push(parentKey);\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Like authority-constrained, but records the OID at the depth-1 node that connects to root. */\nfunction collectRootDomainPolicies(\n\tchain: readonly ParsedCertificate[],\n\tgraph: PolicyGraph | null,\n): ReadonlyMap<string, ConstrainedPolicy> {\n\tif (graph === null) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst leafDepth = Math.max(1, chain.length - 1);\n\tconst finalDepth = graph.nodesByDepth[leafDepth];\n\tif (finalDepth === undefined) {\n\t\treturn new Map<string, ConstrainedPolicy>();\n\t}\n\tconst rootPolicies = new Map<string, ConstrainedPolicy>();\n\tfor (const [key, node] of finalDepth) {\n\t\tif (node.validPolicy === OIDS.anyPolicy) {\n\t\t\trootPolicies.set(OIDS.anyPolicy, buildConstrainedPolicy(OIDS.anyPolicy, node.qualifierSet));\n\t\t\tcontinue;\n\t\t}\n\t\tcollectAuthorityConstrainedPolicyRoots(graph, key, rootPolicies);\n\t}\n\treturn rootPolicies;\n}\n\n/** Walks parent links upward, collecting the depth-1 OID that first connects to the root anyPolicy. */\nfunction collectAuthorityConstrainedPolicyRoots(\n\tgraph: PolicyGraph,\n\tnodeKey: string,\n\tauthorityPolicies: Map<string, ConstrainedPolicy>,\n): void {\n\tconst pending = [nodeKey];\n\tconst visited = new Set<string>();\n\twhile (pending.length > 0) {\n\t\tconst currentKey = pending.pop();\n\t\tif (currentKey === undefined || visited.has(currentKey)) {\n\t\t\tcontinue;\n\t\t}\n\t\tvisited.add(currentKey);\n\t\tconst node = getPolicyGraphNode(graph, currentKey);\n\t\tif (node === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const parentKey of node.parentKeys) {\n\t\t\tconst parent = getPolicyGraphNode(graph, parentKey);\n\t\t\tif (parent === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (parent.depth === 0 && parent.validPolicy === OIDS.anyPolicy) {\n\t\t\t\t// Record the depth-1 policy that connects to root\n\t\t\t\t// If the depth-1 node is anyPolicy itself, record anyPolicy so it can satisfy\n\t\t\t\t// any policy in the initial-policy-set via deriveUserConstrainedPolicies\n\t\t\t\tauthorityPolicies.set(\n\t\t\t\t\tnode.validPolicy,\n\t\t\t\t\tbuildConstrainedPolicy(\n\t\t\t\t\t\tnode.validPolicy,\n\t\t\t\t\t\tcurrentKey === nodeKey ? node.qualifierSet : undefined,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpending.push(parentKey);\n\t\t}\n\t}\n}\n\n/** Intersects root-domain policies with the caller's initial-policy-set. */\nfunction deriveUserConstrainedPolicies(\n\tfinalAuthorityConstrainedPolicies: ReadonlyMap<string, ConstrainedPolicy>,\n\trootDomainPolicies: ReadonlyMap<string, ConstrainedPolicy>,\n\tinitialPolicySet: readonly string[] | 'any',\n): readonly ConstrainedPolicy[] {\n\tif (initialPolicySet === 'any') {\n\t\treturn [...finalAuthorityConstrainedPolicies.values()].sort(comparePolicies);\n\t}\n\tconst anyPolicy = rootDomainPolicies.get(OIDS.anyPolicy);\n\t// If the EE asserts anyPolicy, it satisfies any policy in initial-policy-set\n\tconst eeHasAnyPolicy = finalAuthorityConstrainedPolicies.has(OIDS.anyPolicy);\n\tconst constrained = new Map<string, ConstrainedPolicy>();\n\tfor (const policyIdentifier of initialPolicySet) {\n\t\tconst direct = rootDomainPolicies.get(policyIdentifier);\n\t\tif (direct !== undefined) {\n\t\t\tconstrained.set(policyIdentifier, direct);\n\t\t\tcontinue;\n\t\t}\n\t\t// anyPolicy can satisfy a requested policy if:\n\t\t// 1. The EE asserts the specific policy (finalAuthorityConstrainedPolicies.has), OR\n\t\t// 2. The EE itself asserts anyPolicy (eeHasAnyPolicy)\n\t\tif (\n\t\t\tanyPolicy !== undefined &&\n\t\t\t(finalAuthorityConstrainedPolicies.has(policyIdentifier) || eeHasAnyPolicy)\n\t\t) {\n\t\t\tconstrained.set(\n\t\t\t\tpolicyIdentifier,\n\t\t\t\tbuildConstrainedPolicy(policyIdentifier, anyPolicy.policyQualifiers),\n\t\t\t);\n\t\t}\n\t}\n\treturn [...constrained.values()].sort(comparePolicies);\n}\n\n/** Constructs a {@linkcode ConstrainedPolicy}, omitting qualifiers when absent. */\nfunction buildConstrainedPolicy(\n\tpolicyIdentifier: string,\n\tpolicyQualifiers: readonly PolicyQualifierInfo[] | undefined,\n): ConstrainedPolicy {\n\treturn {\n\t\tpolicyIdentifier,\n\t\t...(policyQualifiers === undefined ? {} : { policyQualifiers }),\n\t};\n}\n\n/** Lexicographic comparator for sorting policies by OID string. */\nfunction comparePolicies(left: ConstrainedPolicy, right: ConstrainedPolicy): number {\n\treturn left.policyIdentifier.localeCompare(right.policyIdentifier);\n}\n\n/** Human-readable comma-joined OID list for error messages; `\"<none>\"` when empty. */\nfunction describeFinalPolicies(policies: readonly ConstrainedPolicy[]): string {\n\treturn policies.length === 0\n\t\t? '<none>'\n\t\t: policies.map((policy) => policy.policyIdentifier).join(',');\n}\n\n/** Applies one certificate's policies, mappings, and constraints to the running state. */\nfunction processPolicyCertificate(\n\tstate: PolicyValidationState,\n\tcertificate: ParsedCertificate,\n\tdepth: number,\n\tisLeaf: boolean,\n): void {\n\tconst certificatePolicies = normalizeCertificatePolicies(certificate.certificatePolicies);\n\tif (state.validPolicyGraph !== null && certificatePolicies === undefined) {\n\t\tstate.validPolicyGraph = null;\n\t} else if (state.validPolicyGraph !== null && certificatePolicies !== undefined) {\n\t\tapplyCertificatePolicyStep(\n\t\t\tstate.validPolicyGraph,\n\t\t\tcertificatePolicies,\n\t\t\tdepth,\n\t\t\tstate.inhibitAnyPolicy > 0 || (!isLeaf && isSelfIssued(certificate)),\n\t\t);\n\t\tif (certificate.policyMappings !== undefined) {\n\t\t\tapplyPolicyMappingsStep(\n\t\t\t\tstate.validPolicyGraph,\n\t\t\t\tdepth,\n\t\t\t\tcertificate.policyMappings,\n\t\t\t\tstate.inhibitPolicyMapping > 0,\n\t\t\t);\n\t\t}\n\t}\n\tupdatePolicyCounters(state, certificate, isLeaf);\n}\n\n/** Deduplicates certificate policies by OID, keeping the first occurrence. */\nfunction normalizeCertificatePolicies(\n\tpolicies: readonly PolicyInformation[] | undefined,\n): Map<string, PolicyInformation> | undefined {\n\tif (policies === undefined) {\n\t\treturn undefined;\n\t}\n\tconst byOid = new Map<string, PolicyInformation>();\n\tfor (const policy of policies) {\n\t\tif (!byOid.has(policy.policyIdentifier)) {\n\t\t\tbyOid.set(policy.policyIdentifier, policy);\n\t\t}\n\t}\n\treturn byOid;\n}\n\n/** Extends the policy graph by one depth level using a certificate's policy extension. */\nfunction applyCertificatePolicyStep(\n\tgraph: PolicyGraph,\n\tcertificatePolicies: ReadonlyMap<string, PolicyInformation>,\n\tdepth: number,\n\tallowAnyPolicyExpansion: boolean,\n): void {\n\tconst previousDepth = graph.nodesByDepth[depth - 1] ?? new Map<string, PolicyGraphNode>();\n\tconst currentDepth = new Map<string, PolicyGraphNode>();\n\tgraph.nodesByDepth[depth] = currentDepth;\n\tconst anyPolicyInfo = certificatePolicies.get(OIDS.anyPolicy);\n\tconst previousAnyPolicy = previousDepth.get(policyNodeKey(depth - 1, OIDS.anyPolicy));\n\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\taddOrMergePolicyNode(\n\t\t\t\tgraph,\n\t\t\t\tcurrentDepth,\n\t\t\t\tdepth,\n\t\t\t\tpolicy.policyIdentifier,\n\t\t\t\tpolicy.policyQualifiers,\n\t\t\t\tmatchingParents,\n\t\t\t\t[policy.policyIdentifier],\n\t\t\t);\n\t\t}\n\t}\n\n\tif (previousAnyPolicy !== undefined) {\n\t\tconst previousAnyPolicyKey = policyNodeKey(depth - 1, OIDS.anyPolicy);\n\t\tfor (const policy of certificatePolicies.values()) {\n\t\t\tif (policy.policyIdentifier === OIDS.anyPolicy) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (currentDepth.has(policyNodeKey(depth, policy.policyIdentifier))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\taddOrMergePolicyNode(\n\t\t\t\tgraph,\n\t\t\t\tcurrentDepth,\n\t\t\t\tdepth,\n\t\t\t\tpolicy.policyIdentifier,\n\t\t\t\tpolicy.policyQualifiers,\n\t\t\t\t[previousAnyPolicyKey],\n\t\t\t\t[policy.policyIdentifier],\n\t\t\t);\n\t\t}\n\t}\n\n\tif (anyPolicyInfo !== undefined && allowAnyPolicyExpansion) {\n\t\tfor (const [validPolicy, parentKeys] of collectExpectedPolicyParents(previousDepth)) {\n\t\t\tif (currentDepth.has(policyNodeKey(depth, validPolicy))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst expansionParents =\n\t\t\t\tvalidPolicy === OIDS.anyPolicy\n\t\t\t\t\t? previousAnyPolicy === undefined\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: [policyNodeKey(depth - 1, OIDS.anyPolicy)]\n\t\t\t\t\t: parentKeys;\n\t\t\tif (expansionParents.length === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\taddOrMergePolicyNode(\n\t\t\t\tgraph,\n\t\t\t\tcurrentDepth,\n\t\t\t\tdepth,\n\t\t\t\tvalidPolicy,\n\t\t\t\tanyPolicyInfo.policyQualifiers,\n\t\t\t\texpansionParents,\n\t\t\t\t[validPolicy],\n\t\t\t);\n\t\t}\n\t}\n\n\tprunePolicyGraph(graph, depth - 1);\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\tif (state.explicitPolicy > 0) {\n\t\t\tstate.explicitPolicy -= 1;\n\t\t}\n\t\tif (isNonNegativeInteger(certificate.policyConstraints?.requireExplicitPolicy)) {\n\t\t\tif (certificate.policyConstraints.requireExplicitPolicy === 0) {\n\t\t\t\tstate.explicitPolicy = 0;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\tif (!isSelfIssued(certificate)) {\n\t\tif (state.explicitPolicy > 0) {\n\t\t\tstate.explicitPolicy -= 1;\n\t\t}\n\t\tif (state.inhibitPolicyMapping > 0) {\n\t\t\tstate.inhibitPolicyMapping -= 1;\n\t\t}\n\t\tif (state.inhibitAnyPolicy > 0) {\n\t\t\tstate.inhibitAnyPolicy -= 1;\n\t\t}\n\t}\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":"mGAuFA,SAAgB,EACf,EACA,EACwB,CACxB,IAAM,EAAkB,EAAc,EACtC,MAAO,CACN,iBAAkB,EAAM,kBAAoB,MAC5C,eAAgB,EAAM,wBAA0B,GAAO,EAAI,EAC3D,qBAAsB,EAAM,uBAAyB,GAAO,EAAI,EAChE,iBAAkB,EAAM,mBAAqB,GAAO,EAAI,EACxD,iBAAkB,EAAyB,CAC5C,CACD,CAMA,SAAgB,EACf,EACA,EACyB,CACzB,GAAI,EAAM,SAAW,EACpB,MAAU,WAAW,qDAAqD,EAE3E,EAAmB,EAAO,CAAK,EAC/B,IAAM,EAAU,EAA8B,EAAO,CAAK,EA4B1D,OA3BI,EAAM,iBAAmB,GAAK,EAAQ,wBAAwB,SAAW,EACrE,CACN,GAAI,GACJ,MAAO,CACN,KAAM,2BACN,QAAS,0DACT,QAAS,CACR,SACC,EAAM,mBAAqB,MAAQ,kBAAoB,EAAM,iBAAiB,KAAK,GAAG,EACvF,OAAQ,EAAsB,EAAQ,uBAAuB,CAC9D,CACD,CACD,EAEG,EAAM,mBAAqB,OAAS,EAAQ,wBAAwB,SAAW,EAC3E,CACN,GAAI,GACJ,MAAO,CACN,KAAM,mCACN,QAAS,sEACT,QAAS,CACR,SAAU,EAAM,iBAAiB,KAAK,GAAG,EACzC,OAAQ,EAAsB,EAAQ,uBAAuB,CAC9D,CACD,CACD,EAEM,CAAE,GAAI,GAAM,MAAO,CAAQ,CACnC,CAGA,SAAS,GAAwC,CAChD,IAAM,EAAW,EAAsB,EAAG,EAAK,UAAW,IAAA,GAAW,CAAC,EAAK,SAAS,EAAG,CAAC,CAAC,EACz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AEH,EAAqB,EAAY,mBAAmB,qBAAqB,GACxE,EAAY,kBAAkB,wBAA0B,IAC3D,EAAM,eAAiB,GAGzB,MACD,CACK,EAAa,CAAW,IACxB,EAAM,eAAiB,GAC1B,IAAM,eAEH,EAAM,qBAAuB,GAChC,IAAM,qBAEH,EAAM,iBAAmB,GAC5B,IAAM,kBAGR,IAAM,EAAoB,EAAY,kBAErC,EAAqB,GAAmB,qBAAqB,GAC7D,EAAkB,sBAAwB,EAAM,iBAEhD,EAAM,eAAiB,EAAkB,uBAGzC,EAAqB,GAAmB,oBAAoB,GAC5D,EAAkB,qBAAuB,EAAM,uBAE/C,EAAM,qBAAuB,EAAkB,sBAG/C,EAAqB,EAAY,kBAAkB,SAAS,GAC5D,EAAY,iBAAiB,UAAY,EAAM,mBAE/C,EAAM,iBAAmB,EAAY,iBAAiB,UAExD,CAEA,SAAS,EAAqB,EAA4C,CACzE,OAAO,IAAU,IAAA,IAAa,OAAO,UAAU,CAAK,GAAK,GAAS,CACnE,CAGA,SAAS,EAAa,EAAyC,CAC9D,OAAO,EAA0B,EAAY,QAAS,EAAY,MAAM,CACzE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"verify-path.js","names":[],"sources":["../../../src/internal/verify/verify-path.ts"],"sourcesContent":["/**\n * Internal certificate path-building and signature-check helpers.\n *\n * Loads and parses candidate certificates, ranks issuer candidates by AKI/root\n * affinity, matches against bare {@linkcode TrustAnchor}s, and performs the\n * depth-first chain search used by the public verify APIs in `verify.ts`.\n *\n * @module\n */\n\nimport { toHex } from '#micro509/internal/asn1/asn1.ts';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify.ts';\nimport { canonicalDnKey, compareDistinguishedNames } from '#micro509/internal/shared/dn.ts';\nimport type {\n\tCertificateSource,\n\tTrustAnchor,\n\tVerifyChainFailure,\n\tVerifyErrorCode,\n\tVerifyFailureDetails,\n} from '#micro509/verify/verify.ts';\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificatesFromSource } from '#micro509/x509/parse.ts';\n\ntype VerifyCertificateSignatureResult =\n\t| { readonly ok: true; readonly valid: boolean }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly code: 'signature_invalid' | 'unsupported_signature_algorithm_parameters';\n\t\t\treadonly reason: string;\n\t };\n\n/** Result of the internal chain-building search. */\nexport interface InternalBuildResult {\n\t/** Deepest chain found (leaf-to-root order), may be partial if no root was reached. */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** `true` when the chain terminates at a trusted root or anchor. */\n\treadonly foundTrustedRoot: boolean;\n\t/** Chain index where no issuer candidate existed, when the search dead-ended. */\n\treadonly missingIssuerAt?: number;\n\t/** Best failure encountered during the search, for diagnostic reporting. */\n\treadonly failure?: VerifyChainFailure;\n}\n\n/** Result of attempting to match a certificate against bare trust anchors. */\ninterface TrustAnchorMatchResult {\n\t/** `true` if a trust anchor verified the certificate's signature. */\n\treadonly matched: boolean;\n\t/** Failure to report when matching was attempted but signature verification failed. */\n\treadonly failure?: VerifyChainFailure;\n}\n\n/** Loose input for constructing failure detail objects during path building. */\ninterface VerifyPathFailureDetailsInput {\n\treadonly subjectCommonName?: string | undefined;\n\treadonly issuerCommonName?: string | undefined;\n\treadonly expected?: string | undefined;\n\treadonly actual?: string | undefined;\n\treadonly chainCommonNames?: readonly string[] | undefined;\n}\n\n/** Callbacks injected by the caller to construct failure objects during path building. */\nexport interface VerifyPathCallbacks {\n\t/** Constructs a {@linkcode VerifyChainFailure} from a code, message, chain index, and details. */\n\treadonly failure: (\n\t\tcode: VerifyErrorCode,\n\t\tmessage: string,\n\t\tindex?: number,\n\t\tdetails?: VerifyFailureDetails,\n\t) => VerifyChainFailure;\n\t/** Constructs a {@linkcode VerifyFailureDetails} from loose inputs. */\n\treadonly detail: (input: VerifyPathFailureDetailsInput) => VerifyFailureDetails;\n}\n\n/** Returns `true` if `at` falls within the certificate's notBefore/notAfter window (inclusive). */\nexport function isWithinValidity(certificate: ParsedCertificate, at: Date): boolean {\n\treturn (\n\t\tcertificate.notBefore.getTime() <= at.getTime() &&\n\t\tat.getTime() <= certificate.notAfter.getTime()\n\t);\n}\n\n/** Returns `true` if the certificate's subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nexport function isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n\n/** Counts non-self-issued CA certificates in positions 0..(index-1) for pathLength checking. */\nexport function countCaCertificatesBelowParsed(\n\tchain: readonly ParsedCertificate[],\n\tindex: number,\n): number {\n\tlet total = 0;\n\tfor (let cursor = 1; cursor < index; cursor += 1) {\n\t\tconst certificate = chain[cursor];\n\t\tif (certificate?.basicConstraints?.ca === true && !isSelfIssued(certificate)) {\n\t\t\ttotal += 1;\n\t\t}\n\t}\n\treturn total;\n}\n\n/** Parses an array of PEM/DER sources into parsed certificates, expanding multi-block PEM. */\nexport function loadCertificates(\n\tsources: readonly CertificateSource[],\n): readonly ParsedCertificate[] {\n\tconst loaded: ParsedCertificate[] = [];\n\tfor (const source of sources) {\n\t\tloaded.push(...expandSource(source));\n\t}\n\treturn loaded;\n}\n\n/** Parses exactly one certificate from a PEM/DER source. Throws if the source contains zero or multiple certificates. */\nexport function loadSingleCertificate(source: CertificateSource): ParsedCertificate {\n\tconst loaded = expandSource(source);\n\tconst first = loaded[0];\n\tif (first === undefined) {\n\t\tthrow new Error('No certificate found');\n\t}\n\tif (loaded.length !== 1) {\n\t\tthrow new Error('Expected a single certificate source');\n\t}\n\treturn first;\n}\n\n/** Verifies that `certificate` was signed by `issuer`'s public key. */\nexport async function verifyCertificateSignature(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): Promise<VerifyCertificateSignatureResult> {\n\tconst result = await verifySignedDataDetailed(\n\t\tcertificate.signatureAlgorithmOid,\n\t\tcertificate.signatureAlgorithmParametersDer,\n\t\tissuer.publicKeyAlgorithmOid,\n\t\tissuer.publicKeyParametersOid,\n\t\tissuer.subjectPublicKeyInfoDer,\n\t\tcertificate.signatureValue,\n\t\tcertificate.tbsCertificateDer,\n\t);\n\tif (!result.ok && result.code === 'verification_error') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'signature_invalid',\n\t\t\treason: result.reason,\n\t\t};\n\t}\n\treturn result;\n}\n\n/**\n * Depth-first chain search from leaf to root. Tries all issuer candidates,\n * checking validity, CA constraints, AKI, pathLength, and signatures at each\n * step. Returns the first fully anchored path or the deepest partial path\n * with the best failure encountered.\n */\nexport async function buildChainInternal(\n\tleaf: ParsedCertificate,\n\tintermediates: readonly ParsedCertificate[],\n\troots: readonly ParsedCertificate[],\n\ttrustAnchors: readonly TrustAnchor[],\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n): Promise<InternalBuildResult> {\n\tconst candidates = [...intermediates, ...roots];\n\tconst subjectIndex = new Map<string, ParsedCertificate[]>();\n\tconst order = new Map<string, number>();\n\tconst rootFingerprints = new Set(roots.map((candidate) => fingerprint(candidate)));\n\tconst anchorIndex = new Map<string, TrustAnchor[]>();\n\tfor (const anchor of trustAnchors) {\n\t\tconst key = canonicalDnKey(anchor.subject);\n\t\tconst existing = anchorIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tanchorIndex.set(key, [anchor]);\n\t\t} else {\n\t\t\texisting.push(anchor);\n\t\t}\n\t}\n\tlet sawUntrustedAnchor = false;\n\tlet deepestPath: readonly ParsedCertificate[] = [leaf];\n\tlet deepestMissingIssuerAt: number | undefined;\n\tlet preferredFailure: VerifyChainFailure | undefined;\n\tconst deadEnds = new Set<string>();\n\n\tcandidates.forEach((candidate, index) => {\n\t\tconst key = canonicalDnKey(candidate.subject);\n\t\tconst existing = subjectIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tsubjectIndex.set(key, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t\torder.set(fingerprint(candidate), index);\n\t});\n\n\tconst maxDepth = candidates.length + 1;\n\tconst startFingerprint = fingerprint(leaf);\n\tconst success = await search(leaf, [leaf], new Set([startFingerprint]), 0);\n\tif (success !== undefined) {\n\t\treturn { chain: success, foundTrustedRoot: true };\n\t}\n\tif (preferredFailure !== undefined) {\n\t\treturn {\n\t\t\tchain: deepestPath,\n\t\t\tfoundTrustedRoot: false,\n\t\t\tfailure: preferredFailure,\n\t\t};\n\t}\n\tif (sawUntrustedAnchor) {\n\t\treturn { chain: deepestPath, foundTrustedRoot: false };\n\t}\n\treturn deepestMissingIssuerAt === undefined\n\t\t? { chain: deepestPath, foundTrustedRoot: false }\n\t\t: {\n\t\t\t\tchain: deepestPath,\n\t\t\t\tfoundTrustedRoot: false,\n\t\t\t\tmissingIssuerAt: deepestMissingIssuerAt,\n\t\t\t};\n\n\tasync function search(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tif (rootFingerprints.has(fingerprint(current))) {\n\t\t\treturn path;\n\t\t}\n\t\tconst matchedAnchor = await matchTrustAnchor(current, anchorIndex, callbacks, path.length - 1);\n\t\tif (matchedAnchor.failure !== undefined) {\n\t\t\trecordFailure(matchedAnchor.failure, path);\n\t\t}\n\t\tif (matchedAnchor.matched) {\n\t\t\treturn path;\n\t\t}\n\t\tif (path.length > maxDepth) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst visitedKey = [...visited].sort().join(',');\n\t\tconst memoKey = `${fingerprint(current)}:${caBelowCount}:${visitedKey}`;\n\t\tif (deadEnds.has(memoKey)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst issuers = rankIssuerCandidates(\n\t\t\tcurrent,\n\t\t\tsubjectIndex.get(canonicalDnKey(current.issuer)) ?? [],\n\t\t\torder,\n\t\t\trootFingerprints,\n\t\t);\n\t\tif (issuers.length === 0) {\n\t\t\tconst wasDeepest = path.length > deepestPath.length;\n\t\t\tupdateDeepest(path);\n\t\t\tif (isSelfIssued(current)) {\n\t\t\t\tsawUntrustedAnchor = true;\n\t\t\t} else if (wasDeepest) {\n\t\t\t\tdeepestMissingIssuerAt = path.length - 1;\n\t\t\t}\n\t\t\tdeadEnds.add(memoKey);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tfor (const issuer of issuers) {\n\t\t\tconst issuerFingerprint = fingerprint(issuer);\n\t\t\tif (visited.has(issuerFingerprint)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isWithinValidity(issuer, at)) {\n\t\t\t\trecordFailure(\n\t\t\t\t\tcallbacks.failure(\n\t\t\t\t\t\t'certificate_expired',\n\t\t\t\t\t\t'certificate not valid at requested time',\n\t\t\t\t\t\tpath.length,\n\t\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\t\t\texpected: describeDateTime(at),\n\t\t\t\t\t\t\tactual: `${describeDateTime(issuer.notBefore)}..${describeDateTime(issuer.notAfter)}`,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (issuer.basicConstraints?.ca !== true) {\n\t\t\t\trecordFailure(\n\t\t\t\t\tcallbacks.failure(\n\t\t\t\t\t\t'ca_required',\n\t\t\t\t\t\t'issuer must be a CA certificate',\n\t\t\t\t\t\tpath.length,\n\t\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (issuer.keyUsage !== undefined && !issuer.keyUsage.flags.includes('keyCertSign')) {\n\t\t\t\trecordFailure(\n\t\t\t\t\tcallbacks.failure(\n\t\t\t\t\t\t'key_cert_sign_required',\n\t\t\t\t\t\t'issuer missing keyCertSign',\n\t\t\t\t\t\tpath.length,\n\t\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcurrent.authorityKeyIdentifier !== undefined &&\n\t\t\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\t\t\tcurrent.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t\t\t) {\n\t\t\t\trecordFailure(\n\t\t\t\t\tcallbacks.failure(\n\t\t\t\t\t\t'authority_key_identifier_mismatch',\n\t\t\t\t\t\t'authorityKeyIdentifier does not match issuer subjectKeyIdentifier',\n\t\t\t\t\t\tpath.length - 1,\n\t\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\t\t\texpected: issuer.subjectKeyIdentifier,\n\t\t\t\t\t\t\tactual: current.authorityKeyIdentifier,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst nextCaBelowCount =\n\t\t\t\tcaBelowCount +\n\t\t\t\t(current.basicConstraints?.ca === true && !isSelfIssued(current) && path.length > 1\n\t\t\t\t\t? 1\n\t\t\t\t\t: 0);\n\t\t\tconst pathLength = issuer.basicConstraints?.pathLength;\n\t\t\tif (isNonNegativeInteger(pathLength) && nextCaBelowCount > pathLength) {\n\t\t\t\trecordFailure(\n\t\t\t\t\tcallbacks.failure(\n\t\t\t\t\t\t'path_length_exceeded',\n\t\t\t\t\t\t'path length constraint exceeded',\n\t\t\t\t\t\tpath.length,\n\t\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\t\t\texpected: String(pathLength),\n\t\t\t\t\t\t\tactual: String(nextCaBelowCount),\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst signatureResult = await verifyCertificateSignature(current, issuer);\n\t\t\tif (!signatureResult.ok) {\n\t\t\t\trecordFailure(\n\t\t\t\t\tcallbacks.failure(\n\t\t\t\t\t\tsignatureResult.code,\n\t\t\t\t\t\tsignatureResult.reason,\n\t\t\t\t\t\tpath.length - 1,\n\t\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\t\t\tactual: signatureResult.reason,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!signatureResult.valid) {\n\t\t\t\trecordFailure(\n\t\t\t\t\tcallbacks.failure(\n\t\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\t\tpath.length - 1,\n\t\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst nextVisited = new Set(visited);\n\t\t\tnextVisited.add(issuerFingerprint);\n\t\t\tconst nextPath = [...path, issuer];\n\t\t\tconst result = await search(issuer, nextPath, nextVisited, nextCaBelowCount);\n\t\t\tif (result !== undefined) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\tdeadEnds.add(memoKey);\n\t\tupdateDeepest(path);\n\t\treturn undefined;\n\t}\n\n\tfunction updateDeepest(path: readonly ParsedCertificate[]): boolean {\n\t\tif (path.length > deepestPath.length) {\n\t\t\tdeepestPath = path;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tfunction recordFailure(\n\t\tcandidateFailure: VerifyChainFailure,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tif (preferredFailure === undefined || path.length > deepestPath.length) {\n\t\t\tpreferredFailure = candidateFailure;\n\t\t\tdeepestPath = path;\n\t\t}\n\t}\n}\n\n/** Expands a PEM (possibly multi-block) or DER source into parsed certificates. */\nfunction expandSource(source: CertificateSource): readonly ParsedCertificate[] {\n\treturn parseCertificatesFromSource(source);\n}\n\n/** Filters and sorts issuer candidates: AKI match first, then roots, then input order. */\nfunction rankIssuerCandidates(\n\tcurrent: ParsedCertificate,\n\tcandidates: readonly ParsedCertificate[],\n\torder: ReadonlyMap<string, number>,\n\trootFingerprints: ReadonlySet<string>,\n): readonly ParsedCertificate[] {\n\tconst aki = current.authorityKeyIdentifier;\n\tconst filtered = [...candidates].filter((candidate) => isIssuerOf(candidate, current));\n\tconst fps = new Map<ParsedCertificate, string>();\n\tfor (const candidate of filtered) {\n\t\tfps.set(candidate, fingerprint(candidate));\n\t}\n\treturn filtered.sort((left, right) => {\n\t\tconst akiScore = compareBooleans(matchesAki(left, aki), matchesAki(right, aki));\n\t\tif (akiScore !== 0) {\n\t\t\treturn akiScore;\n\t\t}\n\t\tconst leftFp = fps.get(left) ?? '';\n\t\tconst rightFp = fps.get(right) ?? '';\n\t\tconst rootScore = compareBooleans(rootFingerprints.has(leftFp), rootFingerprints.has(rightFp));\n\t\tif (rootScore !== 0) {\n\t\t\treturn rootScore;\n\t\t}\n\t\treturn (\n\t\t\t(order.get(leftFp) ?? Number.MAX_SAFE_INTEGER) -\n\t\t\t(order.get(rightFp) ?? Number.MAX_SAFE_INTEGER)\n\t\t);\n\t});\n}\n\n/** Returns `true` if the candidate's SKI matches the given authority key identifier. */\nfunction matchesAki(candidate: ParsedCertificate, aki: string | undefined): boolean {\n\treturn (\n\t\taki !== undefined &&\n\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\tcandidate.subjectKeyIdentifier === aki\n\t);\n}\n\n/** Sort comparator: `true` sorts before `false`. Returns -1, 0, or 1. */\nfunction compareBooleans(left: boolean, right: boolean): number {\n\tif (left === right) {\n\t\treturn 0;\n\t}\n\treturn left ? -1 : 1;\n}\n\n/** Returns `true` if `issuer`'s subject DN semantically matches `child`'s issuer DN (RFC 5280 §7.1). */\nfunction isIssuerOf(issuer: ParsedCertificate, child: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(child.issuer, issuer.subject);\n}\n\n/** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */\nasync function matchTrustAnchor(\n\tcertificate: ParsedCertificate,\n\tanchorIndex: ReadonlyMap<string, readonly TrustAnchor[]>,\n\tcallbacks: VerifyPathCallbacks,\n\tindex: number,\n): Promise<TrustAnchorMatchResult> {\n\tconst anchors = anchorIndex.get(canonicalDnKey(certificate.issuer));\n\tif (anchors === undefined) {\n\t\treturn { matched: false };\n\t}\n\tlet firstFailure: VerifyChainFailure | undefined;\n\tfor (const anchor of anchors) {\n\t\tif (\n\t\t\tanchor.subjectKeyIdentifier !== undefined &&\n\t\t\tcertificate.authorityKeyIdentifier !== undefined &&\n\t\t\tanchor.subjectKeyIdentifier !== certificate.authorityKeyIdentifier\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tlet verified: VerifyCertificateSignatureResult;\n\t\ttry {\n\t\t\tconst verificationResult = await verifySignedDataDetailed(\n\t\t\t\tcertificate.signatureAlgorithmOid,\n\t\t\t\tcertificate.signatureAlgorithmParametersDer,\n\t\t\t\tanchor.publicKeyAlgorithmOid,\n\t\t\t\tanchor.publicKeyParametersOid,\n\t\t\t\tanchor.subjectPublicKeyInfoDer,\n\t\t\t\tcertificate.signatureValue,\n\t\t\t\tcertificate.tbsCertificateDer,\n\t\t\t);\n\t\t\tverified =\n\t\t\t\t!verificationResult.ok && verificationResult.code === 'verification_error'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\tcode: 'signature_invalid',\n\t\t\t\t\t\t\treason: verificationResult.reason,\n\t\t\t\t\t\t}\n\t\t\t\t\t: verificationResult;\n\t\t} catch (error) {\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: error instanceof Error ? error.message : 'trust anchor key is malformed',\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!verified.ok) {\n\t\t\t// Capture the first failure but continue trying other anchors\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\tverified.code,\n\t\t\t\t\tverified.reason,\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: verified.reason,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!verified.valid) {\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: 'certificate signature does not verify',\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\treturn { matched: true };\n\t}\n\treturn firstFailure !== undefined\n\t\t? { matched: false, failure: firstFailure }\n\t\t: { matched: false };\n}\n\nfunction describeDateTime(value: Date): string {\n\treturn Number.isNaN(value.getTime()) ? '<invalid date>' : value.toISOString();\n}\n\nfunction isNonNegativeInteger(value: number | undefined): value is number {\n\treturn value !== undefined && Number.isInteger(value) && value >= 0;\n}\n\n/** Cache for computed fingerprints to avoid repeated toHex() calls. */\nconst fingerprintCache = new WeakMap<ParsedCertificate, string>();\n\n/** Returns a hex fingerprint of the certificate's raw DER, used for cycle detection and dedup. */\nfunction fingerprint(certificate: ParsedCertificate): string {\n\tlet cached = fingerprintCache.get(certificate);\n\tif (cached === undefined) {\n\t\tcached = toHex(certificate.der);\n\t\tfingerprintCache.set(certificate, cached);\n\t}\n\treturn cached;\n}\n"],"mappings":"6PA0EA,SAAgB,EAAiB,EAAgC,EAAmB,CACnF,OACC,EAAY,UAAU,QAAQ,GAAK,EAAG,QAAQ,GAC9C,EAAG,QAAQ,GAAK,EAAY,SAAS,QAAQ,CAE/C,CAGA,SAAgB,EAAa,EAAyC,CACrE,OAAO,EAA0B,EAAY,QAAS,EAAY,MAAM,CACzE,CAGA,SAAgB,EACf,EACA,EACS,CACT,IAAI,EAAQ,EACZ,IAAK,IAAI,EAAS,EAAG,EAAS,EAAO,GAAU,EAAG,CACjD,IAAM,EAAc,EAAM,GACtB,GAAa,kBAAkB,KAAO,IAAQ,CAAC,EAAa,CAAW,IAC1E,GAAS,EAEX,CACA,OAAO,CACR,CAGA,SAAgB,EACf,EAC+B,CAC/B,IAAM,EAA8B,CAAC,EACrC,IAAK,IAAM,KAAU,EACpB,EAAO,KAAK,GAAG,EAAa,CAAM,CAAC,EAEpC,OAAO,CACR,CAGA,SAAgB,EAAsB,EAA8C,CACnF,IAAM,EAAS,EAAa,CAAM,EAC5B,EAAQ,EAAO,GACrB,GAAI,IAAU,IAAA,GACb,MAAU,MAAM,sBAAsB,EAEvC,GAAI,EAAO,SAAW,EACrB,MAAU,MAAM,sCAAsC,EAEvD,OAAO,CACR,CAGA,eAAsB,EACrB,EACA,EAC4C,CAC5C,IAAM,EAAS,MAAM,EACpB,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AAY,QAAQ,OAAO,WAC9C,OAAQ,EAAS,MAClB,CAAC,CACF,GAED,QACD,CACA,GAAI,CAAC,EAAS,MAAO,CAChB,IAAiB,IAAA,KACpB,EAAe,EAAU,QACxB,oBACA,wCACA,EACA,EAAU,OAAO,CAChB,kBAAmB,EAAY,QAAQ,OAAO,WAC9C,OAAQ,uCACT,CAAC,CACF,GAED,QACD,CACA,MAAO,CAAE,QAAS,EAAK,CACxB,CACA,OAAO,IAAiB,IAAA,GAErB,CAAE,QAAS,EAAM,EADjB,CAAE,QAAS,GAAO,QAAS,CAAa,CAE5C,CAEA,SAAS,EAAiB,EAAqB,CAC9C,OAAO,OAAO,MAAM,EAAM,QAAQ,CAAC,EAAI,iBAAmB,EAAM,YAAY,CAC7E,CAEA,SAAS,EAAqB,EAA4C,CACzE,OAAO,IAAU,IAAA,IAAa,OAAO,UAAU,CAAK,GAAK,GAAS,CACnE,CAGA,MAAM,EAAmB,IAAI,QAG7B,SAAS,EAAY,EAAwC,CAC5D,IAAI,EAAS,EAAiB,IAAI,CAAW,EAK7C,OAJI,IAAW,IAAA,KACd,EAAS,EAAM,EAAY,GAAG,EAC9B,EAAiB,IAAI,EAAa,CAAM,GAElC,CACR"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"extension-bits.js","names":[],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der.ts';\nimport type { DistributionPointReason, KeyUsage } from '#micro509/x509/extensions.ts';\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.\n * Verification layers can use this signal to reject non-conformant encodings.\n */\nimport type { ParsedBitFlags } from '#micro509/x509/extensions.ts';\n\nexport type { ParsedBitFlags };\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\t// Detect non-zero padding bits in the unused positions of the last byte.\n\t// DER X.690 §11.2.2 requires these to be zero. Rather than rejecting here\n\t// (which would break interop with real-world non-conformant certificates),\n\t// we record the violation so verification layers can decide.\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":"gEAyBA,MAAM,EAAkB,CACvB,mBACA,iBACA,kBACA,mBACA,eACA,cACA,UACA,eACA,cACD,EAGM,EAAkC,CACvC,gBACA,eACA,qBACA,aACA,uBACA,kBACA,qBACA,cACD,EAOA,SAAgB,EAAwB,EAAyC,CAChF,IAAM,EAAU,EAAe,EAAS,GACvC,EAAa,EAAiB,EAAO,WAAW,CACjD,EACA,OAAO,EAAU,EAAQ,MAAO,EAAQ,UAAU,CACnD,CAOA,SAAgB,EAAuB,EAA6C,CACnF,IAAM,EAAmB,EAAgB,EAAO,CAAE,SAAA,EAAgC,CAAC,EACnF,GAAI,EAAiB,MAAQ,EAC5B,MAAU,MAAM,+BAA+B,EAEhD,OAAO,EACN,EAAe,EAAiB,MAAO,EAAiB,CAAC,EACzD,UACD,CACD,CAQA,SAAgB,EACf,EACa,CACb,IAAM,EAAU,EACf,EACC,GACA,EAAa,EAAiC,EAAQ,2BAA2B,EAAI,CACvF,EACA,OAAO,WAAW,GAAG,EAAQ,WAAY,GAAG,EAAQ,KAAK,CAC1D,CAQA,SAAgB,EACf,EAC0C,CAC1C,OAAO,EACN,EAAe,EAAO,EAAiC,CAAC,EACxD,2BACD,CACD,CAGA,SAAS,EACR,EACA,EAIC,CACD,GAAI,EAAO,SAAW,EACrB,MAAO,CAAE,MAAO,IAAI,WAAe,WAAY,CAAE,EAElD,IAAI,EAAa,GACX,EAAiB,CAAC,EACxB,IAAK,IAAM,KAAS,EAAQ,CAC3B,IAAM,EAAM,EAAY,CAAK,EAC7B,EAAK,KAAK,CAAG,EACT,EAAM,IACT,EAAa,EAEf,CACA,IAAM,EA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O,EAEjD,OAAO,CACR"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"extension-registry.js","names":[],"sources":["../../../src/internal/x509/extension-registry.ts"],"sourcesContent":["/**\n * Internal extension registry for certificate and CSR parsing.\n *\n * Maps each supported extension OID to a definition that can decode DER,\n * encode input, and apply parsed values to the accumulator used during\n * certificate/CSR parsing.\n *\n * @module\n */\n\nimport { hexToBytes, toHex } from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\timplicitPrimitiveContext,\n\toctetString,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport type { ParsedBitFlags } from '#micro509/internal/x509/extension-bits.ts';\nimport type {\n\tAuthorityInformationAccess,\n\tBasicConstraints,\n\tCertificatePolicies,\n\tDistributionPoint,\n\tExtendedKeyUsage,\n\tInhibitAnyPolicy,\n\tKeyUsage,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tPolicyConstraints,\n\tPolicyMappings,\n\tSubjectAltName,\n} from '#micro509/x509/extensions.ts';\nimport {\n\tbuildSubjectKeyIdentifier,\n\tencodeAuthorityInfoAccess,\n\tencodeBasicConstraints,\n\tencodeCertificatePolicies,\n\tencodeCrlDistributionPoints,\n\tencodeExtendedKeyUsage,\n\tencodeInhibitAnyPolicy,\n\tencodeKeyUsage,\n\tencodeNameConstraints,\n\tencodePolicyConstraints,\n\tencodePolicyMappings,\n\tencodeSubjectAltName,\n} from '#micro509/x509/extensions.ts';\nimport type { ParsedDistributionPoint } from '#micro509/x509/parse.ts';\nimport {\n\tparseAuthorityInfoAccess,\n\tparseAuthorityKeyIdentifier,\n\tparseBasicConstraints,\n\tparseCertificatePolicies,\n\tparseCrlDistributionPoints,\n\tparseExtendedKeyUsage,\n\tparseInhibitAnyPolicy,\n\tparseKeyUsage,\n\tparseNameConstraints,\n\tparsePolicyConstraints,\n\tparsePolicyMappings,\n\tparseSubjectAltNames,\n} from '#micro509/x509/parse.ts';\n\n/** Whether an extension applies to certificate parsing, CSR parsing, or both. */\nexport type ExtensionRegistryContext = 'certificate' | 'csr';\n\n/**\n * Readonly snapshot of decoded known extensions collected during parsing.\n *\n * Fields mirror the extension slots on {@linkcode ParsedCertificate}.\n */\nexport interface KnownParsedExtensionAccumulator {\n\t/** Basic Constraints (CA flag + optional pathLength). */\n\treadonly basicConstraints?: BasicConstraints;\n\t/** Key Usage flags (digitalSignature, keyCertSign, etc.). */\n\treadonly keyUsage?: ParsedBitFlags<KeyUsage>;\n\t/** Extended Key Usage purposes (serverAuth, clientAuth, etc.). */\n\treadonly extendedKeyUsage?: readonly ExtendedKeyUsage[];\n\t/** Subject Alternative Names (dns, ip, email, uri, srv, directoryName). */\n\treadonly subjectAltNames?: readonly SubjectAltName[];\n\t/** Name Constraints (permitted/excluded subtrees). */\n\treadonly nameConstraints?: NameConstraints<ParsedNameConstraintForm>;\n\t/** Certificate Policies extension values. */\n\treadonly certificatePolicies?: CertificatePolicies;\n\t/** Policy Mappings from issuer to subject policy domains. */\n\treadonly policyMappings?: PolicyMappings;\n\t/** Policy Constraints (requireExplicitPolicy / inhibitPolicyMapping). */\n\treadonly policyConstraints?: PolicyConstraints;\n\t/** Inhibit Any-Policy skip-certs value. */\n\treadonly inhibitAnyPolicy?: InhibitAnyPolicy;\n\t/** Authority Information Access (OCSP, CA issuers). */\n\treadonly authorityInfoAccess?: readonly AuthorityInformationAccess[];\n\t/** CRL Distribution Points. */\n\treadonly crlDistributionPoints?: readonly ParsedDistributionPoint[];\n\t/** Hex-encoded Subject Key Identifier. */\n\treadonly subjectKeyIdentifier?: string;\n\t/** Hex-encoded Authority Key Identifier. */\n\treadonly authorityKeyIdentifier?: string;\n}\n\n/**\n * Mutable version of {@linkcode KnownParsedExtensionAccumulator} used during\n * extension parsing to progressively fill in decoded values.\n */\nexport interface MutableKnownParsedExtensionAccumulator extends KnownParsedExtensionAccumulator {\n\tbasicConstraints?: BasicConstraints;\n\tkeyUsage?: ParsedBitFlags<KeyUsage>;\n\textendedKeyUsage?: readonly ExtendedKeyUsage[];\n\tsubjectAltNames?: readonly SubjectAltName[];\n\tnameConstraints?: NameConstraints<ParsedNameConstraintForm>;\n\tcertificatePolicies?: CertificatePolicies;\n\tpolicyMappings?: PolicyMappings;\n\tpolicyConstraints?: PolicyConstraints;\n\tinhibitAnyPolicy?: InhibitAnyPolicy;\n\tauthorityInfoAccess?: readonly AuthorityInformationAccess[];\n\tcrlDistributionPoints?: readonly ParsedDistributionPoint[];\n\tsubjectKeyIdentifier?: string;\n\tauthorityKeyIdentifier?: string;\n}\n\n/**\n * Full lifecycle definition for a known X.509 extension: decode, encode,\n * and apply-to-accumulator during parsing.\n *\n * `TParsed` is the type produced when decoding DER; `TInput` is the type\n * accepted when encoding (they may differ, e.g. for NameConstraints).\n */\nexport interface ExtensionDefinition<TParsed, TInput = TParsed> {\n\t/** Dotted-decimal OID of the extension. */\n\treadonly oid: string;\n\t/** Contexts where this extension is valid (`'certificate'`, `'csr'`, or both). */\n\treadonly contexts: readonly ExtensionRegistryContext[];\n\t/** Whether the extension is marked critical by default when encoding. */\n\treadonly defaultCritical: boolean;\n\t/** When true, the extension is computed by the builder (e.g. SKI, AKI) rather than user-supplied. */\n\treadonly autoGenerated?: boolean;\n\t/** Decode the extension's DER extnValue into a typed value. */\n\tdecode(valueDer: Uint8Array): TParsed;\n\t/** Encode a typed input into the extension's DER extnValue. */\n\tencode(value: TInput): Uint8Array;\n\t/** Store a decoded value into the parse-time accumulator. */\n\tapplyParsed(accumulator: MutableKnownParsedExtensionAccumulator, value: TParsed): void;\n}\n\n/**\n * Module-internal decode-and-apply closures, captured at definition time.\n *\n * Each entry is keyed by OID and populated by {@linkcode defineExtensionDefinition}\n * when the concrete generic type is known, avoiding the correlated-union problem\n * that would arise from calling `decode` and `applyParsed` through a union type.\n */\nconst extensionAppliers = new Map<\n\tstring,\n\t(accumulator: MutableKnownParsedExtensionAccumulator, valueDer: Uint8Array) => void\n>();\n\n/** Registry entry for Basic Constraints (OID 2.5.29.19). Critical by default. */\nexport const BASIC_CONSTRAINTS_EXTENSION_DEFINITION: ExtensionDefinition<BasicConstraints> =\n\tdefineExtensionDefinition<BasicConstraints>({\n\t\toid: OIDS.basicConstraints,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parseBasicConstraints(valueDer),\n\t\tencode: (value) => encodeBasicConstraints(value),\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.basicConstraints = value;\n\t\t},\n\t});\n\n/** Registry entry for Key Usage (OID 2.5.29.15). Critical by default. */\nexport const KEY_USAGE_EXTENSION_DEFINITION: ExtensionDefinition<\n\tParsedBitFlags<KeyUsage>,\n\treadonly KeyUsage[]\n> = defineExtensionDefinition<ParsedBitFlags<KeyUsage>, readonly KeyUsage[]>({\n\toid: OIDS.keyUsage,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: true,\n\tdecode: (valueDer) => parseKeyUsage(valueDer),\n\tencode: (value) => encodeKeyUsage(value),\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.keyUsage = value;\n\t},\n});\n\n/** Registry entry for Extended Key Usage (OID 2.5.29.37). Non-critical by default. */\nexport const EXTENDED_KEY_USAGE_EXTENSION_DEFINITION: ExtensionDefinition<\n\treadonly ExtendedKeyUsage[]\n> = defineExtensionDefinition<readonly ExtendedKeyUsage[]>({\n\toid: OIDS.extendedKeyUsage,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseExtendedKeyUsage(valueDer),\n\tencode: (value) => encodeExtendedKeyUsage(value),\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.extendedKeyUsage = value;\n\t},\n});\n\n/** Registry entry for Subject Alternative Name (OID 2.5.29.17). Non-critical by default. */\nexport const SUBJECT_ALT_NAME_EXTENSION_DEFINITION: ExtensionDefinition<readonly SubjectAltName[]> =\n\tdefineExtensionDefinition<readonly SubjectAltName[]>({\n\t\toid: OIDS.subjectAltName,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: false,\n\t\tdecode: (valueDer) => parseSubjectAltNames(valueDer),\n\t\tencode: (value) => sequence(value.map(encodeSubjectAltName)),\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.subjectAltNames = value;\n\t\t},\n\t});\n\n/** Registry entry for Name Constraints (OID 2.5.29.30). Critical by default. */\nexport const NAME_CONSTRAINTS_EXTENSION_DEFINITION: ExtensionDefinition<\n\tNameConstraints<ParsedNameConstraintForm>,\n\tNameConstraints\n> = defineExtensionDefinition<NameConstraints<ParsedNameConstraintForm>, NameConstraints>({\n\toid: OIDS.nameConstraints,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: true,\n\tdecode: (valueDer) => parseNameConstraints(valueDer),\n\tencode: (value) => encodeNameConstraints(value),\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.nameConstraints = value;\n\t},\n});\n\n/** Registry entry for Certificate Policies (OID 2.5.29.32). Non-critical by default. */\nexport const CERTIFICATE_POLICIES_EXTENSION_DEFINITION: ExtensionDefinition<CertificatePolicies> =\n\tdefineExtensionDefinition<CertificatePolicies>({\n\t\toid: OIDS.certificatePolicies,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: false,\n\t\tdecode: (valueDer) => parseCertificatePolicies(valueDer),\n\t\tencode: (value) => encodeCertificatePolicies(value),\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.certificatePolicies = value;\n\t\t},\n\t});\n\n/** Registry entry for Policy Mappings (OID 2.5.29.33). Critical by default. */\nexport const POLICY_MAPPINGS_EXTENSION_DEFINITION: ExtensionDefinition<PolicyMappings> =\n\tdefineExtensionDefinition<PolicyMappings>({\n\t\toid: OIDS.policyMappings,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parsePolicyMappings(valueDer),\n\t\tencode: (value) => encodePolicyMappings(value),\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.policyMappings = value;\n\t\t},\n\t});\n\n/** Registry entry for Policy Constraints (OID 2.5.29.36). Critical by default. */\nexport const POLICY_CONSTRAINTS_EXTENSION_DEFINITION: ExtensionDefinition<PolicyConstraints> =\n\tdefineExtensionDefinition<PolicyConstraints>({\n\t\toid: OIDS.policyConstraints,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parsePolicyConstraints(valueDer),\n\t\tencode: (value) => encodePolicyConstraints(value),\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.policyConstraints = value;\n\t\t},\n\t});\n\n/** Registry entry for Inhibit anyPolicy (OID 2.5.29.54). Critical by default. */\nexport const INHIBIT_ANY_POLICY_EXTENSION_DEFINITION: ExtensionDefinition<InhibitAnyPolicy> =\n\tdefineExtensionDefinition<InhibitAnyPolicy>({\n\t\toid: OIDS.inhibitAnyPolicy,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parseInhibitAnyPolicy(valueDer),\n\t\tencode: (value) => encodeInhibitAnyPolicy(value),\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.inhibitAnyPolicy = value;\n\t\t},\n\t});\n\n/** Registry entry for Authority Information Access (OID 1.3.6.1.5.5.7.1.1). Non-critical. */\nexport const AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION: ExtensionDefinition<\n\treadonly AuthorityInformationAccess[]\n> = defineExtensionDefinition<readonly AuthorityInformationAccess[]>({\n\toid: OIDS.authorityInfoAccess,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseAuthorityInfoAccess(valueDer),\n\tencode: (value) => encodeAuthorityInfoAccess(value),\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.authorityInfoAccess = value;\n\t},\n});\n\n/** Registry entry for CRL Distribution Points (OID 2.5.29.31). Non-critical by default. */\nexport const CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION: ExtensionDefinition<\n\treadonly ParsedDistributionPoint[],\n\treadonly DistributionPoint[]\n> = defineExtensionDefinition<readonly ParsedDistributionPoint[], readonly DistributionPoint[]>({\n\toid: OIDS.cRLDistributionPoints,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseCrlDistributionPoints(valueDer),\n\tencode: (value) => encodeCrlDistributionPoints(value),\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.crlDistributionPoints = value;\n\t},\n});\n\n/** Registry entry for Subject Key Identifier (OID 2.5.29.14). Auto-generated; non-critical. */\nexport const SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION: ExtensionDefinition<\n\tstring,\n\tstring | Uint8Array\n> = defineExtensionDefinition<string, string | Uint8Array>({\n\toid: OIDS.subjectKeyIdentifier,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tautoGenerated: true,\n\tdecode: (valueDer) => decodeSubjectKeyIdentifier(valueDer),\n\tencode: (value) => octetString(normalizeKeyIdentifier(value)),\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.subjectKeyIdentifier = value;\n\t},\n});\n\n/** Registry entry for Authority Key Identifier (OID 2.5.29.35). Auto-generated; non-critical. */\nexport const AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION: ExtensionDefinition<\n\tstring | undefined,\n\tstring | Uint8Array\n> = defineExtensionDefinition<string | undefined, string | Uint8Array>({\n\toid: OIDS.authorityKeyIdentifier,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tautoGenerated: true,\n\tdecode: (valueDer) => parseAuthorityKeyIdentifier(valueDer),\n\tencode: (value) => sequence([implicitPrimitiveContext(0, normalizeKeyIdentifier(value))]),\n\tapplyParsed: (accumulator, value) => {\n\t\tif (value !== undefined) {\n\t\t\taccumulator.authorityKeyIdentifier = value;\n\t\t}\n\t},\n});\n\n/** Union of all built-in extension definition constants. */\nexport type KnownExtensionDefinition =\n\t| typeof BASIC_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof KEY_USAGE_EXTENSION_DEFINITION\n\t| typeof EXTENDED_KEY_USAGE_EXTENSION_DEFINITION\n\t| typeof SUBJECT_ALT_NAME_EXTENSION_DEFINITION\n\t| typeof NAME_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof CERTIFICATE_POLICIES_EXTENSION_DEFINITION\n\t| typeof POLICY_MAPPINGS_EXTENSION_DEFINITION\n\t| typeof POLICY_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof INHIBIT_ANY_POLICY_EXTENSION_DEFINITION\n\t| typeof AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION\n\t| typeof CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION\n\t| typeof SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION\n\t| typeof AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION;\n\n/** All built-in extension definitions, in registration order. */\nexport const CERT_CSR_EXTENSION_DEFINITIONS: readonly KnownExtensionDefinition[] = [\n\tBASIC_CONSTRAINTS_EXTENSION_DEFINITION,\n\tKEY_USAGE_EXTENSION_DEFINITION,\n\tEXTENDED_KEY_USAGE_EXTENSION_DEFINITION,\n\tSUBJECT_ALT_NAME_EXTENSION_DEFINITION,\n\tNAME_CONSTRAINTS_EXTENSION_DEFINITION,\n\tCERTIFICATE_POLICIES_EXTENSION_DEFINITION,\n\tPOLICY_MAPPINGS_EXTENSION_DEFINITION,\n\tPOLICY_CONSTRAINTS_EXTENSION_DEFINITION,\n\tINHIBIT_ANY_POLICY_EXTENSION_DEFINITION,\n\tAUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION,\n\tCRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION,\n\tSUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\tAUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n];\n\n/** OID-keyed lookup for known extension definitions. */\nconst EXTENSION_DEFINITION_MAP = new Map<string, KnownExtensionDefinition>(\n\tCERT_CSR_EXTENSION_DEFINITIONS.map((definition) => [definition.oid, definition]),\n);\n\n/**\n * Return all known extension definitions, optionally filtered by context.\n *\n * @param context If provided, only definitions valid in that context are returned.\n */\nexport function listExtensionDefinitions(\n\tcontext?: ExtensionRegistryContext,\n): readonly KnownExtensionDefinition[] {\n\tif (context === undefined) {\n\t\treturn CERT_CSR_EXTENSION_DEFINITIONS;\n\t}\n\treturn CERT_CSR_EXTENSION_DEFINITIONS.filter((definition) =>\n\t\tdefinition.contexts.includes(context),\n\t);\n}\n\n/**\n * Look up a known extension definition by OID.\n *\n * Overloaded for each built-in OID constant to return the exact definition type.\n *\n * @param oid Dotted-decimal extension OID.\n * @returns The matching definition, or `undefined` for unrecognized OIDs.\n */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.basicConstraints,\n): typeof BASIC_CONSTRAINTS_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.keyUsage,\n): typeof KEY_USAGE_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.extendedKeyUsage,\n): typeof EXTENDED_KEY_USAGE_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.subjectAltName,\n): typeof SUBJECT_ALT_NAME_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.nameConstraints,\n): typeof NAME_CONSTRAINTS_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.certificatePolicies,\n): typeof CERTIFICATE_POLICIES_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.policyMappings,\n): typeof POLICY_MAPPINGS_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.policyConstraints,\n): typeof POLICY_CONSTRAINTS_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.inhibitAnyPolicy,\n): typeof INHIBIT_ANY_POLICY_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.authorityInfoAccess,\n): typeof AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.cRLDistributionPoints,\n): typeof CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.subjectKeyIdentifier,\n): typeof SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(\n\toid: typeof OIDS.authorityKeyIdentifier,\n): typeof AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION;\nexport function getExtensionDefinition(oid: string): KnownExtensionDefinition | undefined;\nexport function getExtensionDefinition(oid: string): KnownExtensionDefinition | undefined {\n\treturn EXTENSION_DEFINITION_MAP.get(oid);\n}\n\n/**\n * If `oid` matches a known extension valid in `context`, decode its DER\n * value and store the result in the accumulator.\n *\n * @returns `true` if the extension was recognized and applied.\n */\nexport function decodeAndApplyKnownExtension(\n\tcontext: ExtensionRegistryContext,\n\toid: string,\n\taccumulator: MutableKnownParsedExtensionAccumulator,\n\tvalueDer: Uint8Array,\n): boolean {\n\tconst definition = getExtensionDefinition(oid);\n\tif (definition === undefined || !definition.contexts.includes(context)) {\n\t\treturn false;\n\t}\n\tconst applier = extensionAppliers.get(oid);\n\tif (applier === undefined) {\n\t\treturn false;\n\t}\n\tapplier(accumulator, valueDer);\n\treturn true;\n}\n\n/**\n * Compute a Subject Key Identifier (SHA-1 of the public key bits) from\n * a DER-encoded SubjectPublicKeyInfo.\n */\nexport function buildSubjectKeyIdentifierFromSubjectPublicKeyInfo(\n\tsubjectPublicKeyInfo: Uint8Array,\n): Uint8Array {\n\treturn buildSubjectKeyIdentifier(subjectPublicKeyInfo);\n}\n\n/**\n * Identity helper that narrows the type of an {@linkcode ExtensionDefinition} literal\n * and captures a decode-and-apply closure in {@linkcode extensionAppliers}.\n *\n * The closure is built here — where `TParsed` is concrete — so that\n * `decodeAndApplyKnownExtension` can call it through the union-typed\n * `KnownExtensionDefinition` without hitting TypeScript's correlated-union limitation.\n */\nfunction defineExtensionDefinition<TParsed, TInput = TParsed>(\n\tdefinition: ExtensionDefinition<TParsed, TInput>,\n): ExtensionDefinition<TParsed, TInput> {\n\textensionAppliers.set(definition.oid, (accumulator, valueDer) => {\n\t\tdefinition.applyParsed(accumulator, definition.decode(valueDer));\n\t});\n\treturn definition;\n}\n\n/** Accept hex string or Uint8Array and return raw bytes. */\nfunction normalizeKeyIdentifier(value: string | Uint8Array): Uint8Array {\n\treturn typeof value === 'string' ? hexToBytes(value) : value;\n}\n\n/** Decode an SKI extension value DER to a hex string. */\nfunction decodeSubjectKeyIdentifier(valueDer: Uint8Array): string {\n\tconst element = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('SubjectKeyIdentifier must be an OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n"],"mappings":"i5BAwJA,MAAM,EAAoB,IAAI,IAMjB,EACZ,EAA4C,CAC3C,IAAK,EAAK,iBACV,SAAU,CAAC,cAAe,KAAK,EAC/B,gBAAiB,GACjB,OAAS,GAAa,EAAsB,CAAQ,EACpD,OAAS,GAAU,EAAuB,CAAK,EAC/C,aAAc,EAAa,IAAU,CACpC,EAAY,iBAAmB,CAChC,CACD,CAAC,EAGW,EAGT,EAAyE,CAC5E,IAAK,EAAK,SACV,SAAU,CAAC,cAAe,KAAK,EAC/B,gBAAiB,GACjB,OAAS,GAAa,EAAc,CAAQ,EAC5C,OAAS,GAAU,EAAe,CAAK,EACvC,aAAc,EAAa,IAAU,CACpC,EAAY,SAAW,CACxB,CACD,CAAC,EAGY,EAET,EAAuD,CAC1D,IAAK,EAAK,iBACV,SAAU,CAAC,cAAe,KAAK,EAC/B,gBAAi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K,CAAU,CAAC,CAChF,EAkEA,SAAgB,EAAuB,EAAmD,CACzF,OAAO,EAAyB,IAAI,CAAG,CACxC,CAQA,SAAgB,EACf,EACA,EACA,EACA,EACU,CACV,IAAM,EAAa,EAAuB,CAAG,EAC7C,GAAI,IAAe,IAAA,IAAa,CAAC,EAAW,SAAS,SAAS,CAAO,EACpE,MAAO,GAER,IAAM,EAAU,EAAkB,IAAI,CAAG,EAKzC,OAJI,IAAY,IAAA,GACR,IAER,EAAQ,EAAa,CAAQ,EACtB,GACR,CAoBA,SAAS,EACR,EACuC,CAIvC,OAHA,EAAkB,IAAI,EAAW,KAAM,EAAa,IAAa,CAChE,EAAW,YAAY,EAAa,EAAW,OAAO,CAAQ,CAAC,CAChE,CAAC,EACM,CACR,CAGA,SAAS,EAAuB,EAAwC,CACvE,OAAO,OAAO,GAAU,SAAW,EAAW,CAAK,EAAI,CACxD,CAGA,SAAS,EAA2B,EAA8B,CACjE,IAAM,EAAU,EAAgB,EAAU,CAAE,SAAA,EAAgC,CAAC,EAC7E,GAAI,EAAQ,MAAQ,EACnB,MAAU,MAAM,8CAA8C,EAE/D,OAAO,EAAM,EAAQ,KAAK,CAC3B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"name-fields.js","names":[],"sources":["../../../src/internal/x509/name-fields.ts"],"sourcesContent":["/**\n * Distinguished-name field metadata.\n *\n * Maps friendly {@linkcode NameFieldKey} names to their ASN.1 OIDs and string-encoding functions.\n * @module\n */\n\nimport { ia5String, printableString, utf8String } from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport type { NameFieldKey } from '#micro509/x509/name.ts';\n\n/**\n * OID and ASN.1 string encoder for one distinguished-name attribute type.\n */\nexport interface NameFieldDefinition {\n\t/** Dotted-decimal OID (e.g. `\"2.5.4.3\"` for commonName). */\n\treadonly oid: string;\n\t/** Encodes the attribute value to the correct ASN.1 string type (UTF8, PrintableString, IA5). */\n\treadonly encode: (value: string) => Uint8Array;\n}\n\n/**\n * Registry mapping every {@linkcode NameFieldKey} to its OID and ASN.1 encoder.\n *\n * Country and serialNumber use PrintableString; emailAddress uses IA5String;\n * all others use UTF8String.\n */\nexport const NAME_FIELD_DEFINITIONS: Record<NameFieldKey, NameFieldDefinition> = {\n\tcommonName: { oid: OIDS.commonName, encode: utf8String },\n\tsurname: { oid: OIDS.surname, encode: utf8String },\n\tserialNumber: { oid: OIDS.serialNumber, encode: printableString },\n\tcountry: { oid: OIDS.countryName, encode: printableString },\n\tlocality: { oid: OIDS.localityName, encode: utf8String },\n\tstate: { oid: OIDS.stateOrProvinceName, encode: utf8String },\n\tstreet: { oid: OIDS.streetAddress, encode: utf8String },\n\torganization: { oid: OIDS.organizationName, encode: utf8String },\n\torganizationalUnit: { oid: OIDS.organizationalUnitName, encode: utf8String },\n\ttitle: { oid: OIDS.title, encode: utf8String },\n\tgivenName: { oid: OIDS.givenName, encode: utf8String },\n\temailAddress: { oid: OIDS.emailAddress, encode: ia5String },\n};\n\n/**\n * Canonical emission order when converting a {@linkcode NameObject} to RDN attributes.\n *\n * Follows the conventional `C/ST/L/STREET/O/OU/CN/…` ordering.\n */\nexport const NAME_OBJECT_ORDER: readonly NameFieldKey[] = [\n\t'country',\n\t'state',\n\t'locality',\n\t'street',\n\t'organization',\n\t'organizationalUnit',\n\t'commonName',\n\t'givenName',\n\t'surname',\n\t'title',\n\t'serialNumber',\n\t'emailAddress',\n];\n\n/** Reverse lookup table: OID string → friendly {@linkcode NameFieldKey}. */\nconst NAME_FIELD_KEYS_BY_OID = new Map<string, NameFieldKey>();\nfor (const key of NAME_OBJECT_ORDER) {\n\tNAME_FIELD_KEYS_BY_OID.set(NAME_FIELD_DEFINITIONS[key].oid, key);\n}\n\n/** Resolves a dotted-decimal OID to its {@linkcode NameFieldKey}, or `undefined` if unknown. */\nexport function nameFieldKeyFromOid(oid: string): NameFieldKey | undefined {\n\treturn NAME_FIELD_KEYS_BY_OID.get(oid);\n}\n"],"mappings":"uHA2BA,MAAa,EAAoE,CAChF,WAAY,CAAE,IAAK,EAAK,WAAY,OAAQ,CAAW,EACvD,QAAS,CAAE,IAAK,EAAK,QAAS,OAAQ,CAAW,EACjD,aAAc,CAAE,IAAK,EAAK,aAAc,OAAQ,CAAgB,EAChE,QAAS,CAAE,IAAK,EAAK,YAAa,OAAQ,CAAgB,EAC1D,SAAU,CAAE,IAAK,EAAK,aAAc,OAAQ,CAAW,EACvD,MAAO,CAAE,IAAK,EAAK,oBAAqB,OAAQ,CAAW,EAC3D,OAAQ,CAAE,IAAK,EAAK,cAAe,OAAQ,CAAW,EACtD,aAAc,CAAE,IAAK,EAAK,iBAAkB,OAAQ,CAAW,EAC/D,mBAAoB,CAAE,IAAK,EAAK,uBAAwB,OAAQ,CAAW,EAC3E,MAAO,CAAE,IAAK,EAAK,MAAO,OAAQ,CAAW,EAC7C,UAAW,CAAE,IAAK,EAAK,UAAW,OAAQ,CAAW,EACrD,aAAc,CAAE,IAAK,EAAK,aAAc,OAAQ,CAAU,CAC3D,EAOa,EAA6C,CACzD,UACA,QACA,WACA,SACA,eACA,qBACA,aACA,YACA,UACA,QACA,eACA,cACD,EAGM,EAAyB,IAAI,IACnC,IAAK,IAAM,KAAO,EACjB,EAAuB,IAAI,EAAuB,EAAI,CAAC,IAAK,CAAG,EAIhE,SAAgB,EAAoB,EAAuC,CAC1E,OAAO,EAAuB,IAAI,CAAG,CACtC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"keys.js","names":[],"sources":["../../src/keys/keys.ts"],"sourcesContent":["/**\n * WebCrypto key generation plus import/export for PKCS#1, PKCS#8, SEC1, SPKI, and JWK.\n *\n * Supports RSA (PKCS#1v1.5 and PSS), ECDSA (P-256, P-384, P-521), and Ed25519 keys.\n * All functions use the WebCrypto API and return extractable keys.\n *\n * @example\n * ```ts\n * import { generateKeyPair, exportPkcs8Pem, importSpkiPem } from 'micro509/keys';\n *\n * // Generate and export\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const privatePem = await exportPkcs8Pem(keys.privateKey);\n *\n * // Import\n * const publicKey = await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @module\n */\n\nimport {\n\tdecodeObjectIdentifier,\n\textractBitStringValue,\n\thexToBytes,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { md5 } from '#micro509/internal/crypto/hash.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisWrongPasswordError,\n\ttype Pbes2EncryptionOptions,\n\twrongPasswordError,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem.ts';\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\n\nexport type {\n\tPbes2EncryptionOptions,\n\tPbes2EncryptionScheme,\n\tPbes2Prf,\n} from '#micro509/internal/crypto/pbes2.ts';\n\n/** Hash algorithm paired with an RSA key. */\nexport type RsaHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** RSA signature padding scheme. */\nexport type RsaScheme = 'pkcs1-v1_5' | 'pss';\n\n/** NIST elliptic curve for ECDSA keys. */\nexport type EcNamedCurve = 'P-256' | 'P-384' | 'P-521';\n\n/** RSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface RsaKeyAlgorithmInput {\n\t/** Discriminant selecting RSA key generation. */\n\treadonly kind: 'rsa';\n\t/** RSA modulus size in bits. Defaults to `2048`. */\n\treadonly modulusLength?: 2048 | 3072 | 4096;\n\t/** Hash algorithm for the key. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode KeyAlgorithmInput}. */\nexport interface EcKeyAlgorithmInput {\n\t/** Discriminant selecting ECDSA key generation. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve. Defaults to `'P-256'`. */\n\treadonly curve?: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode KeyAlgorithmInput}. */\nexport interface Ed25519KeyAlgorithmInput {\n\t/** Discriminant selecting Ed25519 key generation. */\n\treadonly kind: 'ed25519';\n}\n\n/** Input for {@linkcode generateKeyPair}. Selects algorithm family and parameters. */\nexport type KeyAlgorithmInput =\n\t| RsaKeyAlgorithmInput\n\t| EcKeyAlgorithmInput\n\t| Ed25519KeyAlgorithmInput;\n\n/** Key pair with convenience export helpers. Returned by {@linkcode generateKeyPair}. */\nexport interface KeyPairMaterial {\n\t/** The WebCrypto public key (extractable, `verify` usage). */\n\treadonly publicKey: CryptoKey;\n\t/** The WebCrypto private key (extractable, `sign` usage). */\n\treadonly privateKey: CryptoKey;\n\t/** Export the public key as DER-encoded SubjectPublicKeyInfo. */\n\texportSpkiDer(): Promise<Uint8Array>;\n\t/** Export the public key as PEM-encoded SubjectPublicKeyInfo. */\n\texportSpkiPem(): Promise<string>;\n\t/** Export the private key as DER-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Der(): Promise<Uint8Array>;\n\t/** Export the private key as PEM-encoded PKCS#8 PrivateKeyInfo. */\n\texportPkcs8Pem(): Promise<string>;\n\t/** Export the public key as a JSON Web Key. */\n\texportPublicJwk(): Promise<JsonWebKey>;\n\t/** Export the private key as a JSON Web Key. */\n\texportPrivateJwk(): Promise<JsonWebKey>;\n}\n\n/** RSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportRsaKeyInput {\n\t/** Discriminant selecting RSA import. */\n\treadonly kind: 'rsa';\n\t/** Hash algorithm. Defaults to `'SHA-256'`. */\n\treadonly hash?: RsaHash;\n\t/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */\n\treadonly scheme?: RsaScheme;\n}\n\n/** ECDSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEcKeyInput {\n\t/** Discriminant selecting ECDSA import. */\n\treadonly kind: 'ecdsa';\n\t/** NIST curve the key belongs to. Required for EC import. */\n\treadonly curve: EcNamedCurve;\n}\n\n/** Ed25519 variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */\nexport interface ImportEd25519KeyInput {\n\t/** Discriminant selecting Ed25519 import. */\n\treadonly kind: 'ed25519';\n}\n\n/** Algorithm descriptor for public key import functions. */\nexport type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;\n\n/** Algorithm descriptor for private key import functions. Same shape as {@linkcode PublicKeyImportInput}. */\nexport type PrivateKeyImportInput = PublicKeyImportInput;\n\n/** PBES2 encryption options for the encrypted PKCS#8 export/import functions. */\nexport type EncryptedPkcs8Options = Pbes2EncryptionOptions;\n\n/** Options for OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM encryption (PKCS#1/SEC1). */\nexport interface LegacyPemEncryptionOptions {\n\t/** Passphrase used to derive the encryption key. */\n\treadonly password: string;\n\t/** 16-byte initialization vector. Random when omitted. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Defaults to `'AES-256-CBC'`. */\n\treadonly cipher?: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n}\n\n/** Machine-readable failure reason for the `import*` key functions. */\nexport type ImportKeyErrorCode = 'malformed';\n\n/** Structured failure payload for key import. */\nexport interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `import*` key functions.\n *\n * On failure, `code` is always `'malformed'`: structurally invalid input,\n * algorithm mismatches, and wrong-password decryption failures all surface\n * the same way (see the throwing `*OrThrow` variants for raw error messages).\n */\nexport type ImportKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>;\n\n/**\n * Machine-readable failure reason for the `importEncrypted*` key functions.\n *\n * Distinguishes a wrong decryption password (`'invalid_password'`) from\n * structurally invalid input or algorithm mismatches (`'malformed'`).\n */\nexport type ImportEncryptedKeyErrorCode = 'malformed' | 'invalid_password';\n\n/** Structured failure payload for encrypted key import. */\nexport interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result returned by the public `importEncrypted*` key functions.\n *\n * On failure, `code` is `'invalid_password'` when decryption failed (wrong\n * password or corrupted ciphertext) and `'malformed'` for everything else.\n */\nexport type ImportEncryptedKeyResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<ImportEncryptedKeyErrorCode, Record<never, never>, ImportEncryptedKeyFailure>;\n\n/**\n * Generate an asymmetric key pair for signing and verification.\n *\n * @example\n * ```ts\n * const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });\n * const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });\n * const edKeys = await generateKeyPair({ kind: 'ed25519' });\n *\n * // Default: ECDSA P-256\n * const keys = await generateKeyPair();\n * const pem = await keys.exportPkcs8Pem();\n * ```\n */\nexport async function generateKeyPair(\n\talgorithm: KeyAlgorithmInput = { kind: 'ecdsa', curve: 'P-256' },\n): Promise<KeyPairMaterial> {\n\tconst subtle = getCrypto().subtle;\n\tconst generated = await subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, [\n\t\t'sign',\n\t\t'verify',\n\t]);\n\n\tif (!('publicKey' in generated) || !('privateKey' in generated)) {\n\t\tthrow new Error('Expected an asymmetric key pair');\n\t}\n\n\treturn wrapKeyPair(generated.publicKey, generated.privateKey);\n}\n\nfunction wrapKeyPair(publicKey: CryptoKey, privateKey: CryptoKey): KeyPairMaterial {\n\treturn {\n\t\tpublicKey,\n\t\tprivateKey,\n\t\tasync exportSpkiDer() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n\t\t},\n\t\tasync exportSpkiPem() {\n\t\t\treturn pemEncode('PUBLIC KEY', await this.exportSpkiDer());\n\t\t},\n\t\tasync exportPkcs8Der() {\n\t\t\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n\t\t},\n\t\tasync exportPkcs8Pem() {\n\t\t\treturn pemEncode('PRIVATE KEY', await this.exportPkcs8Der());\n\t\t},\n\t\tasync exportPublicJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n\t\t},\n\t\tasync exportPrivateJwk() {\n\t\t\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n\t\t},\n\t};\n}\n\n/**\n * Export a public key as DER-encoded SubjectPublicKeyInfo.\n *\n * @see {@linkcode importSpkiDer} for the inverse operation\n * @see {@linkcode exportSpkiPem} for PEM output\n */\nexport async function exportSpkiDer(publicKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('spki', publicKey));\n}\n\n/**\n * Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see {@linkcode importPkcs8Der} for the inverse operation\n * @see {@linkcode exportPkcs8Pem} for PEM output\n * @see {@linkcode exportEncryptedPkcs8Der} for password-protected export\n */\nexport async function exportPkcs8Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.exportKey('pkcs8', privateKey));\n}\n\n/**\n * Export a public key as a JSON Web Key.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });\n * const jwk = await exportPublicJwk(keys.publicKey);\n * ```\n */\nexport async function exportPublicJwk(publicKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', publicKey);\n}\n\n/**\n * Export a private key as a JSON Web Key.\n *\n * @see {@linkcode importPrivateJwk} for the inverse operation\n * @see {@linkcode exportPublicJwk} for public key export\n */\nexport async function exportPrivateJwk(privateKey: CryptoKey): Promise<JsonWebKey> {\n\treturn getCrypto().subtle.exportKey('jwk', privateKey);\n}\n\n/**\n * Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportPkcs8Pem(keys.privateKey);\n * // -----BEGIN PRIVATE KEY-----\n * // MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEH...\n * // -----END PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importPkcs8Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for password-protected export\n */\nexport async function exportPkcs8Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PRIVATE KEY', await exportPkcs8Der(privateKey));\n}\n\n/**\n * Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Uses PBES2 (PKCS#5 v2.1) with AES-CBC and PBKDF2. Compatible with OpenSSL.\n *\n * @param privateKey - The private key to export\n * @param options - Encryption options including password and optional algorithm settings\n *\n * @see {@linkcode importEncryptedPkcs8Der} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs8Pem} for PEM output\n */\nexport async function exportEncryptedPkcs8Der(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst encryption = await encryptPbes2(pkcs8, options);\n\treturn sequence([encryption.algorithmIdentifierDer, octetString(encryption.encryptedData)]);\n}\n\n/**\n * Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportEncryptedPkcs8Pem(keys.privateKey, { password: 'secret' });\n * // -----BEGIN ENCRYPTED PRIVATE KEY-----\n * // MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAc...\n * // -----END ENCRYPTED PRIVATE KEY-----\n * ```\n *\n * @see {@linkcode importEncryptedPkcs8Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs8Pem(\n\tprivateKey: CryptoKey,\n\toptions: EncryptedPkcs8Options,\n): Promise<string> {\n\treturn pemEncode('ENCRYPTED PRIVATE KEY', await exportEncryptedPkcs8Der(privateKey, options));\n}\n\n/**\n * Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Der} for the inverse operation\n * @see {@linkcode exportPkcs1Pem} for PEM output\n */\nexport async function exportPkcs1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.rsaEncryption) {\n\t\tthrow new Error('PKCS#1 export requires an RSA private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importPkcs1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedPkcs1Pem} for password-protected export\n */\nexport async function exportPkcs1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('RSA PRIVATE KEY', await exportPkcs1Der(privateKey));\n}\n\n/**\n * Export an RSA private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an RSA key\n *\n * @see {@linkcode importEncryptedPkcs1Pem} for the inverse operation\n */\nexport async function exportEncryptedPkcs1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('RSA PRIVATE KEY', await exportPkcs1Der(privateKey), options);\n}\n\n/**\n * Export an EC private key as DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use\n * {@linkcode exportPkcs8Der}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Der} for the inverse operation\n * @see {@linkcode exportSec1Pem} for PEM output\n */\nexport async function exportSec1Der(privateKey: CryptoKey): Promise<Uint8Array> {\n\tconst pkcs8 = await exportPkcs8Der(privateKey);\n\tconst parsed = parsePkcs8PrivateKey(pkcs8);\n\tif (parsed.algorithmOid !== OIDS.ecPublicKey) {\n\t\tthrow new Error('SEC1 export requires an EC private key');\n\t}\n\treturn parsed.privateKeyDer;\n}\n\n/**\n * Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importSec1Pem} for the inverse operation\n * @see {@linkcode exportEncryptedSec1Pem} for password-protected export\n */\nexport async function exportSec1Pem(privateKey: CryptoKey): Promise<string> {\n\treturn pemEncode('EC PRIVATE KEY', await exportSec1Der(privateKey));\n}\n\n/**\n * Export an EC private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.\n * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.\n *\n * @throws {Error} If the key is not an EC key\n *\n * @see {@linkcode importEncryptedSec1Pem} for the inverse operation\n */\nexport async function exportEncryptedSec1Pem(\n\tprivateKey: CryptoKey,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\treturn encryptTraditionalPem('EC PRIVATE KEY', await exportSec1Der(privateKey), options);\n}\n\n/**\n * Export a public key as PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const keys = await generateKeyPair();\n * const pem = await exportSpkiPem(keys.publicKey);\n * ```\n */\nexport async function exportSpkiPem(publicKey: CryptoKey): Promise<string> {\n\treturn pemEncode('PUBLIC KEY', await exportSpkiDer(publicKey));\n}\n\n/**\n * Export a key as raw base64 (no PEM headers).\n *\n * Returns SPKI-encoded base64 for public keys, PKCS#8-encoded base64 for private keys.\n * Useful for compact storage or transmission where PEM overhead is undesirable.\n *\n * @throws {Error} If the key is a symmetric/secret key\n *\n * @see {@linkcode importSpkiBase64} for public key import\n * @see {@linkcode importPkcs8Base64} for private key import\n */\nexport async function exportBinaryBase64(key: CryptoKey): Promise<string> {\n\tif (key.type === 'public') {\n\t\treturn base64Encode(await exportSpkiDer(key));\n\t}\n\tif (key.type === 'private') {\n\t\treturn base64Encode(await exportPkcs8Der(key));\n\t}\n\tthrow new Error('Cannot export secret/symmetric CryptoKey');\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @param der - DER-encoded SubjectPublicKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\n *\n * @see {@linkcode exportSpkiDer} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input\n */\nexport async function importSpkiDerOrThrow(\n\tder: Uint8Array,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tconst parsedSpki = parseSpkiDer(der);\n\tassertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'spki',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['verify'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\n/** Runs a throwing key import and maps an EXPECTED failure to a `'malformed'` result; invariants rethrow. */\nasync function importResult(run: () => Promise<CryptoKey>): Promise<ImportKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : 'Malformed key');\n\t}\n}\n\n/** Like {@link importResult} but distinguishes a typed wrong-password failure (`'invalid_password'`). */\nasync function encryptedImportResult(\n\trun: () => Promise<CryptoKey>,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn failureResult('invalid_password', error.message);\n\t\t}\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed encrypted key',\n\t\t);\n\t}\n}\n\n/**\n * Import a public key from DER-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiDerOrThrow` for the throwing variant\n */\nexport function importSpkiDer(\n\tder: Uint8Array,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiDerOrThrow(der, algorithm));\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @example\n * ```ts\n * const pem = `-----BEGIN PUBLIC KEY-----\n * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n * -----END PUBLIC KEY-----`;\n * const key = await importSpkiPem(pem, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n *\n * @see {@linkcode exportSpkiPem} for the inverse operation\n */\nexport async function importSpkiPemOrThrow(\n\tpem: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importSpkiDerOrThrow(pemDecodeOrThrow('PUBLIC KEY', pem), algorithm);\n}\n\n/**\n * Import a public key from PEM-encoded SubjectPublicKeyInfo.\n *\n * @see `importSpkiPemOrThrow` for the throwing variant\n */\nexport function importSpkiPem(\n\tpem: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiPemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importSpkiPem} for PEM input with headers\n */\nexport async function importSpkiBase64OrThrow(\n\tbase64: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 SubjectPublicKeyInfo');\n\t}\n\treturn importSpkiDerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).\n *\n * @see `importSpkiBase64OrThrow` for the throwing variant\n */\nexport function importSpkiBase64(\n\tbase64: string,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSpkiBase64OrThrow(base64, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes\n * @param algorithm - Expected algorithm (must match key contents)\n * @returns Extractable CryptoKey with `sign` usage\n *\n * @throws {Error} If DER is malformed or algorithm doesn't match key\n *\n * @see {@linkcode exportPkcs8Der} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input\n * @see {@linkcode importEncryptedPkcs8Der} for encrypted PKCS#8\n */\nexport async function importPkcs8DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet parsedPrivateKey: ReturnType<typeof parsePkcs8PrivateKey>;\n\ttry {\n\t\tparsedPrivateKey = parsePkcs8PrivateKey(der);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tassertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey(\n\t\t\t'pkcs8',\n\t\t\tnew Uint8Array(der),\n\t\t\ttoImportAlgorithm(algorithm),\n\t\t\ttrue,\n\t\t\t['sign'],\n\t\t);\n\t} catch {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n}\n\n/**\n * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8DerOrThrow` for the throwing variant\n */\nexport function importPkcs8Der(\n\tder: Uint8Array,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8DerOrThrow(der, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importPkcs8Pem(pemString, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPkcs8PemOrThrow(\n\tpem: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(pemDecodeOrThrow('PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.\n *\n * @see `importPkcs8PemOrThrow` for the throwing variant\n */\nexport function importPkcs8Pem(\n\tpem: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * Decrypts the PBES2 envelope using the provided password, then imports the key.\n *\n * @param der - DER-encoded EncryptedPrivateKeyInfo bytes\n * @param password - Decryption password\n * @param algorithm - Expected algorithm (must match decrypted key)\n *\n * @throws {Error} If DER is malformed, password is wrong, or algorithm doesn't match\n *\n * @see {@linkcode exportEncryptedPkcs8Der} for the inverse operation\n */\nexport async function importEncryptedPkcs8DerOrThrow(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet children: readonly ReturnType<typeof readSequenceChildren>[number][];\n\ttry {\n\t\tchildren = readSequenceChildren(der);\n\t} catch {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst algorithmIdentifier = children[0];\n\tconst encryptedData = children[1];\n\tif (\n\t\tchildren.length !== 2 ||\n\t\talgorithmIdentifier === undefined ||\n\t\tencryptedData === undefined ||\n\t\tencryptedData.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed EncryptedPrivateKeyInfo');\n\t}\n\tconst decrypted = await decryptPbes2(\n\t\tder.slice(\n\t\t\talgorithmIdentifier.start - algorithmIdentifier.headerLength,\n\t\t\talgorithmIdentifier.end,\n\t\t),\n\t\tencryptedData.value,\n\t\tpassword,\n\t);\n\treturn importPkcs8DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8DerOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Der(\n\tder: Uint8Array,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(der, password, algorithm));\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @example\n * ```ts\n * const key = await importEncryptedPkcs8Pem(pem, 'secret', { kind: 'rsa' });\n * ```\n */\nexport async function importEncryptedPkcs8PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn importEncryptedPkcs8DerOrThrow(\n\t\tpemDecodeOrThrow('ENCRYPTED PRIVATE KEY', pem),\n\t\tpassword,\n\t\talgorithm,\n\t);\n}\n\n/**\n * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.\n *\n * @see `importEncryptedPkcs8PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs8Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * PKCS#1 is the legacy RSA-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportPkcs1Der} for the inverse operation\n * @see {@linkcode importPkcs1Pem} for PEM input\n */\nexport async function importPkcs1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapPkcs1InPkcs8(der), algorithm);\n}\n\n/**\n * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1DerOrThrow` for the throwing variant\n */\nexport function importPkcs1Der(\n\tder: Uint8Array,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * Expects the `-----BEGIN RSA PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs1Pem} for encrypted PEM\n */\nexport async function importPkcs1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\treturn importPkcs1DerOrThrow(pemDecodeOrThrow('RSA PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.\n *\n * @see `importPkcs1PemOrThrow` for the throwing variant\n */\nexport function importPkcs1Pem(\n\tpem: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedPkcs1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedPkcs1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('RSA PRIVATE KEY', pem, password);\n\treturn importPkcs1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).\n *\n * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedPkcs1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportRsaKeyInput = { kind: 'rsa' },\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see {@linkcode exportBinaryBase64} for the inverse operation\n * @see {@linkcode importPkcs8Pem} for PEM input with headers\n */\nexport async function importPkcs8Base64OrThrow(\n\tbase64: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\tlet decoded: Uint8Array;\n\ttry {\n\t\tdecoded = base64Decode(base64);\n\t} catch {\n\t\tthrow new Error('Invalid base64 PKCS#8 private key');\n\t}\n\treturn importPkcs8DerOrThrow(decoded, algorithm);\n}\n\n/**\n * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).\n *\n * @see `importPkcs8Base64OrThrow` for the throwing variant\n */\nexport function importPkcs8Base64(\n\tbase64: string,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPkcs8Base64OrThrow(base64, algorithm));\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * SEC 1 is the legacy EC-only format. Internally converts to PKCS#8 for import.\n *\n * @see {@linkcode exportSec1Der} for the inverse operation\n * @see {@linkcode importSec1Pem} for PEM input\n */\nexport async function importSec1DerOrThrow(\n\tder: Uint8Array,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importPkcs8DerOrThrow(wrapSec1InPkcs8(der, algorithm.curve), algorithm);\n}\n\n/**\n * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1DerOrThrow` for the throwing variant\n */\nexport function importSec1Der(\n\tder: Uint8Array,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1DerOrThrow(der, algorithm));\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label.\n *\n * @see {@linkcode exportSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM\n */\nexport async function importSec1PemOrThrow(\n\tpem: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\treturn importSec1DerOrThrow(pemDecodeOrThrow('EC PRIVATE KEY', pem), algorithm);\n}\n\n/**\n * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.\n *\n * @see `importSec1PemOrThrow` for the throwing variant\n */\nexport function importSec1Pem(\n\tpem: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importSec1PemOrThrow(pem, algorithm));\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * Decrypts OpenSSL's traditional PEM encryption format.\n *\n * @see {@linkcode exportEncryptedSec1Pem} for the inverse operation\n * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption\n */\nexport async function importEncryptedSec1PemOrThrow(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<CryptoKey> {\n\tconst decrypted = await decryptTraditionalPem('EC PRIVATE KEY', pem, password);\n\treturn importSec1DerOrThrow(decrypted, algorithm);\n}\n\n/**\n * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).\n *\n * @see `importEncryptedSec1PemOrThrow` for the throwing variant\n */\nexport function importEncryptedSec1Pem(\n\tpem: string,\n\tpassword: string,\n\talgorithm: ImportEcKeyInput,\n): Promise<ImportEncryptedKeyResult<CryptoKey>> {\n\treturn encryptedImportResult(() => importEncryptedSec1PemOrThrow(pem, password, algorithm));\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @param jwk - JSON Web Key object with public key components\n * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)\n * @returns Extractable CryptoKey with `verify` usage\n *\n * @throws {Error} If JWK is malformed or algorithm doesn't match\n *\n * @see {@linkcode exportPublicJwk} for the inverse operation\n */\nexport async function importPublicJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<CryptoKey> {\n\tassertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm);\n\ttry {\n\t\treturn await getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, [\n\t\t\t'verify',\n\t\t]);\n\t} catch {\n\t\tthrow new Error('Malformed public JWK');\n\t}\n}\n\n/**\n * Import a public verification key from a JSON Web Key.\n *\n * @see `importPublicJwkOrThrow` for the throwing variant\n */\nexport function importPublicJwk(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPublicJwkOrThrow(jwk, algorithm));\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @example\n * ```ts\n * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };\n * const key = await importPrivateJwk(jwk, { kind: 'ecdsa', curve: 'P-256' });\n * ```\n */\nexport async function importPrivateJwkOrThrow(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<CryptoKey> {\n\treturn getCrypto().subtle.importKey('jwk', jwk, toImportAlgorithm(algorithm), true, ['sign']);\n}\n\n/**\n * Import a private signing key from a JSON Web Key.\n *\n * @see `importPrivateJwkOrThrow` for the throwing variant\n */\nexport function importPrivateJwk(\n\tjwk: JsonWebKey,\n\talgorithm: PrivateKeyImportInput,\n): Promise<ImportKeyResult<CryptoKey>> {\n\treturn importResult(() => importPrivateJwkOrThrow(jwk, algorithm));\n}\n\n/** Map a {@linkcode KeyAlgorithmInput} to the WebCrypto `generateKey` algorithm parameter. */\nfunction toGenerateKeyAlgorithm(\n\talgorithm: KeyAlgorithmInput,\n): EcKeyGenParams | RsaHashedKeyGenParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\tmodulusLength: algorithm.modulusLength ?? 2048,\n\t\t\t\tpublicExponent: Uint8Array.of(0x01, 0x00, 0x01),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve ?? 'P-256',\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t}\n}\n\n/** Map a {@linkcode PublicKeyImportInput} to the WebCrypto `importKey` algorithm parameter. */\nfunction toImportAlgorithm(\n\talgorithm: PublicKeyImportInput,\n): EcKeyImportParams | RsaHashedImportParams | AlgorithmIdentifier {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\treturn {\n\t\t\t\tname: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),\n\t\t\t\thash: algorithm.hash ?? 'SHA-256',\n\t\t\t};\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tname: 'ECDSA',\n\t\t\t\tnamedCurve: algorithm.curve,\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t}\n}\n\n/** Extract algorithm OID and inner key bytes from a PKCS#8 PrivateKeyInfo envelope. */\nfunction parsePkcs8PrivateKey(der: Uint8Array): {\n\t/** OID identifying the algorithm family (e.g. rsaEncryption, ecPublicKey). */\n\treadonly algorithmOid: string;\n\t/** Optional algorithm parameter OID (e.g. named curve for EC keys). */\n\treadonly parametersOid?: string;\n\t/** Optional algorithm parameter tag. */\n\treadonly parametersTag?: number;\n\t/** Raw DER of the inner private key (PKCS#1 for RSA, SEC 1 for EC). */\n\treadonly privateKeyDer: Uint8Array;\n} {\n\tconst children = readSequenceChildren(der);\n\tconst algorithm = children[1];\n\tconst privateKey = children[2];\n\tif (\n\t\tchildren.length < 3 ||\n\t\tchildren.length > 4 ||\n\t\talgorithm === undefined ||\n\t\talgorithm.tag !== 0x30 ||\n\t\tprivateKey === undefined ||\n\t\tprivateKey.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst algorithmChildren = readSequenceChildren(\n\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\talgorithmOid.tag !== 0x06 ||\n\t\talgorithmChildren.length < 1 ||\n\t\talgorithmChildren.length > 2\n\t) {\n\t\tthrow new Error('Malformed PKCS#8 private key');\n\t}\n\tconst parameters = algorithmChildren[1];\n\treturn {\n\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t...(parameters?.tag === 0x06\n\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t: {}),\n\t\tprivateKeyDer: privateKey.value,\n\t};\n}\n\n/** Wrap a PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapPkcs1InPkcs8(der: Uint8Array): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.rsaEncryption), nullValue()]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Wrap a SEC 1 ECPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */\nfunction wrapSec1InPkcs8(der: Uint8Array, curve: ImportEcKeyInput['curve']): Uint8Array {\n\treturn sequence([\n\t\tUint8Array.of(0x02, 0x01, 0x00),\n\t\tsequence([objectIdentifier(OIDS.ecPublicKey), objectIdentifier(curveToOid(curve))]),\n\t\toctetString(new Uint8Array(der)),\n\t]);\n}\n\n/** Map a curve name to its ASN.1 OID string. */\nfunction curveToOid(curve: ImportEcKeyInput['curve']): string {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn OIDS.prime256v1;\n\t\tcase 'P-384':\n\t\t\treturn OIDS.secp384r1;\n\t\tcase 'P-521':\n\t\t\treturn OIDS.secp521r1;\n\t}\n}\n\n/** Map an {@linkcode RsaScheme} to the WebCrypto algorithm name string. */\nfunction rsaSchemeToWebCryptoAlgorithmName(\n\tscheme: RsaScheme | undefined,\n): 'RSASSA-PKCS1-v1_5' | 'RSA-PSS' {\n\tif (scheme === 'pss') {\n\t\treturn 'RSA-PSS';\n\t}\n\treturn 'RSASSA-PKCS1-v1_5';\n}\n\n/** Encrypt DER key material as an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block. */\nasync function encryptTraditionalPem(\n\tlabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tder: Uint8Array,\n\toptions: LegacyPemEncryptionOptions,\n): Promise<string> {\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tif (iv.length !== 16) {\n\t\tthrow new Error('Traditional PEM encryption requires a 16-byte IV');\n\t}\n\tconst cipher = options.cipher ?? 'AES-256-CBC';\n\tconst key = await importTraditionalPemAesKey(options.password, iv.slice(0, 8), cipher, [\n\t\t'encrypt',\n\t]);\n\tconst encrypted = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(der),\n\t\t),\n\t);\n\tconst body =\n\t\tbase64Encode(encrypted)\n\t\t\t.match(/.{1,64}/g)\n\t\t\t?.join('\\n') ?? '';\n\treturn [\n\t\t`-----BEGIN ${label}-----`,\n\t\t'Proc-Type: 4,ENCRYPTED',\n\t\t`DEK-Info: ${cipher},${toHex(iv).toUpperCase()}`,\n\t\t'',\n\t\tbody,\n\t\t`-----END ${label}-----`,\n\t].join('\\n');\n}\n\n/** Decrypt an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block back to plaintext DER. */\nasync function decryptTraditionalPem(\n\texpectedLabel: 'RSA PRIVATE KEY' | 'EC PRIVATE KEY',\n\tpem: string,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parsed = parseTraditionalPem(pem);\n\tif (parsed.label !== expectedLabel) {\n\t\tthrow new Error(`Expected ${expectedLabel} PEM block`);\n\t}\n\tconst dekInfo = parsed.headers.get('DEK-Info');\n\tif (parsed.headers.get('Proc-Type') !== '4,ENCRYPTED' || dekInfo === undefined) {\n\t\tthrow new Error('Traditional PEM encryption headers missing');\n\t}\n\tconst [cipher, ivHex] = dekInfo.split(',');\n\tif (!isTraditionalPemCipher(cipher) || ivHex === undefined) {\n\t\tthrow new Error(\n\t\t\t'Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported',\n\t\t);\n\t}\n\tif (!isTraditionalPemIvHex(ivHex)) {\n\t\tthrow new Error(\n\t\t\t'Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters',\n\t\t);\n\t}\n\tconst iv = hexToBytes(ivHex);\n\tconst key = await importTraditionalPemAesKey(password, iv.slice(0, 8), cipher, ['decrypt']);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(base64Decode(parsed.base64Body)),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted PEM content');\n\t}\n}\n\n/** Derive and import an AES-CBC key for legacy PEM encryption using OpenSSL `EVP_BytesToKey`. */\nasync function importTraditionalPemAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst keyLength = traditionalPemCipherKeyLength(cipher);\n\tconst keyBytes = opensslBytesToKey(password, salt, keyLength / 8);\n\treturn getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'AES-CBC', length: keyLength },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Type guard for the three AES-CBC ciphers supported by legacy PEM encryption. */\nfunction isTraditionalPemCipher(\n\tcipher: string | undefined,\n): cipher is 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC' {\n\treturn cipher === 'AES-128-CBC' || cipher === 'AES-192-CBC' || cipher === 'AES-256-CBC';\n}\n\nfunction isTraditionalPemIvHex(value: string): boolean {\n\treturn value.length === 32 && /^[0-9A-Fa-f]+$/.test(value);\n}\n\n/** Return the AES key size in bits for a given cipher name. */\nfunction traditionalPemCipherKeyLength(\n\tcipher: 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC',\n): 128 | 192 | 256 {\n\tswitch (cipher) {\n\t\tcase 'AES-128-CBC':\n\t\t\treturn 128;\n\t\tcase 'AES-192-CBC':\n\t\t\treturn 192;\n\t\tcase 'AES-256-CBC':\n\t\t\treturn 256;\n\t}\n}\n\n/** OpenSSL `EVP_BytesToKey` with MD5 — derives a fixed-length key from password + salt. */\nfunction opensslBytesToKey(password: string, salt: Uint8Array, length: number): Uint8Array {\n\tconst passwordBytes = new TextEncoder().encode(password);\n\tconst chunks: Uint8Array[] = [];\n\tlet previous = new Uint8Array();\n\tlet total = 0;\n\twhile (total < length) {\n\t\tconst input = new Uint8Array(previous.length + passwordBytes.length + salt.length);\n\t\tinput.set(previous, 0);\n\t\tinput.set(passwordBytes, previous.length);\n\t\tinput.set(salt, previous.length + passwordBytes.length);\n\t\tprevious = md5(input);\n\t\tchunks.push(previous);\n\t\ttotal += previous.length;\n\t}\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tconst slice = chunk.slice(0, Math.min(chunk.length, length - offset));\n\t\tout.set(slice, offset);\n\t\toffset += slice.length;\n\t\tif (offset >= length) {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Parse a PEM block into its label, RFC 1421 headers, and base64 body. */\nfunction parseTraditionalPem(pem: string): {\n\t/** PEM type label between `BEGIN` and `END` markers. */\n\treadonly label: string;\n\t/** RFC 1421 encapsulated headers (e.g. `Proc-Type`, `DEK-Info`). */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n} {\n\tconst normalized = pem.replace(/\\r/g, '').trim();\n\tconst lines = normalized.split('\\n');\n\tconst begin = lines[0];\n\tconst end = lines[lines.length - 1];\n\tif (\n\t\tbegin === undefined ||\n\t\tend === undefined ||\n\t\t!begin.startsWith('-----BEGIN ') ||\n\t\t!end.startsWith('-----END ')\n\t) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tconst label = begin.slice(11, -5);\n\tif (end !== `-----END ${label}-----`) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tconst delimiter = line.indexOf(': ');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 2));\n\t\tindex += 1;\n\t}\n\tconst body = lines.slice(index, lines.length - 1).join('');\n\treturn { label, headers, base64Body: body };\n}\n\nfunction parseSpkiDer(der: Uint8Array): {\n\treadonly algorithmOid: string;\n\treadonly parametersOid?: string;\n\treadonly parametersTag?: number;\n} {\n\ttry {\n\t\tconst children = readSequenceChildren(der);\n\t\tif (children.length !== 2) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst algorithm = children[0];\n\t\tconst subjectPublicKey = children[1];\n\t\tif (\n\t\t\talgorithm === undefined ||\n\t\t\talgorithm.tag !== 0x30 ||\n\t\t\tsubjectPublicKey === undefined ||\n\t\t\tsubjectPublicKey.tag !== 0x03\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\textractBitStringValue(subjectPublicKey);\n\t\tconst algorithmChildren = readSequenceChildren(\n\t\t\tder.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\t);\n\t\tconst algorithmOid = algorithmChildren[0];\n\t\tif (\n\t\t\talgorithmOid === undefined ||\n\t\t\talgorithmOid.tag !== 0x06 ||\n\t\t\talgorithmChildren.length < 1 ||\n\t\t\talgorithmChildren.length > 2\n\t\t) {\n\t\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t\t}\n\t\tconst parameters = algorithmChildren[1];\n\t\treturn {\n\t\t\talgorithmOid: decodeObjectIdentifier(algorithmOid.value),\n\t\t\t...(parameters === undefined ? {} : { parametersTag: parameters.tag }),\n\t\t\t...(parameters?.tag === 0x06\n\t\t\t\t? { parametersOid: decodeObjectIdentifier(parameters.value) }\n\t\t\t\t: {}),\n\t\t};\n\t} catch {\n\t\tthrow new Error('Malformed SubjectPublicKeyInfo');\n\t}\n}\n\nfunction assertSpkiMatchesRequestedAlgorithm(\n\tparsedSpki: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PublicKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedSpki.parametersTag !== undefined && parsedSpki.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedSpki.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedSpki.parametersTag !== 0x06 ||\n\t\t\t\tparsedSpki.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (parsedSpki.algorithmOid !== OIDS.ed25519 || parsedSpki.parametersTag !== undefined) {\n\t\t\t\tthrow new Error('SubjectPublicKeyInfo algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n\nfunction assertPkcs8MatchesRequestedAlgorithm(\n\tparsedPrivateKey: {\n\t\treadonly algorithmOid: string;\n\t\treadonly parametersOid?: string;\n\t\treadonly parametersTag?: number;\n\t},\n\talgorithm: PrivateKeyImportInput,\n): void {\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.rsaEncryption ||\n\t\t\t\t(parsedPrivateKey.parametersTag !== undefined && parsedPrivateKey.parametersTag !== 0x05)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ecPublicKey ||\n\t\t\t\tparsedPrivateKey.parametersTag !== 0x06 ||\n\t\t\t\tparsedPrivateKey.parametersOid !== curveToOid(algorithm.curve)\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (\n\t\t\t\tparsedPrivateKey.algorithmOid !== OIDS.ed25519 ||\n\t\t\t\tparsedPrivateKey.parametersTag !== undefined\n\t\t\t) {\n\t\t\t\tthrow new Error('PKCS#8 private key algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n\nfunction assertPublicJwkMatchesRequestedAlgorithm(\n\tjwk: JsonWebKey,\n\talgorithm: PublicKeyImportInput,\n): void {\n\tif (\n\t\tjwk.k !== undefined ||\n\t\tjwk.d !== undefined ||\n\t\tjwk.p !== undefined ||\n\t\tjwk.q !== undefined ||\n\t\tjwk.dp !== undefined ||\n\t\tjwk.dq !== undefined ||\n\t\tjwk.qi !== undefined ||\n\t\tjwk.oth !== undefined\n\t) {\n\t\tthrow new Error('Public JWK must not contain private key material');\n\t}\n\tswitch (algorithm.kind) {\n\t\tcase 'rsa':\n\t\t\tif (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ecdsa':\n\t\t\tif (\n\t\t\t\tjwk.kty !== 'EC' ||\n\t\t\t\tjwk.crv !== algorithm.curve ||\n\t\t\t\ttypeof jwk.x !== 'string' ||\n\t\t\t\ttypeof jwk.y !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'ed25519':\n\t\t\tif (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string') {\n\t\t\t\tthrow new Error('Public JWK algorithm does not match requested import algorithm');\n\t\t\t}\n\t\t\treturn;\n\t}\n}\n"],"mappings":"4xBA6NA,eAAsB,GACrB,EAA+B,CAAE,KAAM,QAAS,MAAO,OAAQ,EACpC,CAE3B,IAAM,EAAY,MADH,EAAU,CAAC,CAAC,OACI,YAAY,GAAuB,CAAS,EAAG,GAAM,CACnF,OACA,QACD,CAAC,EAED,GAAI,EAAE,cAAe,IAAc,EAAE,eAAgB,GACpD,MAAU,MAAM,iCAAiC,EAGlD,OAAO,EAAY,EAAU,UAAW,EAAU,UAAU,CAC7D,CAEA,SAAS,EAAY,EAAsB,EAAwC,CAClF,MAAO,CACN,YACA,aACA,MAAM,eAAgB,CACrB,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,OAAQ,CAAS,CAAC,CAC5E,EACA,MAAM,eAAgB,CACrB,OAAO,EAAU,aAAc,MAAM,KAAK,cAAc,CAAC,CAC1D,EACA,MAAM,gBAAiB,CACtB,OAAO,IAAI,WAAW,MAAM,EAAU,CAAC,CAAC,OAAO,UAAU,QAAS,CAAU,CAAC,CAC9E,EACA,MAAM,gBAAiB,CACtB,OAAO,EAAU,cAAe,MAAM,KAAK,eAAe,CAAC,CAC5D,EACA,MAAM,iBAAkB,CACvB,OAAO,EAAU,CAAC,CAAC,OAAO,UAAU,MAAO,C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EAAI,GAAM,SACtE,MAAU,MAAM,gEAAgE,EAEjF,OACD,IAAK,QACJ,GACC,EAAI,MAAQ,MACZ,EAAI,MAAQ,EAAU,OACtB,OAAO,EAAI,GAAM,UACjB,OAAO,EAAI,GAAM,SAEjB,MAAU,MAAM,gEAAgE,EAEjF,OACD,IAAK,UACJ,GAAI,EAAI,MAAQ,OAAS,EAAI,MAAQ,WAAa,OAAO,EAAI,GAAM,SAClE,MAAU,MAAM,gEAAgE,EAEjF,MACF,CACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pem.js","names":[],"sources":["../../src/pem/pem.ts"],"sourcesContent":["/**\n * PEM helpers used across the public API.\n *\n * Encodes, decodes, splits, and categorizes PEM blocks as defined by\n * RFC 7468.\n *\n * @module\n */\n\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64.ts';\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\n\n/** A single decoded PEM block with its label, decoded DER bytes, and original PEM text. */\nexport interface PemBlock {\n\t/** RFC 7468 label between the `BEGIN` / `END` markers (e.g. `\"CERTIFICATE\"`). */\n\treadonly label: string;\n\t/** Decoded DER content of this block. */\n\treadonly bytes: Uint8Array;\n\t/** The original PEM text including `BEGIN`/`END` lines. */\n\treadonly pem: string;\n}\n\n/**\n * PEM blocks grouped by their label into well-known PKI categories.\n * Blocks that don't match any known label land in {@linkcode others}.\n */\nexport interface CategorizedPemBlocks {\n\t/** Blocks with label `CERTIFICATE`. */\n\treadonly certificates: readonly PemBlock[];\n\t/** Blocks with label `CERTIFICATE REQUEST`. */\n\treadonly certificateRequests: readonly PemBlock[];\n\t/** Blocks with label `PRIVATE KEY`, `RSA PRIVATE KEY`, or `EC PRIVATE KEY`. */\n\treadonly privateKeys: readonly PemBlock[];\n\t/** Blocks with label `PUBLIC KEY`. */\n\treadonly publicKeys: readonly PemBlock[];\n\t/** Blocks whose label doesn't match any of the above categories. */\n\treadonly others: readonly PemBlock[];\n}\n\n/**\n * Wraps DER bytes in a PEM envelope with 64-character base64 lines.\n *\n * @param label PEM type label (e.g. `\"CERTIFICATE\"`, `\"PRIVATE KEY\"`).\n * @param der Raw DER-encoded content.\n */\nexport function pemEncode(label: string, der: Uint8Array): string {\n\tconst body = base64Encode(der);\n\tconst lines = body.match(/.{1,64}/g) ?? [];\n\treturn `-----BEGIN ${label}-----\\n${lines.join('\\n')}\\n-----END ${label}-----`;\n}\n\n/** Machine-readable failure reason for the PEM decoders. */\nexport type PemErrorCode = 'malformed';\n\n/** Structured failure payload for PEM decoding. */\nexport interface PemFailure extends Micro509Error<PemErrorCode> {\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode pemDecode}. */\nexport type PemDecodeResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode splitPemBlocks}. */\nexport type SplitPemBlocksResult =\n\t| { readonly ok: true; readonly value: readonly PemBlock[] }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode categorizePemBlocks}. */\nexport type CategorizePemBlocksResult =\n\t| { readonly ok: true; readonly value: CategorizedPemBlocks }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/**\n * Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the\n * DER content from a PEM string. Throws if the `BEGIN`/`END` markers don't\n * match `label`.\n *\n * @param label Expected PEM type label.\n * @param pem PEM-encoded text (may contain `\\r`).\n */\nexport function pemDecodeOrThrow(label: string, pem: string): Uint8Array {\n\tconst normalized = pem.replace(/\\r/g, '').trim();\n\tconst begin = `-----BEGIN ${label}-----`;\n\tconst end = `-----END ${label}-----`;\n\tconst lines = normalized.split('\\n');\n\tif (lines[0] !== begin || lines[lines.length - 1] !== end || lines.length < 3) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\tconst bodyLines = normalizePemBodyLines(lines.slice(1, -1));\n\tif (bodyLines === undefined) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\ttry {\n\t\treturn base64Decode(bodyLines.join(''));\n\t} catch {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns\n * them as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files\n * and ignores non-PEM text between blocks.\n */\nexport function splitPemBlocksOrThrow(input: string): readonly PemBlock[] {\n\tconst normalized = input.replace(/\\r/g, '');\n\tconst blocks: PemBlock[] = [];\n\tconst beginToken = '-----BEGIN ';\n\t// Linear `indexOf` scan rather than a global regex with a lazy body: a\n\t// backtracking pattern like `([\\s\\S]*?)…\\1` is polynomial on many unclosed\n\t// BEGIN markers (ReDoS). `indexOf` advances monotonically, so this stays O(n)\n\t// while preserving the original block/gap/label semantics.\n\tlet cursor = 0;\n\tlet scan = 0;\n\twhile (scan < normalized.length) {\n\t\tconst beginIdx = normalized.indexOf(beginToken, scan);\n\t\tif (beginIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst labelStart = beginIdx + beginToken.length;\n\t\tconst dashIdx = normalized.indexOf('-----', labelStart);\n\t\tif (dashIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst label = normalized.slice(labelStart, dashIdx);\n\t\tconst beginLineEnd = dashIdx + 5;\n\t\t// A well-formed begin line is `-----BEGIN <label>-----\\n` with a dash-free,\n\t\t// single-line label (RFC 7468). Anything else is not a block start; skip it\n\t\t// so it surfaces in the stray-marker checks instead of being parsed.\n\t\tif (\n\t\t\tlabel.length === 0 ||\n\t\t\tlabel.includes('-') ||\n\t\t\tlabel.includes('\\n') ||\n\t\t\tnormalized[beginLineEnd] !== '\\n'\n\t\t) {\n\t\t\tscan = labelStart;\n\t\t\tcontinue;\n\t\t}\n\t\tconst bodyStart = beginLineEnd + 1;\n\t\tconst endToken = `\\n-----END ${label}-----`;\n\t\tconst endIdx = normalized.indexOf(endToken, bodyStart);\n\t\tif (endIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst blockEnd = endIdx + endToken.length;\n\t\tconst pem = normalized.slice(beginIdx, blockEnd);\n\t\tif (containsPemMarker(normalized.slice(cursor, beginIdx))) {\n\t\t\tthrow new Error('Malformed PEM block');\n\t\t}\n\t\tblocks.push({\n\t\t\tlabel,\n\t\t\tbytes: pemDecodeOrThrow(label, pem),\n\t\t\tpem,\n\t\t});\n\t\tcursor = blockEnd;\n\t\tscan = blockEnd;\n\t}\n\tif (containsPemMarker(normalized.slice(cursor))) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\treturn blocks;\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n */\nexport function categorizePemBlocksOrThrow(\n\tinput: string | readonly PemBlock[],\n): CategorizedPemBlocks {\n\tconst blocks = typeof input === 'string' ? splitPemBlocksOrThrow(input) : input;\n\tconst certificates: PemBlock[] = [];\n\tconst certificateRequests: PemBlock[] = [];\n\tconst privateKeys: PemBlock[] = [];\n\tconst publicKeys: PemBlock[] = [];\n\tconst others: PemBlock[] = [];\n\n\tfor (const block of blocks) {\n\t\tswitch (block.label) {\n\t\t\tcase 'CERTIFICATE':\n\t\t\t\tcertificates.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'CERTIFICATE REQUEST':\n\t\t\t\tcertificateRequests.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PRIVATE KEY':\n\t\t\tcase 'RSA PRIVATE KEY':\n\t\t\tcase 'EC PRIVATE KEY':\n\t\t\t\tprivateKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PUBLIC KEY':\n\t\t\t\tpublicKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tothers.push(block);\n\t\t}\n\t}\n\n\treturn { certificates, certificateRequests, privateKeys, publicKeys, others };\n}\n\nfunction normalizePemBodyLines(lines: readonly string[]): readonly string[] | undefined {\n\tconst normalizedLines = lines.map((line) => line.replace(/[ \\t]/g, ''));\n\tconst nonEmptyLines = normalizedLines.filter((line) => line !== '');\n\tif (nonEmptyLines.length === 0) {\n\t\treturn [''];\n\t}\n\treturn nonEmptyLines.every((line) => /^[A-Za-z0-9+/=]+$/.test(line)) ? nonEmptyLines : undefined;\n}\n\nfunction containsPemMarker(value: string): boolean {\n\treturn value.includes('-----BEGIN ') || value.includes('-----END ');\n}\n\n/**\n * Extracts and base64-decodes the DER content from a PEM string.\n *\n * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`\n * markers don't match `label` or the body is not valid base64. For the\n * throwing form use {@linkcode pemDecodeOrThrow}.\n */\nexport function pemDecode(label: string, pem: string): PemDecodeResult {\n\treturn toPemResult(() => pemDecodeOrThrow(label, pem), 'Invalid PEM');\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them\n * as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files and\n * ignores non-PEM text between blocks.\n *\n * Returns a typed failure (`code: 'malformed'`) on stray or truncated PEM\n * markers. For the throwing form use {@linkcode splitPemBlocksOrThrow}.\n */\nexport function splitPemBlocks(input: string): SplitPemBlocksResult {\n\treturn toPemResult(() => splitPemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n *\n * Returns a typed failure (`code: 'malformed'`) when raw text contains stray\n * or truncated PEM markers. For the throwing form use\n * {@linkcode categorizePemBlocksOrThrow}.\n */\nexport function categorizePemBlocks(\n\tinput: string | readonly PemBlock[],\n): CategorizePemBlocksResult {\n\treturn toPemResult(() => categorizePemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/** Shared Result wrapper around the throwing PEM cores. */\nfunction toPemResult<TValue>(\n\toperation: () => TValue,\n\tfallbackMessage: string,\n):\n\t| { readonly ok: true; readonly value: TValue }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure> {\n\ttry {\n\t\treturn successResult(operation());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : fallbackMessage);\n\t}\n}\n"],"mappings":"6KAmDA,SAAgB,EAAU,EAAe,EAAyB,CAGjE,MAAO,cAAc,EAAM,UAFd,EAAa,CACT,CAAC,CAAC,MAAM,UAAU,GAAK,CAAC,EAAA,CACC,KAAK;CAAI,EAAE,aAAa,EAAM,MACzE,CAiCA,SAAgB,EAAiB,EAAe,EAAyB,CACxE,IAAM,EAAa,EAAI,QAAQ,MAAO,EAAE,CAAC,CAAC,KAAK,EACzC,EAAQ,cAAc,EAAM,OAC5B,EAAM,YAAY,EAAM,OACxB,EAAQ,EAAW,MAAM;CAAI,EACnC,GAAI,EAAM,KAAO,GAAS,EAAM,EAAM,OAAS,KAAO,GAAO,EAAM,OAAS,EAC3E,MAAU,MAAM,mBAAmB,GAAO,EAE3C,IAAM,EAAY,EAAsB,EAAM,MAAM,EAAG,EAAE,CAAC,EAC1D,GAAI,IAAc,IAAA,GACjB,MAAU,MAAM,mBAAmB,GAAO,EAE3C,GAAI,CACH,OAAO,EAAa,EAAU,KAAK,EAAE,CAAC,CACvC,MAAQ,CACP,MAAU,MAAM,mBAAmB,GAAO,CAC3C,CACD,CAOA,SAAgB,EAAsB,EAAoC,CACzE,IAAM,EAAa,EAAM,QAAQ,MAAO,EAAE,EACpC,EAAqB,CAAC,EAMxB,EAAS,EACT,EAAO,EACX,KAAO,EAAO,EAAW,QAAQ,CAChC,IAAM,EAAW,EAAW,QAAQ,cAAY,CAAI,EACpD,GAAI,IAAa,GAChB,MAED,IAAM,EAAa,EAAW,GACxB,EAAU,EAAW,QAAQ,QAAS,CAAU,EACtD,GAAI,IAAY,GACf,MAED,I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