micro509 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +78 -30
  2. package/dist/crypto/crypto.d.ts +73 -0
  3. package/dist/crypto/crypto.js +74 -0
  4. package/dist/crypto/crypto.js.map +1 -0
  5. package/dist/crypto.d.ts +4 -0
  6. package/dist/crypto.js +2 -0
  7. package/dist/der/der.d.ts +1 -1
  8. package/dist/index.d.ts +13 -9
  9. package/dist/index.js +17 -15
  10. package/dist/internal/asn1/asn1.js +21 -10
  11. package/dist/internal/asn1/asn1.js.map +1 -1
  12. package/dist/internal/asn1/der.d.ts +4 -2
  13. package/dist/internal/asn1/der.js +18 -5
  14. package/dist/internal/asn1/der.js.map +1 -1
  15. package/dist/internal/asn1/oids.js +7 -1
  16. package/dist/internal/crypto/algorithm-names.js +4 -0
  17. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  18. package/dist/internal/crypto/pbes2.d.ts +38 -0
  19. package/dist/internal/crypto/pbes2.js +9 -10
  20. package/dist/internal/crypto/pbes2.js.map +1 -1
  21. package/dist/internal/crypto/rsa-pss.js +2 -0
  22. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  23. package/dist/internal/crypto/sig-verify.d.ts +31 -0
  24. package/dist/internal/crypto/sig-verify.js +10 -8
  25. package/dist/internal/crypto/sig-verify.js.map +1 -1
  26. package/dist/internal/shared/base64.js +7 -1
  27. package/dist/internal/shared/base64.js.map +1 -1
  28. package/dist/internal/shared/dn.d.ts +16 -0
  29. package/dist/internal/shared/dn.js +13 -6
  30. package/dist/internal/shared/dn.js.map +1 -1
  31. package/dist/internal/shared/ip.d.ts +69 -0
  32. package/dist/internal/shared/ip.js +18 -1
  33. package/dist/internal/shared/ip.js.map +1 -1
  34. package/dist/internal/verify/verify-path.d.ts +7 -0
  35. package/dist/internal/verify/verify-path.js +36 -36
  36. package/dist/internal/x509/directory-name.js +24 -0
  37. package/dist/internal/x509/directory-name.js.map +1 -0
  38. package/dist/internal/x509/extension-bits.js +13 -10
  39. package/dist/internal/x509/extension-bits.js.map +1 -1
  40. package/dist/internal/x509/extension-errors.d.ts +6 -0
  41. package/dist/internal/x509/extension-errors.js +20 -0
  42. package/dist/internal/x509/extension-errors.js.map +1 -0
  43. package/dist/internal/x509/extension-registry.js +113 -55
  44. package/dist/internal/x509/extension-registry.js.map +1 -1
  45. package/dist/internal/x509/general-name-tags.js +28 -0
  46. package/dist/internal/x509/general-name-tags.js.map +1 -0
  47. package/dist/internal/x509/general-name.js +97 -0
  48. package/dist/internal/x509/general-name.js.map +1 -0
  49. package/dist/internal/x509/name-fields.js +20 -10
  50. package/dist/internal/x509/name-fields.js.map +1 -1
  51. package/dist/keys/keys.d.ts +16 -2
  52. package/dist/keys/keys.js +311 -170
  53. package/dist/keys/keys.js.map +1 -1
  54. package/dist/keys.d.ts +3 -2
  55. package/dist/keys.js +3 -2
  56. package/dist/pem/pem.d.ts +3 -2
  57. package/dist/pem/pem.js +112 -30
  58. package/dist/pem/pem.js.map +1 -1
  59. package/dist/pkcs/pkcs12-mac.js +3 -3
  60. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  61. package/dist/pkcs/pkcs7.d.ts +85 -21
  62. package/dist/pkcs/pkcs7.js +261 -186
  63. package/dist/pkcs/pkcs7.js.map +1 -1
  64. package/dist/pkcs.d.ts +2 -2
  65. package/dist/result/result.d.ts +18 -10
  66. package/dist/result/result.js +20 -12
  67. package/dist/result/result.js.map +1 -1
  68. package/dist/result.d.ts +2 -2
  69. package/dist/result.js +2 -2
  70. package/dist/revocation/chain.js +77 -81
  71. package/dist/revocation/chain.js.map +1 -1
  72. package/dist/revocation/crl.d.ts +13 -2
  73. package/dist/revocation/crl.js +415 -236
  74. package/dist/revocation/crl.js.map +1 -1
  75. package/dist/revocation/ocsp.d.ts +58 -17
  76. package/dist/revocation/ocsp.js +185 -173
  77. package/dist/revocation/ocsp.js.map +1 -1
  78. package/dist/revocation/revocation.d.ts +4 -4
  79. package/dist/revocation/revocation.js +48 -30
  80. package/dist/revocation/revocation.js.map +1 -1
  81. package/dist/revocation.d.ts +4 -4
  82. package/dist/revocation.js +5 -5
  83. package/dist/verify/identity.d.ts +2 -1
  84. package/dist/verify/identity.js +2 -1
  85. package/dist/verify/identity.js.map +1 -1
  86. package/dist/verify/policy.d.ts +6 -1
  87. package/dist/verify/verify.d.ts +4 -2
  88. package/dist/verify/verify.js +32 -14
  89. package/dist/verify/verify.js.map +1 -1
  90. package/dist/verify.d.ts +2 -1
  91. package/dist/verify.js +4 -3
  92. package/dist/x509/certificate.d.ts +36 -13
  93. package/dist/x509/certificate.js +36 -19
  94. package/dist/x509/certificate.js.map +1 -1
  95. package/dist/x509/csr.d.ts +6 -3
  96. package/dist/x509/extensions.d.ts +58 -21
  97. package/dist/x509/extensions.js +384 -117
  98. package/dist/x509/extensions.js.map +1 -1
  99. package/dist/x509/name-text.js +2 -0
  100. package/dist/x509/name-text.js.map +1 -1
  101. package/dist/x509/name.d.ts +8 -5
  102. package/dist/x509/name.js +17 -12
  103. package/dist/x509/name.js.map +1 -1
  104. package/dist/x509/parse.d.ts +104 -18
  105. package/dist/x509/parse.js +127 -163
  106. package/dist/x509/parse.js.map +1 -1
  107. package/dist/x509.d.ts +8 -5
  108. package/dist/x509.js +10 -8
  109. package/package.json +28 -20
@@ -1,7 +1,7 @@
1
- import { readElement as e } from "./der.js";
1
+ import { objectIdentifier as e, readElement as t } from "./der.js";
2
2
  //#region src/internal/asn1/asn1.ts
3
3
  /** Shared UTF-8 text decoder for ASN.1 string types. */
