micro509 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/CHANGELOG.md +2064 -0
  2. package/README.md +111 -183
  3. package/dist/crypto/crypto.d.ts +104 -0
  4. package/dist/crypto/crypto.js +105 -0
  5. package/dist/crypto/crypto.js.map +1 -0
  6. package/dist/crypto.d.ts +4 -0
  7. package/dist/crypto.js +1 -0
  8. package/dist/der/der.d.ts +41 -33
  9. package/dist/der/der.js +26 -24
  10. package/dist/der/der.js.map +1 -1
  11. package/dist/index.d.ts +18 -14
  12. package/dist/index.js +19 -17
  13. package/dist/internal/asn1/asn1.d.ts +3 -6
  14. package/dist/internal/asn1/asn1.js +355 -44
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js +146 -0
  17. package/dist/internal/asn1/ber.js.map +1 -0
  18. package/dist/internal/asn1/decode-refusal.js +29 -0
  19. package/dist/internal/asn1/decode-refusal.js.map +1 -0
  20. package/dist/internal/asn1/der.d.ts +42 -43
  21. package/dist/internal/asn1/der.js +148 -56
  22. package/dist/internal/asn1/der.js.map +1 -1
  23. package/dist/internal/asn1/oids.js +90 -54
  24. package/dist/internal/asn1/oids.js.map +1 -1
  25. package/dist/internal/asn1/oids2.js +1 -2
  26. package/dist/internal/asn1/oids2.js.map +1 -1
  27. package/dist/internal/crypto/algorithm-names.js +5 -2
  28. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  29. package/dist/internal/crypto/ecdsa.js +13 -8
  30. package/dist/internal/crypto/ecdsa.js.map +1 -1
  31. package/dist/internal/crypto/hash.js +1 -2
  32. package/dist/internal/crypto/hash.js.map +1 -1
  33. package/dist/internal/crypto/pbes2.d.ts +51 -0
  34. package/dist/internal/crypto/pbes2.js +86 -34
  35. package/dist/internal/crypto/pbes2.js.map +1 -1
  36. package/dist/internal/crypto/rsa-pss.js +48 -44
  37. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  38. package/dist/internal/crypto/sig-verify.d.ts +28 -0
  39. package/dist/internal/crypto/sig-verify.js +111 -62
  40. package/dist/internal/crypto/sig-verify.js.map +1 -1
  41. package/dist/internal/crypto/signing.d.ts +1 -4
  42. package/dist/internal/crypto/signing.js +28 -29
  43. package/dist/internal/crypto/signing.js.map +1 -1
  44. package/dist/internal/crypto/webcrypto.js +1 -2
  45. package/dist/internal/crypto/webcrypto.js.map +1 -1
  46. package/dist/internal/shared/base64.js +8 -3
  47. package/dist/internal/shared/base64.js.map +1 -1
  48. package/dist/internal/shared/dn.d.ts +13 -0
  49. package/dist/internal/shared/dn.js +101 -48
  50. package/dist/internal/shared/dn.js.map +1 -1
  51. package/dist/internal/shared/idna-tables.js +7217 -0
  52. package/dist/internal/shared/idna-tables.js.map +1 -0
  53. package/dist/internal/shared/idna.js +296 -0
  54. package/dist/internal/shared/idna.js.map +1 -0
  55. package/dist/internal/shared/ip.d.ts +66 -0
  56. package/dist/internal/shared/ip.js +19 -3
  57. package/dist/internal/shared/ip.js.map +1 -1
  58. package/dist/internal/shared/mailbox.js +26 -0
  59. package/dist/internal/shared/mailbox.js.map +1 -0
  60. package/dist/internal/shared/punycode.js +101 -0
  61. package/dist/internal/shared/punycode.js.map +1 -0
  62. package/dist/internal/shared/rfc3454-tables.js +1 -2
  63. package/dist/internal/shared/rfc3454-tables.js.map +1 -1
  64. package/dist/internal/shared/rfc4518-tables.js +119 -0
  65. package/dist/internal/shared/rfc4518-tables.js.map +1 -0
  66. package/dist/internal/shared/uri-host.js +102 -0
  67. package/dist/internal/shared/uri-host.js.map +1 -0
  68. package/dist/internal/verify/name-constraints-engine.js +246 -131
  69. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  70. package/dist/internal/verify/policy-engine.js +6 -21
  71. package/dist/internal/verify/policy-engine.js.map +1 -1
  72. package/dist/internal/verify/verify-path.d.ts +4 -0
  73. package/dist/internal/verify/verify-path.js +264 -128
  74. package/dist/internal/verify/verify-path.js.map +1 -1
  75. package/dist/internal/x509/directory-name.js +23 -0
  76. package/dist/internal/x509/directory-name.js.map +1 -0
  77. package/dist/internal/x509/extension-bits.js +15 -13
  78. package/dist/internal/x509/extension-bits.js.map +1 -1
  79. package/dist/internal/x509/extension-errors.d.ts +3 -0
  80. package/dist/internal/x509/extension-errors.js +19 -0
  81. package/dist/internal/x509/extension-errors.js.map +1 -0
  82. package/dist/internal/x509/extension-registry.js +157 -81
  83. package/dist/internal/x509/extension-registry.js.map +1 -1
  84. package/dist/internal/x509/general-name-profile.js +129 -0
  85. package/dist/internal/x509/general-name-profile.js.map +1 -0
  86. package/dist/internal/x509/general-name-tags.js +27 -0
  87. package/dist/internal/x509/general-name-tags.js.map +1 -0
  88. package/dist/internal/x509/general-name.js +183 -0
  89. package/dist/internal/x509/general-name.js.map +1 -0
  90. package/dist/internal/x509/name-fields.js +21 -12
  91. package/dist/internal/x509/name-fields.js.map +1 -1
  92. package/dist/internal/x509/or-address.js +217 -0
  93. package/dist/internal/x509/or-address.js.map +1 -0
  94. package/dist/keys/keys.d.ts +124 -95
  95. package/dist/keys/keys.js +362 -214
  96. package/dist/keys/keys.js.map +1 -1
  97. package/dist/keys.d.ts +3 -2
  98. package/dist/keys.js +3 -2
  99. package/dist/pem/pem.d.ts +17 -19
  100. package/dist/pem/pem.js +122 -41
  101. package/dist/pem/pem.js.map +1 -1
  102. package/dist/pem.js +1 -2
  103. package/dist/pkcs/pfx.d.ts +57 -32
  104. package/dist/pkcs/pfx.js +209 -173
  105. package/dist/pkcs/pfx.js.map +1 -1
  106. package/dist/pkcs/pkcs12-mac.d.ts +104 -27
  107. package/dist/pkcs/pkcs12-mac.js +266 -79
  108. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  109. package/dist/pkcs/pkcs7.d.ts +123 -53
  110. package/dist/pkcs/pkcs7.js +314 -238
  111. package/dist/pkcs/pkcs7.js.map +1 -1
  112. package/dist/pkcs.d.ts +5 -4
  113. package/dist/result/result.d.ts +43 -28
  114. package/dist/result/result.js +27 -14
  115. package/dist/result/result.js.map +1 -1
  116. package/dist/result.d.ts +2 -2
  117. package/dist/result.js +1 -2
  118. package/dist/revocation/chain.d.ts +101 -23
  119. package/dist/revocation/chain.js +456 -206
  120. package/dist/revocation/chain.js.map +1 -1
  121. package/dist/revocation/crl.d.ts +140 -65
  122. package/dist/revocation/crl.js +691 -391
  123. package/dist/revocation/crl.js.map +1 -1
  124. package/dist/revocation/ocsp.d.ts +145 -69
  125. package/dist/revocation/ocsp.js +347 -297
  126. package/dist/revocation/ocsp.js.map +1 -1
  127. package/dist/revocation/revocation.d.ts +48 -36
  128. package/dist/revocation/revocation.js +112 -63
  129. package/dist/revocation/revocation.js.map +1 -1
  130. package/dist/revocation.d.ts +5 -5
  131. package/dist/revocation.js +5 -5
  132. package/dist/verify/identity.d.ts +18 -20
  133. package/dist/verify/identity.js +120 -90
  134. package/dist/verify/identity.js.map +1 -1
  135. package/dist/verify/name-constraints.d.ts +1 -4
  136. package/dist/verify/policy.d.ts +15 -8
  137. package/dist/verify/verify.d.ts +86 -46
  138. package/dist/verify/verify.js +309 -143
  139. package/dist/verify/verify.js.map +1 -1
  140. package/dist/verify.d.ts +3 -2
  141. package/dist/verify.js +4 -3
  142. package/dist/x509/certificate.d.ts +50 -28
  143. package/dist/x509/certificate.js +69 -36
  144. package/dist/x509/certificate.js.map +1 -1
  145. package/dist/x509/csr.d.ts +9 -8
  146. package/dist/x509/csr.js +10 -11
  147. package/dist/x509/csr.js.map +1 -1
  148. package/dist/x509/extensions.d.ts +207 -82
  149. package/dist/x509/extensions.js +561 -128
  150. package/dist/x509/extensions.js.map +1 -1
  151. package/dist/x509/fingerprint.d.ts +4 -7
  152. package/dist/x509/fingerprint.js +1 -2
  153. package/dist/x509/fingerprint.js.map +1 -1
  154. package/dist/x509/name-text.d.ts +7 -9
  155. package/dist/x509/name-text.js +20 -4
  156. package/dist/x509/name-text.js.map +1 -1
  157. package/dist/x509/name.d.ts +15 -14
  158. package/dist/x509/name.js +23 -19
  159. package/dist/x509/name.js.map +1 -1
  160. package/dist/x509/parse.d.ts +165 -64
  161. package/dist/x509/parse.js +444 -459
  162. package/dist/x509/parse.js.map +1 -1
  163. package/dist/x509.d.ts +8 -5
  164. package/dist/x509.js +10 -8
  165. package/package.json +90 -65
