micro509 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2064 -0
- package/README.md +105 -225
- package/dist/crypto/crypto.d.ts +42 -11
- package/dist/crypto/crypto.js +53 -22
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +2 -2
- package/dist/crypto.js +1 -2
- package/dist/der/der.d.ts +41 -33
- package/dist/der/der.js +26 -24
- package/dist/der/der.js.map +1 -1
- package/dist/index.d.ts +10 -10
- package/dist/index.js +19 -19
- package/dist/internal/asn1/asn1.d.ts +3 -6
- package/dist/internal/asn1/asn1.js +343 -43
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js +146 -0
- package/dist/internal/asn1/ber.js.map +1 -0
- package/dist/internal/asn1/decode-refusal.js +29 -0
- package/dist/internal/asn1/decode-refusal.js.map +1 -0
- package/dist/internal/asn1/der.d.ts +38 -41
- package/dist/internal/asn1/der.js +131 -52
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +83 -53
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/asn1/oids2.js +1 -2
- package/dist/internal/asn1/oids2.js.map +1 -1
- package/dist/internal/crypto/algorithm-names.js +1 -2
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js +13 -8
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js +1 -2
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +24 -11
- package/dist/internal/crypto/pbes2.js +79 -26
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/rsa-pss.js +46 -44
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +4 -7
- package/dist/internal/crypto/sig-verify.js +107 -60
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.d.ts +1 -4
- package/dist/internal/crypto/signing.js +28 -29
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/crypto/webcrypto.js +1 -2
- package/dist/internal/crypto/webcrypto.js.map +1 -1
- package/dist/internal/shared/base64.js +1 -2
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +3 -6
- package/dist/internal/shared/dn.js +99 -53
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna-tables.js +7217 -0
- package/dist/internal/shared/idna-tables.js.map +1 -0
- package/dist/internal/shared/idna.js +296 -0
- package/dist/internal/shared/idna.js.map +1 -0
- package/dist/internal/shared/ip.d.ts +4 -7
- package/dist/internal/shared/ip.js +1 -2
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js +26 -0
- package/dist/internal/shared/mailbox.js.map +1 -0
- package/dist/internal/shared/punycode.js +101 -0
- package/dist/internal/shared/punycode.js.map +1 -0
- package/dist/internal/shared/rfc3454-tables.js +1 -2
- package/dist/internal/shared/rfc3454-tables.js.map +1 -1
- package/dist/internal/shared/rfc4518-tables.js +119 -0
- package/dist/internal/shared/rfc4518-tables.js.map +1 -0
- package/dist/internal/shared/uri-host.js +102 -0
- package/dist/internal/shared/uri-host.js.map +1 -0
- package/dist/internal/verify/name-constraints-engine.js +246 -131
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +6 -21
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/verify-path.d.ts +1 -4
- package/dist/internal/verify/verify-path.js +267 -131
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js +1 -2
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js +2 -3
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +1 -4
- package/dist/internal/x509/extension-errors.js +1 -2
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js +107 -89
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js +129 -0
- package/dist/internal/x509/general-name-profile.js.map +1 -0
- package/dist/internal/x509/general-name-tags.js +1 -2
- package/dist/internal/x509/general-name-tags.js.map +1 -1
- package/dist/internal/x509/general-name.js +128 -42
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js +1 -2
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js +217 -0
- package/dist/internal/x509/or-address.js.map +1 -0
- package/dist/keys/keys.d.ts +112 -97
- package/dist/keys/keys.js +211 -204
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +3 -3
- package/dist/pem/pem.d.ts +14 -17
- package/dist/pem/pem.js +16 -17
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.js +1 -2
- package/dist/pkcs/pfx.d.ts +57 -32
- package/dist/pkcs/pfx.js +209 -173
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.d.ts +104 -27
- package/dist/pkcs/pkcs12-mac.js +266 -79
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +43 -37
- package/dist/pkcs/pkcs7.js +218 -217
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +4 -3
- package/dist/result/result.d.ts +27 -20
- package/dist/result/result.js +8 -3
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +2 -2
- package/dist/result.js +1 -2
- package/dist/revocation/chain.d.ts +101 -23
- package/dist/revocation/chain.js +436 -182
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +131 -67
- package/dist/revocation/crl.js +444 -323
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +94 -59
- package/dist/revocation/ocsp.js +331 -293
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +47 -35
- package/dist/revocation/revocation.js +88 -57
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +3 -3
- package/dist/verify/identity.d.ts +16 -19
- package/dist/verify/identity.js +118 -89
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/name-constraints.d.ts +1 -4
- package/dist/verify/policy.d.ts +9 -7
- package/dist/verify/verify.d.ts +84 -46
- package/dist/verify/verify.js +300 -152
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +2 -2
- package/dist/x509/certificate.d.ts +20 -21
- package/dist/x509/certificate.js +62 -46
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +5 -7
- package/dist/x509/csr.js +10 -11
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.d.ts +154 -66
- package/dist/x509/extensions.js +317 -151
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +4 -7
- package/dist/x509/fingerprint.js +1 -2
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.d.ts +7 -9
- package/dist/x509/name-text.js +18 -4
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +9 -11
- package/dist/x509/name.js +18 -19
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +84 -69
- package/dist/x509/parse.js +421 -400
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +2 -2
- package/package.json +76 -59
|
@@ -1 +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 { objectIdentifier, 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 form.\n *\n * @example \"1.2.840.113549.1.1.1\"\n * @throws on empty input, truncated multi-byte sub-identifiers, or incomplete 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/**\n * Reduces an OID to the dotted-decimal form its DER encoding decodes back to, so\n * that spellings differing only by redundant leading zeros in an arc resolve to\n * one identity.\n *\n * @example `canonicalizeOid('2.5.029.17')` returns `'2.5.29.17'`\n * @throws if the OID has a non-numeric segment or violates the X.660 arc constraints.\n */\nexport function canonicalizeOid(oid: string): string {\n\treturn decodeObjectIdentifier(readElement(objectIdentifier(oid), 0).value);\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 {@linkcode Uint8Array} into a standalone {@linkcode 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 {@linkcode DerElement}\n * (SEQUENCE, SET, or context-tagged container).\n *\n * @throws if any child overflows the parent boundary or if there is 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, returning just the payload bytes.\n *\n * Used to extract signature values and public keys from their BIT STRING wrapper.\n *\n * @throws if the tag is not `0x03`.\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/** A BIT STRING payload and the number of unused trailing bits in its final byte. */\nexport interface DerBitString {\n\t/** Payload bytes, excluding the leading unused-bit count octet. */\n\treadonly bytes: Uint8Array;\n\t/** Unused trailing bits in the final byte, 0 through 7. */\n\treadonly unusedBits: number;\n\t/** `true` when the original encoding had non-zero padding bits (DER violation). */\n\treadonly nonZeroPadding: boolean;\n}\n\n/**\n * Decodes a BIT STRING element into its payload and unused-bit count.\n *\n * Accepts a non-zero unused-bit count, so it reads flag strings such as {@linkcode KeyUsage},\n * which {@linkcode extractBitStringValue} rejects.\n *\n * Padding bits that {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1} requires to be zero are reported through\n * {@linkcode DerBitString.nonZeroPadding} rather than rejected, so a caller can decide.\n */\nexport function decodeBitString(element: DerElement): DerBitString {\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\tconst bytes = element.value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst paddingMask = (1 << unusedBits) - 1;\n\tconst nonZeroPadding =\n\t\tunusedBits > 0 && bytes.length > 0 && ((bytes[bytes.length - 1] ?? 0) & paddingMask) !== 0;\n\treturn { bytes, unusedBits, nonZeroPadding };\n}\n\n/**\n * Parses a {@linkcode DerElement} with tag UTCTime (`0x17`) or GeneralizedTime (`0x18`) into a {@linkcode Date}.\n *\n * For UTCTime, the two-digit year is interpreted per RFC 5280:\n * - values >= 50 map to 19xx,\n * - values < 50 map to 20xx.\n *\n * @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 *\n * @throws if the value exceeds {@linkcode Number.MAX_SAFE_INTEGER}, the 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\tlet value = 0;\n\tfor (const byte of bytes) {\n\t\tif (value > Math.floor((Number.MAX_SAFE_INTEGER - byte) / 256)) {\n\t\t\tthrow new Error(`Integer too large for safe number (${bytes.length} bytes)`);\n\t\t}\n\t\tvalue = value * 256 + byte;\n\t}\n\treturn value;\n}\n\n/**\n * Like {@linkcode decodeIntegerNumber}, but optionally rewrites thrown error messages with a caller-specific field label.\n *\n * @param bytes DER INTEGER content octets to decode.\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n * @throws if the value is empty, negative, non-minimally encoded, or exceeds {@linkcode Number.MAX_SAFE_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 {@linkcode 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. X.690 clause 11.1 restricts TRUE to an all-ones octet, so only `0xff` and `0x00` are accepted. */\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.\n *\n * Supports:\n * - UTF8String (`0x0c`),\n * - PrintableString (`0x13`),\n * - IA5String (`0x16`),\n * - UniversalString (`0x1c`), and\n * - BMPString (`0x1e`).\n *\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,YAAY,SAAS,EAAE,OAAO,GAAK,CAAC,GAEtD,IAA2B;;;;;;;AAQjC,SAAgB,uBAAuB,GAA2B;CACjE,IAAI,EAAM,WAAW,GACpB,MAAU,MAAM,cAAc;CAE/B,IAAM,IAAqB,uBAAuB,GAAO,CAAC,GACtD,IAAS,EAAmB,YAC1B,IACL,EAAmB,QAAQ,KACxB,CAAC,GAAG,EAAmB,KAAK,IAC5B,EAAmB,QAAQ,KAC1B,CAAC,GAAG,EAAmB,QAAQ,EAAE,IACjC,CAAC,GAAG,EAAmB,QAAQ,EAAE;CACtC,OAAO,IAAS,EAAM,SAAQ;EAC7B,IAAM,IAAgB,uBAAuB,GAAO,CAAM;EAE1D,AADA,EAAO,KAAK,EAAc,KAAK,GAC/B,IAAS,EAAc;CACxB;CACA,OAAO,EAAO,KAAK,GAAG;AACvB;;;;;;;;;AAUA,SAAgB,gBAAgB,GAAqB;CACpD,OAAO,uBAAuB,EAAY,EAAiB,CAAG,GAAG,CAAC,CAAC,CAAC,KAAK;AAC1E;;AAGA,SAAgB,MAAM,GAA2B;CAChD,OAAO,MAAM,KAAK,IAAQ,MAAU,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AACjF;;;;;AAMA,SAAgB,cAAc,GAAgC;CAC7D,IAAM,IAAM,IAAI,YAAY,EAAM,MAAM;CAExC,OADA,IAAI,WAAW,CAAG,CAAC,CAAC,IAAI,CAAK,GACtB;AACR;;;;;;;AAQA,SAAgB,WAAW,GAAoB,GAAkC;CAChF,I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O;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"}
|
|
1
|
+
{"version":3,"file":"asn1.js","names":["textDecoder","PRINTABLE_STRING_PATTERN","bytes","firstSubidentifier","offset","first","values","subidentifier","readElement","objectIdentifier","oid","value","out","children","parent","child","source","label","element","unusedBits","paddingMask","match","yearText","monthText","dayText","hourText","minuteText","secondText","year","magnitude","byte","error","normalized","index","chunk","month","day","hour","minute","second","date","start","end","throwDecodeRefusal","tag","TELETEX_EMPTY_POSITIONS","left","right","codeUnit","third","fourth","codePoint","unsupported","maxDepth","verdict","rethrowDecodeRefusal","DECODE_LIMIT_CODES","valid","decode","contents","ESCAPE_CONTROLS","CODE_EXTENSION_CONTROLS","text","character","controls","octet","opensSubidentifier","DAYS_IN_MONTH","UTC_TIME","GENERALIZED_TIME","fields","syntax","monthDays","DER_NR3","rest","format","exponent","mantissa","difference","setOrder","previous","previousClass","childClass","setOfOrder","UNIVERSAL_ELEMENTS"],"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 {\n\tDECODE_LIMIT_CODES,\n\trethrowDecodeRefusal,\n\tthrowDecodeRefusal,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\tMAX_OID_SUBIDENTIFIER_OCTETS,\n\tobjectIdentifier,\n\treadElement,\n\twalkDerTree,\n} from '#micro509/internal/asn1/der';\n\nexport { MAX_OID_SUBIDENTIFIER_OCTETS } 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, ignoreBOM: 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 form.\n *\n * @example \"1.2.840.113549.1.1.1\"\n * @throws on empty input, truncated multi-byte sub-identifiers, or incomplete continuation octets,\n * and `limit_exceeded` for a sub-identifier encoded in more than\n * {@linkcode MAX_OID_SUBIDENTIFIER_OCTETS} 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 first = firstSubidentifier.value;\n\tconst values: bigint[] =\n\t\tfirst < 40n ? [0n, first] : first < 80n ? [1n, first - 40n] : [2n, first - 80n];\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/**\n * Reduces an OID to the dotted-decimal form its DER encoding decodes back to, so\n * that spellings differing only by redundant leading zeros in an arc resolve to\n * one identity.\n *\n * @example `canonicalizeOid('2.5.029.17')` returns `'2.5.29.17'`\n * @throws if the OID has a non-numeric segment or violates the X.660 arc constraints.\n */\nexport function canonicalizeOid(oid: string): string {\n\treturn decodeObjectIdentifier(readElement(objectIdentifier(oid), 0).value);\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 {@linkcode Uint8Array} into a standalone {@linkcode 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 {@linkcode DerElement}\n * (SEQUENCE, SET, or context-tagged container).\n *\n * @throws if any child overflows the parent boundary or if there is 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, returning just the payload bytes.\n *\n * Used to extract signature values and public keys from their BIT STRING wrapper.\n *\n * @throws if the tag is not `0x03`.\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/** A BIT STRING payload and the number of unused trailing bits in its final byte. */\nexport interface DerBitString {\n\t/** Payload bytes, excluding the leading unused-bit count octet. */\n\treadonly bytes: Uint8Array;\n\t/** Unused trailing bits in the final byte, 0 through 7. */\n\treadonly unusedBits: number;\n\t/** `true` when the original encoding had non-zero padding bits (DER violation). */\n\treadonly nonZeroPadding: boolean;\n}\n\n/**\n * Decodes a BIT STRING element into its payload and unused-bit count.\n *\n * Accepts a non-zero unused-bit count, so it reads flag strings such as {@linkcode KeyUsage},\n * which {@linkcode extractBitStringValue} rejects.\n *\n * Padding bits that {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1} requires to be zero are reported through\n * {@linkcode DerBitString.nonZeroPadding} rather than rejected, so a caller can decide.\n */\nexport function decodeBitString(element: DerElement): DerBitString {\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\tconst bytes = element.value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst paddingMask = (1 << unusedBits) - 1;\n\tconst nonZeroPadding =\n\t\tunusedBits > 0 && bytes.length > 0 && ((bytes[bytes.length - 1] ?? 0) & paddingMask) !== 0;\n\treturn { bytes, unusedBits, nonZeroPadding };\n}\n\n/**\n * Parses a {@linkcode DerElement} with tag UTCTime (`0x17`) or GeneralizedTime (`0x18`) into a {@linkcode Date}.\n *\n * For UTCTime, the two-digit year is interpreted per RFC 5280:\n * - values >= 50 map to 19xx,\n * - values < 50 map to 20xx.\n *\n * @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 DER INTEGER content octets holding a non-negative value into a JavaScript `number`.\n *\n * @throws if the value is empty, negative, non-minimally encoded, or exceeds {@linkcode Number.MAX_SAFE_INTEGER}.\n */\nexport function decodeIntegerNumber(bytes: Uint8Array): number {\n\tconst magnitude = decodeIntegerMagnitude(bytes);\n\tif (magnitude.type === 'unsafe') {\n\t\tthrow new Error(`Integer too large for safe number (${bytes.length} bytes)`);\n\t}\n\treturn magnitude.value;\n}\n\n/** A non-negative INTEGER value as a `number`, or `unsafe` once it exceeds {@linkcode Number.MAX_SAFE_INTEGER}. */\nexport type IntegerMagnitude =\n\t| { readonly type: 'safe'; readonly value: number }\n\t| { readonly type: 'unsafe' };\n\n/**\n * Decodes DER INTEGER content octets holding a non-negative value, stopping at the first octet past {@linkcode Number.MAX_SAFE_INTEGER}.\n *\n * @param bytes DER INTEGER content octets to decode.\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n * @throws if the value is empty, negative, or non-minimally encoded.\n */\nexport function decodeIntegerMagnitude(bytes: Uint8Array, label = 'INTEGER'): IntegerMagnitude {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error(`${label} is empty`);\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error(`${label} must be non-negative`);\n\t}\n\tif (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 0x80) === 0) {\n\t\tthrow new Error(`${label} must use minimal encoding`);\n\t}\n\tlet value = 0;\n\tfor (const byte of bytes) {\n\t\tif (value > Math.floor((Number.MAX_SAFE_INTEGER - byte) / 256)) {\n\t\t\treturn { type: 'unsafe' };\n\t\t}\n\t\tvalue = value * 256 + byte;\n\t}\n\treturn { type: 'safe', value };\n}\n\n/**\n * Decodes DER INTEGER or ENUMERATED content octets holding a non-negative value of any length into a `bigint`.\n *\n * @param bytes DER content octets to decode.\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n * @throws if the value is empty, negative, or non-minimally encoded.\n */\nexport function decodeNonNegativeIntegerBigInt(bytes: Uint8Array, label = 'INTEGER'): bigint {\n\tdecodeIntegerMagnitude(bytes, label);\n\treturn BigInt(`0x${toHex(bytes)}`);\n}\n\n/**\n * Like {@linkcode decodeIntegerNumber}, but optionally rewrites thrown error messages with a caller-specific field label.\n *\n * @param bytes DER INTEGER content octets to decode.\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n * @throws if the value is empty, negative, non-minimally encoded, or exceeds {@linkcode Number.MAX_SAFE_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 {@linkcode 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. X.690 clause 11.1 restricts TRUE to an all-ones octet, so only `0xff` and `0x00` are accepted. */\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: bigint;\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\tconst end = findOidSubidentifierEnd(bytes, start);\n\tlet value = 0n;\n\tfor (let offset = start; offset <= end; offset += 1) {\n\t\tvalue = (value << 7n) | BigInt((bytes[offset] ?? 0) & 0x7f);\n\t}\n\treturn { value, nextOffset: end + 1 };\n}\n\n/** The offset of the sub-identifier's last octet, checked before any of it is accumulated. */\nfunction findOidSubidentifierEnd(bytes: Uint8Array, start: number): number {\n\tfor (let offset = start; offset < bytes.length; offset += 1) {\n\t\tif (((bytes[offset] ?? 0) & 0x80) === 0) {\n\t\t\treturn offset;\n\t\t}\n\t\tif (offset - start + 1 >= MAX_OID_SUBIDENTIFIER_OCTETS && offset + 1 < bytes.length) {\n\t\t\tthrowDecodeRefusal(\n\t\t\t\t'limit_exceeded',\n\t\t\t\t`OID sub-identifier exceeds ${MAX_OID_SUBIDENTIFIER_OCTETS} octets`,\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.\n *\n * Supports:\n * - UTF8String (`0x0c`),\n * - PrintableString (`0x13`),\n * - TeletexString (`0x14`) in its X.690 §8.23.5.2 initial state,\n * - IA5String (`0x16`),\n * - UniversalString (`0x1c`), and\n * - BMPString (`0x1e`).\n *\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\treturn decodeTeletexString(bytes);\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\n/**\n * Decodes VisibleString contents, which X.680 §43.7 limits to 0x20 through 0x7E.\n *\n * @throws on an octet outside that range.\n */\nexport function decodeVisibleString(bytes: Uint8Array): string {\n\tlet value = '';\n\tfor (const byte of bytes) {\n\t\tif (byte < 0x20 || byte > 0x7e) {\n\t\t\tthrow new Error('Invalid VisibleString: contains octets outside 0x20 to 0x7e');\n\t\t}\n\t\tvalue += String.fromCharCode(byte);\n\t}\n\treturn value;\n}\n\n/** T.61 Table 1 leaves these positions of register entry 102 empty. */\nconst TELETEX_EMPTY_POSITIONS: ReadonlySet<number> = new Set([0x5c, 0x5e, 0x60, 0x7b, 0x7d, 0x7e]);\n\n/**\n * Decodes TeletexString contents in the X.690 §8.23.5.2 initial state, reading\n * register entry 102 by T.61 Table 1 and Figure 2 Note 4, with the SPACE and\n * DELETE that X.680 Table 8 adds.\n *\n * @throws `unsupported` on any other octet.\n */\nfunction decodeTeletexString(bytes: Uint8Array): string {\n\tlet value = '';\n\tfor (const byte of bytes) {\n\t\tif (byte < 0x20 || byte > 0x7f || TELETEX_EMPTY_POSITIONS.has(byte)) {\n\t\t\tthrowDecodeRefusal(\n\t\t\t\t'unsupported',\n\t\t\t\t`Unsupported TeletexString octet: 0x${byte.toString(16).padStart(2, '0')}`,\n\t\t\t);\n\t\t}\n\t\tvalue += byte === 0x24 ? '\\u{a4}' : String.fromCharCode(byte);\n\t}\n\treturn value;\n}\n\n/** X.680 §41.15: BMPString holds code units 0000 to D7FF and E000 to FFFD. */\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) || codeUnit >= 0xfffe) {\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\n/** The verdict of {@linkcode checkStrictDer} on an encoding. */\nexport type StrictDerVerdict = 'valid' | 'malformed' | 'unsupported';\n\n/**\n * Walks {@linkcode bytes} as one DER element and checks each universal-class\n * element against the X.690 rules its tag fixes: the identifier form, the\n * contents, and the DER restrictions of clauses 10 and 11.\n *\n * Where those rules rest on ISO/IEC 2022, ISO 8601 or an implicitly tagged\n * schema, the element is `unsupported`: TeletexString, VideotexString, TIME,\n * EXTERNAL, EMBEDDED PDV, CHARACTER STRING, the types of UNIVERSAL 31 to 36, a\n * REAL with a long-form exponent, a GeneralizedTime at second 60, and text\n * holding an escape sequence or a code-extension control. A SET or SET OF\n * whose children follow neither the DER SET order nor the DER SET OF order is\n * `malformed`. Context-specific, application and private elements get framing\n * checks only, as do the rules that depend on a schema: DEFAULT omission and\n * NamedBitList trailing bits. No value is checked against an ASN.1 type, so\n * ENUMERATED membership, INTEGER ranges, SIZE constraints, CHOICE alternatives\n * and SEQUENCE or SET components stay unchecked.\n *\n * @throws `limit_exceeded` past {@linkcode maxDepth} levels of nesting or on a\n * tag number of 2^53 or more.\n */\nexport function checkStrictDer(\n\tbytes: Uint8Array,\n\tmaxDepth: number = DEFAULT_MAX_DER_DEPTH,\n): StrictDerVerdict {\n\tlet unsupported = false;\n\ttry {\n\t\twalkDerTree(bytes, maxDepth, undefined, (element) => {\n\t\t\tconst verdict = checkUniversalElement(element);\n\t\t\tif (verdict === 'malformed') {\n\t\t\t\tthrow new Error('DER element breaks the rules of its universal type');\n\t\t\t}\n\t\t\tunsupported ||= verdict === 'unsupported';\n\t\t});\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn 'malformed';\n\t}\n\treturn unsupported ? 'unsupported' : 'valid';\n}\n\ntype UniversalElementCheck = (element: DerElement) => StrictDerVerdict;\n\nfunction verdictOf(valid: boolean): StrictDerVerdict {\n\treturn valid ? 'valid' : 'malformed';\n}\n\nfunction decodes(decode: () => unknown): StrictDerVerdict {\n\ttry {\n\t\tdecode();\n\t\treturn 'valid';\n\t} catch {\n\t\treturn 'malformed';\n\t}\n}\n\nfunction asciiText(contents: Uint8Array): string | undefined {\n\ttry {\n\t\treturn decodeIa5String(contents);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nconst ESCAPE = 0x1b;\n\n/** X.690 §8.23.10 and Table 3: UTF8String and IA5String carry no escape sequence. */\nconst ESCAPE_CONTROLS: ReadonlySet<number> = new Set([ESCAPE]);\n\n/** X.690 §8.23.9: SHIFT OUT, SHIFT IN, ESCAPE, SINGLE-SHIFT TWO and THREE, and CONTROL SEQUENCE INTRODUCER. */\nconst CODE_EXTENSION_CONTROLS: ReadonlySet<number> = new Set([\n\t0x0e,\n\t0x0f,\n\tESCAPE,\n\t0x8e,\n\t0x8f,\n\t0x9b,\n]);\n\n/** The verdict on text {@linkcode decode} validates, `unsupported` when it holds one of {@linkcode controls}. */\nfunction checkText(decode: () => string, controls: ReadonlySet<number>): StrictDerVerdict {\n\tlet text: string;\n\ttry {\n\t\ttext = decode();\n\t} catch {\n\t\treturn 'malformed';\n\t}\n\tfor (const character of text) {\n\t\tif (controls.has(character.codePointAt(0) ?? 0)) {\n\t\t\treturn 'unsupported';\n\t\t}\n\t}\n\treturn 'valid';\n}\n\n/** X.690 Table 3: GraphicString and ObjectDescriptor open with register entry 6 as G0 and no C0 or C1 set. */\nfunction checkGraphicString(element: DerElement): StrictDerVerdict {\n\tif (element.value.includes(ESCAPE)) {\n\t\treturn 'unsupported';\n\t}\n\treturn verdictOf(element.value.every((octet) => octet >= 0x20 && octet <= 0x7e));\n}\n\n/** X.690 Table 3: GeneralString opens with register entry 6 as G0 and entry 1 as C0, beside SPACE and DELETE. */\nfunction checkGeneralString(element: DerElement): StrictDerVerdict {\n\tif (element.value.some((octet) => octet === ESCAPE || octet === 0x0e || octet === 0x0f)) {\n\t\treturn 'unsupported';\n\t}\n\treturn verdictOf(element.value.every((octet) => octet <= 0x7f));\n}\n\n/** X.690 §8.3.2: the first nine bits of a multi-octet INTEGER are neither all ones nor all zeros. */\nfunction isMinimalInteger(contents: Uint8Array): boolean {\n\tconst [first, second] = contents;\n\tif (first === undefined) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tsecond === undefined ||\n\t\t((first !== 0x00 || second >= 0x80) && (first !== 0xff || second < 0x80))\n\t);\n}\n\n/** X.690 §8.19.2: every subidentifier ends on an octet with bit 8 clear and never opens with 0x80. */\nfunction isSubidentifierList(contents: Uint8Array): boolean {\n\tlet opensSubidentifier = true;\n\tfor (const octet of contents) {\n\t\tif (opensSubidentifier && octet === 0x80) {\n\t\t\treturn false;\n\t\t}\n\t\topensSubidentifier = (octet & 0x80) === 0;\n\t}\n\treturn opensSubidentifier;\n}\n\nfunction checkBitString(element: DerElement): StrictDerVerdict {\n\ttry {\n\t\treturn verdictOf(!decodeBitString(element).nonZeroPadding);\n\t} catch {\n\t\treturn 'malformed';\n\t}\n}\n\n/** X.680 Table 9: NumericString holds the digits and SPACE. */\nexport function isNumericStringContents(contents: Uint8Array): boolean {\n\treturn contents.every((octet) => octet === 0x20 || (octet >= 0x30 && octet <= 0x39));\n}\n\nfunction isLeapYear(year: number): boolean {\n\treturn (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\nconst DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\ninterface TimeSyntax {\n\treadonly pattern: RegExp;\n\treadonly century: number;\n\treadonly leapSecond: StrictDerVerdict;\n}\n\n/** X.690 §11.8 and X.680 §47.3: `YYMMDDhhmmssZ`, the year as its two low-order digits and seconds 00 to 59. */\nconst UTC_TIME: TimeSyntax = {\n\tpattern: /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/,\n\tcentury: 2000,\n\tleapSecond: 'malformed',\n};\n\n/** X.690 §11.7: seconds present, `.` before a fraction with no trailing zero, and `Z`; ISO 8601 governs second 60. */\nconst GENERALIZED_TIME: TimeSyntax = {\n\tpattern: /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(?:\\.\\d*[1-9])?Z$/,\n\tcentury: 0,\n\tleapSecond: 'unsupported',\n};\n\nfunction checkTime(element: DerElement, syntax: TimeSyntax): StrictDerVerdict {\n\tconst fields = syntax.pattern\n\t\t.exec(asciiText(element.value) ?? '')\n\t\t?.slice(1)\n\t\t.map(Number);\n\tif (fields === undefined) {\n\t\treturn 'malformed';\n\t}\n\tconst [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = fields;\n\tconst monthDays =\n\t\t(DAYS_IN_MONTH[month - 1] ?? 0) + (month === 2 && isLeapYear(syntax.century + year) ? 1 : 0);\n\tif (day < 1 || day > monthDays || hour > 23 || minute > 59 || second > 60) {\n\t\treturn 'malformed';\n\t}\n\treturn second === 60 ? syntax.leapSecond : 'valid';\n}\n\n/**\n * X.690 §11.3.2: NR3 without SPACE, a MINUS SIGN only on a negative value, a\n * mantissa that neither opens nor closes with 0 followed by `.E`, and an\n * exponent written `+0` or with no leading 0 and no PLUS SIGN.\n */\nconst DER_NR3 = /^-?[1-9](?:\\d*[1-9])?\\.E(?:\\+0|-?[1-9]\\d*)$/;\n\n/**\n * X.690 §8.5 and §11.3: an empty plus zero, a one-octet special value, a\n * base-2 binary form with F = 0, the fewest exponent octets and an odd\n * mantissa with no leading zero octet, or a decimal NR3 form. X.690 §8.5.7.4\n * d) leaves the length of a long-form exponent ambiguous.\n */\nfunction checkReal(element: DerElement): StrictDerVerdict {\n\tconst [first] = element.value;\n\tconst rest = element.value.subarray(1);\n\tif (first === undefined) {\n\t\treturn 'valid';\n\t}\n\tif ((first & 0x80) === 0) {\n\t\treturn (first & 0x40) === 0\n\t\t\t? verdictOf(first === 0x03 && DER_NR3.test(asciiText(rest) ?? ''))\n\t\t\t: verdictOf(rest.length === 0 && first <= 0x43);\n\t}\n\tconst format = first & 0x03;\n\tif ((first & 0x3c) !== 0) {\n\t\treturn 'malformed';\n\t}\n\tif (format === 0x03) {\n\t\treturn 'unsupported';\n\t}\n\tconst exponent = rest.subarray(0, format + 1);\n\tconst mantissa = rest.subarray(format + 1);\n\treturn verdictOf(\n\t\texponent.length === format + 1 &&\n\t\t\tisMinimalInteger(exponent) &&\n\t\t\t(mantissa[0] ?? 0) !== 0 &&\n\t\t\t((mantissa.at(-1) ?? 0) & 0x01) === 1,\n\t);\n}\n\n/** X.690 §11.6: set-of encodings compare as octet strings, the shorter padded at its end with zero octets. */\nfunction compareSetOfEncodings(left: Uint8Array, right: Uint8Array): number {\n\tfor (let index = 0; index < Math.max(left.length, right.length); index += 1) {\n\t\tconst difference = (left[index] ?? 0) - (right[index] ?? 0);\n\t\tif (difference !== 0) {\n\t\t\treturn difference;\n\t\t}\n\t}\n\treturn 0;\n}\n\n/**\n * X.690 §10.3 orders SET components by the canonical tag order of X.680 §8.6,\n * which compares class and number and never the constructed bit, and X.690\n * §11.6 orders SET OF components by encoding.\n */\nfunction checkSet(element: DerElement): StrictDerVerdict {\n\tconst children: DerElement[] = [];\n\tfor (let offset = 0; offset < element.value.length; ) {\n\t\tconst child = readElement(element.value, offset);\n\t\tchildren.push(child);\n\t\toffset = child.end;\n\t}\n\tconst encodingOf = (child: DerElement): Uint8Array =>\n\t\telement.value.subarray(child.start - child.headerLength, child.end);\n\tconst setOrder = children.every((child, index) => {\n\t\tconst previous = children[index - 1];\n\t\tif (previous === undefined) {\n\t\t\treturn true;\n\t\t}\n\t\tconst previousClass = previous.tag & 0xc0;\n\t\tconst childClass = child.tag & 0xc0;\n\t\treturn (\n\t\t\tpreviousClass < childClass ||\n\t\t\t(previousClass === childClass && previous.tagNumber < child.tagNumber)\n\t\t);\n\t});\n\tconst setOfOrder = children.every((child, index) => {\n\t\tconst previous = children[index - 1];\n\t\treturn (\n\t\t\tprevious === undefined || compareSetOfEncodings(encodingOf(previous), encodingOf(child)) <= 0\n\t\t);\n\t});\n\treturn verdictOf(setOrder || setOfOrder);\n}\n\n/**\n * The identifier octet DER uses for each universal type, mapped to the check\n * of its contents. A universal identifier missing here is a reserved tag\n * number or a form DER forbids.\n */\nconst UNIVERSAL_ELEMENTS: ReadonlyMap<number, UniversalElementCheck> = new Map<\n\tnumber,\n\tUniversalElementCheck\n>([\n\t[0x01, (element) => decodes(() => decodeBoolean(element.value))],\n\t[0x02, (element) => verdictOf(isMinimalInteger(element.value))],\n\t[0x03, checkBitString],\n\t[0x04, () => 'valid'],\n\t[0x05, (element) => verdictOf(element.value.length === 0)],\n\t[0x06, (element) => verdictOf(element.value.length > 0 && isSubidentifierList(element.value))],\n\t[0x07, checkGraphicString],\n\t[0x09, checkReal],\n\t[0x0a, (element) => verdictOf(isMinimalInteger(element.value))],\n\t[\n\t\t0x0c,\n\t\t(element) => checkText(() => decodeUtf8Text(element.value, 'UTF8String'), ESCAPE_CONTROLS),\n\t],\n\t[0x0d, (element) => verdictOf(element.value.length > 0 && isSubidentifierList(element.value))],\n\t[0x0e, () => 'unsupported'],\n\t[0x12, (element) => verdictOf(isNumericStringContents(element.value))],\n\t[0x13, (element) => decodes(() => decodePrintableString(element.value))],\n\t[0x14, () => 'unsupported'],\n\t[0x15, () => 'unsupported'],\n\t[0x16, (element) => checkText(() => decodeIa5String(element.value), ESCAPE_CONTROLS)],\n\t[0x17, (element) => checkTime(element, UTC_TIME)],\n\t[0x18, (element) => checkTime(element, GENERALIZED_TIME)],\n\t[0x19, checkGraphicString],\n\t[0x1a, (element) => decodes(() => decodeVisibleString(element.value))],\n\t[0x1b, checkGeneralString],\n\t[\n\t\t0x1c,\n\t\t(element) => checkText(() => decodeUniversalString(element.value), CODE_EXTENSION_CONTROLS),\n\t],\n\t[0x1e, (element) => checkText(() => decodeBmpString(element.value), CODE_EXTENSION_CONTROLS)],\n\t[0x28, () => 'unsupported'],\n\t[0x2b, () => 'unsupported'],\n\t[0x30, () => 'valid'],\n\t[0x31, checkSet],\n\t[0x3d, () => 'unsupported'],\n]);\n\n/** X.680 Table 1: UNIVERSAL 31 to 36 are DATE, TIME-OF-DAY, DATE-TIME, DURATION, OID-IRI and RELATIVE-OID-IRI. */\nconst LAST_ASSIGNED_UNIVERSAL_TAG_NUMBER = 36;\n\nfunction checkUniversalElement(element: DerElement): StrictDerVerdict {\n\tif ((element.tag & 0xc0) !== 0) {\n\t\treturn 'valid';\n\t}\n\tif ((element.tag & 0x1f) === 0x1f) {\n\t\treturn element.tagNumber <= LAST_ASSIGNED_UNIVERSAL_TAG_NUMBER ? 'unsupported' : 'malformed';\n\t}\n\treturn UNIVERSAL_ELEMENTS.get(element.tag)?.(element) ?? 'malformed';\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAMA,IAAc,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC,GAEvEC,IAA2B;;;;;;;;;AAUjC,SAAgB,uBAAuB,GAA2B;CACjE,IAAIC,EAAM,WAAW,GACpB,MAAU,MAAM,cAAc;CAE/B,IAAMC,IAAqB,uBAAuBD,GAAO,CAAC,GACtDE,IAASD,EAAmB,YAC1BE,IAAQF,EAAmB,OAC3BG,IACLD,IAAQ,MAAM,CAAC,IAAIA,CAAK,IAAIA,IAAQ,MAAM,CAAC,IAAIA,IAAQ,GAAG,IAAI,CAAC,IAAIA,IAAQ,GAAG;CAC/E,OAAOD,IAASF,EAAM,SAAQ;EAC7B,IAAMK,IAAgB,uBAAuBL,GAAOE,CAAM;EAE1D,AADAE,EAAO,KAAKC,EAAc,KAAK,GAC/B,IAASA,EAAc;CACxB;CACA,OAAOD,EAAO,KAAK,GAAG;AACvB;;;;;;;;;AAUA,SAAgB,gBAAgB,GAAqB;CACpD,OAAO,uBAAuBE,EAAYC,EAAiBC,CAAG,GAAG,CAAC,CAAC,CAAC,KAAK;AAC1E;;AAGA,SAAgB,MAAM,GAA2B;CAChD,OAAO,MAAM,KAAKR,IAAQ,MAAUS,EAAM,SAA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BA,EAAQ,KAAK,CAAC,CAAC;CACrE,CAAC,KAAO,MAAY,cAAc,sBAAsBA,EAAQ,KAAK,CAAC,CAAC;CACvE,CAAC,UAAY,aAAa;CAC1B,CAAC,UAAY,aAAa;CAC1B,CAAC,KAAO,MAAY,gBAAgB,gBAAgBA,EAAQ,KAAK,GAAG0C,CAAe,CAAC;CACpF,CAAC,KAAO,MAAY,UAAU1C,GAASkD,CAAQ,CAAC;CAChD,CAAC,KAAO,MAAY,UAAUlD,GAASmD,CAAgB,CAAC;CACxD,CAAC,IAAM,kBAAkB;CACzB,CAAC,KAAO,MAAY,cAAc,oBAAoBnD,EAAQ,KAAK,CAAC,CAAC;CACrE,CAAC,IAAM,kBAAkB;CACzB,CACC,KACC,MAAY,gBAAgB,sBAAsBA,EAAQ,KAAK,GAAG2C,CAAuB,CAC3F;CACA,CAAC,KAAO,MAAY,gBAAgB,gBAAgB3C,EAAQ,KAAK,GAAG2C,CAAuB,CAAC;CAC5F,CAAC,UAAY,aAAa;CAC1B,CAAC,UAAY,aAAa;CAC1B,CAAC,UAAY,OAAO;CACpB,CAAC,IAAM,QAAQ;CACf,CAAC,UAAY,aAAa;AAC3B,CAAC;AAKD,SAAS,sBAAsB,GAAuC;CAOrE,OANK3C,EAAQ,MAAM,MACX,WAEHA,EAAQ,MAAM,OAAU,KACrBA,EAAQ,aAAa,KAAqC,gBAAgB,cAE3EkE,EAAmB,IAAIlE,EAAQ,GAAG,CAAC,GAAGA,CAAO,KAAK;AAC1D"}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { throwDecodeRefusal as e } from "./decode-refusal.js";
|
|
2
|
+
import { concatBytes as t, encodeLength as n, readIdentifier as r, tlv as i } from "./der.js";
|
|
3
|
+
// src/internal/asn1/ber.ts
|
|
4
|
+
const a = /* @__PURE__ */ new Set([
|
|
5
|
+
4,
|
|
6
|
+
7,
|
|
7
|
+
12,
|
|
8
|
+
18,
|
|
9
|
+
19,
|
|
10
|
+
20,
|
|
11
|
+
21,
|
|
12
|
+
22,
|
|
13
|
+
23,
|
|
14
|
+
24,
|
|
15
|
+
25,
|
|
16
|
+
26,
|
|
17
|
+
27,
|
|
18
|
+
28,
|
|
19
|
+
30
|
|
20
|
+
]);
|
|
21
|
+
function readBerRoot(e, t = 64) {
|
|
22
|
+
if (!Number.isSafeInteger(t) || t < 1) throw RangeError("BER max depth must be a positive safe integer");
|
|
23
|
+
let n = readBerElement(e, 0, e.length, 1, t);
|
|
24
|
+
if (n.end !== e.length) throw Error("Trailing data after BER element");
|
|
25
|
+
return n;
|
|
26
|
+
}
|
|
27
|
+
function berEncoding(e, t) {
|
|
28
|
+
return e.slice(t.headerStart, t.end);
|
|
29
|
+
}
|
|
30
|
+
function berPrimitiveContent(e, t, n) {
|
|
31
|
+
if (t.tag !== n || n & 32) throw Error(`Expected primitive BER tag 0x${n.toString(16)}`);
|
|
32
|
+
return e.slice(t.start, t.contentEnd);
|
|
33
|
+
}
|
|
34
|
+
function berSequenceChildren(e) {
|
|
35
|
+
if (e.tag !== 48) throw Error("Expected SEQUENCE");
|
|
36
|
+
return e.children;
|
|
37
|
+
}
|
|
38
|
+
function berStringContent(e, n, r, i = r) {
|
|
39
|
+
if (n.tag === r) return berPrimitiveContent(e, n, r);
|
|
40
|
+
if (n.tag !== (r | 32)) throw Error(`Expected BER string tag 0x${r.toString(16)}`);
|
|
41
|
+
return t(n.children.map((t) => berStringContent(e, t, i)));
|
|
42
|
+
}
|
|
43
|
+
function definiteElement(e, r, i) {
|
|
44
|
+
return t([
|
|
45
|
+
e.subarray(r.headerStart, r.headerStart + r.identifierLength),
|
|
46
|
+
n(i.length),
|
|
47
|
+
i
|
|
48
|
+
]);
|
|
49
|
+
}
|
|
50
|
+
function berToDefiniteLength(e, n) {
|
|
51
|
+
if (!(n.tag & 32)) return definiteElement(e, n, e.slice(n.start, n.contentEnd));
|
|
52
|
+
let r = n.tag & -33;
|
|
53
|
+
return r === 3 ? i(3, bitStringContent(e, n)) : a.has(r) ? i(r, berStringContent(e, n, r)) : definiteElement(e, n, t(n.children.map((t) => berToDefiniteLength(e, t))));
|
|
54
|
+
}
|
|
55
|
+
function bitStringContent(e, n) {
|
|
56
|
+
let r = bitStringSegments(e, n), i = r.at(-1);
|
|
57
|
+
if (i === void 0) return Uint8Array.of(0);
|
|
58
|
+
let a = [];
|
|
59
|
+
for (let e of r) {
|
|
60
|
+
let t = e[0];
|
|
61
|
+
if (t === void 0 || t > 7) throw Error("Malformed BER BIT STRING segment");
|
|
62
|
+
if (e !== i && t !== 0) throw Error("Only the last BER BIT STRING segment may have unused bits");
|
|
63
|
+
if (e.length === 1 && t !== 0) throw Error("Empty BER BIT STRING segment must have zero unused bits");
|
|
64
|
+
a.push(e.subarray(1));
|
|
65
|
+
}
|
|
66
|
+
return t([Uint8Array.of(i[0] ?? 0), ...a]);
|
|
67
|
+
}
|
|
68
|
+
function bitStringSegments(e, t) {
|
|
69
|
+
if (t.tag === 3) return [e.slice(t.start, t.contentEnd)];
|
|
70
|
+
if (t.tag !== 35) throw Error("Expected BER BIT STRING segment");
|
|
71
|
+
return t.children.flatMap((t) => bitStringSegments(e, t));
|
|
72
|
+
}
|
|
73
|
+
function readBerElement(t, n, i, a, o) {
|
|
74
|
+
a > o && e("limit_exceeded", `BER exceeds max depth of ${o}`);
|
|
75
|
+
let s = byteAt(t, n);
|
|
76
|
+
if (s === 0) throw Error("Unexpected end-of-contents octets");
|
|
77
|
+
let c = r(t, n), l = n + c.length, u = byteAt(t, l), d = !!(s & 32);
|
|
78
|
+
if (u === 128) {
|
|
79
|
+
if (!d) throw Error("Indefinite length requires a constructed encoding");
|
|
80
|
+
return readIndefiniteElement(t, n, c, i, a, o);
|
|
81
|
+
}
|
|
82
|
+
let { lengthOctets: f, length: p } = readDefiniteLength(t, l, u), m = l + f, h = m + p;
|
|
83
|
+
if (h > i) throw Error("BER element exceeds its container");
|
|
84
|
+
return {
|
|
85
|
+
tag: s,
|
|
86
|
+
tagNumber: c.tagNumber,
|
|
87
|
+
headerStart: n,
|
|
88
|
+
identifierLength: c.length,
|
|
89
|
+
start: m,
|
|
90
|
+
contentEnd: h,
|
|
91
|
+
end: h,
|
|
92
|
+
children: d ? readDefiniteChildren(t, m, h, a, o) : []
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function readIndefiniteElement(e, t, n, r, i, a) {
|
|
96
|
+
let o = t + n.length + 1, s = [], c = o;
|
|
97
|
+
for (; c < r && e[c] !== 0;) {
|
|
98
|
+
let t = readBerElement(e, c, r, i + 1, a);
|
|
99
|
+
s.push(t), c = t.end;
|
|
100
|
+
}
|
|
101
|
+
if (c + 1 >= r || e[c + 1] !== 0) throw Error("Missing end-of-contents octets");
|
|
102
|
+
return {
|
|
103
|
+
tag: n.tag,
|
|
104
|
+
tagNumber: n.tagNumber,
|
|
105
|
+
headerStart: t,
|
|
106
|
+
identifierLength: n.length,
|
|
107
|
+
start: o,
|
|
108
|
+
contentEnd: c,
|
|
109
|
+
end: c + 2,
|
|
110
|
+
children: s
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function readDefiniteChildren(e, t, n, r, i) {
|
|
114
|
+
let a = [], o = t;
|
|
115
|
+
for (; o < n;) {
|
|
116
|
+
let t = readBerElement(e, o, n, r + 1, i);
|
|
117
|
+
a.push(t), o = t.end;
|
|
118
|
+
}
|
|
119
|
+
return a;
|
|
120
|
+
}
|
|
121
|
+
function readDefiniteLength(e, t, n) {
|
|
122
|
+
if (!(n & 128)) return {
|
|
123
|
+
lengthOctets: 1,
|
|
124
|
+
length: n
|
|
125
|
+
};
|
|
126
|
+
let r = n & 127;
|
|
127
|
+
if (r === 127) throw Error("Reserved BER length octet");
|
|
128
|
+
let i = 0;
|
|
129
|
+
for (let n = 0; n < r; n += 1) {
|
|
130
|
+
let r = byteAt(e, t + 1 + n);
|
|
131
|
+
if (i > Math.floor((2 ** 53 - 1 - r) / 256)) throw Error("BER length exceeds safe integer range");
|
|
132
|
+
i = i * 256 + r;
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
lengthOctets: 1 + r,
|
|
136
|
+
length: i
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function byteAt(e, t) {
|
|
140
|
+
let n = e[t];
|
|
141
|
+
if (n === void 0) throw Error("Unexpected end of BER input");
|
|
142
|
+
return n;
|
|
143
|
+
}
|
|
144
|
+
export { berEncoding, berPrimitiveContent, berSequenceChildren, berStringContent, berToDefiniteLength, readBerRoot };
|
|
145
|
+
|
|
146
|
+
//# sourceMappingURL=ber.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ber.js","names":["FLATTENED_STRING_TAGS","maxDepth","root","bytes","element","tag","primitiveTag","concatBytes","segment","segmentTag","encodeLength","content","tlv","child","segments","last","data","unusedBits","depth","throwDecodeRefusal","offset","identifier","readIdentifier","lengthOffset","lengthByte","constructed","limit","start","lengthOctets","end","length","children","position","octets","index","next","value"],"sources":["../../../src/internal/asn1/ber.ts"],"sourcesContent":["import { throwDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport type { Identifier } from '#micro509/internal/asn1/der';\nimport {\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\tencodeLength,\n\treadIdentifier,\n\ttlv,\n} from '#micro509/internal/asn1/der';\n\nexport interface BerElement {\n\treadonly tag: number;\n\treadonly tagNumber: number;\n\treadonly headerStart: number;\n\treadonly identifierLength: number;\n\treadonly start: number;\n\treadonly contentEnd: number;\n\treadonly end: number;\n\treadonly children: readonly BerElement[];\n}\n\nconst CONSTRUCTED = 0x20;\nconst BIT_STRING = 0x03;\nconst FLATTENED_STRING_TAGS: ReadonlySet<number> = new Set([\n\t0x04, 0x07, 0x0c, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1e,\n]);\n\nexport function readBerRoot(\n\tbytes: Uint8Array,\n\tmaxDepth: number = DEFAULT_MAX_DER_DEPTH,\n): BerElement {\n\tif (!Number.isSafeInteger(maxDepth) || maxDepth < 1) {\n\t\tthrow new RangeError('BER max depth must be a positive safe integer');\n\t}\n\tconst root = readBerElement(bytes, 0, bytes.length, 1, maxDepth);\n\tif (root.end !== bytes.length) {\n\t\tthrow new Error('Trailing data after BER element');\n\t}\n\treturn root;\n}\n\nexport function berEncoding(bytes: Uint8Array, element: BerElement): Uint8Array {\n\treturn bytes.slice(element.headerStart, element.end);\n}\n\nexport function berPrimitiveContent(\n\tbytes: Uint8Array,\n\telement: BerElement,\n\ttag: number,\n): Uint8Array {\n\tif (element.tag !== tag || (tag & CONSTRUCTED) !== 0) {\n\t\tthrow new Error(`Expected primitive BER tag 0x${tag.toString(16)}`);\n\t}\n\treturn bytes.slice(element.start, element.contentEnd);\n}\n\nexport function berSequenceChildren(element: BerElement): readonly BerElement[] {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('Expected SEQUENCE');\n\t}\n\treturn element.children;\n}\n\nexport function berStringContent(\n\tbytes: Uint8Array,\n\telement: BerElement,\n\tprimitiveTag: number,\n\tsegmentTag: number = primitiveTag,\n): Uint8Array {\n\tif (element.tag === primitiveTag) {\n\t\treturn berPrimitiveContent(bytes, element, primitiveTag);\n\t}\n\tif (element.tag !== (primitiveTag | CONSTRUCTED)) {\n\t\tthrow new Error(`Expected BER string tag 0x${primitiveTag.toString(16)}`);\n\t}\n\treturn concatBytes(\n\t\telement.children.map((segment) => berStringContent(bytes, segment, segmentTag)),\n\t);\n}\n\nfunction definiteElement(bytes: Uint8Array, element: BerElement, content: Uint8Array): Uint8Array {\n\treturn concatBytes([\n\t\tbytes.subarray(element.headerStart, element.headerStart + element.identifierLength),\n\t\tencodeLength(content.length),\n\t\tcontent,\n\t]);\n}\n\nexport function berToDefiniteLength(bytes: Uint8Array, element: BerElement): Uint8Array {\n\tif ((element.tag & CONSTRUCTED) === 0) {\n\t\treturn definiteElement(bytes, element, bytes.slice(element.start, element.contentEnd));\n\t}\n\tconst primitiveTag = element.tag & ~CONSTRUCTED;\n\tif (primitiveTag === BIT_STRING) {\n\t\treturn tlv(BIT_STRING, bitStringContent(bytes, element));\n\t}\n\tif (FLATTENED_STRING_TAGS.has(primitiveTag)) {\n\t\treturn tlv(primitiveTag, berStringContent(bytes, element, primitiveTag));\n\t}\n\treturn definiteElement(\n\t\tbytes,\n\t\telement,\n\t\tconcatBytes(element.children.map((child) => berToDefiniteLength(bytes, child))),\n\t);\n}\n\nfunction bitStringContent(bytes: Uint8Array, element: BerElement): Uint8Array {\n\tconst segments = bitStringSegments(bytes, element);\n\tconst last = segments.at(-1);\n\tif (last === undefined) {\n\t\treturn Uint8Array.of(0);\n\t}\n\tconst data: Uint8Array[] = [];\n\tfor (const segment of segments) {\n\t\tconst unusedBits = segment[0];\n\t\tif (unusedBits === undefined || unusedBits > 7) {\n\t\t\tthrow new Error('Malformed BER BIT STRING segment');\n\t\t}\n\t\tif (segment !== last && unusedBits !== 0) {\n\t\t\tthrow new Error('Only the last BER BIT STRING segment may have unused bits');\n\t\t}\n\t\tif (segment.length === 1 && unusedBits !== 0) {\n\t\t\tthrow new Error('Empty BER BIT STRING segment must have zero unused bits');\n\t\t}\n\t\tdata.push(segment.subarray(1));\n\t}\n\treturn concatBytes([Uint8Array.of(last[0] ?? 0), ...data]);\n}\n\nfunction bitStringSegments(bytes: Uint8Array, element: BerElement): readonly Uint8Array[] {\n\tif (element.tag === BIT_STRING) {\n\t\treturn [bytes.slice(element.start, element.contentEnd)];\n\t}\n\tif (element.tag !== (BIT_STRING | CONSTRUCTED)) {\n\t\tthrow new Error('Expected BER BIT STRING segment');\n\t}\n\treturn element.children.flatMap((segment) => bitStringSegments(bytes, segment));\n}\n\nfunction readBerElement(\n\tbytes: Uint8Array,\n\toffset: number,\n\tlimit: number,\n\tdepth: number,\n\tmaxDepth: number,\n): BerElement {\n\tif (depth > maxDepth) {\n\t\tthrowDecodeRefusal('limit_exceeded', `BER exceeds max depth of ${maxDepth}`);\n\t}\n\tconst tag = byteAt(bytes, offset);\n\tif (tag === 0x00) {\n\t\tthrow new Error('Unexpected end-of-contents octets');\n\t}\n\tconst identifier = readIdentifier(bytes, offset);\n\tconst lengthOffset = offset + identifier.length;\n\tconst lengthByte = byteAt(bytes, lengthOffset);\n\tconst constructed = (tag & CONSTRUCTED) !== 0;\n\tif (lengthByte === 0x80) {\n\t\tif (!constructed) {\n\t\t\tthrow new Error('Indefinite length requires a constructed encoding');\n\t\t}\n\t\treturn readIndefiniteElement(bytes, offset, identifier, limit, depth, maxDepth);\n\t}\n\tconst { lengthOctets, length } = readDefiniteLength(bytes, lengthOffset, lengthByte);\n\tconst start = lengthOffset + lengthOctets;\n\tconst end = start + length;\n\tif (end > limit) {\n\t\tthrow new Error('BER element exceeds its container');\n\t}\n\treturn {\n\t\ttag,\n\t\ttagNumber: identifier.tagNumber,\n\t\theaderStart: offset,\n\t\tidentifierLength: identifier.length,\n\t\tstart,\n\t\tcontentEnd: end,\n\t\tend,\n\t\tchildren: constructed ? readDefiniteChildren(bytes, start, end, depth, maxDepth) : [],\n\t};\n}\n\nfunction readIndefiniteElement(\n\tbytes: Uint8Array,\n\toffset: number,\n\tidentifier: Identifier,\n\tlimit: number,\n\tdepth: number,\n\tmaxDepth: number,\n): BerElement {\n\tconst start = offset + identifier.length + 1;\n\tconst children: BerElement[] = [];\n\tlet position = start;\n\twhile (position < limit && bytes[position] !== 0x00) {\n\t\tconst child = readBerElement(bytes, position, limit, depth + 1, maxDepth);\n\t\tchildren.push(child);\n\t\tposition = child.end;\n\t}\n\tif (position + 1 >= limit || bytes[position + 1] !== 0x00) {\n\t\tthrow new Error('Missing end-of-contents octets');\n\t}\n\treturn {\n\t\ttag: identifier.tag,\n\t\ttagNumber: identifier.tagNumber,\n\t\theaderStart: offset,\n\t\tidentifierLength: identifier.length,\n\t\tstart,\n\t\tcontentEnd: position,\n\t\tend: position + 2,\n\t\tchildren,\n\t};\n}\n\nfunction readDefiniteChildren(\n\tbytes: Uint8Array,\n\tstart: number,\n\tend: number,\n\tdepth: number,\n\tmaxDepth: number,\n): readonly BerElement[] {\n\tconst children: BerElement[] = [];\n\tlet position = start;\n\twhile (position < end) {\n\t\tconst child = readBerElement(bytes, position, end, depth + 1, maxDepth);\n\t\tchildren.push(child);\n\t\tposition = child.end;\n\t}\n\treturn children;\n}\n\nfunction readDefiniteLength(\n\tbytes: Uint8Array,\n\tlengthOffset: number,\n\tlengthByte: number,\n): { readonly lengthOctets: number; readonly length: number } {\n\tif ((lengthByte & 0x80) === 0) {\n\t\treturn { lengthOctets: 1, length: lengthByte };\n\t}\n\tconst octets = lengthByte & 0x7f;\n\tif (octets === 0x7f) {\n\t\tthrow new Error('Reserved BER length octet');\n\t}\n\tlet length = 0;\n\tfor (let index = 0; index < octets; index += 1) {\n\t\tconst next = byteAt(bytes, lengthOffset + 1 + index);\n\t\tif (length > Math.floor((Number.MAX_SAFE_INTEGER - next) / 256)) {\n\t\t\tthrow new Error('BER length exceeds safe integer range');\n\t\t}\n\t\tlength = length * 256 + next;\n\t}\n\treturn { lengthOctets: 1 + octets, length };\n}\n\nfunction byteAt(bytes: Uint8Array, index: number): number {\n\tconst value = bytes[index];\n\tif (value === undefined) {\n\t\tthrow new Error('Unexpected end of BER input');\n\t}\n\treturn value;\n}\n"],"mappings":";;;AAqBA,MAEMA,oBAA6C,IAAI,IAAI;CAC1D;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;AACrF,CAAC;AAED,SAAgB,YACf,GACA,IAAA,IACa;CACb,IAAI,CAAC,OAAO,cAAcC,CAAQ,KAAKA,IAAW,GACjD,MAAU,WAAW,+CAA+C;CAErE,IAAMC,IAAO,eAAeC,GAAO,GAAGA,EAAM,QAAQ,GAAGF,CAAQ;CAC/D,IAAIC,EAAK,QAAQC,EAAM,QACtB,MAAU,MAAM,iCAAiC;CAElD,OAAOD;AACR;AAEA,SAAgB,YAAY,GAAmB,GAAiC;CAC/E,OAAO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AAOkB;AACR;AAEA,SAAS,mBACR,GACA,GACA,GAC6D;CAC7D,IAAA,EAAKP,IAAa,MACjB,OAAO;EAAE,cAAc;EAAG,QAAQA;CAAW;CAE9C,IAAMS,IAAST,IAAa;CAC5B,IAAIS,MAAW,KACd,MAAU,MAAM,2BAA2B;CAE5C,IAAIH,IAAS;CACb,KAAK,IAAII,IAAQ,GAAGA,IAAQD,GAAQ,KAAS,GAAG;EAC/C,IAAME,IAAO,OAAOhC,GAAOoB,IAAe,IAAIW,CAAK;EACnD,IAAIJ,IAAS,KAAK,qBAAiCK,KAAQ,GAAG,GAC7D,MAAU,MAAM,uCAAuC;EAExD,IAASL,IAAS,MAAMK;CACzB;CACA,OAAO;EAAE,cAAc,IAAIF;EAAQ;CAAO;AAC3C;AAEA,SAAS,OAAO,GAAmB,GAAuB;CACzD,IAAMG,IAAQjC,EAAM+B;CACpB,IAAIE,MAAU,KAAA,GACb,MAAU,MAAM,6BAA6B;CAE9C,OAAOA;AACR"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { DECODE_REFUSAL_CODES as e, failureResult as t, isResultError as n, throwMicro509Error as r } from "../../result/result.js";
|
|
2
|
+
// src/internal/asn1/decode-refusal.ts
|
|
3
|
+
/** The limit code alone, for boundaries whose input carries no text. */
|
|
4
|
+
const i = ["limit_exceeded"];
|
|
5
|
+
/** Throws a {@link ResultError} carrying a decode refusal. */
|
|
6
|
+
function throwDecodeRefusal(e, t) {
|
|
7
|
+
return r(e, t);
|
|
8
|
+
}
|
|
9
|
+
/** The refusal `error` carries when its code is one of `codes`. */
|
|
10
|
+
function decodeRefusalOf(e, t) {
|
|
11
|
+
if (!n(e)) return;
|
|
12
|
+
let r = t.find((t) => t === e.code);
|
|
13
|
+
return r === void 0 ? void 0 : {
|
|
14
|
+
code: r,
|
|
15
|
+
message: e.error.message
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Rethrows `error` when it carries one of the refusal `codes`. */
|
|
19
|
+
function rethrowDecodeRefusal(e, t) {
|
|
20
|
+
if (decodeRefusalOf(e, t) !== void 0) throw e;
|
|
21
|
+
}
|
|
22
|
+
/** A boundary's failure for a thrown decode error: its refusal, else `malformed` with its message. */
|
|
23
|
+
function decodeFailureResult(e, n, r) {
|
|
24
|
+
let i = decodeRefusalOf(e, n);
|
|
25
|
+
return i === void 0 ? t("malformed", e instanceof Error ? e.message : r) : t(i.code, i.message);
|
|
26
|
+
}
|
|
27
|
+
export { i as DECODE_LIMIT_CODES, e as DECODE_REFUSAL_CODES, decodeFailureResult, decodeRefusalOf, rethrowDecodeRefusal, throwDecodeRefusal };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=decode-refusal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decode-refusal.js","names":["DECODE_LIMIT_CODES","throwMicro509Error","code","message","isResultError","error","codes","candidate","refusal","failureResult","fallback","DECODE_REFUSAL_CODES"],"sources":["../../../src/internal/asn1/decode-refusal.ts"],"sourcesContent":["/**\n * Typed refusals a decoder throws for input it does not call malformed: an\n * implementation limit, or a construct micro509 does not decode.\n *\n * @module\n */\n\nimport type { DecodeRefusalCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, isResultError, throwMicro509Error } from '#micro509/result/result';\n\nexport type { DecodeRefusalCode } from '#micro509/result/result';\nexport { DECODE_REFUSAL_CODES } from '#micro509/result/result';\n\n/** The limit code alone, for boundaries whose input carries no text. */\nexport const DECODE_LIMIT_CODES = ['limit_exceeded'] as const;\n\n/** Throws a {@link ResultError} carrying a decode refusal. */\nexport function throwDecodeRefusal(code: DecodeRefusalCode, message: string): never {\n\treturn throwMicro509Error<DecodeRefusalCode>(code, message);\n}\n\n/** The refusal `error` carries when its code is one of `codes`. */\nexport function decodeRefusalOf<TCode extends DecodeRefusalCode>(\n\terror: unknown,\n\tcodes: readonly TCode[],\n): { readonly code: TCode; readonly message: string } | undefined {\n\tif (!isResultError(error)) {\n\t\treturn undefined;\n\t}\n\tconst code = codes.find((candidate) => candidate === error.code);\n\treturn code === undefined ? undefined : { code, message: error.error.message };\n}\n\n/** Rethrows `error` when it carries one of the refusal `codes`. */\nexport function rethrowDecodeRefusal(error: unknown, codes: readonly DecodeRefusalCode[]): void {\n\tif (decodeRefusalOf(error, codes) !== undefined) {\n\t\tthrow error;\n\t}\n}\n\n/** A boundary's failure for a thrown decode error: its refusal, else `malformed` with its message. */\nexport function decodeFailureResult<TCode extends DecodeRefusalCode>(\n\terror: unknown,\n\tcodes: readonly TCode[],\n\tfallback: string,\n): ErrorResult<\n\t'malformed' | TCode,\n\tRecord<never, never>,\n\tMicro509Error<'malformed' | TCode> & { readonly ok: false }\n> {\n\tconst refusal = decodeRefusalOf(error, codes);\n\treturn refusal === undefined\n\t\t? failureResult<'malformed' | TCode>(\n\t\t\t\t'malformed',\n\t\t\t\terror instanceof Error ? error.message : fallback,\n\t\t\t)\n\t\t: failureResult<'malformed' | TCode>(refusal.code, refusal.message);\n}\n"],"mappings":";;;AAcA,MAAaA,IAAqB,CAAC,gBAAgB;;AAGnD,SAAgB,mBAAmB,GAAyB,GAAwB;CACnF,OAAOC,EAAsCC,GAAMC,CAAO;AAC3D;;AAGA,SAAgB,gBACf,GACA,GACiE;CACjE,IAAI,CAACC,EAAcC,CAAK,GACvB;CAED,IAAMH,IAAOI,EAAM,MAAM,MAAcC,MAAcF,EAAM,IAAI;CAC/D,OAAOH,MAAS,KAAA,IAAY,KAAA,IAAY;EAAE;EAAM,SAASG,EAAM,MAAM;CAAQ;AAC9E;;AAGA,SAAgB,qBAAqB,GAAgB,GAA2C;CAC/F,IAAI,gBAAgBA,GAAOC,CAAK,MAAM,KAAA,GACrC,MAAMD;AAER;;AAGA,SAAgB,oBACf,GACA,GACA,GAKC;CACD,IAAMG,IAAU,gBAAgBH,GAAOC,CAAK;CAC5C,OAAOE,MAAY,KAAA,IAChBC,EACA,aACAJ,aAAiB,QAAQA,EAAM,UAAUK,CAC1C,IACCD,EAAmCD,EAAQ,MAAMA,EAAQ,OAAO;AACpE"}
|
|
@@ -1,19 +1,11 @@
|
|
|
1
|
-
//#region src/internal/asn1/der.d.ts
|
|
2
|
-
/**
|
|
3
|
-
* Low-level DER encoding and reading helpers shared across the library.
|
|
4
|
-
*
|
|
5
|
-
* These utilities build and traverse ASN.1 TLV (tag-length-value) structures.
|
|
6
|
-
*
|
|
7
|
-
* @module
|
|
8
|
-
*/
|
|
9
1
|
/**
|
|
10
2
|
* Maximum nesting depth allowed when recursively walking a DER structure.
|
|
11
3
|
*
|
|
12
4
|
* Guards against stack exhaustion from pathologically nested input.
|
|
13
5
|
*/
|
|
14
|
-
declare const DEFAULT_MAX_DER_DEPTH = 64;
|
|
6
|
+
export declare const DEFAULT_MAX_DER_DEPTH = 64;
|
|
15
7
|
/** Concatenates multiple byte arrays into a single {@linkcode Uint8Array}. */
|
|
16
|
-
declare function concatBytes(parts: readonly Uint8Array[]): Uint8Array;
|
|
8
|
+
export declare function concatBytes(parts: readonly Uint8Array[]): Uint8Array;
|
|
17
9
|
/**
|
|
18
10
|
* Builds a complete DER TLV (tag-length-value) element:
|
|
19
11
|
*
|
|
@@ -21,51 +13,51 @@ declare function concatBytes(parts: readonly Uint8Array[]): Uint8Array;
|
|
|
21
13
|
* - the DER-encoded length, then
|
|
22
14
|
* - the raw value bytes.
|
|
23
15
|
*/
|
|
24
|
-
declare function tlv(tag: number, value: Uint8Array): Uint8Array;
|
|
16
|
+
export declare function tlv(tag: number, value: Uint8Array): Uint8Array;
|
|
25
17
|
/** Wraps concatenated children in a SEQUENCE (tag `0x30`). */
|
|
26
|
-
declare function sequence(parts: readonly Uint8Array[]): Uint8Array;
|
|
18
|
+
export declare function sequence(parts: readonly Uint8Array[]): Uint8Array;
|
|
27
19
|
/**
|
|
28
20
|
* Wraps children in a SET (tag `0x31`) after DER-sorting them lexicographically by encoded bytes,
|
|
29
21
|
* as required by {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690} DER.
|
|
30
22
|
*/
|
|
31
|
-
declare function setOf(parts: readonly Uint8Array[]): Uint8Array;
|
|
23
|
+
export declare function setOf(parts: readonly Uint8Array[]): Uint8Array;
|
|
32
24
|
/**
|
|
33
25
|
* Wraps a value in an explicit context-specific constructed tag (`0xa0 + tag`).
|
|
34
26
|
*
|
|
35
27
|
* Used for optional SEQUENCE fields tagged with `[tag] EXPLICIT`.
|
|
36
28
|
*/
|
|
37
|
-
declare function explicitContext(tag: number, value: Uint8Array): Uint8Array;
|
|
29
|
+
export declare function explicitContext(tag: number, value: Uint8Array): Uint8Array;
|
|
38
30
|
/**
|
|
39
31
|
* Wraps a value in an implicit context-specific constructed tag (`0xa0 + tag`).
|
|
40
32
|
*
|
|
41
33
|
* Used for `[tag] IMPLICIT` fields whose underlying type is constructed (e.g. SEQUENCE).
|
|
42
34
|
*/
|
|
43
|
-
declare function implicitConstructedContext(tag: number, value: Uint8Array): Uint8Array;
|
|
35
|
+
export declare function implicitConstructedContext(tag: number, value: Uint8Array): Uint8Array;
|
|
44
36
|
/**
|
|
45
37
|
* Wraps a value in an implicit context-specific primitive tag (`0x80 + tag`).
|
|
46
38
|
*
|
|
47
39
|
* Used for `[tag] IMPLICIT` fields whose underlying type is primitive (e.g. OCTET STRING).
|
|
48
40
|
*/
|
|
49
|
-
declare function implicitPrimitiveContext(tag: number, value: Uint8Array): Uint8Array;
|
|
41
|
+
export declare function implicitPrimitiveContext(tag: number, value: Uint8Array): Uint8Array;
|
|
50
42
|
/**
|
|
51
43
|
* Encodes raw big-endian bytes as a DER INTEGER (tag `0x02`).
|
|
52
44
|
*
|
|
53
45
|
* Strips leading zero bytes for minimal encoding and prepends a zero byte when the high bit is set
|
|
54
46
|
* to keep the value non-negative.
|
|
55
47
|
*/
|
|
56
|
-
declare function integer(bytes: Uint8Array): Uint8Array;
|
|
48
|
+
export declare function integer(bytes: Uint8Array): Uint8Array;
|
|
57
49
|
/**
|
|
58
50
|
* Encodes a non-negative JavaScript `number` as a DER INTEGER.
|
|
59
51
|
*
|
|
60
52
|
* @throws if the value is not a non-negative safe integer.
|
|
61
53
|
*/
|
|
62
|
-
declare function integerFromNumber(value: number): Uint8Array;
|
|
54
|
+
export declare function integerFromNumber(value: number): Uint8Array;
|
|
63
55
|
/** Encodes a DER BOOLEAN (tag `0x01`): `true` → `0xff`, `false` → `0x00`. */
|
|
64
|
-
declare function bool(value: boolean): Uint8Array;
|
|
56
|
+
export declare function bool(value: boolean): Uint8Array;
|
|
65
57
|
/** Produces a DER NULL element (tag `0x05`, zero-length value). */
|
|
66
|
-
declare function nullValue(): Uint8Array;
|
|
58
|
+
export declare function nullValue(): Uint8Array;
|
|
67
59
|
/** Wraps raw bytes in an OCTET STRING element (tag `0x04`). */
|
|
68
|
-
declare function octetString(value: Uint8Array): Uint8Array;
|
|
60
|
+
export declare function octetString(value: Uint8Array): Uint8Array;
|
|
69
61
|
/**
|
|
70
62
|
* Encodes a DER BIT STRING (tag `0x03`).
|
|
71
63
|
*
|
|
@@ -73,33 +65,38 @@ declare function octetString(value: Uint8Array): Uint8Array;
|
|
|
73
65
|
*
|
|
74
66
|
* @param unusedBits Number of unused trailing bits (0–7). Defaults to 0.
|
|
75
67
|
*/
|
|
76
|
-
declare function bitString(value: Uint8Array, unusedBits?: number): Uint8Array;
|
|
77
|
-
/**
|
|
78
|
-
|
|
68
|
+
export declare function bitString(value: Uint8Array, unusedBits?: number): Uint8Array;
|
|
69
|
+
/**
|
|
70
|
+
* Encodes a DER UTF8String (tag `0x0c`).
|
|
71
|
+
*
|
|
72
|
+
* @throws on a lone surrogate, which has no UTF-8 encoding.
|
|
73
|
+
*/
|
|
74
|
+
export declare function utf8String(value: string): Uint8Array;
|
|
79
75
|
/**
|
|
80
76
|
* Encodes a DER PrintableString (tag `0x13`).
|
|
81
77
|
*
|
|
82
78
|
* @throws if the input contains characters outside the ITU-T X.680 §41.4 Table 10 PrintableString set.
|
|
83
79
|
*/
|
|
84
|
-
declare function printableString(value: string): Uint8Array;
|
|
80
|
+
export declare function printableString(value: string): Uint8Array;
|
|
85
81
|
/**
|
|
86
82
|
* Encodes a DER IA5String (tag `0x16`).
|
|
87
83
|
*
|
|
88
84
|
* @throws if the input contains any non-ASCII character (code point > 0x7f).
|
|
89
85
|
*/
|
|
90
|
-
declare function ia5String(value: string): Uint8Array;
|
|
86
|
+
export declare function ia5String(value: string): Uint8Array;
|
|
91
87
|
/**
|
|
92
88
|
* Encodes a DER BMPString (tag `0x1e`) as big-endian UTF-16.
|
|
93
89
|
*
|
|
94
|
-
* @throws on lone surrogates
|
|
90
|
+
* @throws on lone surrogates, on U+FFFE and U+FFFF, which X.680 §41.15 leaves
|
|
91
|
+
* out of BMPString, and on code points above the Basic Multilingual Plane.
|
|
95
92
|
*/
|
|
96
|
-
declare function bmpString(value: string): Uint8Array;
|
|
93
|
+
export declare function bmpString(value: string): Uint8Array;
|
|
97
94
|
/**
|
|
98
95
|
* Encodes a DER UniversalString (tag `0x1c`) as big-endian UTF-32.
|
|
99
96
|
*
|
|
100
97
|
* @throws on lone surrogates.
|
|
101
98
|
*/
|
|
102
|
-
declare function universalString(value: string): Uint8Array;
|
|
99
|
+
export declare function universalString(value: string): Uint8Array;
|
|
103
100
|
/**
|
|
104
101
|
* Encodes a dotted-decimal OID string as a DER OBJECT IDENTIFIER (tag `0x06`).
|
|
105
102
|
*
|
|
@@ -108,31 +105,33 @@ declare function universalString(value: string): Uint8Array;
|
|
|
108
105
|
* packing of the first two arcs into one subidentifier.\
|
|
109
106
|
* Sub-identifiers are encoded with base-128 continuation.
|
|
110
107
|
*/
|
|
111
|
-
declare function objectIdentifier(oid: string): Uint8Array;
|
|
108
|
+
export declare function objectIdentifier(oid: string): Uint8Array;
|
|
112
109
|
/**
|
|
113
110
|
* Encodes a `Date` as a DER UTCTime (tag `0x17`), format `YYMMDDHHMMSSZ`.
|
|
114
111
|
*
|
|
115
112
|
* Only the two-digit year is stored; suitable for dates in 1950–2049.
|
|
116
113
|
*/
|
|
117
|
-
declare function utcTime(date: Date): Uint8Array;
|
|
114
|
+
export declare function utcTime(date: Date): Uint8Array;
|
|
118
115
|
/**
|
|
119
116
|
* Encodes a {@linkcode Date} as a DER GeneralizedTime (tag `0x18`), format `YYYYMMDDHHMMSSZ`.
|
|
120
117
|
*
|
|
121
118
|
* Uses a four-digit year; required for dates outside the 1950–2049 range.
|
|
122
119
|
*/
|
|
123
|
-
declare function generalizedTime(date: Date): Uint8Array;
|
|
120
|
+
export declare function generalizedTime(date: Date): Uint8Array;
|
|
124
121
|
/**
|
|
125
122
|
* Encodes a {@linkcode Date} as the appropriate DER time type per RFC 5280.
|
|
126
123
|
*
|
|
127
124
|
* - {@linkcode utcTime} for 1950–2049
|
|
128
125
|
* - {@linkcode generalizedTime} otherwise
|
|
129
126
|
*/
|
|
130
|
-
declare function time(date: Date): Uint8Array;
|
|
127
|
+
export declare function time(date: Date): Uint8Array;
|
|
131
128
|
/** A single parsed ASN.1 TLV element with byte-range metadata. */
|
|
132
|
-
interface DerElement {
|
|
133
|
-
/**
|
|
129
|
+
export interface DerElement {
|
|
130
|
+
/** Leading identifier octet (e.g. `0x30` for SEQUENCE, `0x02` for INTEGER, `0x9f` for any context-specific primitive tag from 31 up). */
|
|
134
131
|
readonly tag: number;
|
|
135
|
-
/**
|
|
132
|
+
/** Tag number within the class, from the leading octet below 31 and from the subsequent identifier octets from 31 up. */
|
|
133
|
+
readonly tagNumber: number;
|
|
134
|
+
/** Number of bytes occupied by the identifier and length octets. */
|
|
136
135
|
readonly headerLength: number;
|
|
137
136
|
/** Byte length of the value portion (excluding tag and length octets). */
|
|
138
137
|
readonly length: number;
|
|
@@ -144,14 +143,14 @@ interface DerElement {
|
|
|
144
143
|
readonly value: Uint8Array;
|
|
145
144
|
}
|
|
146
145
|
/** Options for {@linkcode readSequenceChildren}. */
|
|
147
|
-
interface ReadSequenceChildrenOptions {
|
|
146
|
+
export interface ReadSequenceChildrenOptions {
|
|
148
147
|
/** Maximum nesting depth for the DER depth check. @default {@linkcode DEFAULT_MAX_DER_DEPTH}. */
|
|
149
148
|
readonly maxDepth?: number;
|
|
150
149
|
/** Constructed tags whose inner bytes may not parse as valid TLV children (e.g. opaque extension values). */
|
|
151
150
|
readonly allowOpaqueConstructedTags?: readonly number[];
|
|
152
151
|
}
|
|
153
152
|
/** Options for {@linkcode readRootElement}. */
|
|
154
|
-
interface ReadRootElementOptions {
|
|
153
|
+
export interface ReadRootElementOptions {
|
|
155
154
|
/** Maximum nesting depth for the DER depth check. @default {@linkcode DEFAULT_MAX_DER_DEPTH}. */
|
|
156
155
|
readonly maxDepth?: number;
|
|
157
156
|
/** Constructed tags whose inner bytes may not parse as valid TLV children (e.g. opaque extension values). */
|
|
@@ -164,10 +163,8 @@ interface ReadRootElementOptions {
|
|
|
164
163
|
*
|
|
165
164
|
* @throws if nesting exceeds {@linkcode maxDepth}.
|
|
166
165
|
*/
|
|
167
|
-
declare function assertDerMaxDepth(bytes: Uint8Array, maxDepth?: number, options?: {
|
|
166
|
+
export declare function assertDerMaxDepth(bytes: Uint8Array, maxDepth?: number, options?: {
|
|
168
167
|
/** Constructed tags whose inner bytes may not parse as valid TLV children. */
|
|
169
168
|
readonly allowOpaqueConstructedTags?: readonly number[];
|
|
170
169
|
}): void;
|
|
171
|
-
//#endregion
|
|
172
|
-
export { DEFAULT_MAX_DER_DEPTH, DerElement, ReadRootElementOptions, ReadSequenceChildrenOptions, assertDerMaxDepth, bitString, bmpString, bool, concatBytes, explicitContext, generalizedTime, ia5String, implicitConstructedContext, implicitPrimitiveContext, integer, integerFromNumber, nullValue, objectIdentifier, octetString, printableString, sequence, setOf, time, tlv, universalString, utcTime, utf8String };
|
|
173
170
|
//# sourceMappingURL=der.d.ts.map
|