micro509 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/index.d.ts +3 -3
  2. package/dist/index.js +15 -15
  3. package/dist/internal/asn1/asn1.js +145 -186
  4. package/dist/internal/asn1/asn1.js.map +1 -0
  5. package/dist/internal/asn1/der.js +210 -227
  6. package/dist/internal/asn1/der.js.map +1 -0
  7. package/dist/internal/asn1/oids.js +297 -101
  8. package/dist/internal/asn1/oids.js.map +1 -0
  9. package/dist/internal/asn1/oids2.js +69 -0
  10. package/dist/internal/asn1/oids2.js.map +1 -0
  11. package/dist/internal/crypto/algorithm-names.js +37 -35
  12. package/dist/internal/crypto/algorithm-names.js.map +1 -0
  13. package/dist/internal/crypto/ecdsa.js +25 -28
  14. package/dist/internal/crypto/ecdsa.js.map +1 -0
  15. package/dist/internal/crypto/hash.js +56 -117
  16. package/dist/internal/crypto/hash.js.map +1 -0
  17. package/dist/internal/crypto/pbes2.js +122 -133
  18. package/dist/internal/crypto/pbes2.js.map +1 -0
  19. package/dist/internal/crypto/rsa-pss.js +118 -124
  20. package/dist/internal/crypto/rsa-pss.js.map +1 -0
  21. package/dist/internal/crypto/sig-verify.js +87 -99
  22. package/dist/internal/crypto/sig-verify.js.map +1 -0
  23. package/dist/internal/crypto/signing.d.ts +12 -8
  24. package/dist/internal/crypto/signing.js +53 -55
  25. package/dist/internal/crypto/signing.js.map +1 -0
  26. package/dist/internal/crypto/webcrypto.js +5 -3
  27. package/dist/internal/crypto/webcrypto.js.map +1 -0
  28. package/dist/internal/shared/base64.js +10 -9
  29. package/dist/internal/shared/base64.js.map +1 -0
  30. package/dist/internal/shared/dn.js +50 -57
  31. package/dist/internal/shared/dn.js.map +1 -0
  32. package/dist/internal/shared/ip.js +43 -53
  33. package/dist/internal/shared/ip.js.map +1 -0
  34. package/dist/internal/verify/name-constraints-engine.js +211 -239
  35. package/dist/internal/verify/name-constraints-engine.js.map +1 -0
  36. package/dist/internal/verify/policy-engine.js +228 -247
  37. package/dist/internal/verify/policy-engine.js.map +1 -0
  38. package/dist/internal/verify/verify-path.js +213 -228
  39. package/dist/internal/verify/verify-path.js.map +1 -0
  40. package/dist/internal/x509/extension-bits.js +62 -59
  41. package/dist/internal/x509/extension-bits.js.map +1 -0
  42. package/dist/internal/x509/extension-registry.js +133 -164
  43. package/dist/internal/x509/extension-registry.js.map +1 -0
  44. package/dist/internal/x509/name-fields.js +35 -41
  45. package/dist/internal/x509/name-fields.js.map +1 -0
  46. package/dist/keys/keys.d.ts +583 -547
  47. package/dist/keys/keys.js +519 -431
  48. package/dist/keys/keys.js.map +1 -0
  49. package/dist/keys.js +2 -2
  50. package/dist/pem/pem.d.ts +46 -46
  51. package/dist/pem/pem.js +62 -81
  52. package/dist/pem/pem.js.map +1 -0
  53. package/dist/pem.js +2 -2
  54. package/dist/pkcs/pfx.d.ts +96 -80
  55. package/dist/pkcs/pfx.js +191 -231
  56. package/dist/pkcs/pfx.js.map +1 -0
  57. package/dist/pkcs/pkcs12-mac.d.ts +20 -18
  58. package/dist/pkcs/pkcs12-mac.js +90 -111
  59. package/dist/pkcs/pkcs12-mac.js.map +1 -0
  60. package/dist/pkcs/pkcs7.d.ts +118 -69
  61. package/dist/pkcs/pkcs7.js +401 -443
  62. package/dist/pkcs/pkcs7.js.map +1 -0
  63. package/dist/pkcs.d.ts +2 -2
  64. package/dist/pkcs.js +4 -4
  65. package/dist/result/result.d.ts +37 -32
  66. package/dist/result/result.js +46 -44
  67. package/dist/result/result.js.map +1 -0
  68. package/dist/result.js +2 -2
  69. package/dist/revocation/chain.d.ts +138 -119
  70. package/dist/revocation/chain.js +248 -281
  71. package/dist/revocation/chain.js.map +1 -0
  72. package/dist/revocation/crl.d.ts +125 -123
  73. package/dist/revocation/crl.js +653 -745
  74. package/dist/revocation/crl.js.map +1 -0
  75. package/dist/revocation/ocsp.d.ts +183 -177
  76. package/dist/revocation/ocsp.js +579 -636
  77. package/dist/revocation/ocsp.js.map +1 -0
  78. package/dist/revocation/revocation.d.ts +26 -26
  79. package/dist/revocation/revocation.js +104 -125
  80. package/dist/revocation/revocation.js.map +1 -0
  81. package/dist/revocation.js +5 -5
  82. package/dist/verify/identity.d.ts +42 -42
  83. package/dist/verify/identity.js +158 -167
  84. package/dist/verify/identity.js.map +1 -0
  85. package/dist/verify/name-constraints.d.ts +7 -7
  86. package/dist/verify/policy.d.ts +10 -10
  87. package/dist/verify/verify.d.ts +163 -163
  88. package/dist/verify/verify.js +396 -392
  89. package/dist/verify/verify.js.map +1 -0
  90. package/dist/verify.js +3 -3
  91. package/dist/x509/certificate.d.ts +117 -117
  92. package/dist/x509/certificate.js +51 -60
  93. package/dist/x509/certificate.js.map +1 -0
  94. package/dist/x509/csr.d.ts +25 -25
  95. package/dist/x509/csr.js +26 -30
  96. package/dist/x509/csr.js.map +1 -0
  97. package/dist/x509/extensions.d.ts +228 -184
  98. package/dist/x509/extensions.js +175 -200
  99. package/dist/x509/extensions.js.map +1 -0
  100. package/dist/x509/name.d.ts +94 -93
  101. package/dist/x509/name.js +30 -29
  102. package/dist/x509/name.js.map +1 -0
  103. package/dist/x509/parse.d.ts +185 -185
  104. package/dist/x509/parse.js +638 -676
  105. package/dist/x509/parse.js.map +1 -0
  106. package/dist/x509.js +6 -6
  107. package/package.json +79 -41
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asn1.js","names":[],"sources":["../../../src/internal/asn1/asn1.ts"],"sourcesContent":["/**\n * ASN.1 decoding helpers used by the higher-level DER, parse, and crypto modules.\n *\n * These utilities stay intentionally small and strict so malformed input fails early and\n * higher-level modules can build on one consistent decoding layer.\n *\n * @module\n */\n\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport { readElement } from '#micro509/internal/asn1/der';\n\n/** Shared UTF-8 text decoder for ASN.1 string types. */\nconst textDecoder = new TextDecoder('utf-8', { fatal: true });\n\nconst PRINTABLE_STRING_PATTERN = /^[A-Za-z0-9 '()+,\\-./:=?]*$/u;\n\n/**\n * Decodes a DER-encoded OBJECT IDENTIFIER value into its dotted-decimal string\n * form (e.g. `\"1.2.840.113549.1.1.1\"`).\n *\n * Throws on empty input, truncated multi-byte sub-identifiers, or incomplete\n * continuation octets.\n */\nexport function decodeObjectIdentifier(bytes: Uint8Array): string {\n\tif (bytes.length === 0) {\n\t\tthrow new Error('OID is empty');\n\t}\n\tconst firstSubidentifier = decodeOidSubidentifier(bytes, 0);\n\tlet offset = firstSubidentifier.nextOffset;\n\tconst values =\n\t\tfirstSubidentifier.value < 40\n\t\t\t? [0, firstSubidentifier.value]\n\t\t\t: firstSubidentifier.value < 80\n\t\t\t\t? [1, firstSubidentifier.value - 40]\n\t\t\t\t: [2, firstSubidentifier.value - 80];\n\twhile (offset < bytes.length) {\n\t\tconst subidentifier = decodeOidSubidentifier(bytes, offset);\n\t\tvalues.push(subidentifier.value);\n\t\toffset = subidentifier.nextOffset;\n\t}\n\treturn values.join('.');\n}\n\n/** Converts raw bytes to a lowercase hex string with no separator. */\nexport function toHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Copies a `Uint8Array` into a standalone `ArrayBuffer` suitable for\n * Web Crypto operations that require a non-shared backing buffer.\n */\nexport function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n\tconst out = new ArrayBuffer(bytes.length);\n\tnew Uint8Array(out).set(bytes);\n\treturn out;\n}\n\n/**\n * Iterates through all direct child TLV elements inside a constructed\n * {@linkcode DerElement} (SEQUENCE, SET, or context-tagged container).\n *\n * Throws if any child overflows the parent boundary or if there is\n * leftover data between the last child and the parent end offset.\n */\nexport function childrenOf(source: Uint8Array, parent: DerElement): DerElement[] {\n\tconst children: DerElement[] = [];\n\tlet offset = parent.start;\n\twhile (offset < parent.end) {\n\t\tconst child = readElement(source, offset);\n\t\tif (child.end > parent.end) {\n\t\t\tthrow new Error('DER child exceeds parent length');\n\t\t}\n\t\tchildren.push(child);\n\t\toffset = child.end;\n\t}\n\tif (offset !== parent.end) {\n\t\tthrow new Error('Malformed DER container');\n\t}\n\treturn children;\n}\n\n/**\n * Asserts that a value is not `undefined`, returning it narrowed.\n * Used to enforce the presence of mandatory ASN.1 fields during parsing.\n *\n * @param label Human-readable field name included in the error message on failure.\n */\nexport function requireElement<T>(value: T | undefined, label: string): T {\n\tif (value === undefined) {\n\t\tthrow new Error(`Missing ${label}`);\n\t}\n\treturn value;\n}\n\n/**\n * Strips the leading \"unused bits\" octet from a BIT STRING element,\n * returning just the payload bytes. Throws if the tag is not `0x03`.\n *\n * Used to extract signature values and public keys from their BIT STRING wrapper.\n */\nexport function extractBitStringValue(element: DerElement): Uint8Array {\n\tif (element.tag !== 0x03) {\n\t\tthrow new Error('Expected BIT STRING');\n\t}\n\tconst unusedBits = element.value[0];\n\tif (unusedBits === undefined || unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tif (unusedBits !== 0) {\n\t\tthrow new Error('BIT STRING must have zero unused bits');\n\t}\n\treturn element.value.slice(1);\n}\n\n/**\n * Parses a {@linkcode DerElement} with tag UTCTime (`0x17`) or GeneralizedTime (`0x18`)\n * into a `Date`.\n *\n * For UTCTime, the two-digit year is interpreted per RFC 5280: values >= 50 map\n * to 19xx, values < 50 map to 20xx. Throws on unrecognized time tags.\n */\nexport function parseTime(element: DerElement): Date {\n\tif (element.tag === 0x17) {\n\t\tconst value = decodeUtf8Text(element.value, 'UTCTime');\n\t\tconst match = /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(value);\n\t\tif (match === null) {\n\t\t\tthrow new Error('Invalid UTCTime');\n\t\t}\n\t\tconst yearText = requireElement(match[1], 'UTCTime year');\n\t\tconst monthText = requireElement(match[2], 'UTCTime month');\n\t\tconst dayText = requireElement(match[3], 'UTCTime day');\n\t\tconst hourText = requireElement(match[4], 'UTCTime hour');\n\t\tconst minuteText = requireElement(match[5], 'UTCTime minute');\n\t\tconst secondText = requireElement(match[6], 'UTCTime second');\n\t\tconst year = Number.parseInt(yearText, 10);\n\t\treturn buildStrictUtcDate(\n\t\t\tyear >= 50 ? 1900 + year : 2000 + year,\n\t\t\tmonthText,\n\t\t\tdayText,\n\t\t\thourText,\n\t\t\tminuteText,\n\t\t\tsecondText,\n\t\t\t'UTCTime',\n\t\t);\n\t}\n\tif (element.tag === 0x18) {\n\t\tconst value = decodeUtf8Text(element.value, 'GeneralizedTime');\n\t\tconst match = /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(value);\n\t\tif (match === null) {\n\t\t\tthrow new Error('Invalid GeneralizedTime');\n\t\t}\n\t\tconst yearText = requireElement(match[1], 'GeneralizedTime year');\n\t\tconst monthText = requireElement(match[2], 'GeneralizedTime month');\n\t\tconst dayText = requireElement(match[3], 'GeneralizedTime day');\n\t\tconst hourText = requireElement(match[4], 'GeneralizedTime hour');\n\t\tconst minuteText = requireElement(match[5], 'GeneralizedTime minute');\n\t\tconst secondText = requireElement(match[6], 'GeneralizedTime second');\n\t\treturn buildStrictUtcDate(\n\t\t\tNumber.parseInt(yearText, 10),\n\t\t\tmonthText,\n\t\t\tdayText,\n\t\t\thourText,\n\t\t\tminuteText,\n\t\t\tsecondText,\n\t\t\t'GeneralizedTime',\n\t\t);\n\t}\n\tthrow new Error(`Unsupported time tag: ${element.tag}`);\n}\n\n/**\n * Decodes a big-endian unsigned byte sequence into a JavaScript `number`.\n * Throws if the value exceeds 6 bytes (48 bits), which is the safe-integer\n * boundary for lossless arithmetic.\n */\nexport function decodeIntegerNumber(bytes: Uint8Array): number {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error('INTEGER is empty');\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error('INTEGER must be non-negative');\n\t}\n\tif (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 0x80) === 0) {\n\t\tthrow new Error('INTEGER must use minimal encoding');\n\t}\n\tif (bytes.length > 6) {\n\t\tthrow new Error(`Integer too large for safe number (${bytes.length} bytes)`);\n\t}\n\tlet value = 0;\n\tfor (const byte of bytes) {\n\t\tvalue = value * 256 + byte;\n\t}\n\treturn value;\n}\n\n/**\n * Like {@linkcode decodeIntegerNumber}, but optionally rewrites thrown error\n * messages with a caller-specific field label.\n *\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n */\nexport function decodeNonNegativeIntegerNumber(bytes: Uint8Array, label = 'INTEGER'): number {\n\tif (label === 'INTEGER') {\n\t\treturn decodeIntegerNumber(bytes);\n\t}\n\ttry {\n\t\treturn decodeIntegerNumber(bytes);\n\t} catch (error) {\n\t\tif (!(error instanceof Error)) {\n\t\t\tthrow error;\n\t\t}\n\t\tswitch (error.message) {\n\t\t\tcase 'INTEGER is empty':\n\t\t\t\tthrow new Error(`${label} is empty`);\n\t\t\tcase 'INTEGER must be non-negative':\n\t\t\t\tthrow new Error(`${label} must be non-negative`);\n\t\t\tcase 'INTEGER must use minimal encoding':\n\t\t\t\tthrow new Error(`${label} must use minimal encoding`);\n\t\t\tdefault:\n\t\t\t\tif (error.message.startsWith('Integer too large for safe number')) {\n\t\t\t\t\tthrow new Error(`${label} too large for safe number (${bytes.length} bytes)`);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t}\n\t}\n}\n\n/**\n * Converts a hex string (even or odd length) to a `Uint8Array`.\n * Odd-length strings are left-padded with a zero nibble.\n */\nexport function hexToBytes(value: string): Uint8Array {\n\tconst normalized = value.length % 2 === 0 ? value : `0${value}`;\n\tconst out = new Uint8Array(normalized.length / 2);\n\tfor (let index = 0; index < out.length; index += 1) {\n\t\tconst chunk = normalized.slice(index * 2, index * 2 + 2);\n\t\tif (!/^[0-9a-fA-F]{2}$/.test(chunk)) {\n\t\t\tthrow new Error(`Invalid hex byte: ${chunk}`);\n\t\t}\n\t\tconst parsed = Number.parseInt(chunk, 16);\n\t\tout[index] = parsed;\n\t}\n\treturn out;\n}\n\n/** Decodes a DER BOOLEAN value: any non-zero first byte is `true`. */\nexport function decodeBoolean(bytes: Uint8Array): boolean {\n\tif (bytes.length !== 1) {\n\t\tthrow new Error('BOOLEAN must contain exactly one octet');\n\t}\n\tconst value = bytes[0];\n\tif (value !== 0x00 && value !== 0xff) {\n\t\tthrow new Error('BOOLEAN must use DER encoding');\n\t}\n\treturn value === 0xff;\n}\n\nfunction buildStrictUtcDate(\n\tyear: number,\n\tmonthText: string,\n\tdayText: string,\n\thourText: string,\n\tminuteText: string,\n\tsecondText: string,\n\tlabel: 'UTCTime' | 'GeneralizedTime',\n): Date {\n\tconst month = Number.parseInt(monthText, 10);\n\tconst day = Number.parseInt(dayText, 10);\n\tconst hour = Number.parseInt(hourText, 10);\n\tconst minute = Number.parseInt(minuteText, 10);\n\tconst second = Number.parseInt(secondText, 10);\n\tconst date = new Date(Date.UTC(year, month - 1, day, hour, minute, second));\n\tif (\n\t\tNumber.isNaN(date.getTime()) ||\n\t\tdate.getUTCFullYear() !== year ||\n\t\tdate.getUTCMonth() !== month - 1 ||\n\t\tdate.getUTCDate() !== day ||\n\t\tdate.getUTCHours() !== hour ||\n\t\tdate.getUTCMinutes() !== minute ||\n\t\tdate.getUTCSeconds() !== second\n\t) {\n\t\tthrow new Error(`Invalid ${label}`);\n\t}\n\treturn date;\n}\n\nfunction decodeOidSubidentifier(\n\tbytes: Uint8Array,\n\tstart: number,\n): {\n\treadonly value: number;\n\treadonly nextOffset: number;\n} {\n\tconst first = bytes[start];\n\tif (first === undefined) {\n\t\tthrow new Error('Malformed OID');\n\t}\n\tif (first === 0x80) {\n\t\tthrow new Error('Malformed OID: non-minimal base-128 encoding');\n\t}\n\tlet value = 0;\n\tlet offset = start;\n\tfor (; offset < bytes.length; offset += 1) {\n\t\tconst next = bytes[offset];\n\t\tif (next === undefined) {\n\t\t\tthrow new Error('Malformed OID');\n\t\t}\n\t\tconst digit = next & 0x7f;\n\t\tif (value > Math.floor((Number.MAX_SAFE_INTEGER - digit) / 128)) {\n\t\t\tthrow new Error('Malformed OID: overflow/non-minimal or too-large subidentifier');\n\t\t}\n\t\tvalue = value * 128 + digit;\n\t\tif ((next & 0x80) === 0) {\n\t\t\treturn {\n\t\t\t\tvalue,\n\t\t\t\tnextOffset: offset + 1,\n\t\t\t};\n\t\t}\n\t}\n\tthrow new Error('Malformed OID: incomplete continuation');\n}\n\n/**\n * Decodes a DER string element by tag. Supports UTF8String (`0x0c`),\n * PrintableString (`0x13`), IA5String (`0x16`), UniversalString (`0x1c`),\n * and BMPString (`0x1e`).\n * Throws on unsupported string tags.\n */\nexport function decodeString(tag: number, bytes: Uint8Array): string {\n\tswitch (tag) {\n\t\tcase 0x0c:\n\t\t\treturn decodeUtf8Text(bytes, 'UTF8String');\n\t\tcase 0x13:\n\t\t\treturn decodePrintableString(bytes);\n\t\tcase 0x16:\n\t\t\treturn decodeIa5String(bytes);\n\t\tcase 0x14:\n\t\t\tthrow new Error('Unsupported string tag: 20 (TeletexString)');\n\t\tcase 0x1c:\n\t\t\treturn decodeUniversalString(bytes);\n\t\tcase 0x1e:\n\t\t\treturn decodeBmpString(bytes);\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported string tag: ${tag}`);\n\t}\n}\n\nfunction decodeUtf8Text(\n\tbytes: Uint8Array,\n\tlabel: 'GeneralizedTime' | 'UTCTime' | 'UTF8String',\n): string {\n\ttry {\n\t\treturn textDecoder.decode(bytes);\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tthrow new Error(`Invalid ${label}: invalid UTF-8`, { cause: error });\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction decodeAsciiString(bytes: Uint8Array, label: 'IA5String' | 'PrintableString'): string {\n\tlet value = '';\n\tfor (const byte of bytes) {\n\t\tif (byte > 0x7f) {\n\t\t\tthrow new Error(`Invalid ${label}: contains non-ASCII bytes`);\n\t\t}\n\t\tvalue += String.fromCharCode(byte);\n\t}\n\treturn value;\n}\n\nfunction decodeIa5String(bytes: Uint8Array): string {\n\treturn decodeAsciiString(bytes, 'IA5String');\n}\n\nfunction decodePrintableString(bytes: Uint8Array): string {\n\tconst value = decodeAsciiString(bytes, 'PrintableString');\n\tif (!PRINTABLE_STRING_PATTERN.test(value)) {\n\t\tthrow new Error('Invalid PrintableString: contains characters outside the allowed set');\n\t}\n\treturn value;\n}\n\nfunction decodeBmpString(bytes: Uint8Array): string {\n\tif (bytes.length % 2 !== 0) {\n\t\tthrow new Error('Invalid BMPString length');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < bytes.length; index += 2) {\n\t\tconst left = bytes[index];\n\t\tconst right = bytes[index + 1];\n\t\tif (left === undefined || right === undefined) {\n\t\t\tthrow new Error('Invalid BMPString content');\n\t\t}\n\t\tconst codeUnit = (left << 8) | right;\n\t\tif (codeUnit >= 0xd800 && codeUnit <= 0xdfff) {\n\t\t\tthrow new Error('Invalid BMPString code point');\n\t\t}\n\t\tvalue += String.fromCharCode(codeUnit);\n\t}\n\treturn value;\n}\n\nfunction decodeUniversalString(bytes: Uint8Array): string {\n\tif (bytes.length % 4 !== 0) {\n\t\tthrow new Error('Invalid UniversalString length');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < bytes.length; index += 4) {\n\t\tconst first = bytes[index];\n\t\tconst second = bytes[index + 1];\n\t\tconst third = bytes[index + 2];\n\t\tconst fourth = bytes[index + 3];\n\t\tif (\n\t\t\tfirst === undefined ||\n\t\t\tsecond === undefined ||\n\t\t\tthird === undefined ||\n\t\t\tfourth === undefined\n\t\t) {\n\t\t\tthrow new Error('Invalid UniversalString content');\n\t\t}\n\t\tconst codePoint = ((first * 256 + second) * 256 + third) * 256 + fourth;\n\t\tif (codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) {\n\t\t\tthrow new Error('Invalid UniversalString code point');\n\t\t}\n\t\tvalue += String.fromCodePoint(codePoint);\n\t}\n\treturn value;\n}\n"],"mappings":";;;AAaA,MAAM,IAAc,IAAI,YA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,MAAU,MAAM,0BAA0B;CAE3C,IAAI,IAAQ;CACZ,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAM,QAAQ,KAAS,GAAG;EACrD,IAAM,IAAO,EAAM,IACb,IAAQ,EAAM,IAAQ;EAC5B,IAAI,MAAS,KAAA,KAAa,MAAU,KAAA,GACnC,MAAU,MAAM,2BAA2B;EAE5C,IAAM,IAAY,KAAQ,IAAK;EAC/B,IAAI,KAAY,SAAU,KAAY,OACrC,MAAU,MAAM,8BAA8B;EAE/C,KAAS,OAAO,aAAa,CAAQ;CACtC;CACA,OAAO;AACR;AAEA,SAAS,sBAAsB,GAA2B;CACzD,IAAI,EAAM,SAAS,KAAM,GACxB,MAAU,MAAM,gCAAgC;CAEjD,IAAI,IAAQ;CACZ,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAM,QAAQ,KAAS,GAAG;EACrD,IAAM,IAAQ,EAAM,IACd,IAAS,EAAM,IAAQ,IACvB,IAAQ,EAAM,IAAQ,IACtB,IAAS,EAAM,IAAQ;EAC7B,IACC,MAAU,KAAA,KACV,MAAW,KAAA,KACX,MAAU,KAAA,KACV,MAAW,KAAA,GAEX,MAAU,MAAM,iCAAiC;EAElD,IAAM,MAAc,IAAQ,MAAM,KAAU,MAAM,KAAS,MAAM;EACjE,IAAI,IAAY,WAAa,KAAa,SAAU,KAAa,OAChE,MAAU,MAAM,oCAAoC;EAErD,KAAS,OAAO,cAAc,CAAS;CACxC;CACA,OAAO;AACR"}
@@ -3,110 +3,98 @@
3
3
  * Values < 128 use the short form (one octet); larger values use the
4
4
  * long form (leading octet encodes the number of subsequent length bytes).
5
5
  */
6
- function encodeLength(length) {
7
- assertNonNegativeSafeInteger(length, "DER length");
8
- if (length < 128) return Uint8Array.of(length);
9
- const parts = encodeBase256(length);
10
- return Uint8Array.of(128 | parts.length, ...parts);
6
+ function encodeLength(e) {
7
+ if (assertNonNegativeSafeInteger(e, "DER length"), e < 128) return Uint8Array.of(e);
8
+ let t = encodeBase256(e);
9
+ return Uint8Array.of(128 | t.length, ...t);
11
10
  }
12
11
  /** Concatenates multiple byte arrays into a single `Uint8Array`. */
13
- function concatBytes(parts) {
14
- const length = parts.reduce((sum, part) => sum + part.length, 0);
15
- const out = new Uint8Array(length);
16
- let offset = 0;
17
- for (const part of parts) {
18
- out.set(part, offset);
19
- offset += part.length;
20
- }
21
- return out;
12
+ function concatBytes(e) {
13
+ let t = e.reduce((e, t) => e + t.length, 0), n = new Uint8Array(t), r = 0;
14
+ for (let t of e) n.set(t, r), r += t.length;
15
+ return n;
22
16
  }
23
17
  /**
24
18
  * Builds a complete DER TLV (tag-length-value) element: one tag octet,
25
19
  * the DER-encoded length, then the raw value bytes.
26
20
  */
27
- function tlv(tag, value) {
28
- assertSingleOctetDerTag(tag);
29
- return concatBytes([
30
- Uint8Array.of(tag),
31
- encodeLength(value.length),
32
- value
21
+ function tlv(e, t) {
22
+ return assertSingleOctetDerTag(e), concatBytes([
23
+ Uint8Array.of(e),
24
+ encodeLength(t.length),
25
+ t
33
26
  ]);
34
27
  }
35
28
  /** Wraps concatenated children in a SEQUENCE (tag `0x30`). */
36
- function sequence(parts) {
37
- return tlv(48, concatBytes(parts));
29
+ function sequence(e) {
30
+ return tlv(48, concatBytes(e));
38
31
  }
39
32
  /**
40
33
  * Wraps children in a SET (tag `0x31`) after DER-sorting them
41
34
  * lexicographically by encoded bytes, as required by X.690 DER.
42
35
  */
43
- function setOf(parts) {
44
- return tlv(49, concatBytes(parts.slice().sort((a, b) => {
45
- const len = Math.min(a.length, b.length);
46
- for (let i = 0; i < len; i++) {
47
- const diff = (a[i] ?? 0) - (b[i] ?? 0);
48
- if (diff !== 0) return diff;
36
+ function setOf(e) {
37
+ return tlv(49, concatBytes(e.slice().sort((e, t) => {
38
+ let n = Math.min(e.length, t.length);
39
+ for (let r = 0; r < n; r++) {
40
+ let n = (e[r] ?? 0) - (t[r] ?? 0);
41
+ if (n !== 0) return n;
49
42
  }
50
- return a.length - b.length;
43
+ return e.length - t.length;
51
44
  })));
52
45
  }
53
46
  /**
54
47
  * Wraps a value in an explicit context-specific constructed tag (`0xa0 + tag`).
55
48
  * Used for optional SEQUENCE fields tagged with `[tag] EXPLICIT`.
56
49
  */
57
- function explicitContext(tag, value) {
58
- assertContextSpecificTagNumber(tag);
59
- return tlv(160 + tag, value);
50
+ function explicitContext(e, t) {
51
+ return assertContextSpecificTagNumber(e), tlv(160 + e, t);
60
52
  }
61
53
  /**
62
54
  * Wraps a value in an implicit context-specific constructed tag (`0xa0 + tag`).
63
55
  * Used for `[tag] IMPLICIT` fields whose underlying type is constructed (e.g. SEQUENCE).
64
56
  */
65
- function implicitConstructedContext(tag, value) {
66
- assertContextSpecificTagNumber(tag);
67
- return tlv(160 + tag, value);
57
+ function implicitConstructedContext(e, t) {
58
+ return assertContextSpecificTagNumber(e), tlv(160 + e, t);
68
59
  }
69
60
  /**
70
61
  * Wraps a value in an implicit context-specific primitive tag (`0x80 + tag`).
71
62
  * Used for `[tag] IMPLICIT` fields whose underlying type is primitive (e.g. OCTET STRING).
72
63
  */
73
- function implicitPrimitiveContext(tag, value) {
74
- assertContextSpecificTagNumber(tag);
75
- return tlv(128 + tag, value);
64
+ function implicitPrimitiveContext(e, t) {
65
+ return assertContextSpecificTagNumber(e), tlv(128 + e, t);
76
66
  }
77
67
  /**
78
68
  * Encodes raw big-endian bytes as a DER INTEGER (tag `0x02`).
79
69
  * Strips leading zero bytes for minimal encoding and prepends a zero
80
70
  * byte when the high bit is set to keep the value non-negative.
81
71
  */
82
- function integer(bytes) {
83
- if (bytes.length === 0) return tlv(2, Uint8Array.of(0));
84
- let start = 0;
85
- while (start < bytes.length - 1 && bytes[start] === 0) start += 1;
86
- const value = bytes.slice(start);
87
- if ((value[0] ?? 0) >= 128) return tlv(2, concatBytes([Uint8Array.of(0), value]));
88
- return tlv(2, value);
72
+ function integer(e) {
73
+ if (e.length === 0) return tlv(2, Uint8Array.of(0));
74
+ let t = 0;
75
+ for (; t < e.length - 1 && e[t] === 0;) t += 1;
76
+ let n = e.slice(t);
77
+ return (n[0] ?? 0) >= 128 ? tlv(2, concatBytes([Uint8Array.of(0), n])) : tlv(2, n);
89
78
  }
90
79
  /**
91
80
  * Encodes a non-negative JavaScript `number` as a DER INTEGER.
92
81
  * Throws if the value is not a non-negative safe integer.
93
82
  */
94
- function integerFromNumber(value) {
95
- if (!Number.isSafeInteger(value) || value < 0) throw new Error("INTEGER must be a non-negative safe integer");
96
- if (value === 0) return integer(Uint8Array.of(0));
97
- return integer(Uint8Array.from(encodeBase256(value)));
83
+ function integerFromNumber(e) {
84
+ if (!Number.isSafeInteger(e) || e < 0) throw Error("INTEGER must be a non-negative safe integer");
85
+ return integer(e === 0 ? Uint8Array.of(0) : Uint8Array.from(encodeBase256(e)));
98
86
  }
99
87
  /** Encodes a DER BOOLEAN (tag `0x01`): `true` → `0xff`, `false` → `0x00`. */
100
- function bool(value) {
101
- return tlv(1, Uint8Array.of(value ? 255 : 0));
88
+ function bool(e) {
89
+ return tlv(1, Uint8Array.of(e ? 255 : 0));
102
90
  }
103
91
  /** Produces a DER NULL element (tag `0x05`, zero-length value). */
104
92
  function nullValue() {
105
93
  return tlv(5, /* @__PURE__ */ new Uint8Array());
106
94
  }
107
95
  /** Wraps raw bytes in an OCTET STRING element (tag `0x04`). */
108
- function octetString(value) {
109
- return tlv(4, value);
96
+ function octetString(e) {
97
+ return tlv(4, e);
110
98
  }
111
99
  /**
112
100
  * Encodes a DER BIT STRING (tag `0x03`). The value is prefixed with a
@@ -114,122 +102,110 @@ function octetString(value) {
114
102
  *
115
103
  * @param unusedBits Number of unused trailing bits (0–7). Defaults to 0.
116
104
  */
117
- function bitString(value, unusedBits = 0) {
118
- if (unusedBits < 0 || unusedBits > 7) throw new Error("unusedBits must be between 0 and 7");
119
- if (value.length === 0 && unusedBits !== 0) throw new Error("unusedBits must be 0 when value is empty");
120
- if (value.length > 0 && unusedBits > 0) {
121
- if (((value[value.length - 1] ?? 0) & (1 << unusedBits) - 1) !== 0) throw new Error("unused bits in the last byte must be zero");
122
- }
123
- return tlv(3, concatBytes([Uint8Array.of(unusedBits), value]));
105
+ function bitString(e, t = 0) {
106
+ if (t < 0 || t > 7) throw Error("unusedBits must be between 0 and 7");
107
+ if (e.length === 0 && t !== 0) throw Error("unusedBits must be 0 when value is empty");
108
+ if (e.length > 0 && t > 0 && (e[e.length - 1] ?? 0) & (1 << t) - 1) throw Error("unused bits in the last byte must be zero");
109
+ return tlv(3, concatBytes([Uint8Array.of(t), e]));
124
110
  }
125
111
  /** Encodes a DER UTF8String (tag `0x0c`). */
126
- function utf8String(value) {
127
- return tlv(12, new TextEncoder().encode(value));
112
+ function utf8String(e) {
113
+ return tlv(12, new TextEncoder().encode(e));
128
114
  }
129
115
  /**
130
116
  * Encodes a DER PrintableString (tag `0x13`).
131
117
  * Throws if the input contains characters outside the X.520 PrintableString set.
132
118
  */
133
- function printableString(value) {
134
- if (!/^[A-Za-z0-9 '()+,\-./:=?]*$/.test(value)) throw new Error("Invalid PrintableString: contains characters outside the allowed set");
135
- return tlv(19, new TextEncoder().encode(value));
119
+ function printableString(e) {
120
+ if (!/^[A-Za-z0-9 '()+,\-./:=?]*$/.test(e)) throw Error("Invalid PrintableString: contains characters outside the allowed set");
121
+ return tlv(19, new TextEncoder().encode(e));
136
122
  }
137
123
  /**
138
124
  * Encodes a DER IA5String (tag `0x16`).
139
125
  * Throws if the input contains any non-ASCII character (code point > 0x7f).
140
126
  */
141
- function ia5String(value) {
142
- for (let i = 0; i < value.length; i++) if (value.charCodeAt(i) > 127) throw new Error("Invalid IA5String: contains non-ASCII characters");
143
- return tlv(22, new TextEncoder().encode(value));
127
+ function ia5String(e) {
128
+ for (let t = 0; t < e.length; t++) if (e.charCodeAt(t) > 127) throw Error("Invalid IA5String: contains non-ASCII characters");
129
+ return tlv(22, new TextEncoder().encode(e));
144
130
  }
145
131
  /** Encode a non-negative integer as a base-128 sub-identifier (X.690 §8.19.2). */
146
- function encodeBase128(value) {
147
- const encoded = [Number(value & 127n)];
148
- let current = value >> 7n;
149
- while (current > 0n) {
150
- encoded.unshift(128 | Number(current & 127n));
151
- current >>= 7n;
152
- }
153
- return encoded;
132
+ function encodeBase128(e) {
133
+ let t = [Number(e & 127n)], n = e >> 7n;
134
+ for (; n > 0n;) t.unshift(128 | Number(n & 127n)), n >>= 7n;
135
+ return t;
154
136
  }
155
137
  /**
156
138
  * Encodes a dotted-decimal OID string as a DER OBJECT IDENTIFIER (tag `0x06`).
157
139
  * Validates arc constraints per X.660: first arc must be 0–2, second < 40
158
140
  * for arcs 0 and 1. Sub-identifiers are encoded with base-128 continuation.
159
141
  */
160
- function objectIdentifier(oid) {
161
- const digitPattern = /^\d+$/;
162
- const segments = oid.split(".").map((segment) => {
163
- if (!digitPattern.test(segment)) throw new Error(`Invalid OID segment: ${segment}`);
164
- return BigInt(segment);
142
+ function objectIdentifier(e) {
143
+ let t = /^\d+$/, n = e.split(".").map((e) => {
144
+ if (!t.test(e)) throw Error(`Invalid OID segment: ${e}`);
145
+ return BigInt(e);
165
146
  });
166
- if (segments.length < 2) throw new Error(`Invalid OID: ${oid}`);
167
- const [first, second, ...rest] = segments;
168
- if (first === void 0 || second === void 0) throw new Error(`Invalid OID: ${oid}`);
169
- if (first !== 0n && first !== 1n && first !== 2n) throw new Error(`Invalid OID first arc: ${first}`);
170
- if ((first === 0n || first === 1n) && second >= 40n) throw new Error(`Invalid OID second arc: ${second} (must be < 40 when first arc is ${first})`);
171
- const bytes = encodeBase128(first * 40n + second);
172
- for (const segment of rest) bytes.push(...encodeBase128(segment));
173
- return tlv(6, Uint8Array.from(bytes));
147
+ if (n.length < 2) throw Error(`Invalid OID: ${e}`);
148
+ let [r, i, ...a] = n;
149
+ if (r === void 0 || i === void 0) throw Error(`Invalid OID: ${e}`);
150
+ if (r !== 0n && r !== 1n && r !== 2n) throw Error(`Invalid OID first arc: ${r}`);
151
+ if ((r === 0n || r === 1n) && i >= 40n) throw Error(`Invalid OID second arc: ${i} (must be < 40 when first arc is ${r})`);
152
+ let o = encodeBase128(r * 40n + i);
153
+ for (let e of a) o.push(...encodeBase128(e));
154
+ return tlv(6, Uint8Array.from(o));
174
155
  }
175
156
  /**
176
157
  * Encodes a `Date` as a DER UTCTime (tag `0x17`), format `YYMMDDHHMMSSZ`.
177
158
  * Only the two-digit year is stored; suitable for dates in 1950–2049.
178
159
  */
179
- function utcTime(date) {
180
- assertValidDate(date, "UTCTime");
181
- const year = date.getUTCFullYear();
182
- if (year < 1950 || year > 2049) throw new RangeError("UTCTime year must be between 1950 and 2049");
183
- const value = `${[
184
- twoDigits(year % 100),
185
- twoDigits(date.getUTCMonth() + 1),
186
- twoDigits(date.getUTCDate()),
187
- twoDigits(date.getUTCHours()),
188
- twoDigits(date.getUTCMinutes()),
189
- twoDigits(date.getUTCSeconds())
160
+ function utcTime(e) {
161
+ assertValidDate(e, "UTCTime");
162
+ let t = e.getUTCFullYear();
163
+ if (t < 1950 || t > 2049) throw RangeError("UTCTime year must be between 1950 and 2049");
164
+ let n = `${[
165
+ twoDigits(t % 100),
166
+ twoDigits(e.getUTCMonth() + 1),
167
+ twoDigits(e.getUTCDate()),
168
+ twoDigits(e.getUTCHours()),
169
+ twoDigits(e.getUTCMinutes()),
170
+ twoDigits(e.getUTCSeconds())
190
171
  ].join("")}Z`;
191
- return tlv(23, new TextEncoder().encode(value));
172
+ return tlv(23, new TextEncoder().encode(n));
192
173
  }
193
174
  /**
194
175
  * Encodes a `Date` as a DER GeneralizedTime (tag `0x18`), format `YYYYMMDDHHMMSSZ`.
195
176
  * Uses a four-digit year; required for dates outside the 1950–2049 range.
196
177
  */
197
- function generalizedTime(date) {
198
- assertValidDate(date, "GeneralizedTime");
199
- const year = date.getUTCFullYear();
200
- if (year < 0 || year > 9999) throw new RangeError("GeneralizedTime year must be between 0 and 9999");
201
- const value = `${[
202
- String(year).padStart(4, "0"),
203
- twoDigits(date.getUTCMonth() + 1),
204
- twoDigits(date.getUTCDate()),
205
- twoDigits(date.getUTCHours()),
206
- twoDigits(date.getUTCMinutes()),
207
- twoDigits(date.getUTCSeconds())
178
+ function generalizedTime(e) {
179
+ assertValidDate(e, "GeneralizedTime");
180
+ let t = e.getUTCFullYear();
181
+ if (t < 0 || t > 9999) throw RangeError("GeneralizedTime year must be between 0 and 9999");
182
+ let n = `${[
183
+ String(t).padStart(4, "0"),
184
+ twoDigits(e.getUTCMonth() + 1),
185
+ twoDigits(e.getUTCDate()),
186
+ twoDigits(e.getUTCHours()),
187
+ twoDigits(e.getUTCMinutes()),
188
+ twoDigits(e.getUTCSeconds())
208
189
  ].join("")}Z`;
209
- return tlv(24, new TextEncoder().encode(value));
190
+ return tlv(24, new TextEncoder().encode(n));
210
191
  }
211
192
  /**
212
193
  * Encodes a `Date` as the appropriate DER time type per RFC 5280:
213
194
  * {@linkcode utcTime} for 1950–2049, {@linkcode generalizedTime} otherwise.
214
195
  */
215
- function time(date) {
216
- if (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) return generalizedTime(date);
217
- return utcTime(date);
196
+ function time(e) {
197
+ return e.getUTCFullYear() >= 2050 || e.getUTCFullYear() < 1950 ? generalizedTime(e) : utcTime(e);
218
198
  }
219
199
  /** Zero-pads a number to two digits for time encoding. */
220
- function twoDigits(value) {
221
- return String(value).padStart(2, "0");
200
+ function twoDigits(e) {
201
+ return String(e).padStart(2, "0");
222
202
  }
223
203
  /** Encodes a non-negative integer as big-endian base-256 octets. */
224
- function encodeBase256(value) {
225
- assertNonNegativeSafeInteger(value, "DER integer");
226
- const parts = [];
227
- let current = value;
228
- while (current > 0) {
229
- parts.unshift(current & 255);
230
- current = Math.floor(current / 256);
231
- }
232
- return parts;
204
+ function encodeBase256(e) {
205
+ assertNonNegativeSafeInteger(e, "DER integer");
206
+ let t = [], n = e;
207
+ for (; n > 0;) t.unshift(n & 255), n = Math.floor(n / 256);
208
+ return t;
233
209
  }
234
210
  /**
235
211
  * Reads one TLV element from `bytes` starting at `offset`.
@@ -239,140 +215,147 @@ function encodeBase256(value) {
239
215
  *
240
216
  * @param offset Byte position of the tag octet. Defaults to 0.
241
217
  */
242
- function readElement(bytes, offset = 0) {
243
- const tag = bytes[offset];
244
- if (tag === void 0) throw new Error("Unexpected end of DER input");
245
- if ((tag & 31) === 31) throw new Error("High-tag-number DER form is not supported");
246
- const lengthByte = bytes[offset + 1];
247
- if (lengthByte === void 0) throw new Error("Unexpected end of DER input");
248
- let headerLength = 2;
249
- let length = 0;
250
- if ((lengthByte & 128) === 0) length = lengthByte;
251
- else {
252
- const octets = lengthByte & 127;
253
- if (octets === 0) throw new Error("Indefinite lengths are not supported");
254
- const firstLengthOctet = bytes[offset + 2];
255
- if (firstLengthOctet === void 0) throw new Error("Unexpected end of DER input");
256
- if (firstLengthOctet === 0) throw new Error("Non-minimal DER length encoding");
257
- headerLength += octets;
258
- for (let index = 0; index < octets; index += 1) {
259
- const next = bytes[offset + 2 + index];
260
- if (next === void 0) throw new Error("Unexpected end of DER input");
261
- if (length > Math.floor((Number.MAX_SAFE_INTEGER - next) / 256)) throw new Error("DER length exceeds safe integer range");
262
- length = length * 256 + next;
263
- }
264
- if (length < 128) throw new Error("Non-minimal DER length encoding");
265
- }
266
- const start = offset + headerLength;
267
- const end = start + length;
268
- if (end > bytes.length) throw new Error("DER element exceeds input length");
218
+ function readElement(e, t = 0) {
219
+ let n = e[t];
220
+ if (n === void 0) throw Error("Unexpected end of DER input");
221
+ if ((n & 31) == 31) throw Error("High-tag-number DER form is not supported");
222
+ let r = e[t + 1];
223
+ if (r === void 0) throw Error("Unexpected end of DER input");
224
+ let { headerLength: i, length: a } = readDerLength(e, t, r), o = t + i, s = o + a;
225
+ if (s > e.length) throw Error("DER element exceeds input length");
226
+ return {
227
+ tag: n,
228
+ headerLength: i,
229
+ length: a,
230
+ start: o,
231
+ end: s,
232
+ value: e.slice(o, s)
233
+ };
234
+ }
235
+ /** Decodes and validates the definite-length field of a DER element. */
236
+ function readDerLength(e, t, n) {
237
+ if (!(n & 128)) return {
238
+ headerLength: 2,
239
+ length: n
240
+ };
241
+ let r = n & 127;
242
+ if (r === 0) throw Error("Indefinite lengths are not supported");
243
+ let i = e[t + 2];
244
+ if (i === void 0) throw Error("Unexpected end of DER input");
245
+ if (i === 0) throw Error("Non-minimal DER length encoding");
246
+ let a = readLongFormDerLength(e, t, r);
247
+ if (a < 128) throw Error("Non-minimal DER length encoding");
269
248
  return {
270
- tag,
271
- headerLength,
272
- length,
273
- start,
274
- end,
275
- value: bytes.slice(start, end)
249
+ headerLength: 2 + r,
250
+ length: a
276
251
  };
277
252
  }
253
+ function readLongFormDerLength(e, t, n) {
254
+ let r = 0;
255
+ for (let i = 0; i < n; i += 1) {
256
+ let n = e[t + 2 + i];
257
+ if (n === void 0) throw Error("Unexpected end of DER input");
258
+ if (r > Math.floor((2 ** 53 - 1 - n) / 256)) throw Error("DER length exceeds safe integer range");
259
+ r = r * 256 + n;
260
+ }
261
+ return r;
262
+ }
278
263
  /**
279
264
  * Walks the full DER tree rooted in `bytes` and throws if nesting exceeds
280
265
  * `maxDepth`. Constructed tags with content that cannot be parsed as valid
281
266
  * children are tolerated when listed in `allowOpaqueConstructedTags`.
282
267
  */
283
- function assertDerMaxDepth(bytes, maxDepth = 64, options) {
284
- if (!Number.isSafeInteger(maxDepth) || maxDepth < 1) throw new Error("DER max depth must be a positive safe integer");
285
- const root = readElement(bytes, 0);
286
- if (root.end !== bytes.length) throw new Error("Trailing data after DER element");
287
- const stack = [{
288
- element: root,
268
+ function assertDerMaxDepth(e, t = 64, n) {
269
+ if (!Number.isSafeInteger(t) || t < 1) throw Error("DER max depth must be a positive safe integer");
270
+ let r = readElement(e, 0);
271
+ if (r.end !== e.length) throw Error("Trailing data after DER element");
272
+ let i = [{
273
+ element: r,
289
274
  depth: 1
290
275
  }];
291
- while (stack.length > 0) {
292
- const current = stack.pop();
293
- if (current === void 0) continue;
294
- if (current.depth > maxDepth) throw new Error(`DER exceeds max depth of ${maxDepth}`);
295
- if ((current.element.tag & 32) === 0) continue;
296
- let offset = current.element.start;
297
- let treatedAsOpaqueLeaf = false;
298
- while (offset < current.element.end) {
299
- let child;
300
- try {
301
- child = readElement(bytes, offset);
302
- } catch (error) {
303
- if (canTreatAsOpaqueLeaf(current.element, offset, options)) {
304
- treatedAsOpaqueLeaf = true;
305
- offset = current.element.end;
306
- break;
307
- }
308
- throw error;
309
- }
310
- if (child.end > current.element.end) {
311
- if (canTreatAsOpaqueLeaf(current.element, offset, options)) {
312
- treatedAsOpaqueLeaf = true;
313
- offset = current.element.end;
314
- break;
315
- }
316
- throw new Error("DER child exceeds parent length");
317
- }
318
- stack.push({
319
- element: child,
320
- depth: current.depth + 1
321
- });
322
- offset = child.end;
276
+ for (; i.length > 0;) {
277
+ let r = i.pop();
278
+ if (r !== void 0) {
279
+ if (r.depth > t) throw Error(`DER exceeds max depth of ${t}`);
280
+ r.element.tag & 32 && pushDerChildren(e, r, i, n);
323
281
  }
324
- if (!treatedAsOpaqueLeaf && offset !== current.element.end) throw new Error("Malformed DER container");
325
282
  }
326
283
  }
284
+ function pushDerChildren(e, t, n, r) {
285
+ let i = t.element.start, a = !1;
286
+ for (; i < t.element.end;) {
287
+ let o = readDerChildOrOpaque(e, t.element, i, r);
288
+ if (o === void 0) {
289
+ a = !0, i = t.element.end;
290
+ break;
291
+ }
292
+ n.push({
293
+ element: o,
294
+ depth: t.depth + 1
295
+ }), i = o.end;
296
+ }
297
+ if (!a && i !== t.element.end) throw Error("Malformed DER container");
298
+ }
299
+ function readDerChildOrOpaque(e, t, n, r) {
300
+ let i;
301
+ try {
302
+ i = readElement(e, n);
303
+ } catch (e) {
304
+ if (canTreatAsOpaqueLeaf(t, n, r)) return;
305
+ throw e;
306
+ }
307
+ if (i.end <= t.end) return i;
308
+ if (!canTreatAsOpaqueLeaf(t, n, r)) throw Error("DER child exceeds parent length");
309
+ }
327
310
  /**
328
311
  * Reads the single top-level TLV element from `bytes`, optionally
329
312
  * validating nesting depth. Throws if there is trailing data after the element.
330
313
  */
331
- function readRootElement(bytes, options) {
332
- assertDerMaxDepth(bytes, options?.maxDepth ?? 64, options);
333
- const element = readElement(bytes, 0);
334
- if (element.end !== bytes.length) throw new Error("Trailing data after DER element");
335
- return element;
314
+ function readRootElement(e, t) {
315
+ assertDerMaxDepth(e, t?.maxDepth ?? 64, t);
316
+ let n = readElement(e, 0);
317
+ if (n.end !== e.length) throw Error("Trailing data after DER element");
318
+ return n;
336
319
  }
337
320
  /**
338
321
  * Reads a DER-encoded SEQUENCE from `bytes` and returns its direct children.
339
322
  * Throws if the root element is not a SEQUENCE or if child boundaries are inconsistent.
340
323
  */
341
- function readSequenceChildren(bytes, options) {
342
- const sequenceElement = readRootElement(bytes, options);
343
- if (sequenceElement.tag !== 48) throw new Error("Expected SEQUENCE");
344
- const children = [];
345
- let offset = sequenceElement.start;
346
- while (offset < sequenceElement.end) {
347
- const element = readElement(bytes, offset);
348
- if (element.end > sequenceElement.end) throw new Error("DER child exceeds parent length");
349
- children.push(element);
350
- offset = element.end;
324
+ function readSequenceChildren(e, t) {
325
+ let n = readRootElement(e, t);
326
+ if (n.tag !== 48) throw Error("Expected SEQUENCE");
327
+ let r = [], i = n.start;
328
+ for (; i < n.end;) {
329
+ let t = readElement(e, i);
330
+ if (t.end > n.end) throw Error("DER child exceeds parent length");
331
+ r.push(t), i = t.end;
351
332
  }
352
- if (offset !== sequenceElement.end) throw new Error("Malformed DER sequence");
353
- return children;
333
+ if (i !== n.end) throw Error("Malformed DER sequence");
334
+ return r;
354
335
  }
355
336
  /** Throws if `value` is not a non-negative safe integer. */
356
- function assertNonNegativeSafeInteger(value, label) {
357
- if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label} must be a non-negative safe integer`);
337
+ function assertNonNegativeSafeInteger(e, t) {
338
+ if (!Number.isSafeInteger(e) || e < 0) throw Error(`${t} must be a non-negative safe integer`);
358
339
  }
359
- function assertSingleOctetDerTag(tag) {
360
- if (!Number.isSafeInteger(tag) || tag < 0 || tag > 255) throw new RangeError("DER tag octet must be between 0 and 255");
361
- if ((tag & 31) === 31) throw new Error("High-tag-number DER tags are not supported");
340
+ function assertSingleOctetDerTag(e) {
341
+ if (!Number.isSafeInteger(e) || e < 0 || e > 255) throw RangeError("DER tag octet must be between 0 and 255");
342
+ if ((e & 31) == 31) throw Error("High-tag-number DER tags are not supported");
362
343
  }
363
- function assertContextSpecificTagNumber(tag) {
364
- if (!Number.isSafeInteger(tag) || tag < 0 || tag >= 31) throw new RangeError("Context-specific tag number must be between 0 and 30");
344
+ function assertContextSpecificTagNumber(e) {
345
+ if (!Number.isSafeInteger(e) || e < 0 || e >= 31) throw RangeError("Context-specific tag number must be between 0 and 30");
365
346
  }
366
- function assertValidDate(date, label) {
367
- if (Number.isNaN(date.getTime())) throw new RangeError(`${label} requires a valid Date`);
347
+ function assertValidDate(e, t) {
348
+ if (Number.isNaN(e.getTime())) throw RangeError(`${t} requires a valid Date`);
368
349
  }
369
350
  /**
370
351
  * Returns `true` when a constructed element's content should be treated as
371
352
  * an opaque leaf (not recursed into) because its tag appears in the
372
353
  * `allowOpaqueConstructedTags` list and the offset is at the element start.
373
354
  */
374
- function canTreatAsOpaqueLeaf(element, offset, options) {
375
- return offset === element.start && options?.allowOpaqueConstructedTags?.includes(element.tag) === true;
355
+ function canTreatAsOpaqueLeaf(e, t, n) {
356
+ return t === e.start && n?.allowOpaqueConstructedTags?.includes(e.tag) === !0;
376
357
  }
377
358
  //#endregion
378
359
  export { assertDerMaxDepth, bitString, bool, concatBytes, encodeLength, explicitContext, generalizedTime, ia5String, implicitConstructedContext, implicitPrimitiveContext, integer, integerFromNumber, nullValue, objectIdentifier, octetString, printableString, readElement, readRootElement, readSequenceChildren, sequence, setOf, time, tlv, utcTime, utf8String };
360
+
361
+ //# sourceMappingURL=der.js.map