shogun-core 5.2.0 → 5.2.2

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 (186) hide show
  1. package/README.md +145 -1143
  2. package/dist/browser/defaultVendors-node_modules_hpke_chacha20poly1305_esm_mod_js.shogun-core.js +1220 -0
  3. package/dist/browser/defaultVendors-node_modules_hpke_chacha20poly1305_esm_mod_js.shogun-core.js.map +1 -0
  4. package/dist/browser/defaultVendors-node_modules_hpke_hybridkem-x-wing_esm_mod_js.shogun-core.js +844 -0
  5. package/dist/browser/defaultVendors-node_modules_hpke_hybridkem-x-wing_esm_mod_js.shogun-core.js.map +1 -0
  6. package/dist/browser/defaultVendors-node_modules_mlkem_esm_mod_js.shogun-core.js +2335 -0
  7. package/dist/browser/defaultVendors-node_modules_mlkem_esm_mod_js.shogun-core.js.map +1 -0
  8. package/dist/browser/defaultVendors-node_modules_noble_ciphers_chacha_js.shogun-core.js +999 -0
  9. package/dist/browser/defaultVendors-node_modules_noble_ciphers_chacha_js.shogun-core.js.map +1 -0
  10. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_curve_js-node_modules_noble_curves_esm_-1ce4ed.shogun-core.js +1651 -0
  11. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_curve_js-node_modules_noble_curves_esm_-1ce4ed.shogun-core.js.map +1 -0
  12. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_edwards_js-node_modules_noble_curves_es-a82056.shogun-core.js +825 -0
  13. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_edwards_js-node_modules_noble_curves_es-a82056.shogun-core.js.map +1 -0
  14. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed25519_js.shogun-core.js +508 -0
  15. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed25519_js.shogun-core.js.map +1 -0
  16. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed448_js.shogun-core.js +747 -0
  17. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed448_js.shogun-core.js.map +1 -0
  18. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_nist_js.shogun-core.js +1608 -0
  19. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_nist_js.shogun-core.js.map +1 -0
  20. package/dist/browser/defaultVendors-node_modules_noble_post-quantum_ml-dsa_js.shogun-core.js +2117 -0
  21. package/dist/browser/defaultVendors-node_modules_noble_post-quantum_ml-dsa_js.shogun-core.js.map +1 -0
  22. package/dist/browser/defaultVendors-node_modules_openpgp_dist_openpgp_min_mjs.shogun-core.js +86 -0
  23. package/dist/browser/defaultVendors-node_modules_openpgp_dist_openpgp_min_mjs.shogun-core.js.map +1 -0
  24. package/dist/browser/node_modules_hpke_ml-kem_esm_mod_js.shogun-core.js +539 -0
  25. package/dist/browser/node_modules_hpke_ml-kem_esm_mod_js.shogun-core.js.map +1 -0
  26. package/dist/browser/shogun-core.js +160386 -0
  27. package/dist/browser/shogun-core.js.map +1 -0
  28. package/dist/config/simplified-config.js +236 -0
  29. package/dist/core.js +329 -0
  30. package/dist/crypto/asymmetric.js +99 -0
  31. package/dist/crypto/double-ratchet.js +370 -0
  32. package/dist/crypto/file-encryption.js +213 -0
  33. package/dist/crypto/hashing.js +87 -0
  34. package/dist/crypto/index.js +34 -0
  35. package/dist/crypto/mls-codec.js +202 -0
  36. package/dist/crypto/mls.js +550 -0
  37. package/dist/crypto/pgp.js +390 -0
  38. package/dist/crypto/random-generation.js +341 -0
  39. package/dist/crypto/sframe.js +350 -0
  40. package/dist/crypto/signal-protocol.js +376 -0
  41. package/dist/crypto/symmetric.js +91 -0
  42. package/dist/crypto/types.js +2 -0
  43. package/dist/crypto/utils.js +140 -0
  44. package/dist/examples/auth-test.js +253 -0
  45. package/dist/examples/crypto-identity-example.js +151 -0
  46. package/dist/examples/crypto-working-test.js +83 -0
  47. package/dist/examples/double-ratchet-test.js +155 -0
  48. package/dist/examples/mls-advanced-example.js +294 -0
  49. package/dist/examples/mls-sframe-test.js +304 -0
  50. package/dist/examples/pgp-example.js +200 -0
  51. package/dist/examples/quick-auth-test.js +61 -0
  52. package/dist/examples/random-generation-test.js +151 -0
  53. package/dist/examples/signal-protocol-test.js +38 -0
  54. package/dist/examples/simple-api-test.js +114 -0
  55. package/dist/examples/simple-crypto-identity-example.js +84 -0
  56. package/dist/examples/timeout-test.js +227 -0
  57. package/dist/examples/zkproof-credentials-example.js +212 -0
  58. package/dist/examples/zkproof-example.js +201 -0
  59. package/dist/gundb/api.js +435 -0
  60. package/dist/gundb/crypto.js +283 -0
  61. package/dist/gundb/db.js +1946 -0
  62. package/dist/gundb/derive.js +232 -0
  63. package/dist/gundb/errors.js +76 -0
  64. package/dist/gundb/index.js +22 -0
  65. package/dist/gundb/rxjs.js +447 -0
  66. package/dist/gundb/types.js +5 -0
  67. package/dist/index.js +58 -0
  68. package/dist/interfaces/common.js +2 -0
  69. package/dist/interfaces/events.js +40 -0
  70. package/dist/interfaces/plugin.js +2 -0
  71. package/dist/interfaces/shogun.js +37 -0
  72. package/dist/managers/AuthManager.js +226 -0
  73. package/dist/managers/CoreInitializer.js +228 -0
  74. package/dist/managers/CryptoIdentityManager.js +366 -0
  75. package/dist/managers/EventManager.js +70 -0
  76. package/dist/managers/PluginManager.js +299 -0
  77. package/dist/plugins/base.js +50 -0
  78. package/dist/plugins/index.js +32 -0
  79. package/dist/plugins/nostr/index.js +20 -0
  80. package/dist/plugins/nostr/nostrConnector.js +419 -0
  81. package/dist/plugins/nostr/nostrConnectorPlugin.js +453 -0
  82. package/dist/plugins/nostr/nostrSigner.js +319 -0
  83. package/dist/plugins/nostr/types.js +2 -0
  84. package/dist/plugins/smartwallet/index.js +18 -0
  85. package/dist/plugins/smartwallet/smartWalletPlugin.js +511 -0
  86. package/dist/plugins/smartwallet/types.js +2 -0
  87. package/dist/plugins/web3/index.js +20 -0
  88. package/dist/plugins/web3/types.js +2 -0
  89. package/dist/plugins/web3/web3Connector.js +533 -0
  90. package/dist/plugins/web3/web3ConnectorPlugin.js +455 -0
  91. package/dist/plugins/web3/web3Signer.js +314 -0
  92. package/dist/plugins/webauthn/index.js +19 -0
  93. package/dist/plugins/webauthn/types.js +14 -0
  94. package/dist/plugins/webauthn/webauthn.js +496 -0
  95. package/dist/plugins/webauthn/webauthnPlugin.js +489 -0
  96. package/dist/plugins/webauthn/webauthnSigner.js +310 -0
  97. package/dist/plugins/zkproof/index.js +53 -0
  98. package/dist/plugins/zkproof/types.js +2 -0
  99. package/dist/plugins/zkproof/zkCredentials.js +213 -0
  100. package/dist/plugins/zkproof/zkProofConnector.js +198 -0
  101. package/dist/plugins/zkproof/zkProofPlugin.js +272 -0
  102. package/dist/storage/storage.js +145 -0
  103. package/dist/types/config/simplified-config.d.ts +114 -0
  104. package/dist/types/core.d.ts +305 -0
  105. package/dist/types/crypto/asymmetric.d.ts +6 -0
  106. package/dist/types/crypto/double-ratchet.d.ts +22 -0
  107. package/dist/types/crypto/file-encryption.d.ts +19 -0
  108. package/dist/types/crypto/hashing.d.ts +9 -0
  109. package/dist/types/crypto/index.d.ts +13 -0
  110. package/dist/types/crypto/mls-codec.d.ts +39 -0
  111. package/dist/types/crypto/mls.d.ts +130 -0
  112. package/dist/types/crypto/pgp.d.ts +95 -0
  113. package/dist/types/crypto/random-generation.d.ts +35 -0
  114. package/dist/types/crypto/sframe.d.ts +102 -0
  115. package/dist/types/crypto/signal-protocol.d.ts +26 -0
  116. package/dist/types/crypto/symmetric.d.ts +9 -0
  117. package/dist/types/crypto/types.d.ts +144 -0
  118. package/dist/types/crypto/utils.d.ts +22 -0
  119. package/dist/types/examples/auth-test.d.ts +8 -0
  120. package/dist/types/examples/crypto-identity-example.d.ts +5 -0
  121. package/dist/types/examples/crypto-working-test.d.ts +1 -0
  122. package/dist/types/examples/double-ratchet-test.d.ts +1 -0
  123. package/dist/types/examples/mls-advanced-example.d.ts +53 -0
  124. package/dist/types/examples/mls-sframe-test.d.ts +1 -0
  125. package/dist/types/examples/pgp-example.d.ts +75 -0
  126. package/dist/types/examples/quick-auth-test.d.ts +8 -0
  127. package/dist/types/examples/random-generation-test.d.ts +1 -0
  128. package/dist/types/examples/signal-protocol-test.d.ts +1 -0
  129. package/dist/types/examples/simple-api-test.d.ts +10 -0
  130. package/dist/types/examples/simple-crypto-identity-example.d.ts +6 -0
  131. package/dist/types/examples/timeout-test.d.ts +8 -0
  132. package/dist/types/examples/zkproof-credentials-example.d.ts +12 -0
  133. package/dist/types/examples/zkproof-example.d.ts +11 -0
  134. package/dist/types/gundb/api.d.ts +185 -0
  135. package/dist/types/gundb/crypto.d.ts +95 -0
  136. package/dist/types/gundb/db.d.ts +397 -0
  137. package/dist/types/gundb/derive.d.ts +21 -0
  138. package/dist/types/gundb/errors.d.ts +42 -0
  139. package/dist/types/gundb/index.d.ts +3 -0
  140. package/dist/types/gundb/rxjs.d.ts +110 -0
  141. package/dist/types/gundb/types.d.ts +255 -0
  142. package/dist/types/index.d.ts +16 -0
  143. package/dist/types/interfaces/common.d.ts +85 -0
  144. package/dist/types/interfaces/events.d.ts +131 -0
  145. package/dist/types/interfaces/plugin.d.ts +162 -0
  146. package/dist/types/interfaces/shogun.d.ts +208 -0
  147. package/dist/types/managers/AuthManager.d.ts +72 -0
  148. package/dist/types/managers/CoreInitializer.d.ts +40 -0
  149. package/dist/types/managers/CryptoIdentityManager.d.ts +102 -0
  150. package/dist/types/managers/EventManager.d.ts +49 -0
  151. package/dist/types/managers/PluginManager.d.ts +145 -0
  152. package/dist/types/plugins/base.d.ts +35 -0
  153. package/dist/types/plugins/index.d.ts +18 -0
  154. package/dist/types/plugins/nostr/index.d.ts +4 -0
  155. package/dist/types/plugins/nostr/nostrConnector.d.ts +119 -0
  156. package/dist/types/plugins/nostr/nostrConnectorPlugin.d.ts +163 -0
  157. package/dist/types/plugins/nostr/nostrSigner.d.ts +105 -0
  158. package/dist/types/plugins/nostr/types.d.ts +122 -0
  159. package/dist/types/plugins/smartwallet/index.d.ts +2 -0
  160. package/dist/types/plugins/smartwallet/smartWalletPlugin.d.ts +67 -0
  161. package/dist/types/plugins/smartwallet/types.d.ts +80 -0
  162. package/dist/types/plugins/web3/index.d.ts +4 -0
  163. package/dist/types/plugins/web3/types.d.ts +107 -0
  164. package/dist/types/plugins/web3/web3Connector.d.ts +129 -0
  165. package/dist/types/plugins/web3/web3ConnectorPlugin.d.ts +160 -0
  166. package/dist/types/plugins/web3/web3Signer.d.ts +114 -0
  167. package/dist/types/plugins/webauthn/index.d.ts +3 -0
  168. package/dist/types/plugins/webauthn/types.d.ts +183 -0
  169. package/dist/types/plugins/webauthn/webauthn.d.ts +129 -0
  170. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +179 -0
  171. package/dist/types/plugins/webauthn/webauthnSigner.d.ts +91 -0
  172. package/dist/types/plugins/zkproof/index.d.ts +48 -0
  173. package/dist/types/plugins/zkproof/types.d.ts +123 -0
  174. package/dist/types/plugins/zkproof/zkCredentials.d.ts +112 -0
  175. package/dist/types/plugins/zkproof/zkProofConnector.d.ts +46 -0
  176. package/dist/types/plugins/zkproof/zkProofPlugin.d.ts +76 -0
  177. package/dist/types/storage/storage.d.ts +51 -0
  178. package/dist/types/utils/errorHandler.d.ts +119 -0
  179. package/dist/types/utils/eventEmitter.d.ts +39 -0
  180. package/dist/types/utils/seedPhrase.d.ts +50 -0
  181. package/dist/types/utils/validation.d.ts +27 -0
  182. package/dist/utils/errorHandler.js +246 -0
  183. package/dist/utils/eventEmitter.js +79 -0
  184. package/dist/utils/seedPhrase.js +97 -0
  185. package/dist/utils/validation.js +81 -0
  186. package/package.json +10 -57