@@ -1,21 +1,46 @@
1
- import { readElement as e } from "./der.js";
2
- //#region src/internal/asn1/asn1.ts
1
+ import { DECODE_LIMIT_CODES as e, rethrowDecodeRefusal as t, throwDecodeRefusal as n } from "./decode-refusal.js";
2
+ import { objectIdentifier as r, readElement as i, walkDerTree as a } from "./der.js";
3
+ // src/internal/asn1/asn1.ts
4
+ /**
5
+ * ASN.1 decoding helpers used by the higher-level DER, parse, and crypto modules.
6
+ *
7
+ * These utilities stay intentionally small and strict so malformed input fails early and
8
+ * higher-level modules can build on one consistent decoding layer.
9
+ *
10
+ * @module
11
+ */
3
12
  /** 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;
13
+ const o = new TextDecoder("utf-8", {
14
+ fatal: !0,
15
+ ignoreBOM: !0
16
+ }), s = /^[A-Za-z0-9 '()+,\-./:=?]*$/u;
5
17
  /**
6
18
  * Decodes a DER-encoded OBJECT IDENTIFIER value into its dotted-decimal string form.
7
19
  *
8
20
  * @example "1.2.840.113549.1.1.1"
9
- * @throws on empty input, truncated multi-byte sub-identifiers, or incomplete continuation octets.
21
+ * @throws on empty input, truncated multi-byte sub-identifiers, or incomplete continuation octets,
22
+ * and `limit_exceeded` for a sub-identifier encoded in more than
23
+ * {@linkcode MAX_OID_SUBIDENTIFIER_OCTETS} octets.
10
24
  */
11
25
  function decodeObjectIdentifier(e) {
12
26
  if (e.length === 0) throw Error("OID is empty");
13
- let t = decodeOidSubidentifier(e, 0), n = t.nextOffset, r = t.value < 40 ? [0, t.value] : t.value < 80 ? [1, t.value - 40] : [2, t.value - 80];
27
+ let t = decodeOidSubidentifier(e, 0), n = t.nextOffset, r = t.value, i = r < 40n ? [0n, r] : r < 80n ? [1n, r - 40n] : [2n, r - 80n];
14
28
  for (; n < e.length;) {
15
29
  let t = decodeOidSubidentifier(e, n);
16
- r.push(t.value), n = t.nextOffset;
30
+ i.push(t.value), n = t.nextOffset;
17
31
  }
18
- return r.join(".");
32
+ return i.join(".");
33
+ }
34
+ /**
35
+ * Reduces an OID to the dotted-decimal form its DER encoding decodes back to, so
36
+ * that spellings differing only by redundant leading zeros in an arc resolve to
37
+ * one identity.
38
+ *
39
+ * @example `canonicalizeOid('2.5.029.17')` returns `'2.5.29.17'`
40
+ * @throws if the OID has a non-numeric segment or violates the X.660 arc constraints.
41
+ */
42
+ function canonicalizeOid(e) {
43
+ return decodeObjectIdentifier(i(r(e), 0).value);
19
44
  }
20
45
  /** Converts raw bytes to a lowercase hex string with no separator. */