4
- const t = new TextDecoder("utf-8", { fatal: !0 }), n = /^[A-Za-z0-9 '()+,\-./:=?]*$/u;
4
+ const n = new TextDecoder("utf-8", { fatal: !0 }), r = /^[A-Za-z0-9 '()+,\-./:=?]*$/u;
5
5
  /**
6
6
  * Decodes a DER-encoded OBJECT IDENTIFIER value into its dotted-decimal string form.
7
7
  *
@@ -17,6 +17,17 @@ function decodeObjectIdentifier(e) {
17
17
  }
18
18
  return r.join(".");
19
19
  }
20
+ /**
21
+ * Reduces an OID to the dotted-decimal form its DER encoding decodes back to, so
22
+ * that spellings differing only by redundant leading zeros in an arc resolve to
23
+ * one identity.
24
+ *
25
+ * @example `canonicalizeOid('2.5.029.17')` returns `'2.5.29.17'`
26
+ * @throws if the OID has a non-numeric segment or violates the X.660 arc constraints.
27
+ */
28
+ function canonicalizeOid(n) {
29
+ return decodeObjectIdentifier(t(e(n), 0).value);
30
+ }
20
31
  /** Converts raw bytes to a lowercase hex string with no separator. */
21
32
  function toHex(e) {
22
33
  return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
@@ -35,10 +46,10 @@ function toArrayBuffer(e) {
35
46
  *
36
47
  * @throws if any child overflows the parent boundary or if there is leftover data between the last child and the parent end offset.
37
48
  */
38
- function childrenOf(t, n) {
49
+ function childrenOf(e, n) {
39
50
  let r = [], i = n.start;
40
51
  for (; i < n.end;) {
41
- let a = e(t, i);
52
+ let a = t(e, i);
42
53
  if (a.end > n.end) throw Error("DER child exceeds parent length");
43
54
  r.push(a), i = a.end;
44
55
  }
@@ -166,7 +177,7 @@ function hexToBytes(e) {
166
177
  }
167
178
  return n;
168
179
  }
169
- /** Decodes a DER BOOLEAN value: any non-zero first byte is `true`. */
180
+ /** Decodes a DER BOOLEAN value. X.690 clause 11.1 restricts TRUE to an all-ones octet, so only `0xff` and `0x00` are accepted. */
170
181
  function decodeBoolean(e) {
171
182
  if (e.length !== 1) throw Error("BOOLEAN must contain exactly one octet");
172
183
  let t = e[0];
@@ -218,11 +229,11 @@ function decodeString(e, t) {
218
229
  default: throw Error(`Unsupported string tag: ${e}`);
219
230
  }
220
231
  }
221
- function decodeUtf8Text(e, n) {
232
+ function decodeUtf8Text(e, t) {
222
233
  try {
223
- return t.decode(e);
234
+ return n.decode(e);
224
235
  } catch (e) {
225
- throw e instanceof Error ? Error(`Invalid ${n}: invalid UTF-8`, { cause: e }) : e;
236
+ throw e instanceof Error ? Error(`Invalid ${t}: invalid UTF-8`, { cause: e }) : e;
226
237
  }
227
238
  }
228
239
  function decodeAsciiString(e, t) {
@@ -238,7 +249,7 @@ function decodeIa5String(e) {
238
249
  }
239
250
  function decodePrintableString(e) {
240
251
  let t = decodeAsciiString(e, "PrintableString");
241
- if (!n.test(t)) throw Error("Invalid PrintableString: contains characters outside the allowed set");
252
+ if (!r.test(t)) throw Error("Invalid PrintableString: contains characters outside the allowed set");
242
253
  return t;
243
254
  }
244
255
  function decodeBmpString(e) {
@@ -266,6 +277,6 @@ function decodeUniversalString(e) {
266
277
  return t;
267
278
  }
268
279
  //#endregion
269
- export { childrenOf, decodeBitString, decodeBoolean, decodeIntegerNumber, decodeNonNegativeIntegerNumber, decodeObjectIdentifier, decodeString, extractBitStringValue, hexToBytes, parseTime, requireElement, toArrayBuffer, toHex };
280
+ export { canonicalizeOid, childrenOf, decodeBitString, decodeBoolean, decodeIntegerNumber, decodeNonNegativeIntegerNumber, decodeObjectIdentifier, decodeString, extractBitStringValue, hexToBytes, parseTime, requireElement, toArrayBuffer, toHex };
270
281
 
271
282
  //# sourceMappingURL=asn1.js.map
@@ -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 { 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/** 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: any non-zero first byte is `true`. */\nexport function decodeBoolean(bytes: Uint8Array): boolean {\n\tif (bytes.length !== 1) {\n\t\tthrow new Error('BOOLEAN must contain exactly one octet');\n\t}\n\tconst value = bytes[0];\n\tif (value !== 0x00 && value !== 0xff) {\n\t\tthrow new Error('BOOLEAN must use DER encoding');\n\t}\n\treturn value === 0xff;\n}\n\nfunction buildStrictUtcDate(\n\tyear: number,\n\tmonthText: string,\n\tdayText: string,\n\thourText: string,\n\tminuteText: string,\n\tsecondText: string,\n\tlabel: 'UTCTime' | 'GeneralizedTime',\n): Date {\n\tconst month = Number.parseInt(monthText, 10);\n\tconst day = Number.parseInt(dayText, 10);\n\tconst hour = Number.parseInt(hourText, 10);\n\tconst minute = Number.parseInt(minuteText, 10);\n\tconst second = Number.parseInt(secondText, 10);\n\tconst date = new Date(Date.UTC(year, month - 1, day, hour, minute, second));\n\tif (\n\t\tNumber.isNaN(date.getTime()) ||\n\t\tdate.getUTCFullYear() !== year ||\n\t\tdate.getUTCMonth() !== month - 1 ||\n\t\tdate.getUTCDate() !== day ||\n\t\tdate.getUTCHours() !== hour ||\n\t\tdate.getUTCMinutes() !== minute ||\n\t\tdate.getUTCSeconds() !== second\n\t) {\n\t\tthrow new Error(`Invalid ${label}`);\n\t}\n\treturn date;\n}\n\nfunction decodeOidSubidentifier(\n\tbytes: Uint8Array,\n\tstart: number,\n): {\n\treadonly value: number;\n\treadonly nextOffset: number;\n} {\n\tconst first = bytes[start];\n\tif (first === undefined) {\n\t\tthrow new Error('Malformed OID');\n\t}\n\tif (first === 0x80) {\n\t\tthrow new Error('Malformed OID: non-minimal base-128 encoding');\n\t}\n\tlet value = 0;\n\tlet offset = start;\n\tfor (; offset < bytes.length; offset += 1) {\n\t\tconst next = bytes[offset];\n\t\tif (next === undefined) {\n\t\t\tthrow new Error('Malformed OID');\n\t\t}\n\t\tconst digit = next & 0x7f;\n\t\tif (value > Math.floor((Number.MAX_SAFE_INTEGER - digit) / 128)) {\n\t\t\tthrow new Error('Malformed OID: overflow/non-minimal or too-large subidentifier');\n\t\t}\n\t\tvalue = value * 128 + digit;\n\t\tif ((next & 0x80) === 0) {\n\t\t\treturn {\n\t\t\t\tvalue,\n\t\t\t\tnextOffset: offset + 1,\n\t\t\t};\n\t\t}\n\t}\n\tthrow new Error('Malformed OID: incomplete continuation');\n}\n\n/**\n * Decodes a DER string element by tag.\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,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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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KAAA,GACnC,MAAU,MAAM,2BAA2B;EAE5C,IAAM,IAAY,KAAQ,IAAK;EAC/B,IAAI,KAAY,SAAU,KAAY,OACrC,MAAU,MAAM,8BAA8B;EAE/C,KAAS,OAAO,aAAa,CAAQ;CACtC;CACA,OAAO;AACR;AAEA,SAAS,sBAAsB,GAA2B;CACzD,IAAI,EAAM,SAAS,KAAM,GACxB,MAAU,MAAM,gCAAgC;CAEjD,IAAI,IAAQ;CACZ,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAM,QAAQ,KAAS,GAAG;EACrD,IAAM,IAAQ,EAAM,IACd,IAAS,EAAM,IAAQ,IACvB,IAAQ,EAAM,IAAQ,IACtB,IAAS,EAAM,IAAQ;EAC7B,IACC,MAAU,KAAA,KACV,MAAW,KAAA,KACX,MAAU,KAAA,KACV,MAAW,KAAA,GAEX,MAAU,MAAM,iCAAiC;EAElD,IAAM,MAAc,IAAQ,MAAM,KAAU,MAAM,KAAS,MAAM;EACjE,IAAI,IAAY,WAAa,KAAa,SAAU,KAAa,OAChE,MAAU,MAAM,oCAAoC;EAErD,KAAS,OAAO,cAAc,CAAS;CACxC;CACA,OAAO;AACR"}
@@ -79,7 +79,7 @@ declare function utf8String(value: string): Uint8Array;
79
79
  /**
80
80
  * Encodes a DER PrintableString (tag `0x13`).
81
81
  *
82
- * @throws if the input contains characters outside the X.520 PrintableString set.
82
+ * @throws if the input contains characters outside the ITU-T X.680 §41.4 Table 10 PrintableString set.
83
83
  */
84
84
  declare function printableString(value: string): Uint8Array;
85
85
  /**
@@ -103,7 +103,9 @@ declare function universalString(value: string): Uint8Array;
103
103
  /**
104
104
  * Encodes a dotted-decimal OID string as a DER OBJECT IDENTIFIER (tag `0x06`).
105
105
  *
106
- * Validates arc constraints per X.660: first arc must be 0–2, second < 40 for arcs 0 and 1.\
106
+ * Validates arc constraints per X.660 §7.6: the root arc must be 0–2, and under
107
+ * roots 0 and 1 the second arc must be 0–39. X.690 §8.19.4 defines the `(X*40)+Y`
108
+ * packing of the first two arcs into one subidentifier.\
107
109
  * Sub-identifiers are encoded with base-128 continuation.
108
110
  */
109
111
  declare function objectIdentifier(oid: string): Uint8Array;
@@ -29,6 +29,13 @@ function concatBytes(e) {
29
29
  for (let t of e) n.set(t, r), r += t.length;
30
30
  return n;
31
31
  }
32
+ /** Compares two optional byte arrays; two absent values are equal. */
33
+ function optionalBytesEqual(e, t) {
34
+ if (e === void 0 || t === void 0) return e === t;
35
+ if (e.length !== t.length) return !1;
36
+ for (let n = 0; n < e.length; n += 1) if (e[n] !== t[n]) return !1;
37
+ return !0;
38
+ }
32
39
  /**
33
40
  * Builds a complete DER TLV (tag-length-value) element:
34
41
  *
@@ -139,20 +146,24 @@ function utf8String(e) {
139
146
  /**
140
147
  * Encodes a DER PrintableString (tag `0x13`).
141
148
  *
142
- * @throws if the input contains characters outside the X.520 PrintableString set.
149
+ * @throws if the input contains characters outside the ITU-T X.680 §41.4 Table 10 PrintableString set.
143
150
  */
144
151
  function printableString(e) {
145
152
  if (!/^[A-Za-z0-9 '()+,\-./:=?]*$/.test(e)) throw Error("Invalid PrintableString: contains characters outside the allowed set");
146
153
  return tlv(19, new TextEncoder().encode(e));
147
154
  }
155
+ /** Validates a string is ASCII (IA5) and returns its content bytes, without a tag. */
156
+ function ia5Bytes(e) {
157
+ for (let t = 0; t < e.length; t++) if (e.charCodeAt(t) > 127) throw Error("Invalid IA5String: contains non-ASCII characters");
158
+ return new TextEncoder().encode(e);
159
+ }
148
160
  /**
149
161
  * Encodes a DER IA5String (tag `0x16`).
150
162
  *
151
163
  * @throws if the input contains any non-ASCII character (code point > 0x7f).
152
164
  */
153
165
  function ia5String(e) {
154
- for (let t = 0; t < e.length; t++) if (e.charCodeAt(t) > 127) throw Error("Invalid IA5String: contains non-ASCII characters");
155
- return tlv(22, new TextEncoder().encode(e));
166
+ return tlv(22, ia5Bytes(e));
156
167
  }
157
168
  /**
158
169
  * Encodes a DER BMPString (tag `0x1e`) as big-endian UTF-16.
@@ -192,7 +203,9 @@ function encodeBase128(e) {
192
203
  /**
193
204
  * Encodes a dotted-decimal OID string as a DER OBJECT IDENTIFIER (tag `0x06`).
194
205
  *
195
- * Validates arc constraints per X.660: first arc must be 0–2, second < 40 for arcs 0 and 1.\
206
+ * Validates arc constraints per X.660 §7.6: the root arc must be 0–2, and under
207
+ * roots 0 and 1 the second arc must be 0–39. X.690 §8.19.4 defines the `(X*40)+Y`
208
+ * packing of the first two arcs into one subidentifier.\
196
209
  * Sub-identifiers are encoded with base-128 continuation.
197
210
  */
198
211
  function objectIdentifier(e) {
@@ -421,6 +434,6 @@ function canTreatAsOpaqueLeaf(e, t, n) {
421
434
  return t === e.start && n?.allowOpaqueConstructedTags?.includes(e.tag) === !0;
422
435
  }
423
436
  //#endregion
424
- export { e as DEFAULT_MAX_DER_DEPTH, assertDerMaxDepth, bitString, bmpString, bool, concatBytes, encodeLength, explicitContext, generalizedTime, ia5String, implicitConstructedContext, implicitPrimitiveContext, integer, integerFromNumber, nullValue, objectIdentifier, octetString, printableString, readElement, readRootElement, readSequenceChildren, sequence, setOf, time, tlv, universalString, utcTime, utf8String };
437
+ export { e as DEFAULT_MAX_DER_DEPTH, assertDerMaxDepth, bitString, bmpString, bool, concatBytes, encodeLength, explicitContext, generalizedTime, ia5Bytes, ia5String, implicitConstructedContext, implicitPrimitiveContext, integer, integerFromNumber, nullValue, objectIdentifier, octetString, optionalBytesEqual, printableString, readElement, readRootElement, readSequenceChildren, sequence, setOf, time, tlv, universalString, utcTime, utf8String };
425
438
 
426
439
  //# sourceMappingURL=der.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"der.js","names":[],"sources":["../../../src/internal/asn1/der.ts"],"sourcesContent":["/**\n * Low-level DER encoding and reading helpers shared across the library.\n *\n * These utilities build and traverse ASN.1 TLV (tag-length-value) structures.\n *\n * @module\n */\n\n/**\n * Maximum nesting depth allowed when recursively walking a DER structure.\n *\n * Guards against stack exhaustion from pathologically nested input.\n */\nexport const DEFAULT_MAX_DER_DEPTH = 64;\n\n/**\n * Produces the DER length octets for a given byte count.\n *\n * Values < 128 use the short form (one octet);\n * larger values use the long form (leading octet encodes the number of subsequent length bytes).\n */\nexport function encodeLength(length: number): Uint8Array {\n\tassertNonNegativeSafeInteger(length, 'DER length');\n\tif (length < 128) {\n\t\treturn Uint8Array.of(length);\n\t}\n\n\tconst parts = encodeBase256(length);\n\treturn Uint8Array.of(0x80 | parts.length, ...parts);\n}\n\n/** Concatenates multiple byte arrays into a single {@linkcode Uint8Array}. */\nexport function concatBytes(parts: readonly Uint8Array[]): Uint8Array {\n\tconst length = parts.reduce((sum, part) => sum + part.length, 0);\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const part of parts) {\n\t\tout.set(part, offset);\n\t\toffset += part.length;\n\t}\n\treturn out;\n}\n\n/**\n * Builds a complete DER TLV (tag-length-value) element:\n *\n * - one tag octet,\n * - the DER-encoded length, then\n * - the raw value bytes.\n */\nexport function tlv(tag: number, value: Uint8Array): Uint8Array {\n\tassertSingleOctetDerTag(tag);\n\treturn concatBytes([Uint8Array.of(tag), encodeLength(value.length), value]);\n}\n\n/** Wraps concatenated children in a SEQUENCE (tag `0x30`). */\nexport function sequence(parts: readonly Uint8Array[]): Uint8Array {\n\treturn tlv(0x30, concatBytes(parts));\n}\n\n/**\n * Wraps children in a SET (tag `0x31`) after DER-sorting them lexicographically by encoded bytes,\n * as required by {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690} DER.\n */\nexport function setOf(parts: readonly Uint8Array[]): Uint8Array {\n\tconst sorted = parts.slice().sort((a, b) => {\n\t\tconst len = Math.min(a.length, b.length);\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tconst diff = (a[i] ?? 0) - (b[i] ?? 0);\n\t\t\tif (diff !== 0) return diff;\n\t\t}\n\t\treturn a.length - b.length;\n\t});\n\treturn tlv(0x31, concatBytes(sorted));\n}\n\n/**\n * Wraps a value in an explicit context-specific constructed tag (`0xa0 + tag`).\n *\n * Used for optional SEQUENCE fields tagged with `[tag] EXPLICIT`.\n */\nexport function explicitContext(tag: number, value: Uint8Array): Uint8Array {\n\tassertContextSpecificTagNumber(tag);\n\treturn tlv(0xa0 + tag, value);\n}\n\n/**\n * Wraps a value in an implicit context-specific constructed tag (`0xa0 + tag`).\n *\n * Used for `[tag] IMPLICIT` fields whose underlying type is constructed (e.g. SEQUENCE).\n */\nexport function implicitConstructedContext(tag: number, value: Uint8Array): Uint8Array {\n\tassertContextSpecificTagNumber(tag);\n\treturn tlv(0xa0 + tag, value);\n}\n\n/**\n * Wraps a value in an implicit context-specific primitive tag (`0x80 + tag`).\n *\n * Used for `[tag] IMPLICIT` fields whose underlying type is primitive (e.g. OCTET STRING).\n */\nexport function implicitPrimitiveContext(tag: number, value: Uint8Array): Uint8Array {\n\tassertContextSpecificTagNumber(tag);\n\treturn tlv(0x80 + tag, value);\n}\n\n/**\n * Encodes raw big-endian bytes as a DER INTEGER (tag `0x02`).\n *\n * Strips leading zero bytes for minimal encoding and prepends a zero byte when the high bit is set\n * to keep the value non-negative.\n */\nexport function integer(bytes: Uint8Array): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn tlv(0x02, Uint8Array.of(0));\n\t}\n\n\tlet start = 0;\n\twhile (start < bytes.length - 1 && bytes[start] === 0) {\n\t\tstart += 1;\n\t}\n\n\tconst value = bytes.slice(start);\n\tif ((value[0] ?? 0) >= 0x80) {\n\t\treturn tlv(0x02, concatBytes([Uint8Array.of(0), value]));\n\t}\n\n\treturn tlv(0x02, value);\n}\n\n/**\n * Encodes a non-negative JavaScript `number` as a DER INTEGER.\n *\n * @throws if the value is not a non-negative safe integer.\n */\nexport function integerFromNumber(value: number): Uint8Array {\n\tif (!Number.isSafeInteger(value) || value < 0) {\n\t\tthrow new Error('INTEGER must be a non-negative safe integer');\n\t}\n\n\tif (value === 0) {\n\t\treturn integer(Uint8Array.of(0));\n\t}\n\n\treturn integer(Uint8Array.from(encodeBase256(value)));\n}\n\n/** Encodes a DER BOOLEAN (tag `0x01`): `true` → `0xff`, `false` → `0x00`. */\nexport function bool(value: boolean): Uint8Array {\n\treturn tlv(0x01, Uint8Array.of(value ? 0xff : 0x00));\n}\n\n/** Produces a DER NULL element (tag `0x05`, zero-length value). */\nexport function nullValue(): Uint8Array {\n\treturn tlv(0x05, new Uint8Array());\n}\n\n/** Wraps raw bytes in an OCTET STRING element (tag `0x04`). */\nexport function octetString(value: Uint8Array): Uint8Array {\n\treturn tlv(0x04, value);\n}\n\n/**\n * Encodes a DER BIT STRING (tag `0x03`).\n *\n * The value is prefixed with a single octet indicating how many trailing bits in the last byte are unused.\n *\n * @param unusedBits Number of unused trailing bits (0–7). Defaults to 0.\n */\nexport function bitString(value: Uint8Array, unusedBits = 0): Uint8Array {\n\tif (unusedBits < 0 || unusedBits > 7) {\n\t\tthrow new Error('unusedBits must be between 0 and 7');\n\t}\n\tif (value.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('unusedBits must be 0 when value is empty');\n\t}\n\tif (value.length > 0 && unusedBits > 0) {\n\t\tconst lastByte = value[value.length - 1] ?? 0;\n\t\tif ((lastByte & ((1 << unusedBits) - 1)) !== 0) {\n\t\t\tthrow new Error('unused bits in the last byte must be zero');\n\t\t}\n\t}\n\treturn tlv(0x03, concatBytes([Uint8Array.of(unusedBits), value]));\n}\n\n/** Encodes a DER UTF8String (tag `0x0c`). */\nexport function utf8String(value: string): Uint8Array {\n\treturn tlv(0x0c, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a DER PrintableString (tag `0x13`).\n *\n * @throws if the input contains characters outside the X.520 PrintableString set.\n */\nexport function printableString(value: string): Uint8Array {\n\tif (!/^[A-Za-z0-9 '()+,\\-./:=?]*$/.test(value)) {\n\t\tthrow new Error('Invalid PrintableString: contains characters outside the allowed set');\n\t}\n\treturn tlv(0x13, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a DER IA5String (tag `0x16`).\n *\n * @throws if the input contains any non-ASCII character (code point > 0x7f).\n */\nexport function ia5String(value: string): Uint8Array {\n\tfor (let i = 0; i < value.length; i++) {\n\t\tif (value.charCodeAt(i) > 0x7f) {\n\t\t\tthrow new Error('Invalid IA5String: contains non-ASCII characters');\n\t\t}\n\t}\n\treturn tlv(0x16, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a DER BMPString (tag `0x1e`) as big-endian UTF-16.\n *\n * @throws on lone surrogates and on code points above the Basic Multilingual Plane.\n */\nexport function bmpString(value: string): Uint8Array {\n\tconst units: number[] = [];\n\tfor (const character of value) {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\tif (codePoint > 0xffff) {\n\t\t\tthrow new Error('Invalid BMPString: code point above the Basic Multilingual Plane');\n\t\t}\n\t\tif (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n\t\t\tthrow new Error('Invalid BMPString: lone surrogate');\n\t\t}\n\t\tunits.push((codePoint >> 8) & 0xff, codePoint & 0xff);\n\t}\n\treturn tlv(0x1e, Uint8Array.from(units));\n}\n\n/**\n * Encodes a DER UniversalString (tag `0x1c`) as big-endian UTF-32.\n *\n * @throws on lone surrogates.\n */\nexport function universalString(value: string): Uint8Array {\n\tconst bytes: number[] = [];\n\tfor (const character of value) {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\tif (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n\t\t\tthrow new Error('Invalid UniversalString: lone surrogate');\n\t\t}\n\t\tbytes.push(\n\t\t\t(codePoint >> 24) & 0xff,\n\t\t\t(codePoint >> 16) & 0xff,\n\t\t\t(codePoint >> 8) & 0xff,\n\t\t\tcodePoint & 0xff,\n\t\t);\n\t}\n\treturn tlv(0x1c, Uint8Array.from(bytes));\n}\n\n/** Encode a non-negative integer as a base-128 sub-identifier ({@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §8.19.2}). */\nfunction encodeBase128(value: bigint): number[] {\n\tconst encoded: number[] = [Number(value & 0x7fn)];\n\tlet current = value >> 7n;\n\twhile (current > 0n) {\n\t\tencoded.unshift(0x80 | Number(current & 0x7fn));\n\t\tcurrent >>= 7n;\n\t}\n\treturn encoded;\n}\n\n/**\n * Encodes a dotted-decimal OID string as a DER OBJECT IDENTIFIER (tag `0x06`).\n *\n * Validates arc constraints per X.660: first arc must be 0–2, second < 40 for arcs 0 and 1.\\\n * Sub-identifiers are encoded with base-128 continuation.\n */\nexport function objectIdentifier(oid: string): Uint8Array {\n\tconst digitPattern = /^\\d+$/;\n\tconst segments = oid.split('.').map((segment) => {\n\t\tif (!digitPattern.test(segment)) {\n\t\t\tthrow new Error(`Invalid OID segment: ${segment}`);\n\t\t}\n\t\treturn BigInt(segment);\n\t});\n\tif (segments.length < 2) {\n\t\tthrow new Error(`Invalid OID: ${oid}`);\n\t}\n\n\tconst [first, second, ...rest] = segments;\n\tif (first === undefined || second === undefined) {\n\t\tthrow new Error(`Invalid OID: ${oid}`);\n\t}\n\tif (first !== 0n && first !== 1n && first !== 2n) {\n\t\tthrow new Error(`Invalid OID first arc: ${first}`);\n\t}\n\tif ((first === 0n || first === 1n) && second >= 40n) {\n\t\tthrow new Error(`Invalid OID second arc: ${second} (must be < 40 when first arc is ${first})`);\n\t}\n\tconst bytes: number[] = encodeBase128(first * 40n + second);\n\tfor (const segment of rest) {\n\t\tbytes.push(...encodeBase128(segment));\n\t}\n\n\treturn tlv(0x06, Uint8Array.from(bytes));\n}\n\n/**\n * Encodes a `Date` as a DER UTCTime (tag `0x17`), format `YYMMDDHHMMSSZ`.\n *\n * Only the two-digit year is stored; suitable for dates in 1950–2049.\n */\nexport function utcTime(date: Date): Uint8Array {\n\tassertValidDate(date, 'UTCTime');\n\tconst year = date.getUTCFullYear();\n\tif (year < 1950 || year > 2049) {\n\t\tthrow new RangeError('UTCTime year must be between 1950 and 2049');\n\t}\n\tconst value = `${[\n\t\ttwoDigits(year % 100),\n\t\ttwoDigits(date.getUTCMonth() + 1),\n\t\ttwoDigits(date.getUTCDate()),\n\t\ttwoDigits(date.getUTCHours()),\n\t\ttwoDigits(date.getUTCMinutes()),\n\t\ttwoDigits(date.getUTCSeconds()),\n\t].join('')}Z`;\n\treturn tlv(0x17, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a {@linkcode Date} as a DER GeneralizedTime (tag `0x18`), format `YYYYMMDDHHMMSSZ`.\n *\n * Uses a four-digit year; required for dates outside the 1950–2049 range.\n */\nexport function generalizedTime(date: Date): Uint8Array {\n\tassertValidDate(date, 'GeneralizedTime');\n\tconst year = date.getUTCFullYear();\n\tif (year < 0 || year > 9999) {\n\t\tthrow new RangeError('GeneralizedTime year must be between 0 and 9999');\n\t}\n\tconst value = `${[\n\t\tString(year).padStart(4, '0'),\n\t\ttwoDigits(date.getUTCMonth() + 1),\n\t\ttwoDigits(date.getUTCDate()),\n\t\ttwoDigits(date.getUTCHours()),\n\t\ttwoDigits(date.getUTCMinutes()),\n\t\ttwoDigits(date.getUTCSeconds()),\n\t].join('')}Z`;\n\treturn tlv(0x18, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a {@linkcode Date} as the appropriate DER time type per RFC 5280.\n *\n * - {@linkcode utcTime} for 1950–2049\n * - {@linkcode generalizedTime} otherwise\n */\nexport function time(date: Date): Uint8Array {\n\tif (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) {\n\t\treturn generalizedTime(date);\n\t}\n\treturn utcTime(date);\n}\n\n/** Zero-pads a number to two digits for time encoding. */\nfunction twoDigits(value: number): string {\n\treturn String(value).padStart(2, '0');\n}\n\n/** Encodes a non-negative integer as big-endian base-256 octets. */\nfunction encodeBase256(value: number): readonly number[] {\n\tassertNonNegativeSafeInteger(value, 'DER integer');\n\tconst parts: number[] = [];\n\tlet current = value;\n\twhile (current > 0) {\n\t\tparts.unshift(current & 0xff);\n\t\tcurrent = Math.floor(current / 256);\n\t}\n\treturn parts;\n}\n\n/** A single parsed ASN.1 TLV element with byte-range metadata. */\nexport interface DerElement {\n\t/** ASN.1 tag byte (e.g. `0x30` for SEQUENCE, `0x02` for INTEGER). */\n\treadonly tag: number;\n\t/** Number of bytes occupied by the tag + length octets. */\n\treadonly headerLength: number;\n\t/** Byte length of the value portion (excluding tag and length octets). */\n\treadonly length: number;\n\t/** Byte offset where the value portion begins in the source buffer. */\n\treadonly start: number;\n\t/** Byte offset one past the last value byte. Equals the next element's header offset. */\n\treadonly end: number;\n\t/** The raw value bytes (slice of the source buffer). */\n\treadonly value: Uint8Array;\n}\n\n/** Options for {@linkcode readSequenceChildren}. */\nexport interface ReadSequenceChildrenOptions {\n\t/** Maximum nesting depth for the DER depth check. @default {@linkcode DEFAULT_MAX_DER_DEPTH}. */\n\treadonly maxDepth?: number;\n\t/** Constructed tags whose inner bytes may not parse as valid TLV children (e.g. opaque extension values). */\n\treadonly allowOpaqueConstructedTags?: readonly number[];\n}\n\n/** Options for {@linkcode readRootElement}. */\nexport interface ReadRootElementOptions {\n\t/** Maximum nesting depth for the DER depth check. @default {@linkcode DEFAULT_MAX_DER_DEPTH}. */\n\treadonly maxDepth?: number;\n\t/** Constructed tags whose inner bytes may not parse as valid TLV children (e.g. opaque extension values). */\n\treadonly allowOpaqueConstructedTags?: readonly number[];\n}\n\n/**\n * Reads one TLV element from {@linkcode bytes} starting at {@linkcode offset}.\n *\n * Parses the tag byte, decodes the DER length octets, and slices out the value bytes.\n *\n * @throws on truncated input, indefinite lengths, and non-minimal length encodings.\n * @param offset Byte position of the tag octet. Defaults to 0.\n */\nexport function readElement(bytes: Uint8Array, offset = 0): DerElement {\n\tconst tag = bytes[offset];\n\tif (tag === undefined) {\n\t\tthrow new Error('Unexpected end of DER input');\n\t}\n\tif ((tag & 0x1f) === 0x1f) {\n\t\tthrow new Error('High-tag-number DER form is not supported');\n\t}\n\tconst lengthByte = bytes[offset + 1];\n\tif (lengthByte === undefined) {\n\t\tthrow new Error('Unexpected end of DER input');\n\t}\n\n\tconst { headerLength, length } = readDerLength(bytes, offset, lengthByte);\n\n\tconst start = offset + headerLength;\n\tconst end = start + length;\n\tif (end > bytes.length) {\n\t\tthrow new Error('DER element exceeds input length');\n\t}\n\n\treturn {\n\t\ttag,\n\t\theaderLength,\n\t\tlength,\n\t\tstart,\n\t\tend,\n\t\tvalue: bytes.slice(start, end),\n\t};\n}\n\n/** Decodes and validates the definite-length field of a DER element. */\nfunction readDerLength(\n\tbytes: Uint8Array,\n\toffset: number,\n\tlengthByte: number,\n): { readonly headerLength: number; readonly length: number } {\n\tif ((lengthByte & 0x80) === 0) {\n\t\treturn { headerLength: 2, length: lengthByte };\n\t}\n\tconst octets = lengthByte & 0x7f;\n\tif (octets === 0) {\n\t\tthrow new Error('Indefinite lengths are not supported');\n\t}\n\tconst firstLengthOctet = bytes[offset + 2];\n\tif (firstLengthOctet === undefined) {\n\t\tthrow new Error('Unexpected end of DER input');\n\t}\n\tif (firstLengthOctet === 0) {\n\t\tthrow new Error('Non-minimal DER length encoding');\n\t}\n\tconst length = readLongFormDerLength(bytes, offset, octets);\n\tif (length < 128) {\n\t\tthrow new Error('Non-minimal DER length encoding');\n\t}\n\treturn { headerLength: 2 + octets, length };\n}\n\nfunction readLongFormDerLength(bytes: Uint8Array, offset: number, octets: number): number {\n\tlet length = 0;\n\tfor (let index = 0; index < octets; index += 1) {\n\t\tconst next = bytes[offset + 2 + index];\n\t\tif (next === undefined) {\n\t\t\tthrow new Error('Unexpected end of DER input');\n\t\t}\n\t\tif (length > Math.floor((Number.MAX_SAFE_INTEGER - next) / 256)) {\n\t\t\tthrow new Error('DER length exceeds safe integer range');\n\t\t}\n\t\tlength = length * 256 + next;\n\t}\n\treturn length;\n}\n\n/**\n * Walks the full DER tree rooted in {@linkcode bytes}.\n *\n * Constructed tags with content that cannot be parsed as valid children are tolerated when listed in {@linkcode options | allowOpaqueConstructedTags}.\n *\n * @throws if nesting exceeds {@linkcode maxDepth}.\n */\nexport function assertDerMaxDepth(\n\tbytes: Uint8Array,\n\tmaxDepth: number = DEFAULT_MAX_DER_DEPTH,\n\toptions?: {\n\t\t/** Constructed tags whose inner bytes may not parse as valid TLV children. */\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): void {\n\tif (!Number.isSafeInteger(maxDepth) || maxDepth < 1) {\n\t\tthrow new Error('DER max depth must be a positive safe integer');\n\t}\n\tconst root = readElement(bytes, 0);\n\tif (root.end !== bytes.length) {\n\t\tthrow new Error('Trailing data after DER element');\n\t}\n\tconst stack: {\n\t\treadonly element: DerElement;\n\t\treadonly depth: number;\n\t}[] = [{ element: root, depth: 1 }];\n\twhile (stack.length > 0) {\n\t\tconst current = stack.pop();\n\t\tif (current === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.depth > maxDepth) {\n\t\t\tthrow new Error(`DER exceeds max depth of ${maxDepth}`);\n\t\t}\n\t\tif ((current.element.tag & 0x20) === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tpushDerChildren(bytes, current, stack, options);\n\t}\n}\n\nfunction pushDerChildren(\n\tbytes: Uint8Array,\n\tcurrent: { readonly element: DerElement; readonly depth: number },\n\tstack: { readonly element: DerElement; readonly depth: number }[],\n\toptions?: {\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): void {\n\tlet offset = current.element.start;\n\tlet treatedAsOpaqueLeaf = false;\n\twhile (offset < current.element.end) {\n\t\tconst child = readDerChildOrOpaque(bytes, current.element, offset, options);\n\t\tif (child === undefined) {\n\t\t\ttreatedAsOpaqueLeaf = true;\n\t\t\toffset = current.element.end;\n\t\t\tbreak;\n\t\t}\n\t\tstack.push({ element: child, depth: current.depth + 1 });\n\t\toffset = child.end;\n\t}\n\tif (!treatedAsOpaqueLeaf && offset !== current.element.end) {\n\t\tthrow new Error('Malformed DER container');\n\t}\n}\n\nfunction readDerChildOrOpaque(\n\tbytes: Uint8Array,\n\tparent: DerElement,\n\toffset: number,\n\toptions?: {\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): DerElement | undefined {\n\tlet child: DerElement;\n\ttry {\n\t\tchild = readElement(bytes, offset);\n\t} catch (error) {\n\t\tif (canTreatAsOpaqueLeaf(parent, offset, options)) return undefined;\n\t\tthrow error;\n\t}\n\tif (child.end <= parent.end) {\n\t\treturn child;\n\t}\n\tif (canTreatAsOpaqueLeaf(parent, offset, options)) return undefined;\n\tthrow new Error('DER child exceeds parent length');\n}\n\n/**\n * Reads the single top-level TLV element from {@linkcode bytes}.\n *\n * Optionally validates nesting depth.\n *\n * @throws if there is trailing data after the element.\n */\nexport function readRootElement(bytes: Uint8Array, options?: ReadRootElementOptions): DerElement {\n\tconst maxDepth = options?.maxDepth ?? DEFAULT_MAX_DER_DEPTH;\n\tassertDerMaxDepth(bytes, maxDepth, options);\n\tconst element = readElement(bytes, 0);\n\tif (element.end !== bytes.length) {\n\t\tthrow new Error('Trailing data after DER element');\n\t}\n\treturn element;\n}\n\n/**\n * Reads a DER-encoded SEQUENCE from {@linkcode bytes} and returns its direct children.\n *\n * @throws if the root element is not a SEQUENCE or if child boundaries are inconsistent.\n */\nexport function readSequenceChildren(\n\tbytes: Uint8Array,\n\toptions?: ReadSequenceChildrenOptions,\n): DerElement[] {\n\tconst sequenceElement = readRootElement(bytes, options);\n\tif (sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('Expected SEQUENCE');\n\t}\n\n\tconst children: DerElement[] = [];\n\tlet offset = sequenceElement.start;\n\twhile (offset < sequenceElement.end) {\n\t\tconst element = readElement(bytes, offset);\n\t\tif (element.end > sequenceElement.end) {\n\t\t\tthrow new Error('DER child exceeds parent length');\n\t\t}\n\t\tchildren.push(element);\n\t\toffset = element.end;\n\t}\n\tif (offset !== sequenceElement.end) {\n\t\tthrow new Error('Malformed DER sequence');\n\t}\n\treturn children;\n}\n\n/** @throws if {@linkcode value} is not a non-negative safe integer. */\nfunction assertNonNegativeSafeInteger(value: number, label: string): void {\n\tif (!Number.isSafeInteger(value) || value < 0) {\n\t\tthrow new Error(`${label} must be a non-negative safe integer`);\n\t}\n}\n\nfunction assertSingleOctetDerTag(tag: number): void {\n\tif (!Number.isSafeInteger(tag) || tag < 0 || tag > 0xff) {\n\t\tthrow new RangeError('DER tag octet must be between 0 and 255');\n\t}\n\tif ((tag & 0x1f) === 0x1f) {\n\t\tthrow new Error('High-tag-number DER tags are not supported');\n\t}\n}\n\nfunction assertContextSpecificTagNumber(tag: number): void {\n\tif (!Number.isSafeInteger(tag) || tag < 0 || tag >= 31) {\n\t\tthrow new RangeError('Context-specific tag number must be between 0 and 30');\n\t}\n}\n\nfunction assertValidDate(date: Date, label: 'UTCTime' | 'GeneralizedTime'): void {\n\tif (Number.isNaN(date.getTime())) {\n\t\tthrow new RangeError(`${label} requires a valid Date`);\n\t}\n}\n\n/**\n * @returns `true` when a constructed element's content should be treated as an opaque leaf (not recursed into)\n * because its tag appears in the {@linkcode options | allowOpaqueConstructedTags} list and the offset is at the element start.\n */\nfunction canTreatAsOpaqueLeaf(\n\telement: DerElement,\n\toffset: number,\n\toptions?: {\n\t\t/** Constructed tags whose inner bytes may not parse as valid TLV children. */\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): boolean {\n\treturn (\n\t\toffset === element.start && options?.allowOpaqueConstructedTags?.includes(element.tag) === true\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,IAAwB;;;;;;;AAQrC,SAAgB,aAAa,GAA4B;CAExD,IADA,6BAA6B,GAAQ,YAAY,GAC7C,IAAS,KACZ,OAAO,WAAW,GAAG,CAAM;CAG5B,IAAM,IAAQ,cAAc,CAAM;CAClC,OAAO,WAAW,GAAG,MAAO,EAAM,QAAQ,GAAG,CAAK;AACnD;;AAGA,SAAgB,YAAY,GAA0C;CACrE,IAAM,IAAS,EAAM,QAAQ,GAAK,MAAS,IAAM,EAAK,QAAQ,CAAC,GACzD,IAAM,IAAI,WAAW,CAAM,GAC7B,IAAS;CACb,KAAK,IAAM,KAAQ,GAElB,AADA,EAAI,IAAI,GAAM,CAAM,GACpB,KAAU,EAAK;CAEhB,OAAO;AACR;;;;;;;;AASA,S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M,wBAAwB;CAEzC,OAAO;AACR;;AAGA,SAAS,6BAA6B,GAAe,GAAqB;CACzE,IAAI,CAAC,OAAO,cAAc,CAAK,KAAK,IAAQ,GAC3C,MAAU,MAAM,GAAG,EAAM,qCAAqC;AAEhE;AAEA,SAAS,wBAAwB,GAAmB;CACnD,IAAI,CAAC,OAAO,cAAc,CAAG,KAAK,IAAM,KAAK,IAAM,KAClD,MAAU,WAAW,yCAAyC;CAE/D,KAAK,IAAM,OAAU,IACpB,MAAU,MAAM,4CAA4C;AAE9D;AAEA,SAAS,+BAA+B,GAAmB;CAC1D,IAAI,CAAC,OAAO,cAAc,CAAG,KAAK,IAAM,KAAK,KAAO,IACnD,MAAU,WAAW,sDAAsD;AAE7E;AAEA,SAAS,gBAAgB,GAAY,GAA4C;CAChF,IAAI,OAAO,MAAM,EAAK,QAAQ,CAAC,GAC9B,MAAU,WAAW,GAAG,EAAM,uBAAuB;AAEvD;;;;;AAMA,SAAS,qBACR,GACA,GACA,GAIU;CACV,OACC,MAAW,EAAQ,SAAS,GAAS,4BAA4B,SAAS,EAAQ,GAAG,MAAM;AAE7F"}
1
+ {"version":3,"file":"der.js","names":[],"sources":["../../../src/internal/asn1/der.ts"],"sourcesContent":["/**\n * Low-level DER encoding and reading helpers shared across the library.\n *\n * These utilities build and traverse ASN.1 TLV (tag-length-value) structures.\n *\n * @module\n */\n\n/**\n * Maximum nesting depth allowed when recursively walking a DER structure.\n *\n * Guards against stack exhaustion from pathologically nested input.\n */\nexport const DEFAULT_MAX_DER_DEPTH = 64;\n\n/**\n * Produces the DER length octets for a given byte count.\n *\n * Values < 128 use the short form (one octet);\n * larger values use the long form (leading octet encodes the number of subsequent length bytes).\n */\nexport function encodeLength(length: number): Uint8Array {\n\tassertNonNegativeSafeInteger(length, 'DER length');\n\tif (length < 128) {\n\t\treturn Uint8Array.of(length);\n\t}\n\n\tconst parts = encodeBase256(length);\n\treturn Uint8Array.of(0x80 | parts.length, ...parts);\n}\n\n/** Concatenates multiple byte arrays into a single {@linkcode Uint8Array}. */\nexport function concatBytes(parts: readonly Uint8Array[]): Uint8Array {\n\tconst length = parts.reduce((sum, part) => sum + part.length, 0);\n\tconst out = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const part of parts) {\n\t\tout.set(part, offset);\n\t\toffset += part.length;\n\t}\n\treturn out;\n}\n\n/** Compares two optional byte arrays; two absent values are equal. */\nexport function optionalBytesEqual(\n\tleft: Uint8Array | undefined,\n\tright: Uint8Array | undefined,\n): boolean {\n\tif (left === undefined || right === undefined) {\n\t\treturn left === right;\n\t}\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tif (left[index] !== right[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * Builds a complete DER TLV (tag-length-value) element:\n *\n * - one tag octet,\n * - the DER-encoded length, then\n * - the raw value bytes.\n */\nexport function tlv(tag: number, value: Uint8Array): Uint8Array {\n\tassertSingleOctetDerTag(tag);\n\treturn concatBytes([Uint8Array.of(tag), encodeLength(value.length), value]);\n}\n\n/** Wraps concatenated children in a SEQUENCE (tag `0x30`). */\nexport function sequence(parts: readonly Uint8Array[]): Uint8Array {\n\treturn tlv(0x30, concatBytes(parts));\n}\n\n/**\n * Wraps children in a SET (tag `0x31`) after DER-sorting them lexicographically by encoded bytes,\n * as required by {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690} DER.\n */\nexport function setOf(parts: readonly Uint8Array[]): Uint8Array {\n\tconst sorted = parts.slice().sort((a, b) => {\n\t\tconst len = Math.min(a.length, b.length);\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tconst diff = (a[i] ?? 0) - (b[i] ?? 0);\n\t\t\tif (diff !== 0) return diff;\n\t\t}\n\t\treturn a.length - b.length;\n\t});\n\treturn tlv(0x31, concatBytes(sorted));\n}\n\n/**\n * Wraps a value in an explicit context-specific constructed tag (`0xa0 + tag`).\n *\n * Used for optional SEQUENCE fields tagged with `[tag] EXPLICIT`.\n */\nexport function explicitContext(tag: number, value: Uint8Array): Uint8Array {\n\tassertContextSpecificTagNumber(tag);\n\treturn tlv(0xa0 + tag, value);\n}\n\n/**\n * Wraps a value in an implicit context-specific constructed tag (`0xa0 + tag`).\n *\n * Used for `[tag] IMPLICIT` fields whose underlying type is constructed (e.g. SEQUENCE).\n */\nexport function implicitConstructedContext(tag: number, value: Uint8Array): Uint8Array {\n\tassertContextSpecificTagNumber(tag);\n\treturn tlv(0xa0 + tag, value);\n}\n\n/**\n * Wraps a value in an implicit context-specific primitive tag (`0x80 + tag`).\n *\n * Used for `[tag] IMPLICIT` fields whose underlying type is primitive (e.g. OCTET STRING).\n */\nexport function implicitPrimitiveContext(tag: number, value: Uint8Array): Uint8Array {\n\tassertContextSpecificTagNumber(tag);\n\treturn tlv(0x80 + tag, value);\n}\n\n/**\n * Encodes raw big-endian bytes as a DER INTEGER (tag `0x02`).\n *\n * Strips leading zero bytes for minimal encoding and prepends a zero byte when the high bit is set\n * to keep the value non-negative.\n */\nexport function integer(bytes: Uint8Array): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn tlv(0x02, Uint8Array.of(0));\n\t}\n\n\tlet start = 0;\n\twhile (start < bytes.length - 1 && bytes[start] === 0) {\n\t\tstart += 1;\n\t}\n\n\tconst value = bytes.slice(start);\n\tif ((value[0] ?? 0) >= 0x80) {\n\t\treturn tlv(0x02, concatBytes([Uint8Array.of(0), value]));\n\t}\n\n\treturn tlv(0x02, value);\n}\n\n/**\n * Encodes a non-negative JavaScript `number` as a DER INTEGER.\n *\n * @throws if the value is not a non-negative safe integer.\n */\nexport function integerFromNumber(value: number): Uint8Array {\n\tif (!Number.isSafeInteger(value) || value < 0) {\n\t\tthrow new Error('INTEGER must be a non-negative safe integer');\n\t}\n\n\tif (value === 0) {\n\t\treturn integer(Uint8Array.of(0));\n\t}\n\n\treturn integer(Uint8Array.from(encodeBase256(value)));\n}\n\n/** Encodes a DER BOOLEAN (tag `0x01`): `true` → `0xff`, `false` → `0x00`. */\nexport function bool(value: boolean): Uint8Array {\n\treturn tlv(0x01, Uint8Array.of(value ? 0xff : 0x00));\n}\n\n/** Produces a DER NULL element (tag `0x05`, zero-length value). */\nexport function nullValue(): Uint8Array {\n\treturn tlv(0x05, new Uint8Array());\n}\n\n/** Wraps raw bytes in an OCTET STRING element (tag `0x04`). */\nexport function octetString(value: Uint8Array): Uint8Array {\n\treturn tlv(0x04, value);\n}\n\n/**\n * Encodes a DER BIT STRING (tag `0x03`).\n *\n * The value is prefixed with a single octet indicating how many trailing bits in the last byte are unused.\n *\n * @param unusedBits Number of unused trailing bits (0–7). Defaults to 0.\n */\nexport function bitString(value: Uint8Array, unusedBits = 0): Uint8Array {\n\tif (unusedBits < 0 || unusedBits > 7) {\n\t\tthrow new Error('unusedBits must be between 0 and 7');\n\t}\n\tif (value.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('unusedBits must be 0 when value is empty');\n\t}\n\tif (value.length > 0 && unusedBits > 0) {\n\t\tconst lastByte = value[value.length - 1] ?? 0;\n\t\tif ((lastByte & ((1 << unusedBits) - 1)) !== 0) {\n\t\t\tthrow new Error('unused bits in the last byte must be zero');\n\t\t}\n\t}\n\treturn tlv(0x03, concatBytes([Uint8Array.of(unusedBits), value]));\n}\n\n/** Encodes a DER UTF8String (tag `0x0c`). */\nexport function utf8String(value: string): Uint8Array {\n\treturn tlv(0x0c, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a DER PrintableString (tag `0x13`).\n *\n * @throws if the input contains characters outside the ITU-T X.680 §41.4 Table 10 PrintableString set.\n */\nexport function printableString(value: string): Uint8Array {\n\tif (!/^[A-Za-z0-9 '()+,\\-./:=?]*$/.test(value)) {\n\t\tthrow new Error('Invalid PrintableString: contains characters outside the allowed set');\n\t}\n\treturn tlv(0x13, new TextEncoder().encode(value));\n}\n\n/** Validates a string is ASCII (IA5) and returns its content bytes, without a tag. */\nexport function ia5Bytes(value: string): Uint8Array {\n\tfor (let i = 0; i < value.length; i++) {\n\t\tif (value.charCodeAt(i) > 0x7f) {\n\t\t\tthrow new Error('Invalid IA5String: contains non-ASCII characters');\n\t\t}\n\t}\n\treturn new TextEncoder().encode(value);\n}\n\n/**\n * Encodes a DER IA5String (tag `0x16`).\n *\n * @throws if the input contains any non-ASCII character (code point > 0x7f).\n */\nexport function ia5String(value: string): Uint8Array {\n\treturn tlv(0x16, ia5Bytes(value));\n}\n\n/**\n * Encodes a DER BMPString (tag `0x1e`) as big-endian UTF-16.\n *\n * @throws on lone surrogates and on code points above the Basic Multilingual Plane.\n */\nexport function bmpString(value: string): Uint8Array {\n\tconst units: number[] = [];\n\tfor (const character of value) {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\tif (codePoint > 0xffff) {\n\t\t\tthrow new Error('Invalid BMPString: code point above the Basic Multilingual Plane');\n\t\t}\n\t\tif (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n\t\t\tthrow new Error('Invalid BMPString: lone surrogate');\n\t\t}\n\t\tunits.push((codePoint >> 8) & 0xff, codePoint & 0xff);\n\t}\n\treturn tlv(0x1e, Uint8Array.from(units));\n}\n\n/**\n * Encodes a DER UniversalString (tag `0x1c`) as big-endian UTF-32.\n *\n * @throws on lone surrogates.\n */\nexport function universalString(value: string): Uint8Array {\n\tconst bytes: number[] = [];\n\tfor (const character of value) {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\tif (codePoint >= 0xd800 && codePoint <= 0xdfff) {\n\t\t\tthrow new Error('Invalid UniversalString: lone surrogate');\n\t\t}\n\t\tbytes.push(\n\t\t\t(codePoint >> 24) & 0xff,\n\t\t\t(codePoint >> 16) & 0xff,\n\t\t\t(codePoint >> 8) & 0xff,\n\t\t\tcodePoint & 0xff,\n\t\t);\n\t}\n\treturn tlv(0x1c, Uint8Array.from(bytes));\n}\n\n/** Encode a non-negative integer as a base-128 sub-identifier ({@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §8.19.2}). */\nfunction encodeBase128(value: bigint): number[] {\n\tconst encoded: number[] = [Number(value & 0x7fn)];\n\tlet current = value >> 7n;\n\twhile (current > 0n) {\n\t\tencoded.unshift(0x80 | Number(current & 0x7fn));\n\t\tcurrent >>= 7n;\n\t}\n\treturn encoded;\n}\n\n/**\n * Encodes a dotted-decimal OID string as a DER OBJECT IDENTIFIER (tag `0x06`).\n *\n * Validates arc constraints per X.660 §7.6: the root arc must be 0–2, and under\n * roots 0 and 1 the second arc must be 0–39. X.690 §8.19.4 defines the `(X*40)+Y`\n * packing of the first two arcs into one subidentifier.\\\n * Sub-identifiers are encoded with base-128 continuation.\n */\nexport function objectIdentifier(oid: string): Uint8Array {\n\tconst digitPattern = /^\\d+$/;\n\tconst segments = oid.split('.').map((segment) => {\n\t\tif (!digitPattern.test(segment)) {\n\t\t\tthrow new Error(`Invalid OID segment: ${segment}`);\n\t\t}\n\t\treturn BigInt(segment);\n\t});\n\tif (segments.length < 2) {\n\t\tthrow new Error(`Invalid OID: ${oid}`);\n\t}\n\n\tconst [first, second, ...rest] = segments;\n\tif (first === undefined || second === undefined) {\n\t\tthrow new Error(`Invalid OID: ${oid}`);\n\t}\n\tif (first !== 0n && first !== 1n && first !== 2n) {\n\t\tthrow new Error(`Invalid OID first arc: ${first}`);\n\t}\n\tif ((first === 0n || first === 1n) && second >= 40n) {\n\t\tthrow new Error(`Invalid OID second arc: ${second} (must be < 40 when first arc is ${first})`);\n\t}\n\tconst bytes: number[] = encodeBase128(first * 40n + second);\n\tfor (const segment of rest) {\n\t\tbytes.push(...encodeBase128(segment));\n\t}\n\n\treturn tlv(0x06, Uint8Array.from(bytes));\n}\n\n/**\n * Encodes a `Date` as a DER UTCTime (tag `0x17`), format `YYMMDDHHMMSSZ`.\n *\n * Only the two-digit year is stored; suitable for dates in 1950–2049.\n */\nexport function utcTime(date: Date): Uint8Array {\n\tassertValidDate(date, 'UTCTime');\n\tconst year = date.getUTCFullYear();\n\tif (year < 1950 || year > 2049) {\n\t\tthrow new RangeError('UTCTime year must be between 1950 and 2049');\n\t}\n\tconst value = `${[\n\t\ttwoDigits(year % 100),\n\t\ttwoDigits(date.getUTCMonth() + 1),\n\t\ttwoDigits(date.getUTCDate()),\n\t\ttwoDigits(date.getUTCHours()),\n\t\ttwoDigits(date.getUTCMinutes()),\n\t\ttwoDigits(date.getUTCSeconds()),\n\t].join('')}Z`;\n\treturn tlv(0x17, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a {@linkcode Date} as a DER GeneralizedTime (tag `0x18`), format `YYYYMMDDHHMMSSZ`.\n *\n * Uses a four-digit year; required for dates outside the 1950–2049 range.\n */\nexport function generalizedTime(date: Date): Uint8Array {\n\tassertValidDate(date, 'GeneralizedTime');\n\tconst year = date.getUTCFullYear();\n\tif (year < 0 || year > 9999) {\n\t\tthrow new RangeError('GeneralizedTime year must be between 0 and 9999');\n\t}\n\tconst value = `${[\n\t\tString(year).padStart(4, '0'),\n\t\ttwoDigits(date.getUTCMonth() + 1),\n\t\ttwoDigits(date.getUTCDate()),\n\t\ttwoDigits(date.getUTCHours()),\n\t\ttwoDigits(date.getUTCMinutes()),\n\t\ttwoDigits(date.getUTCSeconds()),\n\t].join('')}Z`;\n\treturn tlv(0x18, new TextEncoder().encode(value));\n}\n\n/**\n * Encodes a {@linkcode Date} as the appropriate DER time type per RFC 5280.\n *\n * - {@linkcode utcTime} for 1950–2049\n * - {@linkcode generalizedTime} otherwise\n */\nexport function time(date: Date): Uint8Array {\n\tif (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) {\n\t\treturn generalizedTime(date);\n\t}\n\treturn utcTime(date);\n}\n\n/** Zero-pads a number to two digits for time encoding. */\nfunction twoDigits(value: number): string {\n\treturn String(value).padStart(2, '0');\n}\n\n/** Encodes a non-negative integer as big-endian base-256 octets. */\nfunction encodeBase256(value: number): readonly number[] {\n\tassertNonNegativeSafeInteger(value, 'DER integer');\n\tconst parts: number[] = [];\n\tlet current = value;\n\twhile (current > 0) {\n\t\tparts.unshift(current & 0xff);\n\t\tcurrent = Math.floor(current / 256);\n\t}\n\treturn parts;\n}\n\n/** A single parsed ASN.1 TLV element with byte-range metadata. */\nexport interface DerElement {\n\t/** ASN.1 tag byte (e.g. `0x30` for SEQUENCE, `0x02` for INTEGER). */\n\treadonly tag: number;\n\t/** Number of bytes occupied by the tag + length octets. */\n\treadonly headerLength: number;\n\t/** Byte length of the value portion (excluding tag and length octets). */\n\treadonly length: number;\n\t/** Byte offset where the value portion begins in the source buffer. */\n\treadonly start: number;\n\t/** Byte offset one past the last value byte. Equals the next element's header offset. */\n\treadonly end: number;\n\t/** The raw value bytes (slice of the source buffer). */\n\treadonly value: Uint8Array;\n}\n\n/** Options for {@linkcode readSequenceChildren}. */\nexport interface ReadSequenceChildrenOptions {\n\t/** Maximum nesting depth for the DER depth check. @default {@linkcode DEFAULT_MAX_DER_DEPTH}. */\n\treadonly maxDepth?: number;\n\t/** Constructed tags whose inner bytes may not parse as valid TLV children (e.g. opaque extension values). */\n\treadonly allowOpaqueConstructedTags?: readonly number[];\n}\n\n/** Options for {@linkcode readRootElement}. */\nexport interface ReadRootElementOptions {\n\t/** Maximum nesting depth for the DER depth check. @default {@linkcode DEFAULT_MAX_DER_DEPTH}. */\n\treadonly maxDepth?: number;\n\t/** Constructed tags whose inner bytes may not parse as valid TLV children (e.g. opaque extension values). */\n\treadonly allowOpaqueConstructedTags?: readonly number[];\n}\n\n/**\n * Reads one TLV element from {@linkcode bytes} starting at {@linkcode offset}.\n *\n * Parses the tag byte, decodes the DER length octets, and slices out the value bytes.\n *\n * @throws on truncated input, indefinite lengths, and non-minimal length encodings.\n * @param offset Byte position of the tag octet. Defaults to 0.\n */\nexport function readElement(bytes: Uint8Array, offset = 0): DerElement {\n\tconst tag = bytes[offset];\n\tif (tag === undefined) {\n\t\tthrow new Error('Unexpected end of DER input');\n\t}\n\tif ((tag & 0x1f) === 0x1f) {\n\t\tthrow new Error('High-tag-number DER form is not supported');\n\t}\n\tconst lengthByte = bytes[offset + 1];\n\tif (lengthByte === undefined) {\n\t\tthrow new Error('Unexpected end of DER input');\n\t}\n\n\tconst { headerLength, length } = readDerLength(bytes, offset, lengthByte);\n\n\tconst start = offset + headerLength;\n\tconst end = start + length;\n\tif (end > bytes.length) {\n\t\tthrow new Error('DER element exceeds input length');\n\t}\n\n\treturn {\n\t\ttag,\n\t\theaderLength,\n\t\tlength,\n\t\tstart,\n\t\tend,\n\t\tvalue: bytes.slice(start, end),\n\t};\n}\n\n/** Decodes and validates the definite-length field of a DER element. */\nfunction readDerLength(\n\tbytes: Uint8Array,\n\toffset: number,\n\tlengthByte: number,\n): { readonly headerLength: number; readonly length: number } {\n\tif ((lengthByte & 0x80) === 0) {\n\t\treturn { headerLength: 2, length: lengthByte };\n\t}\n\tconst octets = lengthByte & 0x7f;\n\tif (octets === 0) {\n\t\tthrow new Error('Indefinite lengths are not supported');\n\t}\n\tconst firstLengthOctet = bytes[offset + 2];\n\tif (firstLengthOctet === undefined) {\n\t\tthrow new Error('Unexpected end of DER input');\n\t}\n\tif (firstLengthOctet === 0) {\n\t\tthrow new Error('Non-minimal DER length encoding');\n\t}\n\tconst length = readLongFormDerLength(bytes, offset, octets);\n\tif (length < 128) {\n\t\tthrow new Error('Non-minimal DER length encoding');\n\t}\n\treturn { headerLength: 2 + octets, length };\n}\n\nfunction readLongFormDerLength(bytes: Uint8Array, offset: number, octets: number): number {\n\tlet length = 0;\n\tfor (let index = 0; index < octets; index += 1) {\n\t\tconst next = bytes[offset + 2 + index];\n\t\tif (next === undefined) {\n\t\t\tthrow new Error('Unexpected end of DER input');\n\t\t}\n\t\tif (length > Math.floor((Number.MAX_SAFE_INTEGER - next) / 256)) {\n\t\t\tthrow new Error('DER length exceeds safe integer range');\n\t\t}\n\t\tlength = length * 256 + next;\n\t}\n\treturn length;\n}\n\n/**\n * Walks the full DER tree rooted in {@linkcode bytes}.\n *\n * Constructed tags with content that cannot be parsed as valid children are tolerated when listed in {@linkcode options | allowOpaqueConstructedTags}.\n *\n * @throws if nesting exceeds {@linkcode maxDepth}.\n */\nexport function assertDerMaxDepth(\n\tbytes: Uint8Array,\n\tmaxDepth: number = DEFAULT_MAX_DER_DEPTH,\n\toptions?: {\n\t\t/** Constructed tags whose inner bytes may not parse as valid TLV children. */\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): void {\n\tif (!Number.isSafeInteger(maxDepth) || maxDepth < 1) {\n\t\tthrow new Error('DER max depth must be a positive safe integer');\n\t}\n\tconst root = readElement(bytes, 0);\n\tif (root.end !== bytes.length) {\n\t\tthrow new Error('Trailing data after DER element');\n\t}\n\tconst stack: {\n\t\treadonly element: DerElement;\n\t\treadonly depth: number;\n\t}[] = [{ element: root, depth: 1 }];\n\twhile (stack.length > 0) {\n\t\tconst current = stack.pop();\n\t\tif (current === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.depth > maxDepth) {\n\t\t\tthrow new Error(`DER exceeds max depth of ${maxDepth}`);\n\t\t}\n\t\tif ((current.element.tag & 0x20) === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tpushDerChildren(bytes, current, stack, options);\n\t}\n}\n\nfunction pushDerChildren(\n\tbytes: Uint8Array,\n\tcurrent: { readonly element: DerElement; readonly depth: number },\n\tstack: { readonly element: DerElement; readonly depth: number }[],\n\toptions?: {\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): void {\n\tlet offset = current.element.start;\n\tlet treatedAsOpaqueLeaf = false;\n\twhile (offset < current.element.end) {\n\t\tconst child = readDerChildOrOpaque(bytes, current.element, offset, options);\n\t\tif (child === undefined) {\n\t\t\ttreatedAsOpaqueLeaf = true;\n\t\t\toffset = current.element.end;\n\t\t\tbreak;\n\t\t}\n\t\tstack.push({ element: child, depth: current.depth + 1 });\n\t\toffset = child.end;\n\t}\n\tif (!treatedAsOpaqueLeaf && offset !== current.element.end) {\n\t\tthrow new Error('Malformed DER container');\n\t}\n}\n\nfunction readDerChildOrOpaque(\n\tbytes: Uint8Array,\n\tparent: DerElement,\n\toffset: number,\n\toptions?: {\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): DerElement | undefined {\n\tlet child: DerElement;\n\ttry {\n\t\tchild = readElement(bytes, offset);\n\t} catch (error) {\n\t\tif (canTreatAsOpaqueLeaf(parent, offset, options)) return undefined;\n\t\tthrow error;\n\t}\n\tif (child.end <= parent.end) {\n\t\treturn child;\n\t}\n\tif (canTreatAsOpaqueLeaf(parent, offset, options)) return undefined;\n\tthrow new Error('DER child exceeds parent length');\n}\n\n/**\n * Reads the single top-level TLV element from {@linkcode bytes}.\n *\n * Optionally validates nesting depth.\n *\n * @throws if there is trailing data after the element.\n */\nexport function readRootElement(bytes: Uint8Array, options?: ReadRootElementOptions): DerElement {\n\tconst maxDepth = options?.maxDepth ?? DEFAULT_MAX_DER_DEPTH;\n\tassertDerMaxDepth(bytes, maxDepth, options);\n\tconst element = readElement(bytes, 0);\n\tif (element.end !== bytes.length) {\n\t\tthrow new Error('Trailing data after DER element');\n\t}\n\treturn element;\n}\n\n/**\n * Reads a DER-encoded SEQUENCE from {@linkcode bytes} and returns its direct children.\n *\n * @throws if the root element is not a SEQUENCE or if child boundaries are inconsistent.\n */\nexport function readSequenceChildren(\n\tbytes: Uint8Array,\n\toptions?: ReadSequenceChildrenOptions,\n): DerElement[] {\n\tconst sequenceElement = readRootElement(bytes, options);\n\tif (sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('Expected SEQUENCE');\n\t}\n\n\tconst children: DerElement[] = [];\n\tlet offset = sequenceElement.start;\n\twhile (offset < sequenceElement.end) {\n\t\tconst element = readElement(bytes, offset);\n\t\tif (element.end > sequenceElement.end) {\n\t\t\tthrow new Error('DER child exceeds parent length');\n\t\t}\n\t\tchildren.push(element);\n\t\toffset = element.end;\n\t}\n\tif (offset !== sequenceElement.end) {\n\t\tthrow new Error('Malformed DER sequence');\n\t}\n\treturn children;\n}\n\n/** @throws if {@linkcode value} is not a non-negative safe integer. */\nfunction assertNonNegativeSafeInteger(value: number, label: string): void {\n\tif (!Number.isSafeInteger(value) || value < 0) {\n\t\tthrow new Error(`${label} must be a non-negative safe integer`);\n\t}\n}\n\nfunction assertSingleOctetDerTag(tag: number): void {\n\tif (!Number.isSafeInteger(tag) || tag < 0 || tag > 0xff) {\n\t\tthrow new RangeError('DER tag octet must be between 0 and 255');\n\t}\n\tif ((tag & 0x1f) === 0x1f) {\n\t\tthrow new Error('High-tag-number DER tags are not supported');\n\t}\n}\n\nfunction assertContextSpecificTagNumber(tag: number): void {\n\tif (!Number.isSafeInteger(tag) || tag < 0 || tag >= 31) {\n\t\tthrow new RangeError('Context-specific tag number must be between 0 and 30');\n\t}\n}\n\nfunction assertValidDate(date: Date, label: 'UTCTime' | 'GeneralizedTime'): void {\n\tif (Number.isNaN(date.getTime())) {\n\t\tthrow new RangeError(`${label} requires a valid Date`);\n\t}\n}\n\n/**\n * @returns `true` when a constructed element's content should be treated as an opaque leaf (not recursed into)\n * because its tag appears in the {@linkcode options | allowOpaqueConstructedTags} list and the offset is at the element start.\n */\nfunction canTreatAsOpaqueLeaf(\n\telement: DerElement,\n\toffset: number,\n\toptions?: {\n\t\t/** Constructed tags whose inner bytes may not parse as valid TLV children. */\n\t\treadonly allowOpaqueConstructedTags?: readonly number[];\n\t},\n): boolean {\n\treturn (\n\t\toffset === element.start && options?.allowOpaqueConstructedTags?.includes(element.tag) === true\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,IAAwB;;;;;;;AAQrC,SAAgB,aAAa,GAA4B;CAExD,IADA,6BAA6B,GAAQ,YAAY,GAC7C,IAAS,KACZ,OAAO,WAAW,GAAG,CAAM;CAG5B,IAAM,IAAQ,cAAc,CAAM;CAClC,OAAO,WAAW,GAAG,MAAO,EAAM,QAAQ,GAAG,CAAK;AACnD;;AAGA,SAAgB,YAAY,GAA0C;CACrE,IAAM,IAAS,EAAM,QAAQ,GAAK,MAAS,IAAM,E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152
152
  arc: "101",
153
- oids: { ed25519: "112" }
153
+ oids: {
154
+ x25519: "110",
155
+ x448: "111",
156
+ ed25519: "112",
157
+ ed448: "113"
158
+ }
154
159
  },
155
160
  dod: {
156
161
  arc: "6",
@@ -252,6 +257,7 @@ var e = {
252
257
  subjectKeyIdentifier: "14",
253
258
  keyUsage: "15",
254
259
  subjectAltName: "17",
260
+ issuerAltName: "18",
255
261
  basicConstraints: "19",
256
262
  cRLNumber: "20",
257
263
  cRLReason: "21",
@@ -36,6 +36,7 @@ function describeSignatureAlgorithm(n, r) {
36
36
  case e.ecdsaWithSHA384: return "ECDSA with SHA-384";
37
37
  case e.ecdsaWithSHA512: return "ECDSA with SHA-512";
38
38
  case e.ed25519: return "Ed25519";
39
+ case e.ed448: return "Ed448";
39
40
  default: return `Unknown (${n})`;
40
41
  }
41
42
  }
@@ -50,7 +51,10 @@ function describePublicKeyAlgorithm(t, n) {
50
51
  case e.secp521r1: return "EC P-521";
51
52
  default: return "EC";
52
53
  }
54
+ case e.x25519: return "X25519";
55
+ case e.x448: return "X448";
53
56
  case e.ed25519: return "Ed25519";
57
+ case e.ed448: return "Ed448";
54
58
  default: return `Unknown (${t})`;
55
59
  }
56
60
  }
@@ -1 +1 @@
1
- {"version":3,"file":"algorithm-names.js","names":[],"sources":["../../../src/internal/crypto/algorithm-names.ts"],"sourcesContent":["/**\n * Human-readable algorithm labels for parsed OIDs.\n *\n * Shared by certificate, revocation, and PKCS parse surfaces so callers can\n * display meaningful algorithm names without memorizing dotted-decimal OIDs.\n *\n * @module\n */\n\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\n\n/** Convert a hash or message-digest OID into a human-readable name. */\nexport function describeHashAlgorithm(oid: string): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1:\n\t\t\treturn 'SHA-1';\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tcase OIDS.sha384:\n\t\t\treturn 'SHA-384';\n\t\tcase OIDS.sha512:\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a signature AlgorithmIdentifier into a human-readable name. */\nexport function describeSignatureAlgorithm(\n\toid: string,\n\tparametersDer: Uint8Array | undefined,\n): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-1';\n\t\tcase OIDS.sha256WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-256';\n\t\tcase OIDS.sha384WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-384';\n\t\tcase OIDS.sha512WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-512';\n\t\tcase OIDS.rsassaPss: {\n\t\t\tconst parsed = parseRsaPssParameters(parametersDer);\n\t\t\treturn parsed.ok ? `RSA-PSS with ${parsed.value.hash}` : 'RSA-PSS';\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA1:\n\t\t\treturn 'ECDSA with SHA-1';\n\t\tcase OIDS.ecdsaWithSHA224:\n\t\t\treturn 'ECDSA with SHA-224';\n\t\tcase OIDS.ecdsaWithSHA256:\n\t\t\treturn 'ECDSA with SHA-256';\n\t\tcase OIDS.ecdsaWithSHA384:\n\t\t\treturn 'ECDSA with SHA-384';\n\t\tcase OIDS.ecdsaWithSHA512:\n\t\t\treturn 'ECDSA with SHA-512';\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a SubjectPublicKeyInfo algorithm identifier into a human-readable name. */\nexport function describePublicKeyAlgorithm(oid: string, parametersOid: string | undefined): string {\n\tswitch (oid) {\n\t\tcase OIDS.rsaEncryption:\n\t\t\treturn 'RSA';\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn 'RSA-PSS';\n\t\tcase OIDS.ecPublicKey:\n\t\t\tswitch (parametersOid) {\n\t\t\t\tcase OIDS.prime256v1:\n\t\t\t\t\treturn 'EC P-256';\n\t\t\t\tcase OIDS.secp384r1:\n\t\t\t\t\treturn 'EC P-384';\n\t\t\t\tcase OIDS.secp521r1:\n\t\t\t\t\treturn 'EC P-521';\n\t\t\t\tdefault:\n\t\t\t\t\treturn 'EC';\n\t\t\t}\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,sBAAsB,GAAqB;CAC1D,QAAQ,GAAR;EACC,KAAK,EAAK,MACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD;;AAGA,SAAgB,2BACf,GACA,GACS;CACT,QAAQ,GAAR;EACC,KAAK,EAAK,uBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,WAAW;GACpB,IAAM,IAAS,EAAsB,CAAa;GAClD,OAAO,EAAO,KAAK,gBAAgB,EAAO,MAAM,SAAS;EAC1D;EACA,KAAK,EAAK,eACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,SACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD;;AAGA,SAAgB,2BAA2B,GAAa,GAA2C;CAClG,QAAQ,GAAR;EACC,KAAK,EAAK,eACT,OAAO;EACR,KAAK,EAAK,WACT,OAAO;EACR,KAAK,EAAK,aACT,QAAQ,GAAR;GACC,KAAK,EAAK,YACT,OAAO;GACR,KAAK,EAAK,WACT,OAAO;GACR,KAAK,EAAK,WACT,OAAO;GACR,SACC,OAAO;EACT;EACD,KAAK,EAAK,SACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD"}
1
+ {"version":3,"file":"algorithm-names.js","names":[],"sources":["../../../src/internal/crypto/algorithm-names.ts"],"sourcesContent":["/**\n * Human-readable algorithm labels for parsed OIDs.\n *\n * Shared by certificate, revocation, and PKCS parse surfaces so callers can\n * display meaningful algorithm names without memorizing dotted-decimal OIDs.\n *\n * @module\n */\n\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\n\n/** Convert a hash or message-digest OID into a human-readable name. */\nexport function describeHashAlgorithm(oid: string): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1:\n\t\t\treturn 'SHA-1';\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tcase OIDS.sha384:\n\t\t\treturn 'SHA-384';\n\t\tcase OIDS.sha512:\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a signature AlgorithmIdentifier into a human-readable name. */\nexport function describeSignatureAlgorithm(\n\toid: string,\n\tparametersDer: Uint8Array | undefined,\n): string {\n\tswitch (oid) {\n\t\tcase OIDS.sha1WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-1';\n\t\tcase OIDS.sha256WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-256';\n\t\tcase OIDS.sha384WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-384';\n\t\tcase OIDS.sha512WithRSAEncryption:\n\t\t\treturn 'RSA PKCS#1 v1.5 with SHA-512';\n\t\tcase OIDS.rsassaPss: {\n\t\t\tconst parsed = parseRsaPssParameters(parametersDer);\n\t\t\treturn parsed.ok ? `RSA-PSS with ${parsed.value.hash}` : 'RSA-PSS';\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA1:\n\t\t\treturn 'ECDSA with SHA-1';\n\t\tcase OIDS.ecdsaWithSHA224:\n\t\t\treturn 'ECDSA with SHA-224';\n\t\tcase OIDS.ecdsaWithSHA256:\n\t\t\treturn 'ECDSA with SHA-256';\n\t\tcase OIDS.ecdsaWithSHA384:\n\t\t\treturn 'ECDSA with SHA-384';\n\t\tcase OIDS.ecdsaWithSHA512:\n\t\t\treturn 'ECDSA with SHA-512';\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tcase OIDS.ed448:\n\t\t\treturn 'Ed448';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n\n/** Convert a SubjectPublicKeyInfo algorithm identifier into a human-readable name. */\nexport function describePublicKeyAlgorithm(oid: string, parametersOid: string | undefined): string {\n\tswitch (oid) {\n\t\tcase OIDS.rsaEncryption:\n\t\t\treturn 'RSA';\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn 'RSA-PSS';\n\t\tcase OIDS.ecPublicKey:\n\t\t\tswitch (parametersOid) {\n\t\t\t\tcase OIDS.prime256v1:\n\t\t\t\t\treturn 'EC P-256';\n\t\t\t\tcase OIDS.secp384r1:\n\t\t\t\t\treturn 'EC P-384';\n\t\t\t\tcase OIDS.secp521r1:\n\t\t\t\t\treturn 'EC P-521';\n\t\t\t\tdefault:\n\t\t\t\t\treturn 'EC';\n\t\t\t}\n\t\tcase OIDS.x25519:\n\t\t\treturn 'X25519';\n\t\tcase OIDS.x448:\n\t\t\treturn 'X448';\n\t\tcase OIDS.ed25519:\n\t\t\treturn 'Ed25519';\n\t\tcase OIDS.ed448:\n\t\t\treturn 'Ed448';\n\t\tdefault:\n\t\t\treturn `Unknown (${oid})`;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,sBAAsB,GAAqB;CAC1D,QAAQ,GAAR;EACC,KAAK,EAAK,MACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD;;AAGA,SAAgB,2BACf,GACA,GACS;CACT,QAAQ,GAAR;EACC,KAAK,EAAK,uBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,yBACT,OAAO;EACR,KAAK,EAAK,WAAW;GACpB,IAAM,IAAS,EAAsB,CAAa;GAClD,OAAO,EAAO,KAAK,gBAAgB,EAAO,MAAM,SAAS;EAC1D;EACA,KAAK,EAAK,eACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,iBACT,OAAO;EACR,KAAK,EAAK,SACT,OAAO;EACR,KAAK,EAAK,OACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD;;AAGA,SAAgB,2BAA2B,GAAa,GAA2C;CAClG,QAAQ,GAAR;EACC,KAAK,EAAK,eACT,OAAO;EACR,KAAK,EAAK,WACT,OAAO;EACR,KAAK,EAAK,aACT,QAAQ,GAAR;GACC,KAAK,EAAK,YACT,OAAO;GACR,KAAK,EAAK,WACT,OAAO;GACR,KAAK,EAAK,WACT,OAAO;GACR,SACC,OAAO;EACT;EACD,KAAK,EAAK,QACT,OAAO;EACR,KAAK,EAAK,MACT,OAAO;EACR,KAAK,EAAK,SACT,OAAO;EACR,KAAK,EAAK,OACT,OAAO;EACR,SACC,OAAO,YAAY,EAAI;CACzB;AACD"}
@@ -0,0 +1,38 @@
1
+ //#region src/internal/crypto/pbes2.d.ts
2
+ /** AES-CBC key sizes supported by this PBES2 implementation. */
3
+ type Pbes2EncryptionScheme = "AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC";
4
+ /** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */
5
+ type Pbes2Prf = "HMAC-SHA-1" | "HMAC-SHA-256";
6
+ /** Input for `encryptPbes2`. */
7
+ interface Pbes2EncryptionOptions {
8
+ /** Password fed to PBKDF2 for key derivation. */
9
+ readonly password: string;
10
+ /** PBKDF2 iteration count. Default: `100_000`. */
11
+ readonly iterations?: number;
12
+ /** PBKDF2 salt. Default: 16 cryptographically random bytes. */
13
+ readonly salt?: Uint8Array;
14
+ /** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */
15
+ readonly iv?: Uint8Array;
16
+ /** AES-CBC cipher. Default: `'AES-256-CBC'`. */
17
+ readonly cipher?: Pbes2EncryptionScheme;
18
+ /** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */
19
+ readonly prf?: Pbes2Prf;
20
+ }
21
+ /** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */
22
+ interface Pbes2Parameters {
23
+ /** PBKDF2 iteration count. */
24
+ readonly iterations: number;
25
+ /** PBKDF2 salt bytes. */
26
+ readonly salt: Uint8Array;
27
+ /** AES-CBC initialization vector. */
28
+ readonly iv: Uint8Array;
29
+ /** AES-CBC key-size variant. */
30
+ readonly cipher: Pbes2EncryptionScheme;
31
+ /** PBKDF2 pseudo-random function. */
32
+ readonly prf: Pbes2Prf;
33
+ }
34
+ /** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */
35
+ declare function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters;
36
+ //#endregion
37
+ export { Pbes2EncryptionOptions, Pbes2EncryptionScheme, Pbes2Parameters, Pbes2Prf, parsePbes2AlgorithmIdentifier };
38
+ //# sourceMappingURL=pbes2.d.ts.map
@@ -11,14 +11,13 @@ import { getCrypto as u } from "./webcrypto.js";
11
11
  *
12
12
  * @module
13
13
  */
14
+ /** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */
15
+ const d = Symbol("micro509.WrongPasswordError");
14
16
  /**
15
17
  * Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in
16
18
  * practice means the supplied password was wrong (or the ciphertext was
17
19
  * corrupted). Lets callers distinguish a bad password from malformed input.
18
20
  */
19
- /** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */
20
- const d = Symbol("micro509.WrongPasswordError");
21
- /** Builds the branded `Error` (no class) thrown when decryption fails — a wrong password or corrupt content. */
22
21
  function wrongPasswordError(e) {
23
22
  return Object.assign(Error(e), {
24
23
  name: "WrongPasswordError",
@@ -71,13 +70,13 @@ async function decryptPbes2(e, t, n) {
71
70
  }
72
71
  /** DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters. */
73
72
  function encodePbes2AlgorithmIdentifier(i) {
74
- let o = resolveEncryptionProfile(i.cipher), s = resolvePrfProfile(i.prf);
75
- return a([n(l.pbes2), a([a([n(l.pbkdf2), a([
73
+ let o = resolveEncryptionProfile(i.cipher), s = resolvePrfProfile(i.prf), c = [
76
74
  r(i.salt),
77
75
  e(i.iterations),
78
76
  e(o.keyLengthBytes),
79
- a([n(s.oid), t()])
80
- ])]), a([n(o.oid), r(i.iv)])])]);
77
+ ...i.prf === "HMAC-SHA-1" ? [] : [a([n(s.oid), t()])]
78
+ ];
79
+ return a([n(l.pbes2), a([a([n(l.pbkdf2), a(c)]), a([n(o.oid), r(i.iv)])])]);
81
80
  }
82
81
  /** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */
83
82
  function parsePbes2AlgorithmIdentifier(e) {
@@ -90,9 +89,8 @@ function parsePbes2AlgorithmIdentifier(e) {
90
89
  if (d !== void 0 && !f && d.tag !== 48) throw Error("Malformed PBKDF2 params");
91
90
  if (f && o(d.value) !== _.keyLengthBytes) throw Error("Unsupported PBKDF2 key length");
92
91
  let v = parsePbkdf2Prf(a, p), y = o(u.value), b = new Uint8Array(l.value), x = new Uint8Array(g.value);
93
- if (y < 1) throw RangeError(`Invalid PBES2 iterations: must be >= 1, got ${y}`);
94
- if (b.length < 8) throw RangeError(`Invalid PBES2 salt: must be >= 8 bytes, got ${b.length}`);
95
- if (x.length !== 16) throw RangeError(`Invalid PBES2 IV: must be exactly 16 bytes, got ${x.length}`);
92
+ if (y < 1) throw Error(`Invalid PBES2 iterations: must be >= 1, got ${y}`);
93
+ if (x.length !== 16) throw Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${x.length}`);
96
94
  return {
97
95
  salt: b,
98
96
  iterations: y,
@@ -194,6 +192,7 @@ function resolvePrfProfile(e) {
194
192
  oid: l.hmacWithSHA256,
195
193
  hash: "SHA-256"
196
194
  };
195
+ default: throw Error(`Unhandled Pbes2Prf: ${String(e)}`);
197
196
  }
198
197
  }
199
198
  //#endregion