@@ -0,0 +1,2117 @@
1
+ "use strict";
2
+ (this["webpackChunkShogunCore"] = this["webpackChunkShogunCore"] || []).push([["defaultVendors-node_modules_noble_post-quantum_ml-dsa_js"],{
3
+
4
+ /***/ "./node_modules/@noble/post-quantum/ml-dsa.js":
5
+ /*!****************************************************************!*\
6
+ !*** ./node_modules/@noble/post-quantum/ml-dsa.js + 7 modules ***!
7
+ \****************************************************************/
8
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
9
+
10
+ // ESM COMPAT FLAG
11
+ __webpack_require__.r(__webpack_exports__);
12
+
13
+ // EXPORTS
14
+ __webpack_require__.d(__webpack_exports__, {
15
+ PARAMS: () => (/* binding */ PARAMS),
16
+ ml_dsa44: () => (/* binding */ ml_dsa44),
17
+ ml_dsa65: () => (/* binding */ ml_dsa65),
18
+ ml_dsa87: () => (/* binding */ ml_dsa87)
19
+ });
20
+
21
+ ;// ./node_modules/@noble/post-quantum/node_modules/@noble/hashes/utils.js
22
+ /**
23
+ * Utilities for hex, bytes, CSPRNG.
24
+ * @module
25
+ */
26
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
27
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
28
+ function isBytes(a) {
29
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
30
+ }
31
+ /** Asserts something is positive integer. */
32
+ function anumber(n, title = '') {
33
+ if (!Number.isSafeInteger(n) || n < 0) {
34
+ const prefix = title && `"${title}" `;
35
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
36
+ }
37
+ }
38
+ /** Asserts something is Uint8Array. */
39
+ function abytes(value, length, title = '') {
40
+ const bytes = isBytes(value);
41
+ const len = value?.length;
42
+ const needsLen = length !== undefined;
43
+ if (!bytes || (needsLen && len !== length)) {
44
+ const prefix = title && `"${title}" `;
45
+ const ofLen = needsLen ? ` of length ${length}` : '';
46
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
47
+ throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
48
+ }
49
+ return value;
50
+ }
51
+ /** Asserts something is hash */
52
+ function ahash(h) {
53
+ if (typeof h !== 'function' || typeof h.create !== 'function')
54
+ throw new Error('Hash must wrapped by utils.createHasher');
55
+ anumber(h.outputLen);
56
+ anumber(h.blockLen);
57
+ }
58
+ /** Asserts a hash instance has not been destroyed / finished */
59
+ function aexists(instance, checkFinished = true) {
60
+ if (instance.destroyed)
61
+ throw new Error('Hash instance has been destroyed');
62
+ if (checkFinished && instance.finished)
63
+ throw new Error('Hash#digest() has already been called');
64
+ }
65
+ /** Asserts output is properly-sized byte array */
66
+ function aoutput(out, instance) {
67
+ abytes(out, undefined, 'digestInto() output');
68
+ const min = instance.outputLen;
69
+ if (out.length < min) {
70
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
71
+ }
72
+ }
73
+ /** Cast u8 / u16 / u32 to u8. */
74
+ function u8(arr) {
75
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
76
+ }
77
+ /** Cast u8 / u16 / u32 to u32. */
78
+ function u32(arr) {
79
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
80
+ }
81
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
82
+ function clean(...arrays) {
83
+ for (let i = 0; i < arrays.length; i++) {
84
+ arrays[i].fill(0);
85
+ }
86
+ }
87
+ /** Create DataView of an array for easy byte-level manipulation. */
88
+ function createView(arr) {
89
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
90
+ }
91
+ /** The rotate right (circular right shift) operation for uint32 */
92
+ function rotr(word, shift) {
93
+ return (word << (32 - shift)) | (word >>> shift);
94
+ }
95
+ /** The rotate left (circular left shift) operation for uint32 */
96
+ function rotl(word, shift) {
97
+ return (word << shift) | ((word >>> (32 - shift)) >>> 0);
98
+ }
99
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
100
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
101
+ /** The byte swap operation for uint32 */
102
+ function byteSwap(word) {
103
+ return (((word << 24) & 0xff000000) |
104
+ ((word << 8) & 0xff0000) |
105
+ ((word >>> 8) & 0xff00) |
106
+ ((word >>> 24) & 0xff));
107
+ }
108
+ /** Conditionally byte swap if on a big-endian platform */
109
+ const swap8IfBE = isLE
110
+ ? (n) => n
111
+ : (n) => byteSwap(n);
112
+ /** In place byte swap for Uint32Array */
113
+ function byteSwap32(arr) {
114
+ for (let i = 0; i < arr.length; i++) {
115
+ arr[i] = byteSwap(arr[i]);
116
+ }
117
+ return arr;
118
+ }
119
+ const swap32IfBE = isLE
120
+ ? (u) => u
121
+ : byteSwap32;
122
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
123
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
124
+ // @ts-ignore
125
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
126
+ // Array where index 0xf0 (240) is mapped to string 'f0'
127
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
128
+ /**
129
+ * Convert byte array to hex string. Uses built-in function, when available.
130
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
131
+ */
132
+ function bytesToHex(bytes) {
133
+ abytes(bytes);
134
+ // @ts-ignore
135
+ if (hasHexBuiltin)
136
+ return bytes.toHex();
137
+ // pre-caching improves the speed 6x
138
+ let hex = '';
139
+ for (let i = 0; i < bytes.length; i++) {
140
+ hex += hexes[bytes[i]];
141
+ }
142
+ return hex;
143
+ }
144
+ // We use optimized technique to convert hex string to byte array
145
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
146
+ function asciiToBase16(ch) {
147
+ if (ch >= asciis._0 && ch <= asciis._9)
148
+ return ch - asciis._0; // '2' => 50-48
149
+ if (ch >= asciis.A && ch <= asciis.F)
150
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
151
+ if (ch >= asciis.a && ch <= asciis.f)
152
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
153
+ return;
154
+ }
155
+ /**
156
+ * Convert hex string to byte array. Uses built-in function, when available.
157
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
158
+ */
159
+ function hexToBytes(hex) {
160
+ if (typeof hex !== 'string')
161
+ throw new Error('hex string expected, got ' + typeof hex);
162
+ // @ts-ignore
163
+ if (hasHexBuiltin)
164
+ return Uint8Array.fromHex(hex);
165
+ const hl = hex.length;
166
+ const al = hl / 2;
167
+ if (hl % 2)
168
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
169
+ const array = new Uint8Array(al);
170
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
171
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
172
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
173
+ if (n1 === undefined || n2 === undefined) {
174
+ const char = hex[hi] + hex[hi + 1];
175
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
176
+ }
177
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
178
+ }
179
+ return array;
180
+ }
181
+ /**
182
+ * There is no setImmediate in browser and setTimeout is slow.
183
+ * Call of async fn will return Promise, which will be fullfiled only on
184
+ * next scheduler queue processing step and this is exactly what we need.
185
+ */
186
+ const nextTick = async () => { };
187
+ /** Returns control to thread each 'tick' ms to avoid blocking. */
188
+ async function asyncLoop(iters, tick, cb) {
189
+ let ts = Date.now();
190
+ for (let i = 0; i < iters; i++) {
191
+ cb(i);
192
+ // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
193
+ const diff = Date.now() - ts;
194
+ if (diff >= 0 && diff < tick)
195
+ continue;
196
+ await nextTick();
197
+ ts += diff;
198
+ }
199
+ }
200
+ /**
201
+ * Converts string to bytes using UTF8 encoding.
202
+ * Built-in doesn't validate input to be string: we do the check.
203
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
204
+ */
205
+ function utf8ToBytes(str) {
206
+ if (typeof str !== 'string')
207
+ throw new Error('string expected');
208
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
209
+ }
210
+ /**
211
+ * Helper for KDFs: consumes uint8array or string.
212
+ * When string is passed, does utf8 decoding, using TextDecoder.
213
+ */
214
+ function kdfInputToBytes(data, errorTitle = '') {
215
+ if (typeof data === 'string')
216
+ return utf8ToBytes(data);
217
+ return abytes(data, undefined, errorTitle);
218
+ }
219
+ /** Copies several Uint8Arrays into one. */
220
+ function concatBytes(...arrays) {
221
+ let sum = 0;
222
+ for (let i = 0; i < arrays.length; i++) {
223
+ const a = arrays[i];
224
+ abytes(a);
225
+ sum += a.length;
226
+ }
227
+ const res = new Uint8Array(sum);
228
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
229
+ const a = arrays[i];
230
+ res.set(a, pad);
231
+ pad += a.length;
232
+ }
233
+ return res;
234
+ }
235
+ /** Merges default options and passed options. */
236
+ function checkOpts(defaults, opts) {
237
+ if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
238
+ throw new Error('options must be object or undefined');
239
+ const merged = Object.assign(defaults, opts);
240
+ return merged;
241
+ }
242
+ /** Creates function with outputLen, blockLen, create properties from a class constructor. */
243
+ function createHasher(hashCons, info = {}) {
244
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
245
+ const tmp = hashCons(undefined);
246
+ hashC.outputLen = tmp.outputLen;
247
+ hashC.blockLen = tmp.blockLen;
248
+ hashC.create = (opts) => hashCons(opts);
249
+ Object.assign(hashC, info);
250
+ return Object.freeze(hashC);
251
+ }
252
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
253
+ function randomBytes(bytesLength = 32) {
254
+ const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
255
+ if (typeof cr?.getRandomValues !== 'function')
256
+ throw new Error('crypto.getRandomValues must be defined');
257
+ return cr.getRandomValues(new Uint8Array(bytesLength));
258
+ }
259
+ /** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */
260
+ const oidNist = (suffix) => ({
261
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
262
+ });
263
+ //# sourceMappingURL=utils.js.map
264
+ ;// ./node_modules/@noble/post-quantum/node_modules/@noble/curves/utils.js
265
+ /**
266
+ * Hex, bytes and number utilities.
267
+ * @module
268
+ */
269
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
270
+
271
+
272
+ const _0n = /* @__PURE__ */ BigInt(0);
273
+ const _1n = /* @__PURE__ */ BigInt(1);
274
+ function abool(value, title = '') {
275
+ if (typeof value !== 'boolean') {
276
+ const prefix = title && `"${title}" `;
277
+ throw new Error(prefix + 'expected boolean, got type=' + typeof value);
278
+ }
279
+ return value;
280
+ }
281
+ // Used in weierstrass, der
282
+ function abignumber(n) {
283
+ if (typeof n === 'bigint') {
284
+ if (!isPosBig(n))
285
+ throw new Error('positive bigint expected, got ' + n);
286
+ }
287
+ else
288
+ anumber(n);
289
+ return n;
290
+ }
291
+ function asafenumber(value, title = '') {
292
+ if (!Number.isSafeInteger(value)) {
293
+ const prefix = title && `"${title}" `;
294
+ throw new Error(prefix + 'expected safe integer, got type=' + typeof value);
295
+ }
296
+ }
297
+ function numberToHexUnpadded(num) {
298
+ const hex = abignumber(num).toString(16);
299
+ return hex.length & 1 ? '0' + hex : hex;
300
+ }
301
+ function hexToNumber(hex) {
302
+ if (typeof hex !== 'string')
303
+ throw new Error('hex string expected, got ' + typeof hex);
304
+ return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
305
+ }
306
+ // BE: Big Endian, LE: Little Endian
307
+ function bytesToNumberBE(bytes) {
308
+ return hexToNumber(bytesToHex(bytes));
309
+ }
310
+ function bytesToNumberLE(bytes) {
311
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
312
+ }
313
+ function numberToBytesBE(n, len) {
314
+ anumber(len);
315
+ n = abignumber(n);
316
+ const res = hexToBytes(n.toString(16).padStart(len * 2, '0'));
317
+ if (res.length !== len)
318
+ throw new Error('number too large');
319
+ return res;
320
+ }
321
+ function numberToBytesLE(n, len) {
322
+ return numberToBytesBE(n, len).reverse();
323
+ }
324
+ // Unpadded, rarely used
325
+ function numberToVarBytesBE(n) {
326
+ return hexToBytes(numberToHexUnpadded(abignumber(n)));
327
+ }
328
+ // Compares 2 u8a-s in kinda constant time
329
+ function equalBytes(a, b) {
330
+ if (a.length !== b.length)
331
+ return false;
332
+ let diff = 0;
333
+ for (let i = 0; i < a.length; i++)
334
+ diff |= a[i] ^ b[i];
335
+ return diff === 0;
336
+ }
337
+ /**
338
+ * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
339
+ * and Buffer#slice creates mutable copy. Never use Buffers!
340
+ */
341
+ function copyBytes(bytes) {
342
+ return Uint8Array.from(bytes);
343
+ }
344
+ /**
345
+ * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
346
+ * Should be safe to use for things expected to be ASCII.
347
+ * Returns exact same result as `TextEncoder` for ASCII or throws.
348
+ */
349
+ function asciiToBytes(ascii) {
350
+ return Uint8Array.from(ascii, (c, i) => {
351
+ const charCode = c.charCodeAt(0);
352
+ if (c.length !== 1 || charCode > 127) {
353
+ throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
354
+ }
355
+ return charCode;
356
+ });
357
+ }
358
+ // Is positive bigint
359
+ const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
360
+ function inRange(n, min, max) {
361
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
362
+ }
363
+ /**
364
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
365
+ * @example
366
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
367
+ */
368
+ function aInRange(title, n, min, max) {
369
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
370
+ // consider P=256n, min=0n, max=P
371
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
372
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
373
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
374
+ if (!inRange(n, min, max))
375
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
376
+ }
377
+ // Bit operations
378
+ /**
379
+ * Calculates amount of bits in a bigint.
380
+ * Same as `n.toString(2).length`
381
+ * TODO: merge with nLength in modular
382
+ */
383
+ function bitLen(n) {
384
+ let len;
385
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
386
+ ;
387
+ return len;
388
+ }
389
+ /**
390
+ * Gets single bit at position.
391
+ * NOTE: first bit position is 0 (same as arrays)
392
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
393
+ */
394
+ function bitGet(n, pos) {
395
+ return (n >> BigInt(pos)) & _1n;
396
+ }
397
+ /**
398
+ * Sets single bit at position.
399
+ */
400
+ function bitSet(n, pos, value) {
401
+ return n | ((value ? _1n : _0n) << BigInt(pos));
402
+ }
403
+ /**
404
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
405
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
406
+ */
407
+ const bitMask = (n) => (_1n << BigInt(n)) - _1n;
408
+ /**
409
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
410
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
411
+ * @example
412
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
413
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
414
+ */
415
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
416
+ anumber(hashLen, 'hashLen');
417
+ anumber(qByteLen, 'qByteLen');
418
+ if (typeof hmacFn !== 'function')
419
+ throw new Error('hmacFn must be a function');
420
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
421
+ const NULL = Uint8Array.of();
422
+ const byte0 = Uint8Array.of(0x00);
423
+ const byte1 = Uint8Array.of(0x01);
424
+ const _maxDrbgIters = 1000;
425
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
426
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
427
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
428
+ let i = 0; // Iterations counter, will throw when over 1000
429
+ const reset = () => {
430
+ v.fill(1);
431
+ k.fill(0);
432
+ i = 0;
433
+ };
434
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs)); // hmac(k)(v, ...values)
435
+ const reseed = (seed = NULL) => {
436
+ // HMAC-DRBG reseed() function. Steps D-G
437
+ k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)
438
+ v = h(); // v = hmac(k || v)
439
+ if (seed.length === 0)
440
+ return;
441
+ k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)
442
+ v = h(); // v = hmac(k || v)
443
+ };
444
+ const gen = () => {
445
+ // HMAC-DRBG generate() function
446
+ if (i++ >= _maxDrbgIters)
447
+ throw new Error('drbg: tried max amount of iterations');
448
+ let len = 0;
449
+ const out = [];
450
+ while (len < qByteLen) {
451
+ v = h();
452
+ const sl = v.slice();
453
+ out.push(sl);
454
+ len += v.length;
455
+ }
456
+ return concatBytes(...out);
457
+ };
458
+ const genUntil = (seed, pred) => {
459
+ reset();
460
+ reseed(seed); // Steps D-G
461
+ let res = undefined; // Step H: grind until k is in [1..n-1]
462
+ while (!(res = pred(gen())))
463
+ reseed();
464
+ reset();
465
+ return res;
466
+ };
467
+ return genUntil;
468
+ }
469
+ function validateObject(object, fields = {}, optFields = {}) {
470
+ if (!object || typeof object !== 'object')
471
+ throw new Error('expected valid options object');
472
+ function checkField(fieldName, expectedType, isOpt) {
473
+ const val = object[fieldName];
474
+ if (isOpt && val === undefined)
475
+ return;
476
+ const current = typeof val;
477
+ if (current !== expectedType || val === null)
478
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
479
+ }
480
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
481
+ iter(fields, false);
482
+ iter(optFields, true);
483
+ }
484
+ /**
485
+ * throws not implemented error
486
+ */
487
+ const notImplemented = () => {
488
+ throw new Error('not implemented');
489
+ };
490
+ /**
491
+ * Memoizes (caches) computation result.
492
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
493
+ */
494
+ function memoized(fn) {
495
+ const map = new WeakMap();
496
+ return (arg, ...args) => {
497
+ const val = map.get(arg);
498
+ if (val !== undefined)
499
+ return val;
500
+ const computed = fn(arg, ...args);
501
+ map.set(arg, computed);
502
+ return computed;
503
+ };
504
+ }
505
+ //# sourceMappingURL=utils.js.map
506
+ ;// ./node_modules/@noble/post-quantum/node_modules/@noble/hashes/_u64.js
507
+ /**
508
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
509
+ * @todo re-check https://issues.chromium.org/issues/42212588
510
+ * @module
511
+ */
512
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
513
+ const _32n = /* @__PURE__ */ BigInt(32);
514
+ function fromBig(n, le = false) {
515
+ if (le)
516
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
517
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
518
+ }
519
+ function split(lst, le = false) {
520
+ const len = lst.length;
521
+ let Ah = new Uint32Array(len);
522
+ let Al = new Uint32Array(len);
523
+ for (let i = 0; i < len; i++) {
524
+ const { h, l } = fromBig(lst[i], le);
525
+ [Ah[i], Al[i]] = [h, l];
526
+ }
527
+ return [Ah, Al];
528
+ }
529
+ const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
530
+ // for Shift in [0, 32)
531
+ const shrSH = (h, _l, s) => h >>> s;
532
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
533
+ // Right rotate for Shift in [1, 32)
534
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
535
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
536
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
537
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
538
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
539
+ // Right rotate for shift===32 (just swaps l&h)
540
+ const rotr32H = (_h, l) => l;
541
+ const rotr32L = (h, _l) => h;
542
+ // Left rotate for Shift in [1, 32)
543
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
544
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
545
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
546
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
547
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
548
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
549
+ // simple take carry out of low bit sum by shift, we need to use division.
550
+ function add(Ah, Al, Bh, Bl) {
551
+ const l = (Al >>> 0) + (Bl >>> 0);
552
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
553
+ }
554
+ // Addition with more than 2 elements
555
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
556
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
557
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
558
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
559
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
560
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
561
+ // prettier-ignore
562
+
563
+ // prettier-ignore
564
+ const u64 = {
565
+ fromBig, split, toBig,
566
+ shrSH, shrSL,
567
+ rotrSH, rotrSL, rotrBH, rotrBL,
568
+ rotr32H, rotr32L,
569
+ rotlSH, rotlSL, rotlBH, rotlBL,
570
+ add, add3L, add3H, add4L, add4H, add5H, add5L,
571
+ };
572
+ /* harmony default export */ const _u64 = (u64);
573
+ //# sourceMappingURL=_u64.js.map
574
+ ;// ./node_modules/@noble/post-quantum/node_modules/@noble/hashes/sha3.js
575
+ /**
576
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
577
+ * Different from older hashes, the internal state is bigger than output size.
578
+ *
579
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
580
+ * [Website](https://keccak.team/keccak.html),
581
+ * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
582
+ *
583
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
584
+ * @module
585
+ */
586
+
587
+ // prettier-ignore
588
+
589
+ // No __PURE__ annotations in sha3 header:
590
+ // EVERYTHING is in fact used on every export.
591
+ // Various per round constants calculations
592
+ const sha3_0n = BigInt(0);
593
+ const sha3_1n = BigInt(1);
594
+ const _2n = BigInt(2);
595
+ const _7n = BigInt(7);
596
+ const _256n = BigInt(256);
597
+ const _0x71n = BigInt(0x71);
598
+ const SHA3_PI = [];
599
+ const SHA3_ROTL = [];
600
+ const _SHA3_IOTA = []; // no pure annotation: var is always used
601
+ for (let round = 0, R = sha3_1n, x = 1, y = 0; round < 24; round++) {
602
+ // Pi
603
+ [x, y] = [y, (2 * x + 3 * y) % 5];
604
+ SHA3_PI.push(2 * (5 * y + x));
605
+ // Rotational
606
+ SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
607
+ // Iota
608
+ let t = sha3_0n;
609
+ for (let j = 0; j < 7; j++) {
610
+ R = ((R << sha3_1n) ^ ((R >> _7n) * _0x71n)) % _256n;
611
+ if (R & _2n)
612
+ t ^= sha3_1n << ((sha3_1n << BigInt(j)) - sha3_1n);
613
+ }
614
+ _SHA3_IOTA.push(t);
615
+ }
616
+ const IOTAS = split(_SHA3_IOTA, true);
617
+ const SHA3_IOTA_H = IOTAS[0];
618
+ const SHA3_IOTA_L = IOTAS[1];
619
+ // Left rotation (without 0, 32, 64)
620
+ const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
621
+ const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
622
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
623
+ function keccakP(s, rounds = 24) {
624
+ const B = new Uint32Array(5 * 2);
625
+ // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
626
+ for (let round = 24 - rounds; round < 24; round++) {
627
+ // Theta θ
628
+ for (let x = 0; x < 10; x++)
629
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
630
+ for (let x = 0; x < 10; x += 2) {
631
+ const idx1 = (x + 8) % 10;
632
+ const idx0 = (x + 2) % 10;
633
+ const B0 = B[idx0];
634
+ const B1 = B[idx0 + 1];
635
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
636
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
637
+ for (let y = 0; y < 50; y += 10) {
638
+ s[x + y] ^= Th;
639
+ s[x + y + 1] ^= Tl;
640
+ }
641
+ }
642
+ // Rho (ρ) and Pi (π)
643
+ let curH = s[2];
644
+ let curL = s[3];
645
+ for (let t = 0; t < 24; t++) {
646
+ const shift = SHA3_ROTL[t];
647
+ const Th = rotlH(curH, curL, shift);
648
+ const Tl = rotlL(curH, curL, shift);
649
+ const PI = SHA3_PI[t];
650
+ curH = s[PI];
651
+ curL = s[PI + 1];
652
+ s[PI] = Th;
653
+ s[PI + 1] = Tl;
654
+ }
655
+ // Chi (χ)
656
+ for (let y = 0; y < 50; y += 10) {
657
+ for (let x = 0; x < 10; x++)
658
+ B[x] = s[y + x];
659
+ for (let x = 0; x < 10; x++)
660
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
661
+ }
662
+ // Iota (ι)
663
+ s[0] ^= SHA3_IOTA_H[round];
664
+ s[1] ^= SHA3_IOTA_L[round];
665
+ }
666
+ clean(B);
667
+ }
668
+ /** Keccak sponge function. */
669
+ class Keccak {
670
+ state;
671
+ pos = 0;
672
+ posOut = 0;
673
+ finished = false;
674
+ state32;
675
+ destroyed = false;
676
+ blockLen;
677
+ suffix;
678
+ outputLen;
679
+ enableXOF = false;
680
+ rounds;
681
+ // NOTE: we accept arguments in bytes instead of bits here.
682
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
683
+ this.blockLen = blockLen;
684
+ this.suffix = suffix;
685
+ this.outputLen = outputLen;
686
+ this.enableXOF = enableXOF;
687
+ this.rounds = rounds;
688
+ // Can be passed from user as dkLen
689
+ anumber(outputLen, 'outputLen');
690
+ // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
691
+ // 0 < blockLen < 200
692
+ if (!(0 < blockLen && blockLen < 200))
693
+ throw new Error('only keccak-f1600 function is supported');
694
+ this.state = new Uint8Array(200);
695
+ this.state32 = u32(this.state);
696
+ }
697
+ clone() {
698
+ return this._cloneInto();
699
+ }
700
+ keccak() {
701
+ swap32IfBE(this.state32);
702
+ keccakP(this.state32, this.rounds);
703
+ swap32IfBE(this.state32);
704
+ this.posOut = 0;
705
+ this.pos = 0;
706
+ }
707
+ update(data) {
708
+ aexists(this);
709
+ abytes(data);
710
+ const { blockLen, state } = this;
711
+ const len = data.length;
712
+ for (let pos = 0; pos < len;) {
713
+ const take = Math.min(blockLen - this.pos, len - pos);
714
+ for (let i = 0; i < take; i++)
715
+ state[this.pos++] ^= data[pos++];
716
+ if (this.pos === blockLen)
717
+ this.keccak();
718
+ }
719
+ return this;
720
+ }
721
+ finish() {
722
+ if (this.finished)
723
+ return;
724
+ this.finished = true;
725
+ const { state, suffix, pos, blockLen } = this;
726
+ // Do the padding
727
+ state[pos] ^= suffix;
728
+ if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
729
+ this.keccak();
730
+ state[blockLen - 1] ^= 0x80;
731
+ this.keccak();
732
+ }
733
+ writeInto(out) {
734
+ aexists(this, false);
735
+ abytes(out);
736
+ this.finish();
737
+ const bufferOut = this.state;
738
+ const { blockLen } = this;
739
+ for (let pos = 0, len = out.length; pos < len;) {
740
+ if (this.posOut >= blockLen)
741
+ this.keccak();
742
+ const take = Math.min(blockLen - this.posOut, len - pos);
743
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
744
+ this.posOut += take;
745
+ pos += take;
746
+ }
747
+ return out;
748
+ }
749
+ xofInto(out) {
750
+ // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
751
+ if (!this.enableXOF)
752
+ throw new Error('XOF is not possible for this instance');
753
+ return this.writeInto(out);
754
+ }
755
+ xof(bytes) {
756
+ anumber(bytes);
757
+ return this.xofInto(new Uint8Array(bytes));
758
+ }
759
+ digestInto(out) {
760
+ aoutput(out, this);
761
+ if (this.finished)
762
+ throw new Error('digest() was already called');
763
+ this.writeInto(out);
764
+ this.destroy();
765
+ return out;
766
+ }
767
+ digest() {
768
+ return this.digestInto(new Uint8Array(this.outputLen));
769
+ }
770
+ destroy() {
771
+ this.destroyed = true;
772
+ clean(this.state);
773
+ }
774
+ _cloneInto(to) {
775
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
776
+ to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
777
+ to.state32.set(this.state32);
778
+ to.pos = this.pos;
779
+ to.posOut = this.posOut;
780
+ to.finished = this.finished;
781
+ to.rounds = rounds;
782
+ // Suffix can change in cSHAKE
783
+ to.suffix = suffix;
784
+ to.outputLen = outputLen;
785
+ to.enableXOF = enableXOF;
786
+ to.destroyed = this.destroyed;
787
+ return to;
788
+ }
789
+ }
790
+ const genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
791
+ /** SHA3-224 hash function. */
792
+ const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28,
793
+ /* @__PURE__ */ oidNist(0x07));
794
+ /** SHA3-256 hash function. Different from keccak-256. */
795
+ const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32,
796
+ /* @__PURE__ */ oidNist(0x08));
797
+ /** SHA3-384 hash function. */
798
+ const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48,
799
+ /* @__PURE__ */ oidNist(0x09));
800
+ /** SHA3-512 hash function. */
801
+ const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64,
802
+ /* @__PURE__ */ oidNist(0x0a));
803
+ /** keccak-224 hash function. */
804
+ const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);
805
+ /** keccak-256 hash function. Different from SHA3-256. */
806
+ const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);
807
+ /** keccak-384 hash function. */
808
+ const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);
809
+ /** keccak-512 hash function. */
810
+ const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);
811
+ const genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);
812
+ /** SHAKE128 XOF with 128-bit security. */
813
+ const shake128 =
814
+ /* @__PURE__ */
815
+ genShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));
816
+ /** SHAKE256 XOF with 256-bit security. */
817
+ const shake256 =
818
+ /* @__PURE__ */
819
+ genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));
820
+ /** SHAKE128 XOF with 256-bit output (NIST version). */
821
+ const shake128_32 =
822
+ /* @__PURE__ */
823
+ genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));
824
+ /** SHAKE256 XOF with 512-bit output (NIST version). */
825
+ const shake256_64 =
826
+ /* @__PURE__ */
827
+ genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));
828
+ //# sourceMappingURL=sha3.js.map
829
+ ;// ./node_modules/@noble/post-quantum/node_modules/@noble/curves/abstract/fft.js
830
+ function checkU32(n) {
831
+ // 0xff_ff_ff_ff
832
+ if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
833
+ throw new Error('wrong u32 integer:' + n);
834
+ return n;
835
+ }
836
+ /** Checks if integer is in form of `1 << X` */
837
+ function isPowerOfTwo(x) {
838
+ checkU32(x);
839
+ return (x & (x - 1)) === 0 && x !== 0;
840
+ }
841
+ function nextPowerOfTwo(n) {
842
+ checkU32(n);
843
+ if (n <= 1)
844
+ return 1;
845
+ return (1 << (log2(n - 1) + 1)) >>> 0;
846
+ }
847
+ function reverseBits(n, bits) {
848
+ checkU32(n);
849
+ let reversed = 0;
850
+ for (let i = 0; i < bits; i++, n >>>= 1)
851
+ reversed = (reversed << 1) | (n & 1);
852
+ return reversed;
853
+ }
854
+ /** Similar to `bitLen(x)-1` but much faster for small integers, like indices */
855
+ function log2(n) {
856
+ checkU32(n);
857
+ return 31 - Math.clz32(n);
858
+ }
859
+ /**
860
+ * Moves lowest bit to highest position, which at first step splits
861
+ * array on even and odd indices, then it applied again to each part,
862
+ * which is core of fft
863
+ */
864
+ function bitReversalInplace(values) {
865
+ const n = values.length;
866
+ if (n < 2 || !isPowerOfTwo(n))
867
+ throw new Error('n must be a power of 2 and greater than 1. Got ' + n);
868
+ const bits = log2(n);
869
+ for (let i = 0; i < n; i++) {
870
+ const j = reverseBits(i, bits);
871
+ if (i < j) {
872
+ const tmp = values[i];
873
+ values[i] = values[j];
874
+ values[j] = tmp;
875
+ }
876
+ }
877
+ return values;
878
+ }
879
+ function bitReversalPermutation(values) {
880
+ return bitReversalInplace(values.slice());
881
+ }
882
+ const fft_1n = /** @__PURE__ */ BigInt(1);
883
+ function findGenerator(field) {
884
+ let G = BigInt(2);
885
+ for (; field.eql(field.pow(G, field.ORDER >> fft_1n), field.ONE); G++)
886
+ ;
887
+ return G;
888
+ }
889
+ /** We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. */
890
+ function rootsOfUnity(field, generator) {
891
+ // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo
892
+ let oddFactor = field.ORDER - fft_1n;
893
+ let powerOfTwo = 0;
894
+ for (; (oddFactor & fft_1n) !== fft_1n; powerOfTwo++, oddFactor >>= fft_1n)
895
+ ;
896
+ // Find non quadratic residue
897
+ let G = generator !== undefined ? BigInt(generator) : findGenerator(field);
898
+ // Powers of generator
899
+ const omegas = new Array(powerOfTwo + 1);
900
+ omegas[powerOfTwo] = field.pow(G, oddFactor);
901
+ for (let i = powerOfTwo; i > 0; i--)
902
+ omegas[i - 1] = field.sqr(omegas[i]);
903
+ // Compute all roots of unity for powers up to maxPower
904
+ const rootsCache = [];
905
+ const checkBits = (bits) => {
906
+ checkU32(bits);
907
+ if (bits > 31 || bits > powerOfTwo)
908
+ throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);
909
+ return bits;
910
+ };
911
+ const precomputeRoots = (maxPower) => {
912
+ checkBits(maxPower);
913
+ for (let power = maxPower; power >= 0; power--) {
914
+ if (rootsCache[power])
915
+ continue; // Skip if we've already computed roots for this power
916
+ const rootsAtPower = [];
917
+ for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))
918
+ rootsAtPower.push(cur);
919
+ rootsCache[power] = rootsAtPower;
920
+ }
921
+ return rootsCache[maxPower];
922
+ };
923
+ const brpCache = new Map();
924
+ const inverseCache = new Map();
925
+ // NOTE: we use bits instead of power, because power = 2**bits,
926
+ // but power is not neccesary isPowerOfTwo(power)!
927
+ return {
928
+ info: { G, powerOfTwo, oddFactor },
929
+ roots: (bits) => {
930
+ const b = checkBits(bits);
931
+ return precomputeRoots(b);
932
+ },
933
+ brp(bits) {
934
+ const b = checkBits(bits);
935
+ if (brpCache.has(b))
936
+ return brpCache.get(b);
937
+ else {
938
+ const res = bitReversalPermutation(this.roots(b));
939
+ brpCache.set(b, res);
940
+ return res;
941
+ }
942
+ },
943
+ inverse(bits) {
944
+ const b = checkBits(bits);
945
+ if (inverseCache.has(b))
946
+ return inverseCache.get(b);
947
+ else {
948
+ const res = field.invertBatch(this.roots(b));
949
+ inverseCache.set(b, res);
950
+ return res;
951
+ }
952
+ },
953
+ omega: (bits) => omegas[checkBits(bits)],
954
+ clear: () => {
955
+ rootsCache.splice(0, rootsCache.length);
956
+ brpCache.clear();
957
+ },
958
+ };
959
+ }
960
+ /**
961
+ * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
962
+ *
963
+ * - DIT (Decimation-in-Time): Bottom-Up (leaves -> root), Cool-Turkey
964
+ * - DIF (Decimation-in-Frequency): Top-Down (root -> leaves), Gentleman–Sande
965
+ *
966
+ * DIT takes brp input, returns natural output.
967
+ * DIF takes natural input, returns brp output.
968
+ *
969
+ * The output is actually identical. Time / frequence distinction is not meaningful
970
+ * for Polynomial multiplication in fields.
971
+ * Which means if protocol supports/needs brp output/inputs, then we can skip this step.
972
+ *
973
+ * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
974
+ * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
975
+ */
976
+ const FFTCore = (F, coreOpts) => {
977
+ const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
978
+ const bits = log2(N);
979
+ if (!isPowerOfTwo(N))
980
+ throw new Error('FFT: Polynomial size should be power of two');
981
+ const isDit = dit !== invertButterflies;
982
+ isDit;
983
+ return (values) => {
984
+ if (values.length !== N)
985
+ throw new Error('FFT: wrong Polynomial length');
986
+ if (dit && brp)
987
+ bitReversalInplace(values);
988
+ for (let i = 0, g = 1; i < bits - skipStages; i++) {
989
+ // For each stage s (sub-FFT length m = 2^s)
990
+ const s = dit ? i + 1 + skipStages : bits - i;
991
+ const m = 1 << s;
992
+ const m2 = m >> 1;
993
+ const stride = N >> s;
994
+ // Loop over each subarray of length m
995
+ for (let k = 0; k < N; k += m) {
996
+ // Loop over each butterfly within the subarray
997
+ for (let j = 0, grp = g++; j < m2; j++) {
998
+ const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
999
+ const i0 = k + j;
1000
+ const i1 = k + j + m2;
1001
+ const omega = roots[rootPos];
1002
+ const b = values[i1];
1003
+ const a = values[i0];
1004
+ // Inlining gives us 10% perf in kyber vs functions
1005
+ if (isDit) {
1006
+ const t = F.mul(b, omega); // Standard DIT butterfly
1007
+ values[i0] = F.add(a, t);
1008
+ values[i1] = F.sub(a, t);
1009
+ }
1010
+ else if (invertButterflies) {
1011
+ values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)
1012
+ values[i1] = F.mul(F.sub(b, a), omega);
1013
+ }
1014
+ else {
1015
+ values[i0] = F.add(a, b); // Standard DIF butterfly
1016
+ values[i1] = F.mul(F.sub(a, b), omega);
1017
+ }
1018
+ }
1019
+ }
1020
+ }
1021
+ if (!dit && brp)
1022
+ bitReversalInplace(values);
1023
+ return values;
1024
+ };
1025
+ };
1026
+ /**
1027
+ * NTT aka FFT over finite field (NOT over complex numbers).
1028
+ * Naming mirrors other libraries.
1029
+ */
1030
+ function FFT(roots, opts) {
1031
+ const getLoop = (N, roots, brpInput = false, brpOutput = false) => {
1032
+ if (brpInput && brpOutput) {
1033
+ // we cannot optimize this case, but lets support it anyway
1034
+ return (values) => FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));
1035
+ }
1036
+ if (brpInput)
1037
+ return FFTCore(opts, { N, roots, dit: true, brp: false });
1038
+ if (brpOutput)
1039
+ return FFTCore(opts, { N, roots, dit: false, brp: false });
1040
+ return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural
1041
+ };
1042
+ return {
1043
+ direct(values, brpInput = false, brpOutput = false) {
1044
+ const N = values.length;
1045
+ if (!isPowerOfTwo(N))
1046
+ throw new Error('FFT: Polynomial size should be power of two');
1047
+ const bits = log2(N);
1048
+ return getLoop(N, roots.roots(bits), brpInput, brpOutput)(values.slice());
1049
+ },
1050
+ inverse(values, brpInput = false, brpOutput = false) {
1051
+ const N = values.length;
1052
+ const bits = log2(N);
1053
+ const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());
1054
+ const ivm = opts.inv(BigInt(values.length)); // scale
1055
+ // we can get brp output if we use dif instead of dit!
1056
+ for (let i = 0; i < res.length; i++)
1057
+ res[i] = opts.mul(res[i], ivm);
1058
+ // Allows to re-use non-inverted roots, but is VERY fragile
1059
+ // return [res[0]].concat(res.slice(1).reverse());
1060
+ // inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)
1061
+ return res;
1062
+ },
1063
+ };
1064
+ }
1065
+ function poly(field, roots, create, fft, length) {
1066
+ const F = field;
1067
+ const _create = create ||
1068
+ ((len, elm) => new Array(len).fill(elm ?? F.ZERO));
1069
+ const isPoly = (x) => Array.isArray(x) || ArrayBuffer.isView(x);
1070
+ const checkLength = (...lst) => {
1071
+ if (!lst.length)
1072
+ return 0;
1073
+ for (const i of lst)
1074
+ if (!isPoly(i))
1075
+ throw new Error('poly: not polynomial: ' + i);
1076
+ const L = lst[0].length;
1077
+ for (let i = 1; i < lst.length; i++)
1078
+ if (lst[i].length !== L)
1079
+ throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
1080
+ if (length !== undefined && L !== length)
1081
+ throw new Error(`poly: expected fixed length ${length}, got ${L}`);
1082
+ return L;
1083
+ };
1084
+ function findOmegaIndex(x, n, brp = false) {
1085
+ const bits = log2(n);
1086
+ const omega = brp ? roots.brp(bits) : roots.roots(bits);
1087
+ for (let i = 0; i < n; i++)
1088
+ if (F.eql(x, omega[i]))
1089
+ return i;
1090
+ return -1;
1091
+ }
1092
+ // TODO: mutating versions for mlkem/mldsa
1093
+ return {
1094
+ roots,
1095
+ create: _create,
1096
+ length,
1097
+ extend: (a, len) => {
1098
+ checkLength(a);
1099
+ const out = _create(len, F.ZERO);
1100
+ for (let i = 0; i < a.length; i++)
1101
+ out[i] = a[i];
1102
+ return out;
1103
+ },
1104
+ degree: (a) => {
1105
+ checkLength(a);
1106
+ for (let i = a.length - 1; i >= 0; i--)
1107
+ if (!F.is0(a[i]))
1108
+ return i;
1109
+ return -1;
1110
+ },
1111
+ add: (a, b) => {
1112
+ const len = checkLength(a, b);
1113
+ const out = _create(len);
1114
+ for (let i = 0; i < len; i++)
1115
+ out[i] = F.add(a[i], b[i]);
1116
+ return out;
1117
+ },
1118
+ sub: (a, b) => {
1119
+ const len = checkLength(a, b);
1120
+ const out = _create(len);
1121
+ for (let i = 0; i < len; i++)
1122
+ out[i] = F.sub(a[i], b[i]);
1123
+ return out;
1124
+ },
1125
+ dot: (a, b) => {
1126
+ const len = checkLength(a, b);
1127
+ const out = _create(len);
1128
+ for (let i = 0; i < len; i++)
1129
+ out[i] = F.mul(a[i], b[i]);
1130
+ return out;
1131
+ },
1132
+ mul: (a, b) => {
1133
+ if (isPoly(b)) {
1134
+ const len = checkLength(a, b);
1135
+ if (fft) {
1136
+ const A = fft.direct(a, false, true);
1137
+ const B = fft.direct(b, false, true);
1138
+ for (let i = 0; i < A.length; i++)
1139
+ A[i] = F.mul(A[i], B[i]);
1140
+ return fft.inverse(A, true, false);
1141
+ }
1142
+ else {
1143
+ // NOTE: this is quadratic and mostly for compat tests with FFT
1144
+ const res = _create(len);
1145
+ for (let i = 0; i < len; i++) {
1146
+ for (let j = 0; j < len; j++) {
1147
+ const k = (i + j) % len; // wrap mod length
1148
+ res[k] = F.add(res[k], F.mul(a[i], b[j]));
1149
+ }
1150
+ }
1151
+ return res;
1152
+ }
1153
+ }
1154
+ else {
1155
+ const out = _create(checkLength(a));
1156
+ for (let i = 0; i < out.length; i++)
1157
+ out[i] = F.mul(a[i], b);
1158
+ return out;
1159
+ }
1160
+ },
1161
+ convolve(a, b) {
1162
+ const len = nextPowerOfTwo(a.length + b.length - 1);
1163
+ return this.mul(this.extend(a, len), this.extend(b, len));
1164
+ },
1165
+ shift(p, factor) {
1166
+ const out = _create(checkLength(p));
1167
+ out[0] = p[0];
1168
+ for (let i = 1, power = F.ONE; i < p.length; i++) {
1169
+ power = F.mul(power, factor);
1170
+ out[i] = F.mul(p[i], power);
1171
+ }
1172
+ return out;
1173
+ },
1174
+ clone: (a) => {
1175
+ checkLength(a);
1176
+ const out = _create(a.length);
1177
+ for (let i = 0; i < a.length; i++)
1178
+ out[i] = a[i];
1179
+ return out;
1180
+ },
1181
+ eval: (a, basis) => {
1182
+ checkLength(a);
1183
+ let acc = F.ZERO;
1184
+ for (let i = 0; i < a.length; i++)
1185
+ acc = F.add(acc, F.mul(a[i], basis[i]));
1186
+ return acc;
1187
+ },
1188
+ monomial: {
1189
+ basis: (x, n) => {
1190
+ const out = _create(n);
1191
+ let pow = F.ONE;
1192
+ for (let i = 0; i < n; i++) {
1193
+ out[i] = pow;
1194
+ pow = F.mul(pow, x);
1195
+ }
1196
+ return out;
1197
+ },
1198
+ eval: (a, x) => {
1199
+ checkLength(a);
1200
+ // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way
1201
+ let acc = F.ZERO;
1202
+ for (let i = a.length - 1; i >= 0; i--)
1203
+ acc = F.add(F.mul(acc, x), a[i]);
1204
+ return acc;
1205
+ },
1206
+ },
1207
+ lagrange: {
1208
+ basis: (x, n, brp = false, weights) => {
1209
+ const bits = log2(n);
1210
+ const cache = weights || brp ? roots.brp(bits) : roots.roots(bits); // [ω⁰, ω¹, ..., ωⁿ⁻¹]
1211
+ const out = _create(n);
1212
+ // Fast Kronecker-δ shortcut
1213
+ const idx = findOmegaIndex(x, n, brp);
1214
+ if (idx !== -1) {
1215
+ out[idx] = F.ONE;
1216
+ return out;
1217
+ }
1218
+ const tm = F.pow(x, BigInt(n));
1219
+ const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (xⁿ - 1)/n
1220
+ const denom = _create(n);
1221
+ for (let i = 0; i < n; i++)
1222
+ denom[i] = F.sub(x, cache[i]);
1223
+ const inv = F.invertBatch(denom);
1224
+ for (let i = 0; i < n; i++)
1225
+ out[i] = F.mul(c, F.mul(cache[i], inv[i]));
1226
+ return out;
1227
+ },
1228
+ eval(a, x, brp = false) {
1229
+ checkLength(a);
1230
+ const idx = findOmegaIndex(x, a.length, brp);
1231
+ if (idx !== -1)
1232
+ return a[idx]; // fast path
1233
+ const L = this.basis(x, a.length, brp); // Lᵢ(x)
1234
+ let acc = F.ZERO;
1235
+ for (let i = 0; i < a.length; i++)
1236
+ if (!F.is0(a[i]))
1237
+ acc = F.add(acc, F.mul(a[i], L[i]));
1238
+ return acc;
1239
+ },
1240
+ },
1241
+ vanishing(roots) {
1242
+ checkLength(roots);
1243
+ const out = _create(roots.length + 1, F.ZERO);
1244
+ out[0] = F.ONE;
1245
+ for (const r of roots) {
1246
+ const neg = F.neg(r);
1247
+ for (let j = out.length - 1; j > 0; j--)
1248
+ out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
1249
+ out[0] = F.mul(out[0], neg);
1250
+ }
1251
+ return out;
1252
+ },
1253
+ };
1254
+ }
1255
+ //# sourceMappingURL=fft.js.map
1256
+ ;// ./node_modules/@noble/post-quantum/utils.js
1257
+ /**
1258
+ * Utilities for hex, bytearray and number handling.
1259
+ * @module
1260
+ */
1261
+ /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
1262
+
1263
+
1264
+
1265
+ const utils_randomBytes = randomBytes;
1266
+ // Compares 2 u8a-s in kinda constant time
1267
+ function utils_equalBytes(a, b) {
1268
+ if (a.length !== b.length)
1269
+ return false;
1270
+ let diff = 0;
1271
+ for (let i = 0; i < a.length; i++)
1272
+ diff |= a[i] ^ b[i];
1273
+ return diff === 0;
1274
+ }
1275
+ // copy bytes to new u8a (aligned). Because Buffer.slice is broken.
1276
+ function utils_copyBytes(bytes) {
1277
+ return Uint8Array.from(bytes);
1278
+ }
1279
+ function validateOpts(opts) {
1280
+ // We try to catch u8a, since it was previously valid argument at this position
1281
+ if (typeof opts !== 'object' || opts === null || isBytes(opts))
1282
+ throw new Error('expected opts to be an object');
1283
+ }
1284
+ function validateVerOpts(opts) {
1285
+ validateOpts(opts);
1286
+ if (opts.context !== undefined)
1287
+ abytes(opts.context, undefined, 'opts.context');
1288
+ }
1289
+ function validateSigOpts(opts) {
1290
+ validateVerOpts(opts);
1291
+ if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)
1292
+ abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');
1293
+ }
1294
+ function splitCoder(label, ...lengths) {
1295
+ const getLength = (c) => (typeof c === 'number' ? c : c.bytesLen);
1296
+ const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);
1297
+ return {
1298
+ bytesLen,
1299
+ encode: (bufs) => {
1300
+ const res = new Uint8Array(bytesLen);
1301
+ for (let i = 0, pos = 0; i < lengths.length; i++) {
1302
+ const c = lengths[i];
1303
+ const l = getLength(c);
1304
+ const b = typeof c === 'number' ? bufs[i] : c.encode(bufs[i]);
1305
+ abytes(b, l, label);
1306
+ res.set(b, pos);
1307
+ if (typeof c !== 'number')
1308
+ b.fill(0); // clean
1309
+ pos += l;
1310
+ }
1311
+ return res;
1312
+ },
1313
+ decode: (buf) => {
1314
+ abytes(buf, bytesLen, label);
1315
+ const res = [];
1316
+ for (const c of lengths) {
1317
+ const l = getLength(c);
1318
+ const b = buf.subarray(0, l);
1319
+ res.push(typeof c === 'number' ? b : c.decode(b));
1320
+ buf = buf.subarray(l);
1321
+ }
1322
+ return res;
1323
+ },
1324
+ };
1325
+ }
1326
+ // nano-packed.array (fixed size)
1327
+ function vecCoder(c, vecLen) {
1328
+ const bytesLen = vecLen * c.bytesLen;
1329
+ return {
1330
+ bytesLen,
1331
+ encode: (u) => {
1332
+ if (u.length !== vecLen)
1333
+ throw new Error(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
1334
+ const res = new Uint8Array(bytesLen);
1335
+ for (let i = 0, pos = 0; i < u.length; i++) {
1336
+ const b = c.encode(u[i]);
1337
+ res.set(b, pos);
1338
+ b.fill(0); // clean
1339
+ pos += b.length;
1340
+ }
1341
+ return res;
1342
+ },
1343
+ decode: (a) => {
1344
+ abytes(a, bytesLen);
1345
+ const r = [];
1346
+ for (let i = 0; i < a.length; i += c.bytesLen)
1347
+ r.push(c.decode(a.subarray(i, i + c.bytesLen)));
1348
+ return r;
1349
+ },
1350
+ };
1351
+ }
1352
+ // cleanBytes(Uint8Array.of(), [Uint16Array.of(), Uint32Array.of()])
1353
+ function cleanBytes(...list) {
1354
+ for (const t of list) {
1355
+ if (Array.isArray(t))
1356
+ for (const b of t)
1357
+ b.fill(0);
1358
+ else
1359
+ t.fill(0);
1360
+ }
1361
+ }
1362
+ function getMask(bits) {
1363
+ return (1 << bits) - 1; // 4 -> 0b1111
1364
+ }
1365
+ const EMPTY = Uint8Array.of();
1366
+ function getMessage(msg, ctx = EMPTY) {
1367
+ abytes(msg);
1368
+ abytes(ctx);
1369
+ if (ctx.length > 255)
1370
+ throw new Error('context should be less than 255 bytes');
1371
+ return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);
1372
+ }
1373
+ // 06 09 60 86 48 01 65 03 04 02
1374
+ const oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);
1375
+ function checkHash(hash, requiredStrength = 0) {
1376
+ if (!hash.oid || !utils_equalBytes(hash.oid.subarray(0, 10), oidNistP))
1377
+ throw new Error('hash.oid is invalid: expected NIST hash');
1378
+ const collisionResistance = (hash.outputLen * 8) / 2;
1379
+ if (requiredStrength > collisionResistance) {
1380
+ throw new Error('Pre-hash security strength too low: ' +
1381
+ collisionResistance +
1382
+ ', required: ' +
1383
+ requiredStrength);
1384
+ }
1385
+ }
1386
+ function getMessagePrehash(hash, msg, ctx = EMPTY) {
1387
+ abytes(msg);
1388
+ abytes(ctx);
1389
+ if (ctx.length > 255)
1390
+ throw new Error('context should be less than 255 bytes');
1391
+ const hashed = hash(msg);
1392
+ return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed);
1393
+ }
1394
+ //# sourceMappingURL=utils.js.map
1395
+ ;// ./node_modules/@noble/post-quantum/_crystals.js
1396
+ /**
1397
+ * Internal methods for lattice-based ML-KEM and ML-DSA.
1398
+ * @module
1399
+ */
1400
+ /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
1401
+
1402
+
1403
+
1404
+ const genCrystals = (opts) => {
1405
+ // isKyber: true means Kyber, false means Dilithium
1406
+ const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;
1407
+ const mod = (a, modulo = Q) => {
1408
+ const result = a % modulo | 0;
1409
+ return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;
1410
+ };
1411
+ // -(Q-1)/2 < a <= (Q-1)/2
1412
+ const smod = (a, modulo = Q) => {
1413
+ const r = mod(a, modulo) | 0;
1414
+ return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;
1415
+ };
1416
+ // Generate zettas (different from roots of unity, negacyclic uses phi, where acyclic uses omega)
1417
+ function getZettas() {
1418
+ const out = newPoly(N);
1419
+ for (let i = 0; i < N; i++) {
1420
+ const b = reverseBits(i, brvBits);
1421
+ const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);
1422
+ out[i] = Number(p) | 0;
1423
+ }
1424
+ return out;
1425
+ }
1426
+ const nttZetas = getZettas();
1427
+ // Number-Theoretic Transform
1428
+ // Explained: https://electricdusk.com/ntt.html
1429
+ // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,
1430
+ // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.
1431
+ const field = {
1432
+ add: (a, b) => mod((a | 0) + (b | 0)) | 0,
1433
+ sub: (a, b) => mod((a | 0) - (b | 0)) | 0,
1434
+ mul: (a, b) => mod((a | 0) * (b | 0)) | 0,
1435
+ inv: (_a) => {
1436
+ throw new Error('not implemented');
1437
+ },
1438
+ };
1439
+ const nttOpts = {
1440
+ N,
1441
+ roots: nttZetas,
1442
+ invertButterflies: true,
1443
+ skipStages: isKyber ? 1 : 0,
1444
+ brp: false,
1445
+ };
1446
+ const dif = FFTCore(field, { dit: false, ...nttOpts });
1447
+ const dit = FFTCore(field, { dit: true, ...nttOpts });
1448
+ const NTT = {
1449
+ encode: (r) => {
1450
+ return dif(r);
1451
+ },
1452
+ decode: (r) => {
1453
+ dit(r);
1454
+ // kyber uses 128 here, because brv && stuff
1455
+ for (let i = 0; i < r.length; i++)
1456
+ r[i] = mod(F * r[i]);
1457
+ return r;
1458
+ },
1459
+ };
1460
+ // Encode polynominal as bits
1461
+ const bitsCoder = (d, c) => {
1462
+ const mask = getMask(d);
1463
+ const bytesLen = d * (N / 8);
1464
+ return {
1465
+ bytesLen,
1466
+ encode: (poly) => {
1467
+ const r = new Uint8Array(bytesLen);
1468
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
1469
+ buf |= (c.encode(poly[i]) & mask) << bufLen;
1470
+ bufLen += d;
1471
+ for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
1472
+ r[pos++] = buf & getMask(bufLen);
1473
+ }
1474
+ return r;
1475
+ },
1476
+ decode: (bytes) => {
1477
+ const r = newPoly(N);
1478
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
1479
+ buf |= bytes[i] << bufLen;
1480
+ bufLen += 8;
1481
+ for (; bufLen >= d; bufLen -= d, buf >>= d)
1482
+ r[pos++] = c.decode(buf & mask);
1483
+ }
1484
+ return r;
1485
+ },
1486
+ };
1487
+ };
1488
+ return { mod, smod, nttZetas, NTT, bitsCoder };
1489
+ };
1490
+ const createXofShake = (shake) => (seed, blockLen) => {
1491
+ if (!blockLen)
1492
+ blockLen = shake.blockLen;
1493
+ // Optimizations that won't mater:
1494
+ // - cached seed update (two .update(), on start and on the end)
1495
+ // - another cache which cloned into working copy
1496
+ // Faster than multiple updates, since seed less than blockLen
1497
+ const _seed = new Uint8Array(seed.length + 2);
1498
+ _seed.set(seed);
1499
+ const seedLen = seed.length;
1500
+ const buf = new Uint8Array(blockLen); // == shake128.blockLen
1501
+ let h = shake.create({});
1502
+ let calls = 0;
1503
+ let xofs = 0;
1504
+ return {
1505
+ stats: () => ({ calls, xofs }),
1506
+ get: (x, y) => {
1507
+ _seed[seedLen + 0] = x;
1508
+ _seed[seedLen + 1] = y;
1509
+ h.destroy();
1510
+ h = shake.create({}).update(_seed);
1511
+ calls++;
1512
+ return () => {
1513
+ xofs++;
1514
+ return h.xofInto(buf);
1515
+ };
1516
+ },
1517
+ clean: () => {
1518
+ h.destroy();
1519
+ cleanBytes(buf, _seed);
1520
+ },
1521
+ };
1522
+ };
1523
+ const XOF128 = /* @__PURE__ */ createXofShake(shake128);
1524
+ const XOF256 = /* @__PURE__ */ createXofShake(shake256);
1525
+ //# sourceMappingURL=_crystals.js.map
1526
+ ;// ./node_modules/@noble/post-quantum/ml-dsa.js
1527
+ /**
1528
+ * ML-DSA: Module Lattice-based Digital Signature Algorithm from
1529
+ * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium.
1530
+ *
1531
+ * Has similar internals to ML-KEM, but their keys and params are different.
1532
+ * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml),
1533
+ * [repo](https://github.com/pq-crystals/dilithium).
1534
+ * @module
1535
+ */
1536
+ /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
1537
+
1538
+
1539
+
1540
+
1541
+ function validateInternalOpts(opts) {
1542
+ validateOpts(opts);
1543
+ if (opts.externalMu !== undefined)
1544
+ abool(opts.externalMu, 'opts.externalMu');
1545
+ }
1546
+ // Constants
1547
+ const N = 256;
1548
+ // 2**23 − 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints
1549
+ const Q = 8380417;
1550
+ const ROOT_OF_UNITY = 1753;
1551
+ // f = 256**−1 mod q, pow(256, -1, q) = 8347681 (python3)
1552
+ const F = 8347681;
1553
+ const D = 13;
1554
+ // Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value.
1555
+ const GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;
1556
+ const GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;
1557
+ /** Internal params for different versions of ML-DSA */
1558
+ // prettier-ignore
1559
+ const PARAMS = {
1560
+ 2: { K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80 },
1561
+ 3: { K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55 },
1562
+ 5: { K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75 },
1563
+ };
1564
+ const newPoly = (n) => new Int32Array(n);
1565
+ const { mod, smod, NTT, bitsCoder } = genCrystals({
1566
+ N,
1567
+ Q,
1568
+ F,
1569
+ ROOT_OF_UNITY,
1570
+ newPoly,
1571
+ isKyber: false,
1572
+ brvBits: 8,
1573
+ });
1574
+ const id = (n) => n;
1575
+ const polyCoder = (d, compress = id, verify = id) => bitsCoder(d, {
1576
+ encode: (i) => compress(verify(i)),
1577
+ decode: (i) => verify(compress(i)),
1578
+ });
1579
+ const polyAdd = (a, b) => {
1580
+ for (let i = 0; i < a.length; i++)
1581
+ a[i] = mod(a[i] + b[i]);
1582
+ return a;
1583
+ };
1584
+ const polySub = (a, b) => {
1585
+ for (let i = 0; i < a.length; i++)
1586
+ a[i] = mod(a[i] - b[i]);
1587
+ return a;
1588
+ };
1589
+ const polyShiftl = (p) => {
1590
+ for (let i = 0; i < N; i++)
1591
+ p[i] <<= D;
1592
+ return p;
1593
+ };
1594
+ const polyChknorm = (p, B) => {
1595
+ // Not very sure about this, but FIPS204 doesn't provide any function for that :(
1596
+ for (let i = 0; i < N; i++)
1597
+ if (Math.abs(smod(p[i])) >= B)
1598
+ return true;
1599
+ return false;
1600
+ };
1601
+ const MultiplyNTTs = (a, b) => {
1602
+ // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints,
1603
+ // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit,
1604
+ // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits).
1605
+ // Barrett reduction is slower than mod :(
1606
+ const c = newPoly(N);
1607
+ for (let i = 0; i < a.length; i++)
1608
+ c[i] = mod(a[i] * b[i]);
1609
+ return c;
1610
+ };
1611
+ // Return poly in NTT representation
1612
+ function RejNTTPoly(xof) {
1613
+ // Samples a polynomial ∈ Tq.
1614
+ const r = newPoly(N);
1615
+ // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :(
1616
+ for (let j = 0; j < N;) {
1617
+ const b = xof();
1618
+ if (b.length % 3)
1619
+ throw new Error('RejNTTPoly: unaligned block');
1620
+ for (let i = 0; j < N && i <= b.length - 3; i += 3) {
1621
+ const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes
1622
+ if (t < Q)
1623
+ r[j++] = t;
1624
+ }
1625
+ }
1626
+ return r;
1627
+ }
1628
+ function getDilithium(opts) {
1629
+ const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;
1630
+ const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts;
1631
+ if (![2, 4].includes(ETA))
1632
+ throw new Error('Wrong ETA');
1633
+ if (![1 << 17, 1 << 19].includes(GAMMA1))
1634
+ throw new Error('Wrong GAMMA1');
1635
+ if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))
1636
+ throw new Error('Wrong GAMMA2');
1637
+ const BETA = TAU * ETA;
1638
+ const decompose = (r) => {
1639
+ // Decomposes r into (r1, r0) such that r ≡ r1(2γ2) + r0 mod q.
1640
+ const rPlus = mod(r);
1641
+ const r0 = smod(rPlus, 2 * GAMMA2) | 0;
1642
+ if (rPlus - r0 === Q - 1)
1643
+ return { r1: 0 | 0, r0: (r0 - 1) | 0 };
1644
+ const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;
1645
+ return { r1, r0 }; // r1 = HighBits, r0 = LowBits
1646
+ };
1647
+ const HighBits = (r) => decompose(r).r1;
1648
+ const LowBits = (r) => decompose(r).r0;
1649
+ const MakeHint = (z, r) => {
1650
+ // Compute hint bit indicating whether adding z to r alters the high bits of r.
1651
+ // From dilithium code
1652
+ const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1;
1653
+ // from FIPS204:
1654
+ // // const r1 = HighBits(r);
1655
+ // // const v1 = HighBits(r + z);
1656
+ // // const res1 = +(r1 !== v1);
1657
+ // But they return different results! However, decompose is same.
1658
+ // So, either there is a bug in Dilithium ref implementation or in FIPS204.
1659
+ // For now, lets use dilithium one, so test vectors can be passed.
1660
+ // See
1661
+ // https://github.com/GiacomoPope/dilithium-py?tab=readme-ov-file#optimising-decomposition-and-making-hints
1662
+ return res0;
1663
+ };
1664
+ const UseHint = (h, r) => {
1665
+ // Returns the high bits of r adjusted according to hint h
1666
+ const m = Math.floor((Q - 1) / (2 * GAMMA2));
1667
+ const { r1, r0 } = decompose(r);
1668
+ // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m
1669
+ // 4: if h = 1 and r0 ≤ 0 return (r1 − 1) mod m
1670
+ if (h === 1)
1671
+ return r0 > 0 ? mod(r1 + 1, m) | 0 : mod(r1 - 1, m) | 0;
1672
+ return r1 | 0;
1673
+ };
1674
+ const Power2Round = (r) => {
1675
+ // Decomposes r into (r1, r0) such that r ≡ r1*(2**d) + r0 mod q.
1676
+ const rPlus = mod(r);
1677
+ const r0 = smod(rPlus, 2 ** D) | 0;
1678
+ return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };
1679
+ };
1680
+ const hintCoder = {
1681
+ bytesLen: OMEGA + K,
1682
+ encode: (h) => {
1683
+ if (h === false)
1684
+ throw new Error('hint.encode: hint is false'); // should never happen
1685
+ const res = new Uint8Array(OMEGA + K);
1686
+ for (let i = 0, k = 0; i < K; i++) {
1687
+ for (let j = 0; j < N; j++)
1688
+ if (h[i][j] !== 0)
1689
+ res[k++] = j;
1690
+ res[OMEGA + i] = k;
1691
+ }
1692
+ return res;
1693
+ },
1694
+ decode: (buf) => {
1695
+ const h = [];
1696
+ let k = 0;
1697
+ for (let i = 0; i < K; i++) {
1698
+ const hi = newPoly(N);
1699
+ if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)
1700
+ return false;
1701
+ for (let j = k; j < buf[OMEGA + i]; j++) {
1702
+ if (j > k && buf[j] <= buf[j - 1])
1703
+ return false;
1704
+ hi[buf[j]] = 1;
1705
+ }
1706
+ k = buf[OMEGA + i];
1707
+ h.push(hi);
1708
+ }
1709
+ for (let j = k; j < OMEGA; j++)
1710
+ if (buf[j] !== 0)
1711
+ return false;
1712
+ return h;
1713
+ },
1714
+ };
1715
+ const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {
1716
+ if (!(-ETA <= i && i <= ETA))
1717
+ throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);
1718
+ return i;
1719
+ });
1720
+ const T0Coder = polyCoder(13, (i) => (1 << (D - 1)) - i);
1721
+ const T1Coder = polyCoder(10);
1722
+ // Requires smod. Need to fix!
1723
+ const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => smod(GAMMA1 - i));
1724
+ const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);
1725
+ const W1Vec = vecCoder(W1Coder, K);
1726
+ // Main structures
1727
+ const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K));
1728
+ const secretCoder = splitCoder('secretKey', 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));
1729
+ const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);
1730
+ const CoefFromHalfByte = ETA === 2
1731
+ ? (n) => (n < 15 ? 2 - (n % 5) : false)
1732
+ : (n) => (n < 9 ? 4 - n : false);
1733
+ // Return poly in NTT representation
1734
+ function RejBoundedPoly(xof) {
1735
+ // Samples an element a ∈ Rq with coeffcients in [−η, η] computed via rejection sampling from ρ.
1736
+ const r = newPoly(N);
1737
+ for (let j = 0; j < N;) {
1738
+ const b = xof();
1739
+ for (let i = 0; j < N && i < b.length; i += 1) {
1740
+ // half byte. Should be superfast with vector instructions. But very slow with js :(
1741
+ const d1 = CoefFromHalfByte(b[i] & 0x0f);
1742
+ const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f);
1743
+ if (d1 !== false)
1744
+ r[j++] = d1;
1745
+ if (j < N && d2 !== false)
1746
+ r[j++] = d2;
1747
+ }
1748
+ }
1749
+ return r;
1750
+ }
1751
+ const SampleInBall = (seed) => {
1752
+ // Samples a polynomial c ∈ Rq with coeffcients from {−1, 0, 1} and Hamming weight τ
1753
+ const pre = newPoly(N);
1754
+ const s = shake256.create({}).update(seed);
1755
+ const buf = new Uint8Array(shake256.blockLen);
1756
+ s.xofInto(buf);
1757
+ const masks = buf.slice(0, 8);
1758
+ for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {
1759
+ let b = i + 1;
1760
+ for (; b > i;) {
1761
+ b = buf[pos++];
1762
+ if (pos < shake256.blockLen)
1763
+ continue;
1764
+ s.xofInto(buf);
1765
+ pos = 0;
1766
+ }
1767
+ pre[i] = pre[b];
1768
+ pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1);
1769
+ if (maskBit >= 8) {
1770
+ maskPos++;
1771
+ maskBit = 0;
1772
+ }
1773
+ }
1774
+ return pre;
1775
+ };
1776
+ const polyPowerRound = (p) => {
1777
+ const res0 = newPoly(N);
1778
+ const res1 = newPoly(N);
1779
+ for (let i = 0; i < p.length; i++) {
1780
+ const { r0, r1 } = Power2Round(p[i]);
1781
+ res0[i] = r0;
1782
+ res1[i] = r1;
1783
+ }
1784
+ return { r0: res0, r1: res1 };
1785
+ };
1786
+ const polyUseHint = (u, h) => {
1787
+ for (let i = 0; i < N; i++)
1788
+ u[i] = UseHint(h[i], u[i]);
1789
+ return u;
1790
+ };
1791
+ const polyMakeHint = (a, b) => {
1792
+ const v = newPoly(N);
1793
+ let cnt = 0;
1794
+ for (let i = 0; i < N; i++) {
1795
+ const h = MakeHint(a[i], b[i]);
1796
+ v[i] = h;
1797
+ cnt += h;
1798
+ }
1799
+ return { v, cnt };
1800
+ };
1801
+ const signRandBytes = 32;
1802
+ const seedCoder = splitCoder('seed', 32, 64, 32);
1803
+ // API & argument positions are exactly as in FIPS204.
1804
+ const internal = {
1805
+ info: { type: 'internal-ml-dsa' },
1806
+ lengths: {
1807
+ secretKey: secretCoder.bytesLen,
1808
+ publicKey: publicCoder.bytesLen,
1809
+ seed: 32,
1810
+ signature: sigCoder.bytesLen,
1811
+ signRand: signRandBytes,
1812
+ },
1813
+ keygen: (seed) => {
1814
+ // H(𝜉||IntegerToBytes(𝑘, 1)||IntegerToBytes(ℓ, 1), 128) 2: ▷ expand seed
1815
+ const seedDst = new Uint8Array(32 + 2);
1816
+ const randSeed = seed === undefined;
1817
+ if (randSeed)
1818
+ seed = utils_randomBytes(32);
1819
+ abytes(seed, 32, 'seed');
1820
+ seedDst.set(seed);
1821
+ if (randSeed)
1822
+ cleanBytes(seed);
1823
+ seedDst[32] = K;
1824
+ seedDst[33] = L;
1825
+ const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));
1826
+ const xofPrime = XOF256(rhoPrime);
1827
+ const s1 = [];
1828
+ for (let i = 0; i < L; i++)
1829
+ s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));
1830
+ const s2 = [];
1831
+ for (let i = L; i < L + K; i++)
1832
+ s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));
1833
+ const s1Hat = s1.map((i) => NTT.encode(i.slice()));
1834
+ const t0 = [];
1835
+ const t1 = [];
1836
+ const xof = XOF128(rho);
1837
+ const t = newPoly(N);
1838
+ for (let i = 0; i < K; i++) {
1839
+ // t ← NTT−1(A*NTT(s1)) + s2
1840
+ cleanBytes(t); // don't-reallocate
1841
+ for (let j = 0; j < L; j++) {
1842
+ const aij = RejNTTPoly(xof.get(j, i)); // super slow!
1843
+ polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));
1844
+ }
1845
+ NTT.decode(t);
1846
+ const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) ← Power2Round(t, d)
1847
+ t0.push(r0);
1848
+ t1.push(r1);
1849
+ }
1850
+ const publicKey = publicCoder.encode([rho, t1]); // pk ← pkEncode(ρ, t1)
1851
+ const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr ← H(BytesToBits(pk), 512)
1852
+ const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]); // sk ← skEncode(ρ, K,tr, s1, s2, t0)
1853
+ xof.clean();
1854
+ xofPrime.clean();
1855
+ // STATS
1856
+ // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 }, Kyber1024: { calls: 16, xofs: 48 }
1857
+ // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 }, DSA87: { calls: 71, xofs: 71 }
1858
+ cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);
1859
+ return { publicKey, secretKey };
1860
+ },
1861
+ getPublicKey: (secretKey) => {
1862
+ const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey); // (ρ, K,tr, s1, s2, t0) ← skDecode(sk)
1863
+ const xof = XOF128(rho);
1864
+ const s1Hat = s1.map((p) => NTT.encode(p.slice()));
1865
+ const t1 = [];
1866
+ const tmp = newPoly(N);
1867
+ for (let i = 0; i < K; i++) {
1868
+ tmp.fill(0);
1869
+ for (let j = 0; j < L; j++) {
1870
+ const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT
1871
+ polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j
1872
+ }
1873
+ NTT.decode(tmp); // NTT⁻¹
1874
+ polyAdd(tmp, s2[i]); // t_i = A·s1 + s2
1875
+ const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 ≈ t0
1876
+ t1.push(r1);
1877
+ }
1878
+ xof.clean();
1879
+ cleanBytes(tmp, s1Hat, _t0, s1, s2);
1880
+ return publicCoder.encode([rho, t1]);
1881
+ },
1882
+ // NOTE: random is optional.
1883
+ sign: (msg, secretKey, opts = {}) => {
1884
+ validateSigOpts(opts);
1885
+ validateInternalOpts(opts);
1886
+ let { extraEntropy: random, externalMu = false } = opts;
1887
+ // This part can be pre-cached per secretKey, but there is only minor performance improvement,
1888
+ // since we re-use a lot of variables to computation.
1889
+ const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey); // (ρ, K,tr, s1, s2, t0) ← skDecode(sk)
1890
+ // Cache matrix to avoid re-compute later
1891
+ const A = []; // A ← ExpandA(ρ)
1892
+ const xof = XOF128(rho);
1893
+ for (let i = 0; i < K; i++) {
1894
+ const pv = [];
1895
+ for (let j = 0; j < L; j++)
1896
+ pv.push(RejNTTPoly(xof.get(j, i)));
1897
+ A.push(pv);
1898
+ }
1899
+ xof.clean();
1900
+ for (let i = 0; i < L; i++)
1901
+ NTT.encode(s1[i]); // sˆ1 ← NTT(s1)
1902
+ for (let i = 0; i < K; i++) {
1903
+ NTT.encode(s2[i]); // sˆ2 ← NTT(s2)
1904
+ NTT.encode(t0[i]); // tˆ0 ← NTT(t0)
1905
+ }
1906
+ // This part is per msg
1907
+ const mu = externalMu
1908
+ ? msg
1909
+ : shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest(); // 6: µ ← H(tr||M, 512) ▷ Compute message representative µ
1910
+ // Compute private random seed
1911
+ const rnd = random === false
1912
+ ? new Uint8Array(32)
1913
+ : random === undefined
1914
+ ? utils_randomBytes(signRandBytes)
1915
+ : random;
1916
+ abytes(rnd, 32, 'extraEntropy');
1917
+ const rhoprime = shake256
1918
+ .create({ dkLen: CRH_BYTES })
1919
+ .update(_K)
1920
+ .update(rnd)
1921
+ .update(mu)
1922
+ .digest(); // ρ′← H(K||rnd||µ, 512)
1923
+ abytes(rhoprime, CRH_BYTES);
1924
+ const x256 = XOF256(rhoprime, ZCoder.bytesLen);
1925
+ // Rejection sampling loop
1926
+ main_loop: for (let kappa = 0;;) {
1927
+ const y = [];
1928
+ // y ← ExpandMask(ρ , κ)
1929
+ for (let i = 0; i < L; i++, kappa++)
1930
+ y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)()));
1931
+ const z = y.map((i) => NTT.encode(i.slice()));
1932
+ const w = [];
1933
+ for (let i = 0; i < K; i++) {
1934
+ // w ← NTT−1(A ◦ NTT(y))
1935
+ const wi = newPoly(N);
1936
+ for (let j = 0; j < L; j++)
1937
+ polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));
1938
+ NTT.decode(wi);
1939
+ w.push(wi);
1940
+ }
1941
+ const w1 = w.map((j) => j.map(HighBits)); // w1 ← HighBits(w)
1942
+ // Commitment hash: c˜ ∈{0, 1 2λ } ← H(µ||w1Encode(w1), 2λ)
1943
+ const cTilde = shake256
1944
+ .create({ dkLen: C_TILDE_BYTES })
1945
+ .update(mu)
1946
+ .update(W1Vec.encode(w1))
1947
+ .digest();
1948
+ // Verifer’s challenge
1949
+ const cHat = NTT.encode(SampleInBall(cTilde)); // c ← SampleInBall(c˜1); cˆ ← NTT(c)
1950
+ // ⟨⟨cs1⟩⟩ ← NTT−1(cˆ◦ sˆ1)
1951
+ const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));
1952
+ for (let i = 0; i < L; i++) {
1953
+ polyAdd(NTT.decode(cs1[i]), y[i]); // z ← y + ⟨⟨cs1⟩⟩
1954
+ if (polyChknorm(cs1[i], GAMMA1 - BETA))
1955
+ continue main_loop; // ||z||∞ ≥ γ1 − β
1956
+ }
1957
+ // cs1 is now z (▷ Signer’s response)
1958
+ let cnt = 0;
1959
+ const h = [];
1960
+ for (let i = 0; i < K; i++) {
1961
+ const cs2 = NTT.decode(MultiplyNTTs(s2[i], cHat)); // ⟨⟨cs2⟩⟩ ← NTT−1(cˆ◦ sˆ2)
1962
+ const r0 = polySub(w[i], cs2).map(LowBits); // r0 ← LowBits(w − ⟨⟨cs2⟩⟩)
1963
+ if (polyChknorm(r0, GAMMA2 - BETA))
1964
+ continue main_loop; // ||r0||∞ ≥ γ2 − β
1965
+ const ct0 = NTT.decode(MultiplyNTTs(t0[i], cHat)); // ⟨⟨ct0⟩⟩ ← NTT−1(cˆ◦ tˆ0)
1966
+ if (polyChknorm(ct0, GAMMA2))
1967
+ continue main_loop;
1968
+ polyAdd(r0, ct0);
1969
+ // ▷ Signer’s hint
1970
+ const hint = polyMakeHint(r0, w1[i]); // h ← MakeHint(−⟨⟨ct0⟩⟩, w− ⟨⟨cs2⟩⟩ + ⟨⟨ct0⟩⟩)
1971
+ h.push(hint.v);
1972
+ cnt += hint.cnt;
1973
+ }
1974
+ if (cnt > OMEGA)
1975
+ continue; // the number of 1’s in h is greater than ω
1976
+ x256.clean();
1977
+ const res = sigCoder.encode([cTilde, cs1, h]); // σ ← sigEncode(c˜, z mod±q, h)
1978
+ // rho, _K, tr is subarray of secretKey, cannot clean.
1979
+ cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, mu, s1, s2, t0, ...A);
1980
+ return res;
1981
+ }
1982
+ // @ts-ignore
1983
+ throw new Error('Unreachable code path reached, report this error');
1984
+ },
1985
+ verify: (sig, msg, publicKey, opts = {}) => {
1986
+ validateInternalOpts(opts);
1987
+ const { externalMu = false } = opts;
1988
+ // ML-DSA.Verify(pk, M, σ): Verifes a signature σ for a message M.
1989
+ const [rho, t1] = publicCoder.decode(publicKey); // (ρ, t1) ← pkDecode(pk)
1990
+ const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr ← H(BytesToBits(pk), 512)
1991
+ if (sig.length !== sigCoder.bytesLen)
1992
+ return false; // return false instead of exception
1993
+ const [cTilde, z, h] = sigCoder.decode(sig); // (c˜, z, h) ← sigDecode(σ), ▷ Signer’s commitment hash c ˜, response z and hint
1994
+ if (h === false)
1995
+ return false; // if h = ⊥ then return false
1996
+ for (let i = 0; i < L; i++)
1997
+ if (polyChknorm(z[i], GAMMA1 - BETA))
1998
+ return false;
1999
+ const mu = externalMu
2000
+ ? msg
2001
+ : shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest(); // 7: µ ← H(tr||M, 512)
2002
+ // Compute verifer’s challenge from c˜
2003
+ const c = NTT.encode(SampleInBall(cTilde)); // c ← SampleInBall(c˜1)
2004
+ const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z)
2005
+ for (let i = 0; i < L; i++)
2006
+ NTT.encode(zNtt[i]);
2007
+ const wTick1 = [];
2008
+ const xof = XOF128(rho);
2009
+ for (let i = 0; i < K; i++) {
2010
+ const ct12d = MultiplyNTTs(NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d)
2011
+ const Az = newPoly(N); // // A * z
2012
+ for (let j = 0; j < L; j++) {
2013
+ const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace
2014
+ polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));
2015
+ }
2016
+ // wApprox = A*z - c*t1 * (2**d)
2017
+ const wApprox = NTT.decode(polySub(Az, ct12d));
2018
+ // Reconstruction of signer’s commitment
2019
+ wTick1.push(polyUseHint(wApprox, h[i])); // w ′ ← UseHint(h, w'approx )
2020
+ }
2021
+ xof.clean();
2022
+ // c˜′← H (µ||w1Encode(w′1), 2λ), Hash it; this should match c˜
2023
+ const c2 = shake256
2024
+ .create({ dkLen: C_TILDE_BYTES })
2025
+ .update(mu)
2026
+ .update(W1Vec.encode(wTick1))
2027
+ .digest();
2028
+ // Additional checks in FIPS-204:
2029
+ // [[ ||z||∞ < γ1 − β ]] and [[c ˜ = c˜′]] and [[number of 1’s in h is ≤ ω]]
2030
+ for (const t of h) {
2031
+ const sum = t.reduce((acc, i) => acc + i, 0);
2032
+ if (!(sum <= OMEGA))
2033
+ return false;
2034
+ }
2035
+ for (const t of z)
2036
+ if (polyChknorm(t, GAMMA1 - BETA))
2037
+ return false;
2038
+ return utils_equalBytes(cTilde, c2);
2039
+ },
2040
+ };
2041
+ return {
2042
+ info: { type: 'ml-dsa' },
2043
+ internal,
2044
+ securityLevel: securityLevel,
2045
+ keygen: internal.keygen,
2046
+ lengths: internal.lengths,
2047
+ getPublicKey: internal.getPublicKey,
2048
+ sign: (msg, secretKey, opts = {}) => {
2049
+ validateSigOpts(opts);
2050
+ const M = getMessage(msg, opts.context);
2051
+ const res = internal.sign(M, secretKey, opts);
2052
+ cleanBytes(M);
2053
+ return res;
2054
+ },
2055
+ verify: (sig, msg, publicKey, opts = {}) => {
2056
+ validateVerOpts(opts);
2057
+ return internal.verify(sig, getMessage(msg, opts.context), publicKey);
2058
+ },
2059
+ prehash: (hash) => {
2060
+ checkHash(hash, securityLevel);
2061
+ return {
2062
+ info: { type: 'hashml-dsa' },
2063
+ securityLevel: securityLevel,
2064
+ lengths: internal.lengths,
2065
+ keygen: internal.keygen,
2066
+ getPublicKey: internal.getPublicKey,
2067
+ sign: (msg, secretKey, opts = {}) => {
2068
+ validateSigOpts(opts);
2069
+ const M = getMessagePrehash(hash, msg, opts.context);
2070
+ const res = internal.sign(M, secretKey, opts);
2071
+ cleanBytes(M);
2072
+ return res;
2073
+ },
2074
+ verify: (sig, msg, publicKey, opts = {}) => {
2075
+ validateVerOpts(opts);
2076
+ return internal.verify(sig, getMessagePrehash(hash, msg, opts.context), publicKey);
2077
+ },
2078
+ };
2079
+ },
2080
+ };
2081
+ }
2082
+ /** ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD. */
2083
+ const ml_dsa44 = /* @__PURE__ */ getDilithium({
2084
+ ...PARAMS[2],
2085
+ CRH_BYTES: 64,
2086
+ TR_BYTES: 64,
2087
+ C_TILDE_BYTES: 32,
2088
+ XOF128: XOF128,
2089
+ XOF256: XOF256,
2090
+ securityLevel: 128,
2091
+ });
2092
+ /** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */
2093
+ const ml_dsa65 = /* @__PURE__ */ getDilithium({
2094
+ ...PARAMS[3],
2095
+ CRH_BYTES: 64,
2096
+ TR_BYTES: 64,
2097
+ C_TILDE_BYTES: 48,
2098
+ XOF128: XOF128,
2099
+ XOF256: XOF256,
2100
+ securityLevel: 192,
2101
+ });
2102
+ /** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */
2103
+ const ml_dsa87 = /* @__PURE__ */ getDilithium({
2104
+ ...PARAMS[5],
2105
+ CRH_BYTES: 64,
2106
+ TR_BYTES: 64,
2107
+ C_TILDE_BYTES: 64,
2108
+ XOF128: XOF128,
2109
+ XOF256: XOF256,
2110
+ securityLevel: 256,
2111
+ });
2112
+ //# sourceMappingURL=ml-dsa.js.map
2113
+
2114
+ /***/ })
2115
+
2116
+ }]);
2117
+ //# sourceMappingURL=defaultVendors-node_modules_noble_post-quantum_ml-dsa_js.shogun-core.js.map