21
46
  function toHex(e) {
@@ -35,15 +60,15 @@ function toArrayBuffer(e) {
35
60
  *
36
61
  * @throws if any child overflows the parent boundary or if there is leftover data between the last child and the parent end offset.
37
62
  */
38
- function childrenOf(t, n) {
39
- let r = [], i = n.start;
40
- for (; i < n.end;) {
41
- let a = e(t, i);
42
- if (a.end > n.end) throw Error("DER child exceeds parent length");
43
- r.push(a), i = a.end;
63
+ function childrenOf(e, t) {
64
+ let n = [], r = t.start;
65
+ for (; r < t.end;) {
66
+ let a = i(e, r);
67
+ if (a.end > t.end) throw Error("DER child exceeds parent length");
68
+ n.push(a), r = a.end;
44
69
  }
45
- if (i !== n.end) throw Error("Malformed DER container");
46
- return r;
70
+ if (r !== t.end) throw Error("Malformed DER container");
71
+ return n;
47
72
  }
48
73
  /**
49
74
  * Asserts that a value is not `undefined`, returning it narrowed.\
@@ -116,21 +141,46 @@ function parseTime(e) {
116
141
  throw Error(`Unsupported time tag: ${e.tag}`);
117
142
  }
118
143
  /**
119
- * Decodes a big-endian unsigned byte sequence into a JavaScript `number`.
144
+ * Decodes DER INTEGER content octets holding a non-negative value into a JavaScript `number`.
120
145
  *
121
- * @throws if the value exceeds {@linkcode Number.MAX_SAFE_INTEGER}, the boundary for lossless arithmetic.
146
+ * @throws if the value is empty, negative, non-minimally encoded, or exceeds {@linkcode Number.MAX_SAFE_INTEGER}.
122
147
  */
123
148
  function decodeIntegerNumber(e) {
124
- let t = e[0];
125
- if (t === void 0) throw Error("INTEGER is empty");
126
- if (t & 128) throw Error("INTEGER must be non-negative");
127
- if (e.length > 1 && t === 0 && !((e[1] ?? 0) & 128)) throw Error("INTEGER must use minimal encoding");
128
- let n = 0;
149
+ let t = decodeIntegerMagnitude(e);
150
+ if (t.type === "unsafe") throw Error(`Integer too large for safe number (${e.length} bytes)`);
151
+ return t.value;
152
+ }
153
+ /**
154
+ * Decodes DER INTEGER content octets holding a non-negative value, stopping at the first octet past {@linkcode Number.MAX_SAFE_INTEGER}.
155
+ *
156
+ * @param bytes DER INTEGER content octets to decode.
157
+ * @param label Field name for error messages (defaults to `"INTEGER"`).
158
+ * @throws if the value is empty, negative, or non-minimally encoded.
159
+ */
160
+ function decodeIntegerMagnitude(e, t = "INTEGER") {
161
+ let n = e[0];
162
+ if (n === void 0) throw Error(`${t} is empty`);
163
+ if (n & 128) throw Error(`${t} must be non-negative`);
164
+ if (e.length > 1 && n === 0 && !((e[1] ?? 0) & 128)) throw Error(`${t} must use minimal encoding`);
165
+ let r = 0;
129
166
  for (let t of e) {
130
- if (n > Math.floor((2 ** 53 - 1 - t) / 256)) throw Error(`Integer too large for safe number (${e.length} bytes)`);
131
- n = n * 256 + t;
167
+ if (r > Math.floor((2 ** 53 - 1 - t) / 256)) return { type: "unsafe" };
168
+ r = r * 256 + t;
132
169
  }
133
- return n;
170
+ return {
171
+ type: "safe",
172
+ value: r
173
+ };
174
+ }
175
+ /**
176
+ * Decodes DER INTEGER or ENUMERATED content octets holding a non-negative value of any length into a `bigint`.
177
+ *
178
+ * @param bytes DER content octets to decode.
179
+ * @param label Field name for error messages (defaults to `"INTEGER"`).
180
+ * @throws if the value is empty, negative, or non-minimally encoded.
181
+ */
182
+ function decodeNonNegativeIntegerBigInt(e, t = "INTEGER") {
183
+ return decodeIntegerMagnitude(e, t), BigInt(`0x${toHex(e)}`);
134
184
  }
135
185
  /**
136
186
  * Like {@linkcode decodeIntegerNumber}, but optionally rewrites thrown error messages with a caller-specific field label.
@@ -166,7 +216,7 @@ function hexToBytes(e) {
166
216
  }
167
217
  return n;
168
218
  }
169
- /** Decodes a DER BOOLEAN value: any non-zero first byte is `true`. */
219
+ /** 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
220
  function decodeBoolean(e) {
171
221
  if (e.length !== 1) throw Error("BOOLEAN must contain exactly one octet");
172
222
  let t = e[0];
@@ -182,16 +232,18 @@ function decodeOidSubidentifier(e, t) {
182
232
  let n = e[t];
183
233
  if (n === void 0) throw Error("Malformed OID");
184
234
  if (n === 128) throw Error("Malformed OID: non-minimal base-128 encoding");
185
- let r = 0, i = t;
186
- for (; i < e.length; i += 1) {
187
- let t = e[i];
188
- if (t === void 0) throw Error("Malformed OID");
189
- let n = t & 127;
190
- if (r > Math.floor((2 ** 53 - 1 - n) / 128)) throw Error("Malformed OID: overflow/non-minimal or too-large subidentifier");
191
- if (r = r * 128 + n, !(t & 128)) return {
192
- value: r,
193
- nextOffset: i + 1
194
- };
235
+ let r = findOidSubidentifierEnd(e, t), i = 0n;
236
+ for (let n = t; n <= r; n += 1) i = i << 7n | BigInt((e[n] ?? 0) & 127);
237
+ return {
238
+ value: i,
239
+ nextOffset: r + 1
240
+ };
241
+ }
242
+ /** The offset of the sub-identifier's last octet, checked before any of it is accumulated. */
243
+ function findOidSubidentifierEnd(e, t) {
244
+ for (let r = t; r < e.length; r += 1) {
245
+ if (!((e[r] ?? 0) & 128)) return r;
246
+ r - t + 1 >= 64 && r + 1 < e.length && n("limit_exceeded", "OID sub-identifier exceeds 64 octets");
195
247
  }
196
248
  throw Error("Malformed OID: incomplete continuation");
197
249
  }
@@ -201,6 +253,7 @@ function decodeOidSubidentifier(e, t) {
201
253
  * Supports:
202
254
  * - UTF8String (`0x0c`),
203
255
  * - PrintableString (`0x13`),
256
+ * - TeletexString (`0x14`) in its X.690 §8.23.5.2 initial state,
204
257
  * - IA5String (`0x16`),
205
258
  * - UniversalString (`0x1c`), and
206
259
  * - BMPString (`0x1e`).
@@ -212,17 +265,17 @@ function decodeString(e, t) {
212
265
  case 12: return decodeUtf8Text(t, "UTF8String");
213
266
  case 19: return decodePrintableString(t);
214
267
  case 22: return decodeIa5String(t);
215
- case 20: throw Error("Unsupported string tag: 20 (TeletexString)");
268
+ case 20: return decodeTeletexString(t);
216
269
  case 28: return decodeUniversalString(t);
217
270
  case 30: return decodeBmpString(t);
218
271
  default: throw Error(`Unsupported string tag: ${e}`);
219
272
  }
220
273
  }
221
- function decodeUtf8Text(e, n) {
274
+ function decodeUtf8Text(e, t) {
222
275
  try {
223
- return t.decode(e);
276
+ return o.decode(e);
224
277
  } catch (e) {
225
- throw e instanceof Error ? Error(`Invalid ${n}: invalid UTF-8`, { cause: e }) : e;
278
+ throw e instanceof Error ? Error(`Invalid ${t}: invalid UTF-8`, { cause: e }) : e;
226
279
  }
227
280
  }
228
281
  function decodeAsciiString(e, t) {
@@ -238,9 +291,44 @@ function decodeIa5String(e) {
238
291
  }
239
292
  function decodePrintableString(e) {
240
293
  let t = decodeAsciiString(e, "PrintableString");
241
- if (!n.test(t)) throw Error("Invalid PrintableString: contains characters outside the allowed set");
294
+ if (!s.test(t)) throw Error("Invalid PrintableString: contains characters outside the allowed set");
242
295
  return t;
243
296
  }
297
+ /**
298
+ * Decodes VisibleString contents, which X.680 §43.7 limits to 0x20 through 0x7E.
299
+ *
300
+ * @throws on an octet outside that range.
301
+ */
302
+ function decodeVisibleString(e) {
303
+ let t = "";
304
+ for (let n of e) {
305
+ if (n < 32 || n > 126) throw Error("Invalid VisibleString: contains octets outside 0x20 to 0x7e");
306
+ t += String.fromCharCode(n);
307
+ }
308
+ return t;
309
+ }
310
+ /** T.61 Table 1 leaves these positions of register entry 102 empty. */
311
+ const c = /* @__PURE__ */ new Set([
312
+ 92,
313
+ 94,
314
+ 96,
315
+ 123,
316
+ 125,
317
+ 126
318
+ ]);
319
+ /**
320
+ * Decodes TeletexString contents in the X.690 §8.23.5.2 initial state, reading
321
+ * register entry 102 by T.61 Table 1 and Figure 2 Note 4, with the SPACE and
322
+ * DELETE that X.680 Table 8 adds.
323
+ *
324
+ * @throws `unsupported` on any other octet.
325
+ */
326
+ function decodeTeletexString(e) {
327
+ let t = "";
328
+ for (let r of e) (r < 32 || r > 127 || c.has(r)) && n("unsupported", `Unsupported TeletexString octet: 0x${r.toString(16).padStart(2, "0")}`), t += r === 36 ? "¤" : String.fromCharCode(r);
329
+ return t;
330
+ }
331
+ /** X.680 §41.15: BMPString holds code units 0000 to D7FF and E000 to FFFD. */
244
332
  function decodeBmpString(e) {
245
333
  if (e.length % 2 != 0) throw Error("Invalid BMPString length");
246
334
  let t = "";
@@ -248,7 +336,7 @@ function decodeBmpString(e) {
248
336
  let r = e[n], i = e[n + 1];
249
337
  if (r === void 0 || i === void 0) throw Error("Invalid BMPString content");
250
338
  let a = r << 8 | i;
251
- if (a >= 55296 && a <= 57343) throw Error("Invalid BMPString code point");
339
+ if (a >= 55296 && a <= 57343 || a >= 65534) throw Error("Invalid BMPString code point");
252
340
  t += String.fromCharCode(a);
253
341
  }
254
342
  return t;
@@ -265,7 +353,230 @@ function decodeUniversalString(e) {
265
353
  }
266
354
  return t;
267
355
  }
268
- //#endregion
269
- export { childrenOf, decodeBitString, decodeBoolean, decodeIntegerNumber, decodeNonNegativeIntegerNumber, decodeObjectIdentifier, decodeString, extractBitStringValue, hexToBytes, parseTime, requireElement, toArrayBuffer, toHex };
356
+ /**
357
+ * Walks {@linkcode bytes} as one DER element and checks each universal-class
358
+ * element against the X.690 rules its tag fixes: the identifier form, the
359
+ * contents, and the DER restrictions of clauses 10 and 11.
360
+ *
361
+ * Where those rules rest on ISO/IEC 2022, ISO 8601 or an implicitly tagged
362
+ * schema, the element is `unsupported`: TeletexString, VideotexString, TIME,
363
+ * EXTERNAL, EMBEDDED PDV, CHARACTER STRING, the types of UNIVERSAL 31 to 36, a
364
+ * REAL with a long-form exponent, a GeneralizedTime at second 60, and text
365
+ * holding an escape sequence or a code-extension control. A SET or SET OF
366
+ * whose children follow neither the DER SET order nor the DER SET OF order is
367
+ * `malformed`. Context-specific, application and private elements get framing
368
+ * checks only, as do the rules that depend on a schema: DEFAULT omission and
369
+ * NamedBitList trailing bits. No value is checked against an ASN.1 type, so
370
+ * ENUMERATED membership, INTEGER ranges, SIZE constraints, CHOICE alternatives
371
+ * and SEQUENCE or SET components stay unchecked.
372
+ *
373
+ * @throws `limit_exceeded` past {@linkcode maxDepth} levels of nesting or on a
374
+ * tag number of 2^53 or more.
375
+ */
376
+ function checkStrictDer(n, r = 64) {
377
+ let i = !1;
378
+ try {
379
+ a(n, r, void 0, (e) => {
380
+ let t = checkUniversalElement(e);
381
+ if (t === "malformed") throw Error("DER element breaks the rules of its universal type");
382
+ i ||= t === "unsupported";
383
+ });
384
+ } catch (n) {
385
+ return t(n, e), "malformed";
386
+ }
387
+ return i ? "unsupported" : "valid";
388
+ }
389
+ function verdictOf(e) {
390
+ return e ? "valid" : "malformed";
391
+ }
392
+ function decodes(e) {
393
+ try {
394
+ return e(), "valid";
395
+ } catch {
396
+ return "malformed";
397
+ }
398
+ }
399
+ function asciiText(e) {
400
+ try {
401
+ return decodeIa5String(e);
402
+ } catch {
403
+ return;
404
+ }
405
+ }
406
+ const l = /* @__PURE__ */ new Set([27]), u = /* @__PURE__ */ new Set([
407
+ 14,
408
+ 15,
409
+ 27,
410
+ 142,
411
+ 143,
412
+ 155
413
+ ]);
414
+ /** The verdict on text {@linkcode decode} validates, `unsupported` when it holds one of {@linkcode controls}. */
415
+ function checkText(e, t) {
416
+ let n;
417
+ try {
418
+ n = e();
419
+ } catch {
420
+ return "malformed";
421
+ }
422
+ for (let e of n) if (t.has(e.codePointAt(0) ?? 0)) return "unsupported";
423
+ return "valid";
424
+ }
425
+ /** X.690 Table 3: GraphicString and ObjectDescriptor open with register entry 6 as G0 and no C0 or C1 set. */
426
+ function checkGraphicString(e) {
427
+ return e.value.includes(27) ? "unsupported" : verdictOf(e.value.every((e) => e >= 32 && e <= 126));
428
+ }
429
+ /** X.690 Table 3: GeneralString opens with register entry 6 as G0 and entry 1 as C0, beside SPACE and DELETE. */
430
+ function checkGeneralString(e) {
431
+ return e.value.some((e) => e === 27 || e === 14 || e === 15) ? "unsupported" : verdictOf(e.value.every((e) => e <= 127));
432
+ }
433
+ /** X.690 §8.3.2: the first nine bits of a multi-octet INTEGER are neither all ones nor all zeros. */
434
+ function isMinimalInteger(e) {
435
+ let [t, n] = e;
436
+ return t === void 0 ? !1 : n === void 0 || (t !== 0 || n >= 128) && (t !== 255 || n < 128);
437
+ }
438
+ /** X.690 §8.19.2: every subidentifier ends on an octet with bit 8 clear and never opens with 0x80. */
439
+ function isSubidentifierList(e) {
440
+ let t = !0;
441
+ for (let n of e) {
442
+ if (t && n === 128) return !1;
443
+ t = !(n & 128);
444
+ }
445
+ return t;
446
+ }
447
+ function checkBitString(e) {
448
+ try {
449
+ return verdictOf(!decodeBitString(e).nonZeroPadding);
450
+ } catch {
451
+ return "malformed";
452
+ }
453
+ }
454
+ /** X.680 Table 9: NumericString holds the digits and SPACE. */
455
+ function isNumericStringContents(e) {
456
+ return e.every((e) => e === 32 || e >= 48 && e <= 57);
457
+ }
458
+ function isLeapYear(e) {
459
+ return e % 4 == 0 && e % 100 != 0 || e % 400 == 0;
460
+ }
461
+ const d = [
462
+ 31,
463
+ 28,
464
+ 31,
465
+ 30,
466
+ 31,
467
+ 30,
468
+ 31,
469
+ 31,
470
+ 30,
471
+ 31,
472
+ 30,
473
+ 31
474
+ ], f = {
475
+ pattern: /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/,
476
+ century: 2e3,
477
+ leapSecond: "malformed"
478
+ }, p = {
479
+ pattern: /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:\.\d*[1-9])?Z$/,
480
+ century: 0,
481
+ leapSecond: "unsupported"
482
+ };
483
+ function checkTime(e, t) {
484
+ let n = t.pattern.exec(asciiText(e.value) ?? "")?.slice(1).map(Number);
485
+ if (n === void 0) return "malformed";
486
+ let [r = 0, i = 0, a = 0, o = 0, s = 0, c = 0] = n, l = (d[i - 1] ?? 0) + (i === 2 && isLeapYear(t.century + r) ? 1 : 0);
487
+ return a < 1 || a > l || o > 23 || s > 59 || c > 60 ? "malformed" : c === 60 ? t.leapSecond : "valid";
488
+ }
489
+ /**
490
+ * X.690 §11.3.2: NR3 without SPACE, a MINUS SIGN only on a negative value, a
491
+ * mantissa that neither opens nor closes with 0 followed by `.E`, and an
492
+ * exponent written `+0` or with no leading 0 and no PLUS SIGN.
493
+ */
494
+ const m = /^-?[1-9](?:\d*[1-9])?\.E(?:\+0|-?[1-9]\d*)$/;
495
+ /**
496
+ * X.690 §8.5 and §11.3: an empty plus zero, a one-octet special value, a
497
+ * base-2 binary form with F = 0, the fewest exponent octets and an odd
498
+ * mantissa with no leading zero octet, or a decimal NR3 form. X.690 §8.5.7.4
499
+ * d) leaves the length of a long-form exponent ambiguous.
500
+ */
501
+ function checkReal(e) {
502
+ let [t] = e.value, n = e.value.subarray(1);
503
+ if (t === void 0) return "valid";
504
+ if (!(t & 128)) return t & 64 ? verdictOf(n.length === 0 && t <= 67) : verdictOf(t === 3 && m.test(asciiText(n) ?? ""));
505
+ let r = t & 3;
506
+ if (t & 60) return "malformed";
507
+ if (r === 3) return "unsupported";
508
+ let i = n.subarray(0, r + 1), a = n.subarray(r + 1);
509
+ return verdictOf(i.length === r + 1 && isMinimalInteger(i) && (a[0] ?? 0) !== 0 && ((a.at(-1) ?? 0) & 1) == 1);
510
+ }
511
+ /** X.690 §11.6: set-of encodings compare as octet strings, the shorter padded at its end with zero octets. */
512
+ function compareSetOfEncodings(e, t) {
513
+ for (let n = 0; n < Math.max(e.length, t.length); n += 1) {
514
+ let r = (e[n] ?? 0) - (t[n] ?? 0);
515
+ if (r !== 0) return r;
516
+ }
517
+ return 0;
518
+ }
519
+ /**
520
+ * X.690 §10.3 orders SET components by the canonical tag order of X.680 §8.6,
521
+ * which compares class and number and never the constructed bit, and X.690
522
+ * §11.6 orders SET OF components by encoding.
523
+ */
524
+ function checkSet(e) {
525
+ let t = [];
526
+ for (let n = 0; n < e.value.length;) {
527
+ let r = i(e.value, n);
528
+ t.push(r), n = r.end;
529
+ }
530
+ let encodingOf = (t) => e.value.subarray(t.start - t.headerLength, t.end), n = t.every((e, n) => {
531
+ let r = t[n - 1];
532
+ if (r === void 0) return !0;
533
+ let i = r.tag & 192, a = e.tag & 192;
534
+ return i < a || i === a && r.tagNumber < e.tagNumber;
535
+ }), r = t.every((e, n) => {
536
+ let r = t[n - 1];
537
+ return r === void 0 || compareSetOfEncodings(encodingOf(r), encodingOf(e)) <= 0;
538
+ });
539
+ return verdictOf(n || r);
540
+ }
541
+ /**
542
+ * The identifier octet DER uses for each universal type, mapped to the check
543
+ * of its contents. A universal identifier missing here is a reserved tag
544
+ * number or a form DER forbids.
545
+ */
546
+ const h = /* @__PURE__ */ new Map([
547
+ [1, (e) => decodes(() => decodeBoolean(e.value))],
548
+ [2, (e) => verdictOf(isMinimalInteger(e.value))],
549
+ [3, checkBitString],
550
+ [4, () => "valid"],
551
+ [5, (e) => verdictOf(e.value.length === 0)],
552
+ [6, (e) => verdictOf(e.value.length > 0 && isSubidentifierList(e.value))],
553
+ [7, checkGraphicString],
554
+ [9, checkReal],
555
+ [10, (e) => verdictOf(isMinimalInteger(e.value))],
556
+ [12, (e) => checkText(() => decodeUtf8Text(e.value, "UTF8String"), l)],
557
+ [13, (e) => verdictOf(e.value.length > 0 && isSubidentifierList(e.value))],
558
+ [14, () => "unsupported"],
559
+ [18, (e) => verdictOf(isNumericStringContents(e.value))],
560
+ [19, (e) => decodes(() => decodePrintableString(e.value))],
561
+ [20, () => "unsupported"],
562
+ [21, () => "unsupported"],
563
+ [22, (e) => checkText(() => decodeIa5String(e.value), l)],
564
+ [23, (e) => checkTime(e, f)],
565
+ [24, (e) => checkTime(e, p)],
566
+ [25, checkGraphicString],
567
+ [26, (e) => decodes(() => decodeVisibleString(e.value))],
568
+ [27, checkGeneralString],
569
+ [28, (e) => checkText(() => decodeUniversalString(e.value), u)],
570
+ [30, (e) => checkText(() => decodeBmpString(e.value), u)],
571
+ [40, () => "unsupported"],
572
+ [43, () => "unsupported"],
573
+ [48, () => "valid"],
574
+ [49, checkSet],
575
+ [61, () => "unsupported"]
576
+ ]);
577
+ function checkUniversalElement(e) {
578
+ return e.tag & 192 ? "valid" : (e.tag & 31) == 31 ? e.tagNumber <= 36 ? "unsupported" : "malformed" : h.get(e.tag)?.(e) ?? "malformed";
579
+ }
580
+ export { canonicalizeOid, checkStrictDer, childrenOf, decodeBitString, decodeBoolean, decodeIntegerMagnitude, decodeIntegerNumber, decodeNonNegativeIntegerBigInt, decodeNonNegativeIntegerNumber, decodeObjectIdentifier, decodeString, decodeVisibleString, extractBitStringValue, hexToBytes, isNumericStringContents, parseTime, requireElement, toArrayBuffer, toHex };
270
581
 
271
582
  //# 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,C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O;AACR"}
1
+ {"version":3,"file":"asn1.js","names":["textDecoder","PRINTABLE_STRING_PATTERN","bytes","firstSubidentifier","offset","first","values","subidentifier","readElement","objectIdentifier","oid","value","out","children","parent","child","source","label","element","unusedBits","paddingMask","match","yearText","monthText","dayText","hourText","minuteText","secondText","year","magnitude","byte","error","normalized","index","chunk","month","day","hour","minute","second","date","start","end","throwDecodeRefusal","tag","TELETEX_EMPTY_POSITIONS","left","right","codeUnit","third","fourth","codePoint","unsupported","maxDepth","verdict","rethrowDecodeRefusal","DECODE_LIMIT_CODES","valid","decode","contents","ESCAPE_CONTROLS","CODE_EXTENSION_CONTROLS","text","character","controls","octet","opensSubidentifier","DAYS_IN_MONTH","UTC_TIME","GENERALIZED_TIME","fields","syntax","monthDays","DER_NR3","rest","format","exponent","mantissa","difference","setOrder","previous","previousClass","childClass","setOfOrder","UNIVERSAL_ELEMENTS"],"sources":["../../../src/internal/asn1/asn1.ts"],"sourcesContent":["/**\n * ASN.1 decoding helpers used by the higher-level DER, parse, and crypto modules.\n *\n * These utilities stay intentionally small and strict so malformed input fails early and\n * higher-level modules can build on one consistent decoding layer.\n *\n * @module\n */\n\nimport {\n\tDECODE_LIMIT_CODES,\n\trethrowDecodeRefusal,\n\tthrowDecodeRefusal,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\tMAX_OID_SUBIDENTIFIER_OCTETS,\n\tobjectIdentifier,\n\treadElement,\n\twalkDerTree,\n} from '#micro509/internal/asn1/der';\n\nexport { MAX_OID_SUBIDENTIFIER_OCTETS } from '#micro509/internal/asn1/der';\n\n/** Shared UTF-8 text decoder for ASN.1 string types. */\nconst textDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\nconst PRINTABLE_STRING_PATTERN = /^[A-Za-z0-9 '()+,\\-./:=?]*$/u;\n\n/**\n * Decodes a DER-encoded OBJECT IDENTIFIER value into its dotted-decimal string form.\n *\n * @example \"1.2.840.113549.1.1.1\"\n * @throws on empty input, truncated multi-byte sub-identifiers, or incomplete continuation octets,\n * and `limit_exceeded` for a sub-identifier encoded in more than\n * {@linkcode MAX_OID_SUBIDENTIFIER_OCTETS} octets.\n */\nexport function decodeObjectIdentifier(bytes: Uint8Array): string {\n\tif (bytes.length === 0) {\n\t\tthrow new Error('OID is empty');\n\t}\n\tconst firstSubidentifier = decodeOidSubidentifier(bytes, 0);\n\tlet offset = firstSubidentifier.nextOffset;\n\tconst first = firstSubidentifier.value;\n\tconst values: bigint[] =\n\t\tfirst < 40n ? [0n, first] : first < 80n ? [1n, first - 40n] : [2n, first - 80n];\n\twhile (offset < bytes.length) {\n\t\tconst subidentifier = decodeOidSubidentifier(bytes, offset);\n\t\tvalues.push(subidentifier.value);\n\t\toffset = subidentifier.nextOffset;\n\t}\n\treturn values.join('.');\n}\n\n/**\n * Reduces an OID to the dotted-decimal form its DER encoding decodes back to, so\n * that spellings differing only by redundant leading zeros in an arc resolve to\n * one identity.\n *\n * @example `canonicalizeOid('2.5.029.17')` returns `'2.5.29.17'`\n * @throws if the OID has a non-numeric segment or violates the X.660 arc constraints.\n */\nexport function canonicalizeOid(oid: string): string {\n\treturn decodeObjectIdentifier(readElement(objectIdentifier(oid), 0).value);\n}\n\n/** Converts raw bytes to a lowercase hex string with no separator. */\nexport function toHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Copies a {@linkcode Uint8Array} into a standalone {@linkcode ArrayBuffer} suitable for\n * Web Crypto operations that require a non-shared backing buffer.\n */\nexport function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n\tconst out = new ArrayBuffer(bytes.length);\n\tnew Uint8Array(out).set(bytes);\n\treturn out;\n}\n\n/**\n * Iterates through all direct child TLV elements inside a constructed {@linkcode DerElement}\n * (SEQUENCE, SET, or context-tagged container).\n *\n * @throws if any child overflows the parent boundary or if there is leftover data between the last child and the parent end offset.\n */\nexport function childrenOf(source: Uint8Array, parent: DerElement): DerElement[] {\n\tconst children: DerElement[] = [];\n\tlet offset = parent.start;\n\twhile (offset < parent.end) {\n\t\tconst child = readElement(source, offset);\n\t\tif (child.end > parent.end) {\n\t\t\tthrow new Error('DER child exceeds parent length');\n\t\t}\n\t\tchildren.push(child);\n\t\toffset = child.end;\n\t}\n\tif (offset !== parent.end) {\n\t\tthrow new Error('Malformed DER container');\n\t}\n\treturn children;\n}\n\n/**\n * Asserts that a value is not `undefined`, returning it narrowed.\\\n * Used to enforce the presence of mandatory ASN.1 fields during parsing.\n *\n * @param label Human-readable field name included in the error message on failure.\n */\nexport function requireElement<T>(value: T | undefined, label: string): T {\n\tif (value === undefined) {\n\t\tthrow new Error(`Missing ${label}`);\n\t}\n\treturn value;\n}\n\n/**\n * Strips the leading \"unused bits\" octet from a BIT STRING element, returning just the payload bytes.\n *\n * Used to extract signature values and public keys from their BIT STRING wrapper.\n *\n * @throws if the tag is not `0x03`.\n */\nexport function extractBitStringValue(element: DerElement): Uint8Array {\n\tif (element.tag !== 0x03) {\n\t\tthrow new Error('Expected BIT STRING');\n\t}\n\tconst unusedBits = element.value[0];\n\tif (unusedBits === undefined || unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tif (unusedBits !== 0) {\n\t\tthrow new Error('BIT STRING must have zero unused bits');\n\t}\n\treturn element.value.slice(1);\n}\n\n/** A BIT STRING payload and the number of unused trailing bits in its final byte. */\nexport interface DerBitString {\n\t/** Payload bytes, excluding the leading unused-bit count octet. */\n\treadonly bytes: Uint8Array;\n\t/** Unused trailing bits in the final byte, 0 through 7. */\n\treadonly unusedBits: number;\n\t/** `true` when the original encoding had non-zero padding bits (DER violation). */\n\treadonly nonZeroPadding: boolean;\n}\n\n/**\n * Decodes a BIT STRING element into its payload and unused-bit count.\n *\n * Accepts a non-zero unused-bit count, so it reads flag strings such as {@linkcode KeyUsage},\n * which {@linkcode extractBitStringValue} rejects.\n *\n * Padding bits that {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1} requires to be zero are reported through\n * {@linkcode DerBitString.nonZeroPadding} rather than rejected, so a caller can decide.\n */\nexport function decodeBitString(element: DerElement): DerBitString {\n\tif (element.tag !== 0x03) {\n\t\tthrow new Error('Expected BIT STRING');\n\t}\n\tconst unusedBits = element.value[0];\n\tif (unusedBits === undefined || unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = element.value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst paddingMask = (1 << unusedBits) - 1;\n\tconst nonZeroPadding =\n\t\tunusedBits > 0 && bytes.length > 0 && ((bytes[bytes.length - 1] ?? 0) & paddingMask) !== 0;\n\treturn { bytes, unusedBits, nonZeroPadding };\n}\n\n/**\n * Parses a {@linkcode DerElement} with tag UTCTime (`0x17`) or GeneralizedTime (`0x18`) into a {@linkcode Date}.\n *\n * For UTCTime, the two-digit year is interpreted per RFC 5280:\n * - values >= 50 map to 19xx,\n * - values < 50 map to 20xx.\n *\n * @throws on unrecognized time tags.\n */\nexport function parseTime(element: DerElement): Date {\n\tif (element.tag === 0x17) {\n\t\tconst value = decodeUtf8Text(element.value, 'UTCTime');\n\t\tconst match = /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(value);\n\t\tif (match === null) {\n\t\t\tthrow new Error('Invalid UTCTime');\n\t\t}\n\t\tconst yearText = requireElement(match[1], 'UTCTime year');\n\t\tconst monthText = requireElement(match[2], 'UTCTime month');\n\t\tconst dayText = requireElement(match[3], 'UTCTime day');\n\t\tconst hourText = requireElement(match[4], 'UTCTime hour');\n\t\tconst minuteText = requireElement(match[5], 'UTCTime minute');\n\t\tconst secondText = requireElement(match[6], 'UTCTime second');\n\t\tconst year = Number.parseInt(yearText, 10);\n\t\treturn buildStrictUtcDate(\n\t\t\tyear >= 50 ? 1900 + year : 2000 + year,\n\t\t\tmonthText,\n\t\t\tdayText,\n\t\t\thourText,\n\t\t\tminuteText,\n\t\t\tsecondText,\n\t\t\t'UTCTime',\n\t\t);\n\t}\n\tif (element.tag === 0x18) {\n\t\tconst value = decodeUtf8Text(element.value, 'GeneralizedTime');\n\t\tconst match = /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(value);\n\t\tif (match === null) {\n\t\t\tthrow new Error('Invalid GeneralizedTime');\n\t\t}\n\t\tconst yearText = requireElement(match[1], 'GeneralizedTime year');\n\t\tconst monthText = requireElement(match[2], 'GeneralizedTime month');\n\t\tconst dayText = requireElement(match[3], 'GeneralizedTime day');\n\t\tconst hourText = requireElement(match[4], 'GeneralizedTime hour');\n\t\tconst minuteText = requireElement(match[5], 'GeneralizedTime minute');\n\t\tconst secondText = requireElement(match[6], 'GeneralizedTime second');\n\t\treturn buildStrictUtcDate(\n\t\t\tNumber.parseInt(yearText, 10),\n\t\t\tmonthText,\n\t\t\tdayText,\n\t\t\thourText,\n\t\t\tminuteText,\n\t\t\tsecondText,\n\t\t\t'GeneralizedTime',\n\t\t);\n\t}\n\tthrow new Error(`Unsupported time tag: ${element.tag}`);\n}\n\n/**\n * Decodes DER INTEGER content octets holding a non-negative value into a JavaScript `number`.\n *\n * @throws if the value is empty, negative, non-minimally encoded, or exceeds {@linkcode Number.MAX_SAFE_INTEGER}.\n */\nexport function decodeIntegerNumber(bytes: Uint8Array): number {\n\tconst magnitude = decodeIntegerMagnitude(bytes);\n\tif (magnitude.type === 'unsafe') {\n\t\tthrow new Error(`Integer too large for safe number (${bytes.length} bytes)`);\n\t}\n\treturn magnitude.value;\n}\n\n/** A non-negative INTEGER value as a `number`, or `unsafe` once it exceeds {@linkcode Number.MAX_SAFE_INTEGER}. */\nexport type IntegerMagnitude =\n\t| { readonly type: 'safe'; readonly value: number }\n\t| { readonly type: 'unsafe' };\n\n/**\n * Decodes DER INTEGER content octets holding a non-negative value, stopping at the first octet past {@linkcode Number.MAX_SAFE_INTEGER}.\n *\n * @param bytes DER INTEGER content octets to decode.\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n * @throws if the value is empty, negative, or non-minimally encoded.\n */\nexport function decodeIntegerMagnitude(bytes: Uint8Array, label = 'INTEGER'): IntegerMagnitude {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error(`${label} is empty`);\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error(`${label} must be non-negative`);\n\t}\n\tif (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 0x80) === 0) {\n\t\tthrow new Error(`${label} must use minimal encoding`);\n\t}\n\tlet value = 0;\n\tfor (const byte of bytes) {\n\t\tif (value > Math.floor((Number.MAX_SAFE_INTEGER - byte) / 256)) {\n\t\t\treturn { type: 'unsafe' };\n\t\t}\n\t\tvalue = value * 256 + byte;\n\t}\n\treturn { type: 'safe', value };\n}\n\n/**\n * Decodes DER INTEGER or ENUMERATED content octets holding a non-negative value of any length into a `bigint`.\n *\n * @param bytes DER content octets to decode.\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n * @throws if the value is empty, negative, or non-minimally encoded.\n */\nexport function decodeNonNegativeIntegerBigInt(bytes: Uint8Array, label = 'INTEGER'): bigint {\n\tdecodeIntegerMagnitude(bytes, label);\n\treturn BigInt(`0x${toHex(bytes)}`);\n}\n\n/**\n * Like {@linkcode decodeIntegerNumber}, but optionally rewrites thrown error messages with a caller-specific field label.\n *\n * @param bytes DER INTEGER content octets to decode.\n * @param label Field name for error messages (defaults to `\"INTEGER\"`).\n * @throws if the value is empty, negative, non-minimally encoded, or exceeds {@linkcode Number.MAX_SAFE_INTEGER}.\n */\nexport function decodeNonNegativeIntegerNumber(bytes: Uint8Array, label = 'INTEGER'): number {\n\tif (label === 'INTEGER') {\n\t\treturn decodeIntegerNumber(bytes);\n\t}\n\ttry {\n\t\treturn decodeIntegerNumber(bytes);\n\t} catch (error) {\n\t\tif (!(error instanceof Error)) {\n\t\t\tthrow error;\n\t\t}\n\t\tswitch (error.message) {\n\t\t\tcase 'INTEGER is empty':\n\t\t\t\tthrow new Error(`${label} is empty`);\n\t\t\tcase 'INTEGER must be non-negative':\n\t\t\t\tthrow new Error(`${label} must be non-negative`);\n\t\t\tcase 'INTEGER must use minimal encoding':\n\t\t\t\tthrow new Error(`${label} must use minimal encoding`);\n\t\t\tdefault:\n\t\t\t\tif (error.message.startsWith('Integer too large for safe number')) {\n\t\t\t\t\tthrow new Error(`${label} too large for safe number (${bytes.length} bytes)`);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t}\n\t}\n}\n\n/**\n * Converts a hex string (even or odd length) to a {@linkcode Uint8Array}.\n * Odd-length strings are left-padded with a zero nibble.\n */\nexport function hexToBytes(value: string): Uint8Array {\n\tconst normalized = value.length % 2 === 0 ? value : `0${value}`;\n\tconst out = new Uint8Array(normalized.length / 2);\n\tfor (let index = 0; index < out.length; index += 1) {\n\t\tconst chunk = normalized.slice(index * 2, index * 2 + 2);\n\t\tif (!/^[0-9a-fA-F]{2}$/.test(chunk)) {\n\t\t\tthrow new Error(`Invalid hex byte: ${chunk}`);\n\t\t}\n\t\tconst parsed = Number.parseInt(chunk, 16);\n\t\tout[index] = parsed;\n\t}\n\treturn out;\n}\n\n/** Decodes a DER BOOLEAN value. X.690 clause 11.1 restricts TRUE to an all-ones octet, so only `0xff` and `0x00` are accepted. */\nexport function decodeBoolean(bytes: Uint8Array): boolean {\n\tif (bytes.length !== 1) {\n\t\tthrow new Error('BOOLEAN must contain exactly one octet');\n\t}\n\tconst value = bytes[0];\n\tif (value !== 0x00 && value !== 0xff) {\n\t\tthrow new Error('BOOLEAN must use DER encoding');\n\t}\n\treturn value === 0xff;\n}\n\nfunction buildStrictUtcDate(\n\tyear: number,\n\tmonthText: string,\n\tdayText: string,\n\thourText: string,\n\tminuteText: string,\n\tsecondText: string,\n\tlabel: 'UTCTime' | 'GeneralizedTime',\n): Date {\n\tconst month = Number.parseInt(monthText, 10);\n\tconst day = Number.parseInt(dayText, 10);\n\tconst hour = Number.parseInt(hourText, 10);\n\tconst minute = Number.parseInt(minuteText, 10);\n\tconst second = Number.parseInt(secondText, 10);\n\tconst date = new Date(Date.UTC(year, month - 1, day, hour, minute, second));\n\tif (\n\t\tNumber.isNaN(date.getTime()) ||\n\t\tdate.getUTCFullYear() !== year ||\n\t\tdate.getUTCMonth() !== month - 1 ||\n\t\tdate.getUTCDate() !== day ||\n\t\tdate.getUTCHours() !== hour ||\n\t\tdate.getUTCMinutes() !== minute ||\n\t\tdate.getUTCSeconds() !== second\n\t) {\n\t\tthrow new Error(`Invalid ${label}`);\n\t}\n\treturn date;\n}\n\nfunction decodeOidSubidentifier(\n\tbytes: Uint8Array,\n\tstart: number,\n): {\n\treadonly value: bigint;\n\treadonly nextOffset: number;\n} {\n\tconst first = bytes[start];\n\tif (first === undefined) {\n\t\tthrow new Error('Malformed OID');\n\t}\n\tif (first === 0x80) {\n\t\tthrow new Error('Malformed OID: non-minimal base-128 encoding');\n\t}\n\tconst end = findOidSubidentifierEnd(bytes, start);\n\tlet value = 0n;\n\tfor (let offset = start; offset <= end; offset += 1) {\n\t\tvalue = (value << 7n) | BigInt((bytes[offset] ?? 0) & 0x7f);\n\t}\n\treturn { value, nextOffset: end + 1 };\n}\n\n/** The offset of the sub-identifier's last octet, checked before any of it is accumulated. */\nfunction findOidSubidentifierEnd(bytes: Uint8Array, start: number): number {\n\tfor (let offset = start; offset < bytes.length; offset += 1) {\n\t\tif (((bytes[offset] ?? 0) & 0x80) === 0) {\n\t\t\treturn offset;\n\t\t}\n\t\tif (offset - start + 1 >= MAX_OID_SUBIDENTIFIER_OCTETS && offset + 1 < bytes.length) {\n\t\t\tthrowDecodeRefusal(\n\t\t\t\t'limit_exceeded',\n\t\t\t\t`OID sub-identifier exceeds ${MAX_OID_SUBIDENTIFIER_OCTETS} octets`,\n\t\t\t);\n\t\t}\n\t}\n\tthrow new Error('Malformed OID: incomplete continuation');\n}\n\n/**\n * Decodes a DER string element by tag.\n *\n * Supports:\n * - UTF8String (`0x0c`),\n * - PrintableString (`0x13`),\n * - TeletexString (`0x14`) in its X.690 §8.23.5.2 initial state,\n * - IA5String (`0x16`),\n * - UniversalString (`0x1c`), and\n * - BMPString (`0x1e`).\n *\n * @throws on unsupported string tags.\n */\nexport function decodeString(tag: number, bytes: Uint8Array): string {\n\tswitch (tag) {\n\t\tcase 0x0c:\n\t\t\treturn decodeUtf8Text(bytes, 'UTF8String');\n\t\tcase 0x13:\n\t\t\treturn decodePrintableString(bytes);\n\t\tcase 0x16:\n\t\t\treturn decodeIa5String(bytes);\n\t\tcase 0x14:\n\t\t\treturn decodeTeletexString(bytes);\n\t\tcase 0x1c:\n\t\t\treturn decodeUniversalString(bytes);\n\t\tcase 0x1e:\n\t\t\treturn decodeBmpString(bytes);\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported string tag: ${tag}`);\n\t}\n}\n\nfunction decodeUtf8Text(\n\tbytes: Uint8Array,\n\tlabel: 'GeneralizedTime' | 'UTCTime' | 'UTF8String',\n): string {\n\ttry {\n\t\treturn textDecoder.decode(bytes);\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tthrow new Error(`Invalid ${label}: invalid UTF-8`, { cause: error });\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction decodeAsciiString(bytes: Uint8Array, label: 'IA5String' | 'PrintableString'): string {\n\tlet value = '';\n\tfor (const byte of bytes) {\n\t\tif (byte > 0x7f) {\n\t\t\tthrow new Error(`Invalid ${label}: contains non-ASCII bytes`);\n\t\t}\n\t\tvalue += String.fromCharCode(byte);\n\t}\n\treturn value;\n}\n\nfunction decodeIa5String(bytes: Uint8Array): string {\n\treturn decodeAsciiString(bytes, 'IA5String');\n}\n\nfunction decodePrintableString(bytes: Uint8Array): string {\n\tconst value = decodeAsciiString(bytes, 'PrintableString');\n\tif (!PRINTABLE_STRING_PATTERN.test(value)) {\n\t\tthrow new Error('Invalid PrintableString: contains characters outside the allowed set');\n\t}\n\treturn value;\n}\n\n/**\n * Decodes VisibleString contents, which X.680 §43.7 limits to 0x20 through 0x7E.\n *\n * @throws on an octet outside that range.\n */\nexport function decodeVisibleString(bytes: Uint8Array): string {\n\tlet value = '';\n\tfor (const byte of bytes) {\n\t\tif (byte < 0x20 || byte > 0x7e) {\n\t\t\tthrow new Error('Invalid VisibleString: contains octets outside 0x20 to 0x7e');\n\t\t}\n\t\tvalue += String.fromCharCode(byte);\n\t}\n\treturn value;\n}\n\n/** T.61 Table 1 leaves these positions of register entry 102 empty. */\nconst TELETEX_EMPTY_POSITIONS: ReadonlySet<number> = new Set([0x5c, 0x5e, 0x60, 0x7b, 0x7d, 0x7e]);\n\n/**\n * Decodes TeletexString contents in the X.690 §8.23.5.2 initial state, reading\n * register entry 102 by T.61 Table 1 and Figure 2 Note 4, with the SPACE and\n * DELETE that X.680 Table 8 adds.\n *\n * @throws `unsupported` on any other octet.\n */\nfunction decodeTeletexString(bytes: Uint8Array): string {\n\tlet value = '';\n\tfor (const byte of bytes) {\n\t\tif (byte < 0x20 || byte > 0x7f || TELETEX_EMPTY_POSITIONS.has(byte)) {\n\t\t\tthrowDecodeRefusal(\n\t\t\t\t'unsupported',\n\t\t\t\t`Unsupported TeletexString octet: 0x${byte.toString(16).padStart(2, '0')}`,\n\t\t\t);\n\t\t}\n\t\tvalue += byte === 0x24 ? '\\u{a4}' : String.fromCharCode(byte);\n\t}\n\treturn value;\n}\n\n/** X.680 §41.15: BMPString holds code units 0000 to D7FF and E000 to FFFD. */\nfunction decodeBmpString(bytes: Uint8Array): string {\n\tif (bytes.length % 2 !== 0) {\n\t\tthrow new Error('Invalid BMPString length');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < bytes.length; index += 2) {\n\t\tconst left = bytes[index];\n\t\tconst right = bytes[index + 1];\n\t\tif (left === undefined || right === undefined) {\n\t\t\tthrow new Error('Invalid BMPString content');\n\t\t}\n\t\tconst codeUnit = (left << 8) | right;\n\t\tif ((codeUnit >= 0xd800 && codeUnit <= 0xdfff) || codeUnit >= 0xfffe) {\n\t\t\tthrow new Error('Invalid BMPString code point');\n\t\t}\n\t\tvalue += String.fromCharCode(codeUnit);\n\t}\n\treturn value;\n}\n\nfunction decodeUniversalString(bytes: Uint8Array): string {\n\tif (bytes.length % 4 !== 0) {\n\t\tthrow new Error('Invalid UniversalString length');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < bytes.length; index += 4) {\n\t\tconst first = bytes[index];\n\t\tconst second = bytes[index + 1];\n\t\tconst third = bytes[index + 2];\n\t\tconst fourth = bytes[index + 3];\n\t\tif (\n\t\t\tfirst === undefined ||\n\t\t\tsecond === undefined ||\n\t\t\tthird === undefined ||\n\t\t\tfourth === undefined\n\t\t) {\n\t\t\tthrow new Error('Invalid UniversalString content');\n\t\t}\n\t\tconst codePoint = ((first * 256 + second) * 256 + third) * 256 + fourth;\n\t\tif (codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) {\n\t\t\tthrow new Error('Invalid UniversalString code point');\n\t\t}\n\t\tvalue += String.fromCodePoint(codePoint);\n\t}\n\treturn value;\n}\n\n/** The verdict of {@linkcode checkStrictDer} on an encoding. */\nexport type StrictDerVerdict = 'valid' | 'malformed' | 'unsupported';\n\n/**\n * Walks {@linkcode bytes} as one DER element and checks each universal-class\n * element against the X.690 rules its tag fixes: the identifier form, the\n * contents, and the DER restrictions of clauses 10 and 11.\n *\n * Where those rules rest on ISO/IEC 2022, ISO 8601 or an implicitly tagged\n * schema, the element is `unsupported`: TeletexString, VideotexString, TIME,\n * EXTERNAL, EMBEDDED PDV, CHARACTER STRING, the types of UNIVERSAL 31 to 36, a\n * REAL with a long-form exponent, a GeneralizedTime at second 60, and text\n * holding an escape sequence or a code-extension control. A SET or SET OF\n * whose children follow neither the DER SET order nor the DER SET OF order is\n * `malformed`. Context-specific, application and private elements get framing\n * checks only, as do the rules that depend on a schema: DEFAULT omission and\n * NamedBitList trailing bits. No value is checked against an ASN.1 type, so\n * ENUMERATED membership, INTEGER ranges, SIZE constraints, CHOICE alternatives\n * and SEQUENCE or SET components stay unchecked.\n *\n * @throws `limit_exceeded` past {@linkcode maxDepth} levels of nesting or on a\n * tag number of 2^53 or more.\n */\nexport function checkStrictDer(\n\tbytes: Uint8Array,\n\tmaxDepth: number = DEFAULT_MAX_DER_DEPTH,\n): StrictDerVerdict {\n\tlet unsupported = false;\n\ttry {\n\t\twalkDerTree(bytes, maxDepth, undefined, (element) => {\n\t\t\tconst verdict = checkUniversalElement(element);\n\t\t\tif (verdict === 'malformed') {\n\t\t\t\tthrow new Error('DER element breaks the rules of its universal type');\n\t\t\t}\n\t\t\tunsupported ||= verdict === 'unsupported';\n\t\t});\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn 'malformed';\n\t}\n\treturn unsupported ? 'unsupported' : 'valid';\n}\n\ntype UniversalElementCheck = (element: DerElement) => StrictDerVerdict;\n\nfunction verdictOf(valid: boolean): StrictDerVerdict {\n\treturn valid ? 'valid' : 'malformed';\n}\n\nfunction decodes(decode: () => unknown): StrictDerVerdict {\n\ttry {\n\t\tdecode();\n\t\treturn 'valid';\n\t} catch {\n\t\treturn 'malformed';\n\t}\n}\n\nfunction asciiText(contents: Uint8Array): string | undefined {\n\ttry {\n\t\treturn decodeIa5String(contents);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nconst ESCAPE = 0x1b;\n\n/** X.690 §8.23.10 and Table 3: UTF8String and IA5String carry no escape sequence. */\nconst ESCAPE_CONTROLS: ReadonlySet<number> = new Set([ESCAPE]);\n\n/** X.690 §8.23.9: SHIFT OUT, SHIFT IN, ESCAPE, SINGLE-SHIFT TWO and THREE, and CONTROL SEQUENCE INTRODUCER. */\nconst CODE_EXTENSION_CONTROLS: ReadonlySet<number> = new Set([\n\t0x0e,\n\t0x0f,\n\tESCAPE,\n\t0x8e,\n\t0x8f,\n\t0x9b,\n]);\n\n/** The verdict on text {@linkcode decode} validates, `unsupported` when it holds one of {@linkcode controls}. */\nfunction checkText(decode: () => string, controls: ReadonlySet<number>): StrictDerVerdict {\n\tlet text: string;\n\ttry {\n\t\ttext = decode();\n\t} catch {\n\t\treturn 'malformed';\n\t}\n\tfor (const character of text) {\n\t\tif (controls.has(character.codePointAt(0) ?? 0)) {\n\t\t\treturn 'unsupported';\n\t\t}\n\t}\n\treturn 'valid';\n}\n\n/** X.690 Table 3: GraphicString and ObjectDescriptor open with register entry 6 as G0 and no C0 or C1 set. */\nfunction checkGraphicString(element: DerElement): StrictDerVerdict {\n\tif (element.value.includes(ESCAPE)) {\n\t\treturn 'unsupported';\n\t}\n\treturn verdictOf(element.value.every((octet) => octet >= 0x20 && octet <= 0x7e));\n}\n\n/** X.690 Table 3: GeneralString opens with register entry 6 as G0 and entry 1 as C0, beside SPACE and DELETE. */\nfunction checkGeneralString(element: DerElement): StrictDerVerdict {\n\tif (element.value.some((octet) => octet === ESCAPE || octet === 0x0e || octet === 0x0f)) {\n\t\treturn 'unsupported';\n\t}\n\treturn verdictOf(element.value.every((octet) => octet <= 0x7f));\n}\n\n/** X.690 §8.3.2: the first nine bits of a multi-octet INTEGER are neither all ones nor all zeros. */\nfunction isMinimalInteger(contents: Uint8Array): boolean {\n\tconst [first, second] = contents;\n\tif (first === undefined) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tsecond === undefined ||\n\t\t((first !== 0x00 || second >= 0x80) && (first !== 0xff || second < 0x80))\n\t);\n}\n\n/** X.690 §8.19.2: every subidentifier ends on an octet with bit 8 clear and never opens with 0x80. */\nfunction isSubidentifierList(contents: Uint8Array): boolean {\n\tlet opensSubidentifier = true;\n\tfor (const octet of contents) {\n\t\tif (opensSubidentifier && octet === 0x80) {\n\t\t\treturn false;\n\t\t}\n\t\topensSubidentifier = (octet & 0x80) === 0;\n\t}\n\treturn opensSubidentifier;\n}\n\nfunction checkBitString(element: DerElement): StrictDerVerdict {\n\ttry {\n\t\treturn verdictOf(!decodeBitString(element).nonZeroPadding);\n\t} catch {\n\t\treturn 'malformed';\n\t}\n}\n\n/** X.680 Table 9: NumericString holds the digits and SPACE. */\nexport function isNumericStringContents(contents: Uint8Array): boolean {\n\treturn contents.every((octet) => octet === 0x20 || (octet >= 0x30 && octet <= 0x39));\n}\n\nfunction isLeapYear(year: number): boolean {\n\treturn (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\nconst DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\ninterface TimeSyntax {\n\treadonly pattern: RegExp;\n\treadonly century: number;\n\treadonly leapSecond: StrictDerVerdict;\n}\n\n/** X.690 §11.8 and X.680 §47.3: `YYMMDDhhmmssZ`, the year as its two low-order digits and seconds 00 to 59. */\nconst UTC_TIME: TimeSyntax = {\n\tpattern: /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/,\n\tcentury: 2000,\n\tleapSecond: 'malformed',\n};\n\n/** X.690 §11.7: seconds present, `.` before a fraction with no trailing zero, and `Z`; ISO 8601 governs second 60. */\nconst GENERALIZED_TIME: TimeSyntax = {\n\tpattern: /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(?:\\.\\d*[1-9])?Z$/,\n\tcentury: 0,\n\tleapSecond: 'unsupported',\n};\n\nfunction checkTime(element: DerElement, syntax: TimeSyntax): StrictDerVerdict {\n\tconst fields = syntax.pattern\n\t\t.exec(asciiText(element.value) ?? '')\n\t\t?.slice(1)\n\t\t.map(Number);\n\tif (fields === undefined) {\n\t\treturn 'malformed';\n\t}\n\tconst [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = fields;\n\tconst monthDays =\n\t\t(DAYS_IN_MONTH[month - 1] ?? 0) + (month === 2 && isLeapYear(syntax.century + year) ? 1 : 0);\n\tif (day < 1 || day > monthDays || hour > 23 || minute > 59 || second > 60) {\n\t\treturn 'malformed';\n\t}\n\treturn second === 60 ? syntax.leapSecond : 'valid';\n}\n\n/**\n * X.690 §11.3.2: NR3 without SPACE, a MINUS SIGN only on a negative value, a\n * mantissa that neither opens nor closes with 0 followed by `.E`, and an\n * exponent written `+0` or with no leading 0 and no PLUS SIGN.\n */\nconst DER_NR3 = /^-?[1-9](?:\\d*[1-9])?\\.E(?:\\+0|-?[1-9]\\d*)$/;\n\n/**\n * X.690 §8.5 and §11.3: an empty plus zero, a one-octet special value, a\n * base-2 binary form with F = 0, the fewest exponent octets and an odd\n * mantissa with no leading zero octet, or a decimal NR3 form. X.690 §8.5.7.4\n * d) leaves the length of a long-form exponent ambiguous.\n */\nfunction checkReal(element: DerElement): StrictDerVerdict {\n\tconst [first] = element.value;\n\tconst rest = element.value.subarray(1);\n\tif (first === undefined) {\n\t\treturn 'valid';\n\t}\n\tif ((first & 0x80) === 0) {\n\t\treturn (first & 0x40) === 0\n\t\t\t? verdictOf(first === 0x03 && DER_NR3.test(asciiText(rest) ?? ''))\n\t\t\t: verdictOf(rest.length === 0 && first <= 0x43);\n\t}\n\tconst format = first & 0x03;\n\tif ((first & 0x3c) !== 0) {\n\t\treturn 'malformed';\n\t}\n\tif (format === 0x03) {\n\t\treturn 'unsupported';\n\t}\n\tconst exponent = rest.subarray(0, format + 1);\n\tconst mantissa = rest.subarray(format + 1);\n\treturn verdictOf(\n\t\texponent.length === format + 1 &&\n\t\t\tisMinimalInteger(exponent) &&\n\t\t\t(mantissa[0] ?? 0) !== 0 &&\n\t\t\t((mantissa.at(-1) ?? 0) & 0x01) === 1,\n\t);\n}\n\n/** X.690 §11.6: set-of encodings compare as octet strings, the shorter padded at its end with zero octets. */\nfunction compareSetOfEncodings(left: Uint8Array, right: Uint8Array): number {\n\tfor (let index = 0; index < Math.max(left.length, right.length); index += 1) {\n\t\tconst difference = (left[index] ?? 0) - (right[index] ?? 0);\n\t\tif (difference !== 0) {\n\t\t\treturn difference;\n\t\t}\n\t}\n\treturn 0;\n}\n\n/**\n * X.690 §10.3 orders SET components by the canonical tag order of X.680 §8.6,\n * which compares class and number and never the constructed bit, and X.690\n * §11.6 orders SET OF components by encoding.\n */\nfunction checkSet(element: DerElement): StrictDerVerdict {\n\tconst children: DerElement[] = [];\n\tfor (let offset = 0; offset < element.value.length; ) {\n\t\tconst child = readElement(element.value, offset);\n\t\tchildren.push(child);\n\t\toffset = child.end;\n\t}\n\tconst encodingOf = (child: DerElement): Uint8Array =>\n\t\telement.value.subarray(child.start - child.headerLength, child.end);\n\tconst setOrder = children.every((child, index) => {\n\t\tconst previous = children[index - 1];\n\t\tif (previous === undefined) {\n\t\t\treturn true;\n\t\t}\n\t\tconst previousClass = previous.tag & 0xc0;\n\t\tconst childClass = child.tag & 0xc0;\n\t\treturn (\n\t\t\tpreviousClass < childClass ||\n\t\t\t(previousClass === childClass && previous.tagNumber < child.tagNumber)\n\t\t);\n\t});\n\tconst setOfOrder = children.every((child, index) => {\n\t\tconst previous = children[index - 1];\n\t\treturn (\n\t\t\tprevious === undefined || compareSetOfEncodings(encodingOf(previous), encodingOf(child)) <= 0\n\t\t);\n\t});\n\treturn verdictOf(setOrder || setOfOrder);\n}\n\n/**\n * The identifier octet DER uses for each universal type, mapped to the check\n * of its contents. A universal identifier missing here is a reserved tag\n * number or a form DER forbids.\n */\nconst UNIVERSAL_ELEMENTS: ReadonlyMap<number, UniversalElementCheck> = new Map<\n\tnumber,\n\tUniversalElementCheck\n>([\n\t[0x01, (element) => decodes(() => decodeBoolean(element.value))],\n\t[0x02, (element) => verdictOf(isMinimalInteger(element.value))],\n\t[0x03, checkBitString],\n\t[0x04, () => 'valid'],\n\t[0x05, (element) => verdictOf(element.value.length === 0)],\n\t[0x06, (element) => verdictOf(element.value.length > 0 && isSubidentifierList(element.value))],\n\t[0x07, checkGraphicString],\n\t[0x09, checkReal],\n\t[0x0a, (element) => verdictOf(isMinimalInteger(element.value))],\n\t[\n\t\t0x0c,\n\t\t(element) => checkText(() => decodeUtf8Text(element.value, 'UTF8String'), ESCAPE_CONTROLS),\n\t],\n\t[0x0d, (element) => verdictOf(element.value.length > 0 && isSubidentifierList(element.value))],\n\t[0x0e, () => 'unsupported'],\n\t[0x12, (element) => verdictOf(isNumericStringContents(element.value))],\n\t[0x13, (element) => decodes(() => decodePrintableString(element.value))],\n\t[0x14, () => 'unsupported'],\n\t[0x15, () => 'unsupported'],\n\t[0x16, (element) => checkText(() => decodeIa5String(element.value), ESCAPE_CONTROLS)],\n\t[0x17, (element) => checkTime(element, UTC_TIME)],\n\t[0x18, (element) => checkTime(element, GENERALIZED_TIME)],\n\t[0x19, checkGraphicString],\n\t[0x1a, (element) => decodes(() => decodeVisibleString(element.value))],\n\t[0x1b, checkGeneralString],\n\t[\n\t\t0x1c,\n\t\t(element) => checkText(() => decodeUniversalString(element.value), CODE_EXTENSION_CONTROLS),\n\t],\n\t[0x1e, (element) => checkText(() => decodeBmpString(element.value), CODE_EXTENSION_CONTROLS)],\n\t[0x28, () => 'unsupported'],\n\t[0x2b, () => 'unsupported'],\n\t[0x30, () => 'valid'],\n\t[0x31, checkSet],\n\t[0x3d, () => 'unsupported'],\n]);\n\n/** X.680 Table 1: UNIVERSAL 31 to 36 are DATE, TIME-OF-DAY, DATE-TIME, DURATION, OID-IRI and RELATIVE-OID-IRI. */\nconst LAST_ASSIGNED_UNIVERSAL_TAG_NUMBER = 36;\n\nfunction checkUniversalElement(element: DerElement): StrictDerVerdict {\n\tif ((element.tag & 0xc0) !== 0) {\n\t\treturn 'valid';\n\t}\n\tif ((element.tag & 0x1f) === 0x1f) {\n\t\treturn element.tagNumber <= LAST_ASSIGNED_UNIVERSAL_TAG_NUMBER ? 'unsupported' : 'malformed';\n\t}\n\treturn UNIVERSAL_ELEMENTS.get(element.tag)?.(element) ?? 'malformed';\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAMA,IAAc,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC,GAEvEC,IAA2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