@forgezero/agent 0.1.36 → 0.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/fz-agent.js CHANGED
@@ -2,4141 +2,16 @@
2
2
  // @bun
3
3
 
4
4
  // src/index.ts
5
- import { randomBytes as randomBytes5 } from "crypto";
5
+ import { randomBytes } from "crypto";
6
6
  import { readFileSync as readFileSync10, writeFileSync as writeFileSync9, existsSync as existsSync13, mkdirSync as mkdirSync9, chmodSync as chmodSync13 } from "fs";
7
7
  import { dirname as dirname7, join as join7 } from "path";
8
-
9
- // ../access/dist/security.js
10
- var HEX = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0"));
11
- function toBase64Url(bytes) {
12
- let binary = "";
13
- for (const byte of bytes)
14
- binary += String.fromCharCode(byte);
15
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
16
- }
17
- function fromBase64Url(value) {
18
- const padded = value.replace(/-/g, "+").replace(/_/g, "/");
19
- const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
20
- return Uint8Array.from(binary, (character) => character.charCodeAt(0));
21
- }
22
-
23
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js
24
- function isBytes(a) {
25
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
26
- }
27
- function anumber(n, title = "") {
28
- if (typeof n !== "number") {
29
- const prefix = title && `"${title}" `;
30
- throw new TypeError(`${prefix}expected number, got ${typeof n}`);
31
- }
32
- if (!Number.isSafeInteger(n) || n < 0) {
33
- const prefix = title && `"${title}" `;
34
- throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
35
- }
36
- }
37
- function abytes(value, length, title = "") {
38
- const bytes = isBytes(value);
39
- const len = value?.length;
40
- const needsLen = length !== undefined;
41
- if (!bytes || needsLen && len !== length) {
42
- const prefix = title && `"${title}" `;
43
- const ofLen = needsLen ? ` of length ${length}` : "";
44
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
45
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
46
- if (!bytes)
47
- throw new TypeError(message);
48
- throw new RangeError(message);
49
- }
50
- return value;
51
- }
52
- function ahash(h) {
53
- if (typeof h !== "function" || typeof h.create !== "function")
54
- throw new TypeError("Hash must wrapped by utils.createHasher");
55
- anumber(h.outputLen);
56
- anumber(h.blockLen);
57
- if (h.outputLen < 1)
58
- throw new Error('"outputLen" must be >= 1');
59
- if (h.blockLen < 1)
60
- throw new Error('"blockLen" must be >= 1');
61
- }
62
- function aexists(instance, checkFinished = true) {
63
- if (instance.destroyed)
64
- throw new Error("Hash instance has been destroyed");
65
- if (checkFinished && instance.finished)
66
- throw new Error("Hash#digest() has already been called");
67
- }
68
- function aoutput(out, instance) {
69
- abytes(out, undefined, "digestInto() output");
70
- const min = instance.outputLen;
71
- if (out.length < min) {
72
- throw new RangeError('"digestInto() output" expected to be of length >=' + min);
73
- }
74
- }
75
- function u32(arr) {
76
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
77
- }
78
- function clean(...arrays) {
79
- for (let i = 0;i < arrays.length; i++) {
80
- arrays[i].fill(0);
81
- }
82
- }
83
- function createView(arr) {
84
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
85
- }
86
- function rotr(word, shift) {
87
- return word << 32 - shift | word >>> shift;
88
- }
89
- var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
90
- function byteSwap(word) {
91
- return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
92
- }
93
- function byteSwap32(arr) {
94
- for (let i = 0;i < arr.length; i++) {
95
- arr[i] = byteSwap(arr[i]);
96
- }
97
- return arr;
98
- }
99
- var swap32IfBE = isLE ? (u) => u : byteSwap32;
100
- var hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
101
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
102
- function bytesToHex(bytes) {
103
- abytes(bytes);
104
- if (hasHexBuiltin)
105
- return bytes.toHex();
106
- let hex = "";
107
- for (let i = 0;i < bytes.length; i++) {
108
- hex += hexes[bytes[i]];
109
- }
110
- return hex;
111
- }
112
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
113
- function asciiToBase16(ch) {
114
- if (ch >= asciis._0 && ch <= asciis._9)
115
- return ch - asciis._0;
116
- if (ch >= asciis.A && ch <= asciis.F)
117
- return ch - (asciis.A - 10);
118
- if (ch >= asciis.a && ch <= asciis.f)
119
- return ch - (asciis.a - 10);
120
- return;
121
- }
122
- function hexToBytes(hex) {
123
- if (typeof hex !== "string")
124
- throw new TypeError("hex string expected, got " + typeof hex);
125
- if (hasHexBuiltin) {
126
- try {
127
- return Uint8Array.fromHex(hex);
128
- } catch (error) {
129
- if (error instanceof SyntaxError)
130
- throw new RangeError(error.message);
131
- throw error;
132
- }
133
- }
134
- const hl = hex.length;
135
- const al = hl / 2;
136
- if (hl % 2)
137
- throw new RangeError("hex string expected, got unpadded hex of length " + hl);
138
- const array = new Uint8Array(al);
139
- for (let ai = 0, hi = 0;ai < al; ai++, hi += 2) {
140
- const n1 = asciiToBase16(hex.charCodeAt(hi));
141
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
142
- if (n1 === undefined || n2 === undefined) {
143
- const char = hex[hi] + hex[hi + 1];
144
- throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
145
- }
146
- array[ai] = n1 * 16 + n2;
147
- }
148
- return array;
149
- }
150
- function concatBytes(...arrays) {
151
- let sum = 0;
152
- for (let i = 0;i < arrays.length; i++) {
153
- const a = arrays[i];
154
- abytes(a);
155
- sum += a.length;
156
- }
157
- const res = new Uint8Array(sum);
158
- for (let i = 0, pad = 0;i < arrays.length; i++) {
159
- const a = arrays[i];
160
- res.set(a, pad);
161
- pad += a.length;
162
- }
163
- return res;
164
- }
165
- function createHasher(hashCons, info = {}) {
166
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
167
- const tmp = hashCons(undefined);
168
- hashC.outputLen = tmp.outputLen;
169
- hashC.blockLen = tmp.blockLen;
170
- hashC.canXOF = tmp.canXOF;
171
- hashC.create = (opts) => hashCons(opts);
172
- Object.assign(hashC, info);
173
- return Object.freeze(hashC);
174
- }
175
- function randomBytes(bytesLength = 32) {
176
- anumber(bytesLength, "bytesLength");
177
- const cr = typeof globalThis === "object" ? globalThis.crypto : null;
178
- if (typeof cr?.getRandomValues !== "function")
179
- throw new Error("crypto.getRandomValues must be defined");
180
- if (bytesLength > 65536)
181
- throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
182
- return cr.getRandomValues(new Uint8Array(bytesLength));
183
- }
184
- var oidNist = (suffix) => ({
185
- oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
186
- });
187
-
188
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js
189
- function Chi(a, b, c) {
190
- return a & b ^ ~a & c;
191
- }
192
- function Maj(a, b, c) {
193
- return a & b ^ a & c ^ b & c;
194
- }
195
-
196
- class HashMD {
197
- blockLen;
198
- outputLen;
199
- canXOF = false;
200
- padOffset;
201
- isLE;
202
- buffer;
203
- view;
204
- finished = false;
205
- length = 0;
206
- pos = 0;
207
- destroyed = false;
208
- constructor(blockLen, outputLen, padOffset, isLE2) {
209
- this.blockLen = blockLen;
210
- this.outputLen = outputLen;
211
- this.padOffset = padOffset;
212
- this.isLE = isLE2;
213
- this.buffer = new Uint8Array(blockLen);
214
- this.view = createView(this.buffer);
215
- }
216
- update(data) {
217
- aexists(this);
218
- abytes(data);
219
- const { view, buffer, blockLen } = this;
220
- const len = data.length;
221
- for (let pos = 0;pos < len; ) {
222
- const take = Math.min(blockLen - this.pos, len - pos);
223
- if (take === blockLen) {
224
- const dataView = createView(data);
225
- for (;blockLen <= len - pos; pos += blockLen)
226
- this.process(dataView, pos);
227
- continue;
228
- }
229
- buffer.set(data.subarray(pos, pos + take), this.pos);
230
- this.pos += take;
231
- pos += take;
232
- if (this.pos === blockLen) {
233
- this.process(view, 0);
234
- this.pos = 0;
235
- }
236
- }
237
- this.length += data.length;
238
- this.roundClean();
239
- return this;
240
- }
241
- digestInto(out) {
242
- aexists(this);
243
- aoutput(out, this);
244
- this.finished = true;
245
- const { buffer, view, blockLen, isLE: isLE2 } = this;
246
- let { pos } = this;
247
- buffer[pos++] = 128;
248
- clean(this.buffer.subarray(pos));
249
- if (this.padOffset > blockLen - pos) {
250
- this.process(view, 0);
251
- pos = 0;
252
- }
253
- for (let i = pos;i < blockLen; i++)
254
- buffer[i] = 0;
255
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
256
- this.process(view, 0);
257
- const oview = createView(out);
258
- const len = this.outputLen;
259
- if (len % 4)
260
- throw new Error("_sha2: outputLen must be aligned to 32bit");
261
- const outLen = len / 4;
262
- const state = this.get();
263
- if (outLen > state.length)
264
- throw new Error("_sha2: outputLen bigger than state");
265
- for (let i = 0;i < outLen; i++)
266
- oview.setUint32(4 * i, state[i], isLE2);
267
- }
268
- digest() {
269
- const { buffer, outputLen } = this;
270
- this.digestInto(buffer);
271
- const res = buffer.slice(0, outputLen);
272
- this.destroy();
273
- return res;
274
- }
275
- _cloneInto(to) {
276
- to ||= new this.constructor;
277
- to.set(...this.get());
278
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
279
- to.destroyed = destroyed;
280
- to.finished = finished;
281
- to.length = length;
282
- to.pos = pos;
283
- if (length % blockLen)
284
- to.buffer.set(buffer);
285
- return to;
286
- }
287
- clone() {
288
- return this._cloneInto();
289
- }
290
- }
291
- var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
292
- 1779033703,
293
- 3144134277,
294
- 1013904242,
295
- 2773480762,
296
- 1359893119,
297
- 2600822924,
298
- 528734635,
299
- 1541459225
300
- ]);
301
- var SHA224_IV = /* @__PURE__ */ Uint32Array.from([
302
- 3238371032,
303
- 914150663,
304
- 812702999,
305
- 4144912697,
306
- 4290775857,
307
- 1750603025,
308
- 1694076839,
309
- 3204075428
310
- ]);
311
- var SHA384_IV = /* @__PURE__ */ Uint32Array.from([
312
- 3418070365,
313
- 3238371032,
314
- 1654270250,
315
- 914150663,
316
- 2438529370,
317
- 812702999,
318
- 355462360,
319
- 4144912697,
320
- 1731405415,
321
- 4290775857,
322
- 2394180231,
323
- 1750603025,
324
- 3675008525,
325
- 1694076839,
326
- 1203062813,
327
- 3204075428
328
- ]);
329
- var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
330
- 1779033703,
331
- 4089235720,
332
- 3144134277,
333
- 2227873595,
334
- 1013904242,
335
- 4271175723,
336
- 2773480762,
337
- 1595750129,
338
- 1359893119,
339
- 2917565137,
340
- 2600822924,
341
- 725511199,
342
- 528734635,
343
- 4215389547,
344
- 1541459225,
345
- 327033209
346
- ]);
347
-
348
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js
349
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
350
- var _32n = /* @__PURE__ */ BigInt(32);
351
- function fromBig(n, le = false) {
352
- if (le)
353
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
354
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
355
- }
356
- function split(lst, le = false) {
357
- const len = lst.length;
358
- let Ah = new Uint32Array(len);
359
- let Al = new Uint32Array(len);
360
- for (let i = 0;i < len; i++) {
361
- const { h, l } = fromBig(lst[i], le);
362
- [Ah[i], Al[i]] = [h, l];
363
- }
364
- return [Ah, Al];
365
- }
366
- var shrSH = (h, _l, s) => h >>> s;
367
- var shrSL = (h, l, s) => h << 32 - s | l >>> s;
368
- var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
369
- var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
370
- var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
371
- var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
372
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
373
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
374
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
375
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
376
- function add(Ah, Al, Bh, Bl) {
377
- const l = (Al >>> 0) + (Bl >>> 0);
378
- return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
379
- }
380
- var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
381
- var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
382
- var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
383
- var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
384
- var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
385
- var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
386
-
387
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js
388
- var SHA256_K = /* @__PURE__ */ Uint32Array.from([
389
- 1116352408,
390
- 1899447441,
391
- 3049323471,
392
- 3921009573,
393
- 961987163,
394
- 1508970993,
395
- 2453635748,
396
- 2870763221,
397
- 3624381080,
398
- 310598401,
399
- 607225278,
400
- 1426881987,
401
- 1925078388,
402
- 2162078206,
403
- 2614888103,
404
- 3248222580,
405
- 3835390401,
406
- 4022224774,
407
- 264347078,
408
- 604807628,
409
- 770255983,
410
- 1249150122,
411
- 1555081692,
412
- 1996064986,
413
- 2554220882,
414
- 2821834349,
415
- 2952996808,
416
- 3210313671,
417
- 3336571891,
418
- 3584528711,
419
- 113926993,
420
- 338241895,
421
- 666307205,
422
- 773529912,
423
- 1294757372,
424
- 1396182291,
425
- 1695183700,
426
- 1986661051,
427
- 2177026350,
428
- 2456956037,
429
- 2730485921,
430
- 2820302411,
431
- 3259730800,
432
- 3345764771,
433
- 3516065817,
434
- 3600352804,
435
- 4094571909,
436
- 275423344,
437
- 430227734,
438
- 506948616,
439
- 659060556,
440
- 883997877,
441
- 958139571,
442
- 1322822218,
443
- 1537002063,
444
- 1747873779,
445
- 1955562222,
446
- 2024104815,
447
- 2227730452,
448
- 2361852424,
449
- 2428436474,
450
- 2756734187,
451
- 3204031479,
452
- 3329325298
453
- ]);
454
- var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
455
-
456
- class SHA2_32B extends HashMD {
457
- constructor(outputLen) {
458
- super(64, outputLen, 8, false);
459
- }
460
- get() {
461
- const { A, B, C, D, E, F, G, H } = this;
462
- return [A, B, C, D, E, F, G, H];
463
- }
464
- set(A, B, C, D, E, F, G, H) {
465
- this.A = A | 0;
466
- this.B = B | 0;
467
- this.C = C | 0;
468
- this.D = D | 0;
469
- this.E = E | 0;
470
- this.F = F | 0;
471
- this.G = G | 0;
472
- this.H = H | 0;
473
- }
474
- process(view, offset) {
475
- for (let i = 0;i < 16; i++, offset += 4)
476
- SHA256_W[i] = view.getUint32(offset, false);
477
- for (let i = 16;i < 64; i++) {
478
- const W15 = SHA256_W[i - 15];
479
- const W2 = SHA256_W[i - 2];
480
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
481
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
482
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
483
- }
484
- let { A, B, C, D, E, F, G, H } = this;
485
- for (let i = 0;i < 64; i++) {
486
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
487
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
488
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
489
- const T2 = sigma0 + Maj(A, B, C) | 0;
490
- H = G;
491
- G = F;
492
- F = E;
493
- E = D + T1 | 0;
494
- D = C;
495
- C = B;
496
- B = A;
497
- A = T1 + T2 | 0;
498
- }
499
- A = A + this.A | 0;
500
- B = B + this.B | 0;
501
- C = C + this.C | 0;
502
- D = D + this.D | 0;
503
- E = E + this.E | 0;
504
- F = F + this.F | 0;
505
- G = G + this.G | 0;
506
- H = H + this.H | 0;
507
- this.set(A, B, C, D, E, F, G, H);
508
- }
509
- roundClean() {
510
- clean(SHA256_W);
511
- }
512
- destroy() {
513
- this.destroyed = true;
514
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
515
- clean(this.buffer);
516
- }
517
- }
518
-
519
- class _SHA256 extends SHA2_32B {
520
- A = SHA256_IV[0] | 0;
521
- B = SHA256_IV[1] | 0;
522
- C = SHA256_IV[2] | 0;
523
- D = SHA256_IV[3] | 0;
524
- E = SHA256_IV[4] | 0;
525
- F = SHA256_IV[5] | 0;
526
- G = SHA256_IV[6] | 0;
527
- H = SHA256_IV[7] | 0;
528
- constructor() {
529
- super(32);
530
- }
531
- }
532
-
533
- class _SHA224 extends SHA2_32B {
534
- A = SHA224_IV[0] | 0;
535
- B = SHA224_IV[1] | 0;
536
- C = SHA224_IV[2] | 0;
537
- D = SHA224_IV[3] | 0;
538
- E = SHA224_IV[4] | 0;
539
- F = SHA224_IV[5] | 0;
540
- G = SHA224_IV[6] | 0;
541
- H = SHA224_IV[7] | 0;
542
- constructor() {
543
- super(28);
544
- }
545
- }
546
- var K512 = /* @__PURE__ */ (() => split([
547
- "0x428a2f98d728ae22",
548
- "0x7137449123ef65cd",
549
- "0xb5c0fbcfec4d3b2f",
550
- "0xe9b5dba58189dbbc",
551
- "0x3956c25bf348b538",
552
- "0x59f111f1b605d019",
553
- "0x923f82a4af194f9b",
554
- "0xab1c5ed5da6d8118",
555
- "0xd807aa98a3030242",
556
- "0x12835b0145706fbe",
557
- "0x243185be4ee4b28c",
558
- "0x550c7dc3d5ffb4e2",
559
- "0x72be5d74f27b896f",
560
- "0x80deb1fe3b1696b1",
561
- "0x9bdc06a725c71235",
562
- "0xc19bf174cf692694",
563
- "0xe49b69c19ef14ad2",
564
- "0xefbe4786384f25e3",
565
- "0x0fc19dc68b8cd5b5",
566
- "0x240ca1cc77ac9c65",
567
- "0x2de92c6f592b0275",
568
- "0x4a7484aa6ea6e483",
569
- "0x5cb0a9dcbd41fbd4",
570
- "0x76f988da831153b5",
571
- "0x983e5152ee66dfab",
572
- "0xa831c66d2db43210",
573
- "0xb00327c898fb213f",
574
- "0xbf597fc7beef0ee4",
575
- "0xc6e00bf33da88fc2",
576
- "0xd5a79147930aa725",
577
- "0x06ca6351e003826f",
578
- "0x142929670a0e6e70",
579
- "0x27b70a8546d22ffc",
580
- "0x2e1b21385c26c926",
581
- "0x4d2c6dfc5ac42aed",
582
- "0x53380d139d95b3df",
583
- "0x650a73548baf63de",
584
- "0x766a0abb3c77b2a8",
585
- "0x81c2c92e47edaee6",
586
- "0x92722c851482353b",
587
- "0xa2bfe8a14cf10364",
588
- "0xa81a664bbc423001",
589
- "0xc24b8b70d0f89791",
590
- "0xc76c51a30654be30",
591
- "0xd192e819d6ef5218",
592
- "0xd69906245565a910",
593
- "0xf40e35855771202a",
594
- "0x106aa07032bbd1b8",
595
- "0x19a4c116b8d2d0c8",
596
- "0x1e376c085141ab53",
597
- "0x2748774cdf8eeb99",
598
- "0x34b0bcb5e19b48a8",
599
- "0x391c0cb3c5c95a63",
600
- "0x4ed8aa4ae3418acb",
601
- "0x5b9cca4f7763e373",
602
- "0x682e6ff3d6b2b8a3",
603
- "0x748f82ee5defb2fc",
604
- "0x78a5636f43172f60",
605
- "0x84c87814a1f0ab72",
606
- "0x8cc702081a6439ec",
607
- "0x90befffa23631e28",
608
- "0xa4506cebde82bde9",
609
- "0xbef9a3f7b2c67915",
610
- "0xc67178f2e372532b",
611
- "0xca273eceea26619c",
612
- "0xd186b8c721c0c207",
613
- "0xeada7dd6cde0eb1e",
614
- "0xf57d4f7fee6ed178",
615
- "0x06f067aa72176fba",
616
- "0x0a637dc5a2c898a6",
617
- "0x113f9804bef90dae",
618
- "0x1b710b35131c471b",
619
- "0x28db77f523047d84",
620
- "0x32caab7b40c72493",
621
- "0x3c9ebe0a15c9bebc",
622
- "0x431d67c49c100d4c",
623
- "0x4cc5d4becb3e42b6",
624
- "0x597f299cfc657e2a",
625
- "0x5fcb6fab3ad6faec",
626
- "0x6c44198c4a475817"
627
- ].map((n) => BigInt(n))))();
628
- var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
629
- var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
630
- var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
631
- var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
632
-
633
- class SHA2_64B extends HashMD {
634
- constructor(outputLen) {
635
- super(128, outputLen, 16, false);
636
- }
637
- get() {
638
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
639
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
640
- }
641
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
642
- this.Ah = Ah | 0;
643
- this.Al = Al | 0;
644
- this.Bh = Bh | 0;
645
- this.Bl = Bl | 0;
646
- this.Ch = Ch | 0;
647
- this.Cl = Cl | 0;
648
- this.Dh = Dh | 0;
649
- this.Dl = Dl | 0;
650
- this.Eh = Eh | 0;
651
- this.El = El | 0;
652
- this.Fh = Fh | 0;
653
- this.Fl = Fl | 0;
654
- this.Gh = Gh | 0;
655
- this.Gl = Gl | 0;
656
- this.Hh = Hh | 0;
657
- this.Hl = Hl | 0;
658
- }
659
- process(view, offset) {
660
- for (let i = 0;i < 16; i++, offset += 4) {
661
- SHA512_W_H[i] = view.getUint32(offset);
662
- SHA512_W_L[i] = view.getUint32(offset += 4);
663
- }
664
- for (let i = 16;i < 80; i++) {
665
- const W15h = SHA512_W_H[i - 15] | 0;
666
- const W15l = SHA512_W_L[i - 15] | 0;
667
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
668
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
669
- const W2h = SHA512_W_H[i - 2] | 0;
670
- const W2l = SHA512_W_L[i - 2] | 0;
671
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
672
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
673
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
674
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
675
- SHA512_W_H[i] = SUMh | 0;
676
- SHA512_W_L[i] = SUMl | 0;
677
- }
678
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
679
- for (let i = 0;i < 80; i++) {
680
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
681
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
682
- const CHIh = Eh & Fh ^ ~Eh & Gh;
683
- const CHIl = El & Fl ^ ~El & Gl;
684
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
685
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
686
- const T1l = T1ll | 0;
687
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
688
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
689
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
690
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
691
- Hh = Gh | 0;
692
- Hl = Gl | 0;
693
- Gh = Fh | 0;
694
- Gl = Fl | 0;
695
- Fh = Eh | 0;
696
- Fl = El | 0;
697
- ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
698
- Dh = Ch | 0;
699
- Dl = Cl | 0;
700
- Ch = Bh | 0;
701
- Cl = Bl | 0;
702
- Bh = Ah | 0;
703
- Bl = Al | 0;
704
- const All = add3L(T1l, sigma0l, MAJl);
705
- Ah = add3H(All, T1h, sigma0h, MAJh);
706
- Al = All | 0;
707
- }
708
- ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
709
- ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
710
- ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
711
- ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
712
- ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
713
- ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
714
- ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
715
- ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
716
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
717
- }
718
- roundClean() {
719
- clean(SHA512_W_H, SHA512_W_L);
720
- }
721
- destroy() {
722
- this.destroyed = true;
723
- clean(this.buffer);
724
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
725
- }
726
- }
727
-
728
- class _SHA512 extends SHA2_64B {
729
- Ah = SHA512_IV[0] | 0;
730
- Al = SHA512_IV[1] | 0;
731
- Bh = SHA512_IV[2] | 0;
732
- Bl = SHA512_IV[3] | 0;
733
- Ch = SHA512_IV[4] | 0;
734
- Cl = SHA512_IV[5] | 0;
735
- Dh = SHA512_IV[6] | 0;
736
- Dl = SHA512_IV[7] | 0;
737
- Eh = SHA512_IV[8] | 0;
738
- El = SHA512_IV[9] | 0;
739
- Fh = SHA512_IV[10] | 0;
740
- Fl = SHA512_IV[11] | 0;
741
- Gh = SHA512_IV[12] | 0;
742
- Gl = SHA512_IV[13] | 0;
743
- Hh = SHA512_IV[14] | 0;
744
- Hl = SHA512_IV[15] | 0;
745
- constructor() {
746
- super(64);
747
- }
748
- }
749
-
750
- class _SHA384 extends SHA2_64B {
751
- Ah = SHA384_IV[0] | 0;
752
- Al = SHA384_IV[1] | 0;
753
- Bh = SHA384_IV[2] | 0;
754
- Bl = SHA384_IV[3] | 0;
755
- Ch = SHA384_IV[4] | 0;
756
- Cl = SHA384_IV[5] | 0;
757
- Dh = SHA384_IV[6] | 0;
758
- Dl = SHA384_IV[7] | 0;
759
- Eh = SHA384_IV[8] | 0;
760
- El = SHA384_IV[9] | 0;
761
- Fh = SHA384_IV[10] | 0;
762
- Fl = SHA384_IV[11] | 0;
763
- Gh = SHA384_IV[12] | 0;
764
- Gl = SHA384_IV[13] | 0;
765
- Hh = SHA384_IV[14] | 0;
766
- Hl = SHA384_IV[15] | 0;
767
- constructor() {
768
- super(48);
769
- }
770
- }
771
- var T224_IV = /* @__PURE__ */ Uint32Array.from([
772
- 2352822216,
773
- 424955298,
774
- 1944164710,
775
- 2312950998,
776
- 502970286,
777
- 855612546,
778
- 1738396948,
779
- 1479516111,
780
- 258812777,
781
- 2077511080,
782
- 2011393907,
783
- 79989058,
784
- 1067287976,
785
- 1780299464,
786
- 286451373,
787
- 2446758561
788
- ]);
789
- var T256_IV = /* @__PURE__ */ Uint32Array.from([
790
- 573645204,
791
- 4230739756,
792
- 2673172387,
793
- 3360449730,
794
- 596883563,
795
- 1867755857,
796
- 2520282905,
797
- 1497426621,
798
- 2519219938,
799
- 2827943907,
800
- 3193839141,
801
- 1401305490,
802
- 721525244,
803
- 746961066,
804
- 246885852,
805
- 2177182882
806
- ]);
807
-
808
- class _SHA512_224 extends SHA2_64B {
809
- Ah = T224_IV[0] | 0;
810
- Al = T224_IV[1] | 0;
811
- Bh = T224_IV[2] | 0;
812
- Bl = T224_IV[3] | 0;
813
- Ch = T224_IV[4] | 0;
814
- Cl = T224_IV[5] | 0;
815
- Dh = T224_IV[6] | 0;
816
- Dl = T224_IV[7] | 0;
817
- Eh = T224_IV[8] | 0;
818
- El = T224_IV[9] | 0;
819
- Fh = T224_IV[10] | 0;
820
- Fl = T224_IV[11] | 0;
821
- Gh = T224_IV[12] | 0;
822
- Gl = T224_IV[13] | 0;
823
- Hh = T224_IV[14] | 0;
824
- Hl = T224_IV[15] | 0;
825
- constructor() {
826
- super(28);
827
- }
828
- }
829
-
830
- class _SHA512_256 extends SHA2_64B {
831
- Ah = T256_IV[0] | 0;
832
- Al = T256_IV[1] | 0;
833
- Bh = T256_IV[2] | 0;
834
- Bl = T256_IV[3] | 0;
835
- Ch = T256_IV[4] | 0;
836
- Cl = T256_IV[5] | 0;
837
- Dh = T256_IV[6] | 0;
838
- Dl = T256_IV[7] | 0;
839
- Eh = T256_IV[8] | 0;
840
- El = T256_IV[9] | 0;
841
- Fh = T256_IV[10] | 0;
842
- Fl = T256_IV[11] | 0;
843
- Gh = T256_IV[12] | 0;
844
- Gl = T256_IV[13] | 0;
845
- Hh = T256_IV[14] | 0;
846
- Hl = T256_IV[15] | 0;
847
- constructor() {
848
- super(32);
849
- }
850
- }
851
- var sha256 = /* @__PURE__ */ createHasher(() => new _SHA256, /* @__PURE__ */ oidNist(1));
852
- var sha512 = /* @__PURE__ */ createHasher(() => new _SHA512, /* @__PURE__ */ oidNist(3));
853
-
854
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/utils.js
855
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
856
- var abytes2 = (value, length, title) => abytes(value, length, title);
857
- var anumber2 = anumber;
858
- var bytesToHex2 = bytesToHex;
859
- var concatBytes2 = (...arrays) => concatBytes(...arrays);
860
- var hexToBytes2 = (hex) => hexToBytes(hex);
861
- var isBytes2 = isBytes;
862
- var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
863
- var _0n = /* @__PURE__ */ BigInt(0);
864
- var _1n = /* @__PURE__ */ BigInt(1);
865
- function abool(value, title = "") {
866
- if (typeof value !== "boolean") {
867
- const prefix = title && `"${title}" `;
868
- throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
869
- }
870
- return value;
871
- }
872
- function abignumber(n) {
873
- if (typeof n === "bigint") {
874
- if (!isPosBig(n))
875
- throw new RangeError("positive bigint expected, got " + n);
876
- } else
877
- anumber2(n);
878
- return n;
879
- }
880
- function asafenumber(value, title = "") {
881
- if (typeof value !== "number") {
882
- const prefix = title && `"${title}" `;
883
- throw new TypeError(prefix + "expected number, got type=" + typeof value);
884
- }
885
- if (!Number.isSafeInteger(value)) {
886
- const prefix = title && `"${title}" `;
887
- throw new RangeError(prefix + "expected safe integer, got " + value);
888
- }
889
- }
890
- function hexToNumber(hex) {
891
- if (typeof hex !== "string")
892
- throw new TypeError("hex string expected, got " + typeof hex);
893
- return hex === "" ? _0n : BigInt("0x" + hex);
894
- }
895
- function bytesToNumberBE(bytes) {
896
- return hexToNumber(bytesToHex(bytes));
897
- }
898
- function bytesToNumberLE(bytes) {
899
- return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
900
- }
901
- function numberToBytesBE(n, len) {
902
- anumber(len);
903
- if (len === 0)
904
- throw new RangeError("zero length");
905
- n = abignumber(n);
906
- const hex = n.toString(16);
907
- if (hex.length > len * 2)
908
- throw new RangeError("number too large");
909
- return hexToBytes(hex.padStart(len * 2, "0"));
910
- }
911
- function numberToBytesLE(n, len) {
912
- return numberToBytesBE(n, len).reverse();
913
- }
914
- function equalBytes(a, b) {
915
- a = abytes2(a);
916
- b = abytes2(b);
917
- if (a.length !== b.length)
918
- return false;
919
- let diff = 0;
920
- for (let i = 0;i < a.length; i++)
921
- diff |= a[i] ^ b[i];
922
- return diff === 0;
923
- }
924
- function copyBytes(bytes) {
925
- return Uint8Array.from(abytes2(bytes));
926
- }
927
- function asciiToBytes(ascii) {
928
- if (typeof ascii !== "string")
929
- throw new TypeError("ascii string expected, got " + typeof ascii);
930
- return Uint8Array.from(ascii, (c, i) => {
931
- const charCode = c.charCodeAt(0);
932
- if (c.length !== 1 || charCode > 127) {
933
- throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
934
- }
935
- return charCode;
936
- });
937
- }
938
- var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
939
- function inRange(n, min, max) {
940
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
941
- }
942
- function aInRange(title, n, min, max) {
943
- if (!inRange(n, min, max))
944
- throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
945
- }
946
- function bitLen(n) {
947
- if (n < _0n)
948
- throw new Error("expected non-negative bigint, got " + n);
949
- let len;
950
- for (len = 0;n > _0n; n >>= _1n, len += 1)
951
- ;
952
- return len;
953
- }
954
- var bitMask = (n) => (_1n << BigInt(n)) - _1n;
955
- function validateObject(object, fields = {}, optFields = {}) {
956
- if (Object.prototype.toString.call(object) !== "[object Object]")
957
- throw new TypeError("expected valid options object");
958
- function checkField(fieldName, expectedType, isOpt) {
959
- if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
960
- throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
961
- const val = object[fieldName];
962
- if (isOpt && val === undefined)
963
- return;
964
- const current = typeof val;
965
- if (current !== expectedType || val === null)
966
- throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
967
- }
968
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
969
- iter(fields, false);
970
- iter(optFields, true);
971
- }
972
- var notImplemented = () => {
973
- throw new Error("not implemented");
974
- };
975
-
976
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/modular.js
977
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
978
- var _0n2 = /* @__PURE__ */ BigInt(0);
979
- var _1n2 = /* @__PURE__ */ BigInt(1);
980
- var _2n = /* @__PURE__ */ BigInt(2);
981
- var _3n = /* @__PURE__ */ BigInt(3);
982
- var _4n = /* @__PURE__ */ BigInt(4);
983
- var _5n = /* @__PURE__ */ BigInt(5);
984
- var _7n = /* @__PURE__ */ BigInt(7);
985
- var _8n = /* @__PURE__ */ BigInt(8);
986
- var _9n = /* @__PURE__ */ BigInt(9);
987
- var _16n = /* @__PURE__ */ BigInt(16);
988
- function mod(a, b) {
989
- if (b <= _0n2)
990
- throw new Error("mod: expected positive modulus, got " + b);
991
- const result = a % b;
992
- return result >= _0n2 ? result : b + result;
993
- }
994
- function pow2(x, power, modulo) {
995
- if (power < _0n2)
996
- throw new Error("pow2: expected non-negative exponent, got " + power);
997
- let res = x;
998
- while (power-- > _0n2) {
999
- res *= res;
1000
- res %= modulo;
1001
- }
1002
- return res;
1003
- }
1004
- function invert(number, modulo) {
1005
- if (number === _0n2)
1006
- throw new Error("invert: expected non-zero number");
1007
- if (modulo <= _0n2)
1008
- throw new Error("invert: expected positive modulus, got " + modulo);
1009
- let a = mod(number, modulo);
1010
- let b = modulo;
1011
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
1012
- while (a !== _0n2) {
1013
- const q = b / a;
1014
- const r = b - a * q;
1015
- const m = x - u * q;
1016
- const n = y - v * q;
1017
- b = a, a = r, x = u, y = v, u = m, v = n;
1018
- }
1019
- const gcd = b;
1020
- if (gcd !== _1n2)
1021
- throw new Error("invert: does not exist");
1022
- return mod(x, modulo);
1023
- }
1024
- function assertIsSquare(Fp, root, n) {
1025
- const F = Fp;
1026
- if (!F.eql(F.sqr(root), n))
1027
- throw new Error("Cannot find square root");
1028
- }
1029
- function sqrt3mod4(Fp, n) {
1030
- const F = Fp;
1031
- const p1div4 = (F.ORDER + _1n2) / _4n;
1032
- const root = F.pow(n, p1div4);
1033
- assertIsSquare(F, root, n);
1034
- return root;
1035
- }
1036
- function sqrt5mod8(Fp, n) {
1037
- const F = Fp;
1038
- const p5div8 = (F.ORDER - _5n) / _8n;
1039
- const n2 = F.mul(n, _2n);
1040
- const v = F.pow(n2, p5div8);
1041
- const nv = F.mul(n, v);
1042
- const i = F.mul(F.mul(nv, _2n), v);
1043
- const root = F.mul(nv, F.sub(i, F.ONE));
1044
- assertIsSquare(F, root, n);
1045
- return root;
1046
- }
1047
- function sqrt9mod16(P) {
1048
- const Fp_ = Field(P);
1049
- const tn = tonelliShanks(P);
1050
- const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1051
- const c2 = tn(Fp_, c1);
1052
- const c3 = tn(Fp_, Fp_.neg(c1));
1053
- const c4 = (P + _7n) / _16n;
1054
- return (Fp, n) => {
1055
- const F = Fp;
1056
- let tv1 = F.pow(n, c4);
1057
- let tv2 = F.mul(tv1, c1);
1058
- const tv3 = F.mul(tv1, c2);
1059
- const tv4 = F.mul(tv1, c3);
1060
- const e1 = F.eql(F.sqr(tv2), n);
1061
- const e2 = F.eql(F.sqr(tv3), n);
1062
- tv1 = F.cmov(tv1, tv2, e1);
1063
- tv2 = F.cmov(tv4, tv3, e2);
1064
- const e3 = F.eql(F.sqr(tv2), n);
1065
- const root = F.cmov(tv1, tv2, e3);
1066
- assertIsSquare(F, root, n);
1067
- return root;
1068
- };
1069
- }
1070
- function tonelliShanks(P) {
1071
- if (P < _3n)
1072
- throw new Error("sqrt is not defined for small field");
1073
- let Q = P - _1n2;
1074
- let S = 0;
1075
- while (Q % _2n === _0n2) {
1076
- Q /= _2n;
1077
- S++;
1078
- }
1079
- let Z = _2n;
1080
- const _Fp = Field(P);
1081
- while (FpLegendre(_Fp, Z) === 1) {
1082
- if (Z++ > 1000)
1083
- throw new Error("Cannot find square root: probably non-prime P");
1084
- }
1085
- if (S === 1)
1086
- return sqrt3mod4;
1087
- let cc = _Fp.pow(Z, Q);
1088
- const Q1div2 = (Q + _1n2) / _2n;
1089
- return function tonelliSlow(Fp, n) {
1090
- const F = Fp;
1091
- if (F.is0(n))
1092
- return n;
1093
- if (FpLegendre(F, n) !== 1)
1094
- throw new Error("Cannot find square root");
1095
- let M = S;
1096
- let c = F.mul(F.ONE, cc);
1097
- let t = F.pow(n, Q);
1098
- let R = F.pow(n, Q1div2);
1099
- while (!F.eql(t, F.ONE)) {
1100
- if (F.is0(t))
1101
- return F.ZERO;
1102
- let i = 1;
1103
- let t_tmp = F.sqr(t);
1104
- while (!F.eql(t_tmp, F.ONE)) {
1105
- i++;
1106
- t_tmp = F.sqr(t_tmp);
1107
- if (i === M)
1108
- throw new Error("Cannot find square root");
1109
- }
1110
- const exponent = _1n2 << BigInt(M - i - 1);
1111
- const b = F.pow(c, exponent);
1112
- M = i;
1113
- c = F.sqr(b);
1114
- t = F.mul(t, c);
1115
- R = F.mul(R, b);
1116
- }
1117
- return R;
1118
- };
1119
- }
1120
- function FpSqrt(P) {
1121
- if (P % _4n === _3n)
1122
- return sqrt3mod4;
1123
- if (P % _8n === _5n)
1124
- return sqrt5mod8;
1125
- if (P % _16n === _9n)
1126
- return sqrt9mod16(P);
1127
- return tonelliShanks(P);
1128
- }
1129
- var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
1130
- var FIELD_FIELDS = [
1131
- "create",
1132
- "isValid",
1133
- "is0",
1134
- "neg",
1135
- "inv",
1136
- "sqrt",
1137
- "sqr",
1138
- "eql",
1139
- "add",
1140
- "sub",
1141
- "mul",
1142
- "pow",
1143
- "div",
1144
- "addN",
1145
- "subN",
1146
- "mulN",
1147
- "sqrN"
1148
- ];
1149
- function validateField(field) {
1150
- const initial = {
1151
- ORDER: "bigint",
1152
- BYTES: "number",
1153
- BITS: "number"
1154
- };
1155
- const opts = FIELD_FIELDS.reduce((map, val) => {
1156
- map[val] = "function";
1157
- return map;
1158
- }, initial);
1159
- validateObject(field, opts);
1160
- asafenumber(field.BYTES, "BYTES");
1161
- asafenumber(field.BITS, "BITS");
1162
- if (field.BYTES < 1 || field.BITS < 1)
1163
- throw new Error("invalid field: expected BYTES/BITS > 0");
1164
- if (field.ORDER <= _1n2)
1165
- throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
1166
- return field;
1167
- }
1168
- function FpPow(Fp, num, power) {
1169
- const F = Fp;
1170
- if (power < _0n2)
1171
- throw new Error("invalid exponent, negatives unsupported");
1172
- if (power === _0n2)
1173
- return F.ONE;
1174
- if (power === _1n2)
1175
- return num;
1176
- let p = F.ONE;
1177
- let d = num;
1178
- while (power > _0n2) {
1179
- if (power & _1n2)
1180
- p = F.mul(p, d);
1181
- d = F.sqr(d);
1182
- power >>= _1n2;
1183
- }
1184
- return p;
1185
- }
1186
- function FpInvertBatch(Fp, nums, passZero = false) {
1187
- const F = Fp;
1188
- const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);
1189
- const multipliedAcc = nums.reduce((acc, num, i) => {
1190
- if (F.is0(num))
1191
- return acc;
1192
- inverted[i] = acc;
1193
- return F.mul(acc, num);
1194
- }, F.ONE);
1195
- const invertedAcc = F.inv(multipliedAcc);
1196
- nums.reduceRight((acc, num, i) => {
1197
- if (F.is0(num))
1198
- return acc;
1199
- inverted[i] = F.mul(acc, inverted[i]);
1200
- return F.mul(acc, num);
1201
- }, invertedAcc);
1202
- return inverted;
1203
- }
1204
- function FpLegendre(Fp, n) {
1205
- const F = Fp;
1206
- const p1mod2 = (F.ORDER - _1n2) / _2n;
1207
- const powered = F.pow(n, p1mod2);
1208
- const yes = F.eql(powered, F.ONE);
1209
- const zero = F.eql(powered, F.ZERO);
1210
- const no = F.eql(powered, F.neg(F.ONE));
1211
- if (!yes && !zero && !no)
1212
- throw new Error("invalid Legendre symbol result");
1213
- return yes ? 1 : zero ? 0 : -1;
1214
- }
1215
- function nLength(n, nBitLength) {
1216
- if (nBitLength !== undefined)
1217
- anumber2(nBitLength);
1218
- if (n <= _0n2)
1219
- throw new Error("invalid n length: expected positive n, got " + n);
1220
- if (nBitLength !== undefined && nBitLength < 1)
1221
- throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
1222
- const bits = bitLen(n);
1223
- if (nBitLength !== undefined && nBitLength < bits)
1224
- throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
1225
- const _nBitLength = nBitLength !== undefined ? nBitLength : bits;
1226
- const nByteLength = Math.ceil(_nBitLength / 8);
1227
- return { nBitLength: _nBitLength, nByteLength };
1228
- }
1229
- var FIELD_SQRT = new WeakMap;
1230
-
1231
- class _Field {
1232
- ORDER;
1233
- BITS;
1234
- BYTES;
1235
- isLE;
1236
- ZERO = _0n2;
1237
- ONE = _1n2;
1238
- _lengths;
1239
- _mod;
1240
- constructor(ORDER, opts = {}) {
1241
- if (ORDER <= _1n2)
1242
- throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
1243
- let _nbitLength = undefined;
1244
- this.isLE = false;
1245
- if (opts != null && typeof opts === "object") {
1246
- if (typeof opts.BITS === "number")
1247
- _nbitLength = opts.BITS;
1248
- if (typeof opts.sqrt === "function")
1249
- Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
1250
- if (typeof opts.isLE === "boolean")
1251
- this.isLE = opts.isLE;
1252
- if (opts.allowedLengths)
1253
- this._lengths = Object.freeze(opts.allowedLengths.slice());
1254
- if (typeof opts.modFromBytes === "boolean")
1255
- this._mod = opts.modFromBytes;
1256
- }
1257
- const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1258
- if (nByteLength > 2048)
1259
- throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1260
- this.ORDER = ORDER;
1261
- this.BITS = nBitLength;
1262
- this.BYTES = nByteLength;
1263
- Object.freeze(this);
1264
- }
1265
- create(num) {
1266
- return mod(num, this.ORDER);
1267
- }
1268
- isValid(num) {
1269
- if (typeof num !== "bigint")
1270
- throw new TypeError("invalid field element: expected bigint, got " + typeof num);
1271
- return _0n2 <= num && num < this.ORDER;
1272
- }
1273
- is0(num) {
1274
- return num === _0n2;
1275
- }
1276
- isValidNot0(num) {
1277
- return !this.is0(num) && this.isValid(num);
1278
- }
1279
- isOdd(num) {
1280
- return (num & _1n2) === _1n2;
1281
- }
1282
- neg(num) {
1283
- return mod(-num, this.ORDER);
1284
- }
1285
- eql(lhs, rhs) {
1286
- return lhs === rhs;
1287
- }
1288
- sqr(num) {
1289
- return mod(num * num, this.ORDER);
1290
- }
1291
- add(lhs, rhs) {
1292
- return mod(lhs + rhs, this.ORDER);
1293
- }
1294
- sub(lhs, rhs) {
1295
- return mod(lhs - rhs, this.ORDER);
1296
- }
1297
- mul(lhs, rhs) {
1298
- return mod(lhs * rhs, this.ORDER);
1299
- }
1300
- pow(num, power) {
1301
- return FpPow(this, num, power);
1302
- }
1303
- div(lhs, rhs) {
1304
- return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1305
- }
1306
- sqrN(num) {
1307
- return num * num;
1308
- }
1309
- addN(lhs, rhs) {
1310
- return lhs + rhs;
1311
- }
1312
- subN(lhs, rhs) {
1313
- return lhs - rhs;
1314
- }
1315
- mulN(lhs, rhs) {
1316
- return lhs * rhs;
1317
- }
1318
- inv(num) {
1319
- return invert(num, this.ORDER);
1320
- }
1321
- sqrt(num) {
1322
- let sqrt = FIELD_SQRT.get(this);
1323
- if (!sqrt)
1324
- FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
1325
- return sqrt(this, num);
1326
- }
1327
- toBytes(num) {
1328
- return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1329
- }
1330
- fromBytes(bytes, skipValidation = false) {
1331
- abytes2(bytes);
1332
- const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
1333
- if (allowedLengths) {
1334
- if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1335
- throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1336
- }
1337
- const padded = new Uint8Array(BYTES);
1338
- padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
1339
- bytes = padded;
1340
- }
1341
- if (bytes.length !== BYTES)
1342
- throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1343
- let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1344
- if (modFromBytes)
1345
- scalar = mod(scalar, ORDER);
1346
- if (!skipValidation) {
1347
- if (!this.isValid(scalar))
1348
- throw new Error("invalid field element: outside of range 0..ORDER");
1349
- }
1350
- return scalar;
1351
- }
1352
- invertBatch(lst) {
1353
- return FpInvertBatch(this, lst);
1354
- }
1355
- cmov(a, b, condition) {
1356
- abool(condition, "condition");
1357
- return condition ? b : a;
1358
- }
1359
- }
1360
- Object.freeze(_Field.prototype);
1361
- function Field(ORDER, opts = {}) {
1362
- return new _Field(ORDER, opts);
1363
- }
1364
-
1365
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/curve.js
1366
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1367
- var _0n3 = /* @__PURE__ */ BigInt(0);
1368
- var _1n3 = /* @__PURE__ */ BigInt(1);
1369
- function negateCt(condition, item) {
1370
- const neg = item.negate();
1371
- return condition ? neg : item;
1372
- }
1373
- function normalizeZ(c, points) {
1374
- const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1375
- return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1376
- }
1377
- function validateW(W, bits) {
1378
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1379
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1380
- }
1381
- function calcWOpts(W, scalarBits) {
1382
- validateW(W, scalarBits);
1383
- const windows = Math.ceil(scalarBits / W) + 1;
1384
- const windowSize = 2 ** (W - 1);
1385
- const maxNumber = 2 ** W;
1386
- const mask = bitMask(W);
1387
- const shiftBy = BigInt(W);
1388
- return { windows, windowSize, mask, maxNumber, shiftBy };
1389
- }
1390
- function calcOffsets(n, window, wOpts) {
1391
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1392
- let wbits = Number(n & mask);
1393
- let nextN = n >> shiftBy;
1394
- if (wbits > windowSize) {
1395
- wbits -= maxNumber;
1396
- nextN += _1n3;
1397
- }
1398
- const offsetStart = window * windowSize;
1399
- const offset = offsetStart + Math.abs(wbits) - 1;
1400
- const isZero = wbits === 0;
1401
- const isNeg = wbits < 0;
1402
- const isNegF = window % 2 !== 0;
1403
- const offsetF = offsetStart;
1404
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1405
- }
1406
- var pointPrecomputes = new WeakMap;
1407
- var pointWindowSizes = new WeakMap;
1408
- function getW(P) {
1409
- return pointWindowSizes.get(P) || 1;
1410
- }
1411
- function assert0(n) {
1412
- if (n !== _0n3)
1413
- throw new Error("invalid wNAF");
1414
- }
1415
-
1416
- class wNAF {
1417
- BASE;
1418
- ZERO;
1419
- Fn;
1420
- bits;
1421
- constructor(Point, bits) {
1422
- this.BASE = Point.BASE;
1423
- this.ZERO = Point.ZERO;
1424
- this.Fn = Point.Fn;
1425
- this.bits = bits;
1426
- }
1427
- _unsafeLadder(elm, n, p = this.ZERO) {
1428
- let d = elm;
1429
- while (n > _0n3) {
1430
- if (n & _1n3)
1431
- p = p.add(d);
1432
- d = d.double();
1433
- n >>= _1n3;
1434
- }
1435
- return p;
1436
- }
1437
- precomputeWindow(point, W) {
1438
- const { windows, windowSize } = calcWOpts(W, this.bits);
1439
- const points = [];
1440
- let p = point;
1441
- let base = p;
1442
- for (let window = 0;window < windows; window++) {
1443
- base = p;
1444
- points.push(base);
1445
- for (let i = 1;i < windowSize; i++) {
1446
- base = base.add(p);
1447
- points.push(base);
1448
- }
1449
- p = base.double();
1450
- }
1451
- return points;
1452
- }
1453
- wNAF(W, precomputes, n) {
1454
- if (!this.Fn.isValid(n))
1455
- throw new Error("invalid scalar");
1456
- let p = this.ZERO;
1457
- let f = this.BASE;
1458
- const wo = calcWOpts(W, this.bits);
1459
- for (let window = 0;window < wo.windows; window++) {
1460
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1461
- n = nextN;
1462
- if (isZero) {
1463
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
1464
- } else {
1465
- p = p.add(negateCt(isNeg, precomputes[offset]));
1466
- }
1467
- }
1468
- assert0(n);
1469
- return { p, f };
1470
- }
1471
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1472
- const wo = calcWOpts(W, this.bits);
1473
- for (let window = 0;window < wo.windows; window++) {
1474
- if (n === _0n3)
1475
- break;
1476
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1477
- n = nextN;
1478
- if (isZero) {
1479
- continue;
1480
- } else {
1481
- const item = precomputes[offset];
1482
- acc = acc.add(isNeg ? item.negate() : item);
1483
- }
1484
- }
1485
- assert0(n);
1486
- return acc;
1487
- }
1488
- getPrecomputes(W, point, transform) {
1489
- let comp = pointPrecomputes.get(point);
1490
- if (!comp) {
1491
- comp = this.precomputeWindow(point, W);
1492
- if (W !== 1) {
1493
- if (typeof transform === "function")
1494
- comp = transform(comp);
1495
- pointPrecomputes.set(point, comp);
1496
- }
1497
- }
1498
- return comp;
1499
- }
1500
- cached(point, scalar, transform) {
1501
- const W = getW(point);
1502
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1503
- }
1504
- unsafe(point, scalar, transform, prev) {
1505
- const W = getW(point);
1506
- if (W === 1)
1507
- return this._unsafeLadder(point, scalar, prev);
1508
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1509
- }
1510
- createCache(P, W) {
1511
- validateW(W, this.bits);
1512
- pointWindowSizes.set(P, W);
1513
- pointPrecomputes.delete(P);
1514
- }
1515
- hasCache(elm) {
1516
- return getW(elm) !== 1;
1517
- }
1518
- }
1519
- function createField(order, field, isLE2) {
1520
- if (field) {
1521
- if (field.ORDER !== order)
1522
- throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1523
- validateField(field);
1524
- return field;
1525
- } else {
1526
- return Field(order, { isLE: isLE2 });
1527
- }
1528
- }
1529
- function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1530
- if (FpFnLE === undefined)
1531
- FpFnLE = type === "edwards";
1532
- if (!CURVE || typeof CURVE !== "object")
1533
- throw new Error(`expected valid ${type} CURVE object`);
1534
- for (const p of ["p", "n", "h"]) {
1535
- const val = CURVE[p];
1536
- if (!(typeof val === "bigint" && val > _0n3))
1537
- throw new Error(`CURVE.${p} must be positive bigint`);
1538
- }
1539
- const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1540
- const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1541
- const _b = type === "weierstrass" ? "b" : "d";
1542
- const params = ["Gx", "Gy", "a", _b];
1543
- for (const p of params) {
1544
- if (!Fp.isValid(CURVE[p]))
1545
- throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1546
- }
1547
- CURVE = Object.freeze(Object.assign({}, CURVE));
1548
- return { CURVE, Fp, Fn };
1549
- }
1550
- function createKeygen(randomSecretKey, getPublicKey) {
1551
- return function keygen(seed) {
1552
- const secretKey = randomSecretKey(seed);
1553
- return { secretKey, publicKey: getPublicKey(secretKey) };
1554
- };
1555
- }
1556
-
1557
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/edwards.js
1558
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1559
- var _0n4 = /* @__PURE__ */ BigInt(0);
1560
- var _1n4 = /* @__PURE__ */ BigInt(1);
1561
- var _2n2 = /* @__PURE__ */ BigInt(2);
1562
- var _8n2 = /* @__PURE__ */ BigInt(8);
1563
- function isEdValidXY(Fp, CURVE, x, y) {
1564
- const x2 = Fp.sqr(x);
1565
- const y2 = Fp.sqr(y);
1566
- const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
1567
- const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
1568
- return Fp.eql(left, right);
1569
- }
1570
- function edwards(params, extraOpts = {}) {
1571
- const opts = extraOpts;
1572
- const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
1573
- const { Fp, Fn } = validated;
1574
- let CURVE = validated.CURVE;
1575
- const { h: cofactor } = CURVE;
1576
- validateObject(opts, {}, { uvRatio: "function" });
1577
- const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
1578
- const modP = (n) => Fp.create(n);
1579
- const uvRatio = opts.uvRatio === undefined ? (u, v) => {
1580
- try {
1581
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
1582
- } catch (e) {
1583
- return { isValid: false, value: _0n4 };
1584
- }
1585
- } : opts.uvRatio;
1586
- if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
1587
- throw new Error("bad curve params: generator point");
1588
- function acoord(title, n, banZero = false) {
1589
- const min = banZero ? _1n4 : _0n4;
1590
- aInRange("coordinate " + title, n, min, MASK);
1591
- return n;
1592
- }
1593
- function aedpoint(other) {
1594
- if (!(other instanceof Point))
1595
- throw new Error("EdwardsPoint expected");
1596
- }
1597
-
1598
- class Point {
1599
- static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
1600
- static ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
1601
- static Fp = Fp;
1602
- static Fn = Fn;
1603
- X;
1604
- Y;
1605
- Z;
1606
- T;
1607
- constructor(X, Y, Z, T) {
1608
- this.X = acoord("x", X);
1609
- this.Y = acoord("y", Y);
1610
- this.Z = acoord("z", Z, true);
1611
- this.T = acoord("t", T);
1612
- Object.freeze(this);
1613
- }
1614
- static CURVE() {
1615
- return CURVE;
1616
- }
1617
- static fromAffine(p) {
1618
- if (p instanceof Point)
1619
- throw new Error("extended point not allowed");
1620
- const { x, y } = p || {};
1621
- acoord("x", x);
1622
- acoord("y", y);
1623
- return new Point(x, y, _1n4, modP(x * y));
1624
- }
1625
- static fromBytes(bytes, zip215 = false) {
1626
- const len = Fp.BYTES;
1627
- const { a, d } = CURVE;
1628
- bytes = copyBytes(abytes2(bytes, len, "point"));
1629
- abool(zip215, "zip215");
1630
- const normed = copyBytes(bytes);
1631
- const lastByte = bytes[len - 1];
1632
- normed[len - 1] = lastByte & ~128;
1633
- const y = bytesToNumberLE(normed);
1634
- const max = zip215 ? MASK : Fp.ORDER;
1635
- aInRange("point.y", y, _0n4, max);
1636
- const y2 = modP(y * y);
1637
- const u = modP(y2 - _1n4);
1638
- const v = modP(d * y2 - a);
1639
- let { isValid, value: x } = uvRatio(u, v);
1640
- if (!isValid)
1641
- throw new Error("bad point: invalid y coordinate");
1642
- const isXOdd = (x & _1n4) === _1n4;
1643
- const isLastByteOdd = (lastByte & 128) !== 0;
1644
- if (!zip215 && x === _0n4 && isLastByteOdd)
1645
- throw new Error("bad point: x=0 and x_0=1");
1646
- if (isLastByteOdd !== isXOdd)
1647
- x = modP(-x);
1648
- return Point.fromAffine({ x, y });
1649
- }
1650
- static fromHex(hex, zip215 = false) {
1651
- return Point.fromBytes(hexToBytes2(hex), zip215);
1652
- }
1653
- get x() {
1654
- return this.toAffine().x;
1655
- }
1656
- get y() {
1657
- return this.toAffine().y;
1658
- }
1659
- precompute(windowSize = 8, isLazy = true) {
1660
- wnaf.createCache(this, windowSize);
1661
- if (!isLazy)
1662
- this.multiply(_2n2);
1663
- return this;
1664
- }
1665
- assertValidity() {
1666
- const p = this;
1667
- const { a, d } = CURVE;
1668
- if (p.is0())
1669
- throw new Error("bad point: ZERO");
1670
- const { X, Y, Z, T } = p;
1671
- const X2 = modP(X * X);
1672
- const Y2 = modP(Y * Y);
1673
- const Z2 = modP(Z * Z);
1674
- const Z4 = modP(Z2 * Z2);
1675
- const aX2 = modP(X2 * a);
1676
- const left = modP(Z2 * modP(aX2 + Y2));
1677
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1678
- if (left !== right)
1679
- throw new Error("bad point: equation left != right (1)");
1680
- const XY = modP(X * Y);
1681
- const ZT = modP(Z * T);
1682
- if (XY !== ZT)
1683
- throw new Error("bad point: equation left != right (2)");
1684
- }
1685
- equals(other) {
1686
- aedpoint(other);
1687
- const { X: X1, Y: Y1, Z: Z1 } = this;
1688
- const { X: X2, Y: Y2, Z: Z2 } = other;
1689
- const X1Z2 = modP(X1 * Z2);
1690
- const X2Z1 = modP(X2 * Z1);
1691
- const Y1Z2 = modP(Y1 * Z2);
1692
- const Y2Z1 = modP(Y2 * Z1);
1693
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1694
- }
1695
- is0() {
1696
- return this.equals(Point.ZERO);
1697
- }
1698
- negate() {
1699
- return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1700
- }
1701
- double() {
1702
- const { a } = CURVE;
1703
- const { X: X1, Y: Y1, Z: Z1 } = this;
1704
- const A = modP(X1 * X1);
1705
- const B = modP(Y1 * Y1);
1706
- const C = modP(_2n2 * modP(Z1 * Z1));
1707
- const D = modP(a * A);
1708
- const x1y1 = X1 + Y1;
1709
- const E = modP(modP(x1y1 * x1y1) - A - B);
1710
- const G = D + B;
1711
- const F = G - C;
1712
- const H = D - B;
1713
- const X3 = modP(E * F);
1714
- const Y3 = modP(G * H);
1715
- const T3 = modP(E * H);
1716
- const Z3 = modP(F * G);
1717
- return new Point(X3, Y3, Z3, T3);
1718
- }
1719
- add(other) {
1720
- aedpoint(other);
1721
- const { a, d } = CURVE;
1722
- const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1723
- const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1724
- const A = modP(X1 * X2);
1725
- const B = modP(Y1 * Y2);
1726
- const C = modP(T1 * d * T2);
1727
- const D = modP(Z1 * Z2);
1728
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1729
- const F = D - C;
1730
- const G = D + C;
1731
- const H = modP(B - a * A);
1732
- const X3 = modP(E * F);
1733
- const Y3 = modP(G * H);
1734
- const T3 = modP(E * H);
1735
- const Z3 = modP(F * G);
1736
- return new Point(X3, Y3, Z3, T3);
1737
- }
1738
- subtract(other) {
1739
- aedpoint(other);
1740
- return this.add(other.negate());
1741
- }
1742
- multiply(scalar) {
1743
- if (!Fn.isValidNot0(scalar))
1744
- throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1745
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1746
- return normalizeZ(Point, [p, f])[0];
1747
- }
1748
- multiplyUnsafe(scalar) {
1749
- if (!Fn.isValid(scalar))
1750
- throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1751
- if (scalar === _0n4)
1752
- return Point.ZERO;
1753
- if (this.is0() || scalar === _1n4)
1754
- return this;
1755
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));
1756
- }
1757
- isSmallOrder() {
1758
- return this.clearCofactor().is0();
1759
- }
1760
- isTorsionFree() {
1761
- return wnaf.unsafe(this, CURVE.n).is0();
1762
- }
1763
- toAffine(invertedZ) {
1764
- const p = this;
1765
- let iz = invertedZ;
1766
- const { X, Y, Z } = p;
1767
- const is0 = p.is0();
1768
- if (iz == null)
1769
- iz = is0 ? _8n2 : Fp.inv(Z);
1770
- const x = modP(X * iz);
1771
- const y = modP(Y * iz);
1772
- const zz = Fp.mul(Z, iz);
1773
- if (is0)
1774
- return { x: _0n4, y: _1n4 };
1775
- if (zz !== _1n4)
1776
- throw new Error("invZ was invalid");
1777
- return { x, y };
1778
- }
1779
- clearCofactor() {
1780
- if (cofactor === _1n4)
1781
- return this;
1782
- return this.multiplyUnsafe(cofactor);
1783
- }
1784
- toBytes() {
1785
- const { x, y } = this.toAffine();
1786
- const bytes = Fp.toBytes(y);
1787
- bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1788
- return bytes;
1789
- }
1790
- toHex() {
1791
- return bytesToHex2(this.toBytes());
1792
- }
1793
- toString() {
1794
- return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1795
- }
1796
- }
1797
- const wnaf = new wNAF(Point, Fn.BITS);
1798
- if (Fn.BITS >= 8)
1799
- Point.BASE.precompute(8);
1800
- Object.freeze(Point.prototype);
1801
- Object.freeze(Point);
1802
- return Point;
1803
- }
1804
-
1805
- class PrimeEdwardsPoint {
1806
- static BASE;
1807
- static ZERO;
1808
- static Fp;
1809
- static Fn;
1810
- ep;
1811
- constructor(ep) {
1812
- this.ep = ep;
1813
- }
1814
- static fromBytes(_bytes) {
1815
- notImplemented();
1816
- }
1817
- static fromHex(_hex) {
1818
- notImplemented();
1819
- }
1820
- get x() {
1821
- return this.toAffine().x;
1822
- }
1823
- get y() {
1824
- return this.toAffine().y;
1825
- }
1826
- clearCofactor() {
1827
- return this;
1828
- }
1829
- assertValidity() {
1830
- this.ep.assertValidity();
1831
- }
1832
- toAffine(invertedZ) {
1833
- return this.ep.toAffine(invertedZ);
1834
- }
1835
- toHex() {
1836
- return bytesToHex2(this.toBytes());
1837
- }
1838
- toString() {
1839
- return this.toHex();
1840
- }
1841
- isTorsionFree() {
1842
- return true;
1843
- }
1844
- isSmallOrder() {
1845
- return false;
1846
- }
1847
- add(other) {
1848
- this.assertSame(other);
1849
- return this.init(this.ep.add(other.ep));
1850
- }
1851
- subtract(other) {
1852
- this.assertSame(other);
1853
- return this.init(this.ep.subtract(other.ep));
1854
- }
1855
- multiply(scalar) {
1856
- return this.init(this.ep.multiply(scalar));
1857
- }
1858
- multiplyUnsafe(scalar) {
1859
- return this.init(this.ep.multiplyUnsafe(scalar));
1860
- }
1861
- double() {
1862
- return this.init(this.ep.double());
1863
- }
1864
- negate() {
1865
- return this.init(this.ep.negate());
1866
- }
1867
- precompute(windowSize, isLazy) {
1868
- this.ep.precompute(windowSize, isLazy);
1869
- return this;
1870
- }
1871
- }
1872
- function eddsa(Point, cHash, eddsaOpts = {}) {
1873
- if (typeof cHash !== "function")
1874
- throw new Error('"hash" function param is required');
1875
- const hash = cHash;
1876
- const opts = eddsaOpts;
1877
- validateObject(opts, {}, {
1878
- adjustScalarBytes: "function",
1879
- randomBytes: "function",
1880
- domain: "function",
1881
- prehash: "function",
1882
- zip215: "boolean",
1883
- mapToCurve: "function"
1884
- });
1885
- const { prehash } = opts;
1886
- const { BASE, Fp, Fn } = Point;
1887
- const outputLen = hash.outputLen;
1888
- const expectedLen = 2 * Fp.BYTES;
1889
- if (outputLen !== undefined) {
1890
- asafenumber(outputLen, "hash.outputLen");
1891
- if (outputLen !== expectedLen)
1892
- throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
1893
- }
1894
- const randomBytes3 = opts.randomBytes === undefined ? randomBytes2 : opts.randomBytes;
1895
- const adjustScalarBytes = opts.adjustScalarBytes === undefined ? (bytes) => bytes : opts.adjustScalarBytes;
1896
- const domain = opts.domain === undefined ? (data, ctx, phflag) => {
1897
- abool(phflag, "phflag");
1898
- if (ctx.length || phflag)
1899
- throw new Error("Contexts/pre-hash are not supported");
1900
- return data;
1901
- } : opts.domain;
1902
- function modN_LE(hash2) {
1903
- return Fn.create(bytesToNumberLE(hash2));
1904
- }
1905
- function getPrivateScalar(key) {
1906
- const len = lengths.secretKey;
1907
- abytes2(key, lengths.secretKey, "secretKey");
1908
- const hashed = abytes2(hash(key), 2 * len, "hashedSecretKey");
1909
- const head = adjustScalarBytes(hashed.slice(0, len));
1910
- const prefix = hashed.slice(len, 2 * len);
1911
- const scalar = modN_LE(head);
1912
- return { head, prefix, scalar };
1913
- }
1914
- function getExtendedPublicKey(secretKey) {
1915
- const { head, prefix, scalar } = getPrivateScalar(secretKey);
1916
- const point = BASE.multiply(scalar);
1917
- const pointBytes = point.toBytes();
1918
- return { head, prefix, scalar, point, pointBytes };
1919
- }
1920
- function getPublicKey(secretKey) {
1921
- return getExtendedPublicKey(secretKey).pointBytes;
1922
- }
1923
- function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
1924
- const msg = concatBytes2(...msgs);
1925
- return modN_LE(hash(domain(msg, abytes2(context, undefined, "context"), !!prehash)));
1926
- }
1927
- function sign(msg, secretKey, options = {}) {
1928
- msg = abytes2(msg, undefined, "message");
1929
- if (prehash)
1930
- msg = prehash(msg);
1931
- const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
1932
- const r = hashDomainToScalar(options.context, prefix, msg);
1933
- const R = BASE.multiply(r).toBytes();
1934
- const k = hashDomainToScalar(options.context, R, pointBytes, msg);
1935
- const s = Fn.create(r + k * scalar);
1936
- if (!Fn.isValid(s))
1937
- throw new Error("sign failed: invalid s");
1938
- const rs = concatBytes2(R, Fn.toBytes(s));
1939
- return abytes2(rs, lengths.signature, "result");
1940
- }
1941
- const verifyOpts = {
1942
- zip215: opts.zip215
1943
- };
1944
- function verify(sig, msg, publicKey, options = verifyOpts) {
1945
- const { context } = options;
1946
- const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;
1947
- const len = lengths.signature;
1948
- sig = abytes2(sig, len, "signature");
1949
- msg = abytes2(msg, undefined, "message");
1950
- publicKey = abytes2(publicKey, lengths.publicKey, "publicKey");
1951
- if (zip215 !== undefined)
1952
- abool(zip215, "zip215");
1953
- if (prehash)
1954
- msg = prehash(msg);
1955
- const mid = len / 2;
1956
- const r = sig.subarray(0, mid);
1957
- const s = bytesToNumberLE(sig.subarray(mid, len));
1958
- let A, R, SB;
1959
- try {
1960
- A = Point.fromBytes(publicKey, zip215);
1961
- R = Point.fromBytes(r, zip215);
1962
- SB = BASE.multiplyUnsafe(s);
1963
- } catch (error) {
1964
- return false;
1965
- }
1966
- if (!zip215 && A.isSmallOrder())
1967
- return false;
1968
- const k = hashDomainToScalar(context, r, publicKey, msg);
1969
- const RkA = R.add(A.multiplyUnsafe(k));
1970
- return RkA.subtract(SB).clearCofactor().is0();
1971
- }
1972
- const _size = Fp.BYTES;
1973
- const lengths = {
1974
- secretKey: _size,
1975
- publicKey: _size,
1976
- signature: 2 * _size,
1977
- seed: _size
1978
- };
1979
- function randomSecretKey(seed) {
1980
- seed = seed === undefined ? randomBytes3(lengths.seed) : seed;
1981
- return abytes2(seed, lengths.seed, "seed");
1982
- }
1983
- function isValidSecretKey(key) {
1984
- return isBytes2(key) && key.length === lengths.secretKey;
1985
- }
1986
- function isValidPublicKey(key, zip215) {
1987
- try {
1988
- return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);
1989
- } catch (error) {
1990
- return false;
1991
- }
1992
- }
1993
- const utils = {
1994
- getExtendedPublicKey,
1995
- randomSecretKey,
1996
- isValidSecretKey,
1997
- isValidPublicKey,
1998
- toMontgomery(publicKey) {
1999
- const { y } = Point.fromBytes(publicKey);
2000
- const size = lengths.publicKey;
2001
- const is25519 = size === 32;
2002
- if (!is25519 && size !== 57)
2003
- throw new Error("only defined for 25519 and 448");
2004
- const u = is25519 ? Fp.div(_1n4 + y, _1n4 - y) : Fp.div(y - _1n4, y + _1n4);
2005
- return Fp.toBytes(u);
2006
- },
2007
- toMontgomerySecret(secretKey) {
2008
- const size = lengths.secretKey;
2009
- abytes2(secretKey, size);
2010
- const hashed = hash(secretKey.subarray(0, size));
2011
- return adjustScalarBytes(hashed).subarray(0, size);
2012
- }
2013
- };
2014
- Object.freeze(lengths);
2015
- Object.freeze(utils);
2016
- return Object.freeze({
2017
- keygen: createKeygen(randomSecretKey, getPublicKey),
2018
- getPublicKey,
2019
- sign,
2020
- verify,
2021
- utils,
2022
- Point,
2023
- lengths
2024
- });
2025
- }
2026
-
2027
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/fft.js
2028
- function checkU32(n) {
2029
- if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
2030
- throw new Error("wrong u32 integer:" + n);
2031
- return n;
2032
- }
2033
- function isPowerOfTwo(x) {
2034
- checkU32(x);
2035
- return (x & x - 1) === 0 && x !== 0;
2036
- }
2037
- function reverseBits(n, bits) {
2038
- checkU32(n);
2039
- if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
2040
- throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
2041
- let reversed = 0;
2042
- for (let i = 0;i < bits; i++, n >>>= 1)
2043
- reversed = reversed << 1 | n & 1;
2044
- return reversed >>> 0;
2045
- }
2046
- function log2(n) {
2047
- checkU32(n);
2048
- return 31 - Math.clz32(n);
2049
- }
2050
- function bitReversalInplace(values) {
2051
- const n = values.length;
2052
- if (!isPowerOfTwo(n))
2053
- throw new Error("expected positive power-of-two length, got " + n);
2054
- const bits = log2(n);
2055
- for (let i = 0;i < n; i++) {
2056
- const j = reverseBits(i, bits);
2057
- if (i < j) {
2058
- const tmp = values[i];
2059
- values[i] = values[j];
2060
- values[j] = tmp;
2061
- }
2062
- }
2063
- return values;
2064
- }
2065
- var FFTCore = (F, coreOpts) => {
2066
- const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
2067
- const bits = log2(N);
2068
- if (!isPowerOfTwo(N))
2069
- throw new Error("FFT: Polynomial size should be power of two");
2070
- if (roots.length !== N)
2071
- throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);
2072
- const isDit = dit !== invertButterflies;
2073
- return (values) => {
2074
- if (values.length !== N)
2075
- throw new Error("FFT: wrong Polynomial length");
2076
- if (dit && brp)
2077
- bitReversalInplace(values);
2078
- for (let i = 0, g = 1;i < bits - skipStages; i++) {
2079
- const s = dit ? i + 1 + skipStages : bits - i;
2080
- const m = 1 << s;
2081
- const m2 = m >> 1;
2082
- const stride = N >> s;
2083
- for (let k = 0;k < N; k += m) {
2084
- for (let j = 0, grp = g++;j < m2; j++) {
2085
- const rootPos = invertButterflies ? dit ? N - grp : grp : j * stride;
2086
- const i0 = k + j;
2087
- const i1 = k + j + m2;
2088
- const omega = roots[rootPos];
2089
- const b = values[i1];
2090
- const a = values[i0];
2091
- if (isDit) {
2092
- const t = F.mul(b, omega);
2093
- values[i0] = F.add(a, t);
2094
- values[i1] = F.sub(a, t);
2095
- } else if (invertButterflies) {
2096
- values[i0] = F.add(b, a);
2097
- values[i1] = F.mul(F.sub(b, a), omega);
2098
- } else {
2099
- values[i0] = F.add(a, b);
2100
- values[i1] = F.mul(F.sub(a, b), omega);
2101
- }
2102
- }
2103
- }
2104
- }
2105
- if (!dit && brp)
2106
- bitReversalInplace(values);
2107
- return values;
2108
- };
2109
- };
2110
-
2111
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/hash-to-curve.js
2112
- function i2osp(value, length) {
2113
- asafenumber(value);
2114
- asafenumber(length);
2115
- if (length < 0 || length > 4)
2116
- throw new Error("invalid I2OSP length: " + length);
2117
- if (value < 0 || value > 2 ** (8 * length) - 1)
2118
- throw new Error("invalid I2OSP input: " + value);
2119
- const res = Array.from({ length }).fill(0);
2120
- for (let i = length - 1;i >= 0; i--) {
2121
- res[i] = value & 255;
2122
- value >>>= 8;
2123
- }
2124
- return new Uint8Array(res);
2125
- }
2126
- function strxor(a, b) {
2127
- const arr = new Uint8Array(a.length);
2128
- for (let i = 0;i < a.length; i++) {
2129
- arr[i] = a[i] ^ b[i];
2130
- }
2131
- return arr;
2132
- }
2133
- function normDST(DST) {
2134
- if (!isBytes2(DST) && typeof DST !== "string")
2135
- throw new Error("DST must be Uint8Array or ascii string");
2136
- const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
2137
- if (dst.length === 0)
2138
- throw new Error("DST must be non-empty");
2139
- return dst;
2140
- }
2141
- function expand_message_xmd(msg, DST, lenInBytes, H) {
2142
- abytes2(msg);
2143
- asafenumber(lenInBytes);
2144
- DST = normDST(DST);
2145
- if (DST.length > 255)
2146
- DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
2147
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
2148
- const ell = Math.ceil(lenInBytes / b_in_bytes);
2149
- if (lenInBytes > 65535 || ell > 255)
2150
- throw new Error("expand_message_xmd: invalid lenInBytes");
2151
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
2152
- const Z_pad = new Uint8Array(r_in_bytes);
2153
- const l_i_b_str = i2osp(lenInBytes, 2);
2154
- const b = new Array(ell);
2155
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
2156
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
2157
- for (let i = 1;i < ell; i++) {
2158
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
2159
- b[i] = H(concatBytes2(...args));
2160
- }
2161
- const pseudo_random_bytes = concatBytes2(...b);
2162
- return pseudo_random_bytes.slice(0, lenInBytes);
2163
- }
2164
- var _DST_scalar = "HashToScalar-";
2165
-
2166
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/montgomery.js
2167
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2168
- var _0n5 = BigInt(0);
2169
- var _1n5 = BigInt(1);
2170
- var _2n3 = BigInt(2);
2171
- function validateOpts(curve) {
2172
- validateObject(curve, {
2173
- P: "bigint",
2174
- type: "string",
2175
- adjustScalarBytes: "function",
2176
- powPminus2: "function"
2177
- }, {
2178
- randomBytes: "function"
2179
- });
2180
- return Object.freeze({ ...curve });
2181
- }
2182
- function montgomery(curveDef) {
2183
- const CURVE = validateOpts(curveDef);
2184
- const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;
2185
- const is25519 = type === "x25519";
2186
- if (!is25519 && type !== "x448")
2187
- throw new Error("invalid type");
2188
- const randomBytes_ = rand === undefined ? randomBytes2 : rand;
2189
- const montgomeryBits = is25519 ? 255 : 448;
2190
- const fieldLen = is25519 ? 32 : 56;
2191
- const Gu = is25519 ? BigInt(9) : BigInt(5);
2192
- const a24 = is25519 ? BigInt(121665) : BigInt(39081);
2193
- const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
2194
- const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
2195
- const maxScalar = minScalar + maxAdded + _1n5;
2196
- const modP = (n) => mod(n, P);
2197
- const GuBytes = encodeU(Gu);
2198
- function encodeU(u) {
2199
- return numberToBytesLE(modP(u), fieldLen);
2200
- }
2201
- function decodeU(u) {
2202
- const _u = copyBytes(abytes2(u, fieldLen, "uCoordinate"));
2203
- if (is25519)
2204
- _u[31] &= 127;
2205
- return modP(bytesToNumberLE(_u));
2206
- }
2207
- function decodeScalar(scalar) {
2208
- return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
2209
- }
2210
- function scalarMult(scalar, u) {
2211
- const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
2212
- if (pu === _0n5)
2213
- throw new Error("invalid private or public key received");
2214
- return encodeU(pu);
2215
- }
2216
- function scalarMultBase(scalar) {
2217
- return scalarMult(scalar, GuBytes);
2218
- }
2219
- const getPublicKey = scalarMultBase;
2220
- const getSharedSecret = scalarMult;
2221
- function cswap(swap, x_2, x_3) {
2222
- const dummy = modP(swap * (x_2 - x_3));
2223
- x_2 = modP(x_2 - dummy);
2224
- x_3 = modP(x_3 + dummy);
2225
- return { x_2, x_3 };
2226
- }
2227
- function montgomeryLadder(u, scalar) {
2228
- aInRange("u", u, _0n5, P);
2229
- aInRange("scalar", scalar, minScalar, maxScalar);
2230
- const k = scalar;
2231
- const x_1 = u;
2232
- let x_2 = _1n5;
2233
- let z_2 = _0n5;
2234
- let x_3 = u;
2235
- let z_3 = _1n5;
2236
- let swap = _0n5;
2237
- for (let t = BigInt(montgomeryBits - 1);t >= _0n5; t--) {
2238
- const k_t = k >> t & _1n5;
2239
- swap ^= k_t;
2240
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
2241
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
2242
- swap = k_t;
2243
- const A = x_2 + z_2;
2244
- const AA = modP(A * A);
2245
- const B = x_2 - z_2;
2246
- const BB = modP(B * B);
2247
- const E = AA - BB;
2248
- const C = x_3 + z_3;
2249
- const D = x_3 - z_3;
2250
- const DA = modP(D * A);
2251
- const CB = modP(C * B);
2252
- const dacb = DA + CB;
2253
- const da_cb = DA - CB;
2254
- x_3 = modP(dacb * dacb);
2255
- z_3 = modP(x_1 * modP(da_cb * da_cb));
2256
- x_2 = modP(AA * BB);
2257
- z_2 = modP(E * (AA + modP(a24 * E)));
2258
- }
2259
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
2260
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
2261
- const z2 = powPminus2(z_2);
2262
- return modP(x_2 * z2);
2263
- }
2264
- const lengths = {
2265
- secretKey: fieldLen,
2266
- publicKey: fieldLen,
2267
- seed: fieldLen
2268
- };
2269
- const randomSecretKey = (seed) => {
2270
- seed = seed === undefined ? randomBytes_(fieldLen) : seed;
2271
- abytes2(seed, lengths.seed, "seed");
2272
- return seed;
2273
- };
2274
- const utils = { randomSecretKey };
2275
- Object.freeze(lengths);
2276
- Object.freeze(utils);
2277
- return Object.freeze({
2278
- keygen: createKeygen(randomSecretKey, getPublicKey),
2279
- getSharedSecret,
2280
- getPublicKey,
2281
- scalarMult,
2282
- scalarMultBase,
2283
- utils,
2284
- GuBytes: GuBytes.slice(),
2285
- lengths
2286
- });
2287
- }
2288
-
2289
- // ../../node_modules/.bun/@noble+curves@2.2.0/node_modules/@noble/curves/ed25519.js
2290
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2291
- var _0n6 = /* @__PURE__ */ BigInt(0);
2292
- var _1n6 = /* @__PURE__ */ BigInt(1);
2293
- var _2n4 = /* @__PURE__ */ BigInt(2);
2294
- var _3n2 = /* @__PURE__ */ BigInt(3);
2295
- var _5n2 = /* @__PURE__ */ BigInt(5);
2296
- var _8n3 = /* @__PURE__ */ BigInt(8);
2297
- var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2298
- var ed25519_CURVE = /* @__PURE__ */ (() => ({
2299
- p: ed25519_CURVE_p,
2300
- n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2301
- h: _8n3,
2302
- a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2303
- d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2304
- Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2305
- Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2306
- }))();
2307
- function ed25519_pow_2_252_3(x) {
2308
- const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2309
- const P = ed25519_CURVE_p;
2310
- const x2 = x * x % P;
2311
- const b2 = x2 * x % P;
2312
- const b4 = pow2(b2, _2n4, P) * b2 % P;
2313
- const b5 = pow2(b4, _1n6, P) * x % P;
2314
- const b10 = pow2(b5, _5n2, P) * b5 % P;
2315
- const b20 = pow2(b10, _10n, P) * b10 % P;
2316
- const b40 = pow2(b20, _20n, P) * b20 % P;
2317
- const b80 = pow2(b40, _40n, P) * b40 % P;
2318
- const b160 = pow2(b80, _80n, P) * b80 % P;
2319
- const b240 = pow2(b160, _80n, P) * b80 % P;
2320
- const b250 = pow2(b240, _10n, P) * b10 % P;
2321
- const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
2322
- return { pow_p_5_8, b2 };
2323
- }
2324
- function adjustScalarBytes(bytes) {
2325
- bytes[0] &= 248;
2326
- bytes[31] &= 127;
2327
- bytes[31] |= 64;
2328
- return bytes;
2329
- }
2330
- var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2331
- function uvRatio(u, v) {
2332
- const P = ed25519_CURVE_p;
2333
- const v3 = mod(v * v * v, P);
2334
- const v7 = mod(v3 * v3 * v, P);
2335
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2336
- let x = mod(u * v3 * pow, P);
2337
- const vx2 = mod(v * x * x, P);
2338
- const root1 = x;
2339
- const root2 = mod(x * ED25519_SQRT_M1, P);
2340
- const useRoot1 = vx2 === u;
2341
- const useRoot2 = vx2 === mod(-u, P);
2342
- const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2343
- if (useRoot1)
2344
- x = root1;
2345
- if (useRoot2 || noRoot)
2346
- x = root2;
2347
- if (isNegativeLE(x, P))
2348
- x = mod(-x, P);
2349
- return { isValid: useRoot1 || useRoot2, value: x };
2350
- }
2351
- var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2352
- var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2353
- var Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
2354
- function ed(opts) {
2355
- return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, zip215: true }, opts));
2356
- }
2357
- var ed25519 = /* @__PURE__ */ ed({});
2358
- var x25519 = /* @__PURE__ */ (() => {
2359
- const P = ed25519_CURVE_p;
2360
- return montgomery({
2361
- P,
2362
- type: "x25519",
2363
- powPminus2: (x) => {
2364
- const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2365
- return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2366
- },
2367
- adjustScalarBytes
2368
- });
2369
- })();
2370
- var SQRT_M1 = ED25519_SQRT_M1;
2371
- var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2372
- var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2373
- var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2374
- var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2375
- var invertSqrt = (number) => uvRatio(_1n6, number);
2376
- var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2377
- var bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
2378
- function calcElligatorRistrettoMap(r0) {
2379
- const { d } = ed25519_CURVE;
2380
- const P = ed25519_CURVE_p;
2381
- const mod2 = (n) => Fp.create(n);
2382
- const r = mod2(SQRT_M1 * r0 * r0);
2383
- const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2384
- let c = BigInt(-1);
2385
- const D = mod2((c - d * r) * mod2(r + d));
2386
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2387
- let s_ = mod2(s * r0);
2388
- if (!isNegativeLE(s_, P))
2389
- s_ = mod2(-s_);
2390
- if (!Ns_D_is_sq)
2391
- s = s_;
2392
- if (!Ns_D_is_sq)
2393
- c = r;
2394
- const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2395
- const s2 = s * s;
2396
- const W0 = mod2((s + s) * D);
2397
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2398
- const W2 = mod2(_1n6 - s2);
2399
- const W3 = mod2(_1n6 + s2);
2400
- return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2401
- }
2402
-
2403
- class _RistrettoPoint extends PrimeEdwardsPoint {
2404
- static BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();
2405
- static ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();
2406
- static Fp = /* @__PURE__ */ (() => Fp)();
2407
- static Fn = /* @__PURE__ */ (() => Fn)();
2408
- constructor(ep) {
2409
- super(ep);
2410
- }
2411
- static fromAffine(ap) {
2412
- return new _RistrettoPoint(ed25519_Point.fromAffine(ap));
2413
- }
2414
- assertSame(other) {
2415
- if (!(other instanceof _RistrettoPoint))
2416
- throw new Error("RistrettoPoint expected");
2417
- }
2418
- init(ep) {
2419
- return new _RistrettoPoint(ep);
2420
- }
2421
- static fromBytes(bytes) {
2422
- abytes(bytes, 32);
2423
- const { a, d } = ed25519_CURVE;
2424
- const P = ed25519_CURVE_p;
2425
- const mod2 = (n) => Fp.create(n);
2426
- const s = bytes255ToNumberLE(bytes);
2427
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2428
- throw new Error("invalid ristretto255 encoding 1");
2429
- const s2 = mod2(s * s);
2430
- const u1 = mod2(_1n6 + a * s2);
2431
- const u2 = mod2(_1n6 - a * s2);
2432
- const u1_2 = mod2(u1 * u1);
2433
- const u2_2 = mod2(u2 * u2);
2434
- const v = mod2(a * d * u1_2 - u2_2);
2435
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2436
- const Dx = mod2(I * u2);
2437
- const Dy = mod2(I * Dx * v);
2438
- let x = mod2((s + s) * Dx);
2439
- if (isNegativeLE(x, P))
2440
- x = mod2(-x);
2441
- const y = mod2(u1 * Dy);
2442
- const t = mod2(x * y);
2443
- if (!isValid || isNegativeLE(t, P) || y === _0n6)
2444
- throw new Error("invalid ristretto255 encoding 2");
2445
- return new _RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2446
- }
2447
- static fromHex(hex) {
2448
- return _RistrettoPoint.fromBytes(hexToBytes(hex));
2449
- }
2450
- toBytes() {
2451
- let { X, Y, Z, T } = this.ep;
2452
- const P = ed25519_CURVE_p;
2453
- const mod2 = (n) => Fp.create(n);
2454
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2455
- const u2 = mod2(X * Y);
2456
- const u2sq = mod2(u2 * u2);
2457
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2458
- const D1 = mod2(invsqrt * u1);
2459
- const D2 = mod2(invsqrt * u2);
2460
- const zInv = mod2(D1 * D2 * T);
2461
- let D;
2462
- if (isNegativeLE(T * zInv, P)) {
2463
- let _x = mod2(Y * SQRT_M1);
2464
- let _y = mod2(X * SQRT_M1);
2465
- X = _x;
2466
- Y = _y;
2467
- D = mod2(D1 * INVSQRT_A_MINUS_D);
2468
- } else {
2469
- D = D2;
2470
- }
2471
- if (isNegativeLE(X * zInv, P))
2472
- Y = mod2(-Y);
2473
- let s = mod2((Z - Y) * D);
2474
- if (isNegativeLE(s, P))
2475
- s = mod2(-s);
2476
- return Fp.toBytes(s);
2477
- }
2478
- equals(other) {
2479
- this.assertSame(other);
2480
- const { X: X1, Y: Y1 } = this.ep;
2481
- const { X: X2, Y: Y2 } = other.ep;
2482
- const mod2 = (n) => Fp.create(n);
2483
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2484
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2485
- return one || two;
2486
- }
2487
- is0() {
2488
- return this.equals(_RistrettoPoint.ZERO);
2489
- }
2490
- }
2491
- Object.freeze(_RistrettoPoint.BASE);
2492
- Object.freeze(_RistrettoPoint.ZERO);
2493
- Object.freeze(_RistrettoPoint.prototype);
2494
- Object.freeze(_RistrettoPoint);
2495
- var ristretto255_hasher = Object.freeze({
2496
- Point: _RistrettoPoint,
2497
- hashToCurve(msg, options) {
2498
- const DST = options?.DST === undefined ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2499
- const xmd = expand_message_xmd(msg, DST, 64, sha512);
2500
- return ristretto255_hasher.deriveToCurve(xmd);
2501
- },
2502
- hashToScalar(msg, options = { DST: _DST_scalar }) {
2503
- const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2504
- return Fn.create(bytesToNumberLE(xmd));
2505
- },
2506
- deriveToCurve(bytes) {
2507
- abytes(bytes, 64);
2508
- const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2509
- const R1 = calcElligatorRistrettoMap(r1);
2510
- const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2511
- const R2 = calcElligatorRistrettoMap(r2);
2512
- return new _RistrettoPoint(R1.add(R2));
2513
- }
2514
- });
2515
-
2516
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha3.js
2517
- var _0n7 = BigInt(0);
2518
- var _1n7 = BigInt(1);
2519
- var _2n5 = BigInt(2);
2520
- var _7n2 = BigInt(7);
2521
- var _256n = BigInt(256);
2522
- var _0x71n = BigInt(113);
2523
- var SHA3_PI = [];
2524
- var SHA3_ROTL = [];
2525
- var _SHA3_IOTA = [];
2526
- for (let round = 0, R = _1n7, x = 1, y = 0;round < 24; round++) {
2527
- [x, y] = [y, (2 * x + 3 * y) % 5];
2528
- SHA3_PI.push(2 * (5 * y + x));
2529
- SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
2530
- let t = _0n7;
2531
- for (let j = 0;j < 7; j++) {
2532
- R = (R << _1n7 ^ (R >> _7n2) * _0x71n) % _256n;
2533
- if (R & _2n5)
2534
- t ^= _1n7 << (_1n7 << BigInt(j)) - _1n7;
2535
- }
2536
- _SHA3_IOTA.push(t);
2537
- }
2538
- var IOTAS = split(_SHA3_IOTA, true);
2539
- var SHA3_IOTA_H = IOTAS[0];
2540
- var SHA3_IOTA_L = IOTAS[1];
2541
- var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
2542
- var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
2543
- function keccakP(s, rounds = 24) {
2544
- anumber(rounds, "rounds");
2545
- if (rounds < 1 || rounds > 24)
2546
- throw new Error('"rounds" expected integer 1..24');
2547
- const B = new Uint32Array(5 * 2);
2548
- for (let round = 24 - rounds;round < 24; round++) {
2549
- for (let x = 0;x < 10; x++)
2550
- B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2551
- for (let x = 0;x < 10; x += 2) {
2552
- const idx1 = (x + 8) % 10;
2553
- const idx0 = (x + 2) % 10;
2554
- const B0 = B[idx0];
2555
- const B1 = B[idx0 + 1];
2556
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
2557
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2558
- for (let y = 0;y < 50; y += 10) {
2559
- s[x + y] ^= Th;
2560
- s[x + y + 1] ^= Tl;
2561
- }
2562
- }
2563
- let curH = s[2];
2564
- let curL = s[3];
2565
- for (let t = 0;t < 24; t++) {
2566
- const shift = SHA3_ROTL[t];
2567
- const Th = rotlH(curH, curL, shift);
2568
- const Tl = rotlL(curH, curL, shift);
2569
- const PI = SHA3_PI[t];
2570
- curH = s[PI];
2571
- curL = s[PI + 1];
2572
- s[PI] = Th;
2573
- s[PI + 1] = Tl;
2574
- }
2575
- for (let y = 0;y < 50; y += 10) {
2576
- const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
2577
- s[y] ^= ~s[y + 2] & s[y + 4];
2578
- s[y + 1] ^= ~s[y + 3] & s[y + 5];
2579
- s[y + 2] ^= ~s[y + 4] & s[y + 6];
2580
- s[y + 3] ^= ~s[y + 5] & s[y + 7];
2581
- s[y + 4] ^= ~s[y + 6] & s[y + 8];
2582
- s[y + 5] ^= ~s[y + 7] & s[y + 9];
2583
- s[y + 6] ^= ~s[y + 8] & b0;
2584
- s[y + 7] ^= ~s[y + 9] & b1;
2585
- s[y + 8] ^= ~b0 & b2;
2586
- s[y + 9] ^= ~b1 & b3;
2587
- }
2588
- s[0] ^= SHA3_IOTA_H[round];
2589
- s[1] ^= SHA3_IOTA_L[round];
2590
- }
2591
- clean(B);
2592
- }
2593
-
2594
- class Keccak {
2595
- state;
2596
- pos = 0;
2597
- posOut = 0;
2598
- finished = false;
2599
- state32;
2600
- destroyed = false;
2601
- blockLen;
2602
- suffix;
2603
- outputLen;
2604
- canXOF;
2605
- enableXOF = false;
2606
- rounds;
2607
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2608
- this.blockLen = blockLen;
2609
- this.suffix = suffix;
2610
- this.outputLen = outputLen;
2611
- this.enableXOF = enableXOF;
2612
- this.canXOF = enableXOF;
2613
- this.rounds = rounds;
2614
- anumber(outputLen, "outputLen");
2615
- if (!(0 < blockLen && blockLen < 200))
2616
- throw new Error("only keccak-f1600 function is supported");
2617
- this.state = new Uint8Array(200);
2618
- this.state32 = u32(this.state);
2619
- }
2620
- clone() {
2621
- return this._cloneInto();
2622
- }
2623
- keccak() {
2624
- swap32IfBE(this.state32);
2625
- keccakP(this.state32, this.rounds);
2626
- swap32IfBE(this.state32);
2627
- this.posOut = 0;
2628
- this.pos = 0;
2629
- }
2630
- update(data) {
2631
- aexists(this);
2632
- abytes(data);
2633
- const { blockLen, state } = this;
2634
- const len = data.length;
2635
- for (let pos = 0;pos < len; ) {
2636
- const take = Math.min(blockLen - this.pos, len - pos);
2637
- for (let i = 0;i < take; i++)
2638
- state[this.pos++] ^= data[pos++];
2639
- if (this.pos === blockLen)
2640
- this.keccak();
2641
- }
2642
- return this;
2643
- }
2644
- finish() {
2645
- if (this.finished)
2646
- return;
2647
- this.finished = true;
2648
- const { state, suffix, pos, blockLen } = this;
2649
- state[pos] ^= suffix;
2650
- if ((suffix & 128) !== 0 && pos === blockLen - 1)
2651
- this.keccak();
2652
- state[blockLen - 1] ^= 128;
2653
- this.keccak();
2654
- }
2655
- writeInto(out) {
2656
- aexists(this, false);
2657
- abytes(out);
2658
- this.finish();
2659
- const bufferOut = this.state;
2660
- const { blockLen } = this;
2661
- for (let pos = 0, len = out.length;pos < len; ) {
2662
- if (this.posOut >= blockLen)
2663
- this.keccak();
2664
- const take = Math.min(blockLen - this.posOut, len - pos);
2665
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2666
- this.posOut += take;
2667
- pos += take;
2668
- }
2669
- return out;
2670
- }
2671
- xofInto(out) {
2672
- if (!this.enableXOF)
2673
- throw new Error("XOF is not possible for this instance");
2674
- return this.writeInto(out);
2675
- }
2676
- xof(bytes) {
2677
- anumber(bytes);
2678
- return this.xofInto(new Uint8Array(bytes));
2679
- }
2680
- digestInto(out) {
2681
- aoutput(out, this);
2682
- if (this.finished)
2683
- throw new Error("digest() was already called");
2684
- this.writeInto(out.subarray(0, this.outputLen));
2685
- this.destroy();
2686
- }
2687
- digest() {
2688
- const out = new Uint8Array(this.outputLen);
2689
- this.digestInto(out);
2690
- return out;
2691
- }
2692
- destroy() {
2693
- this.destroyed = true;
2694
- clean(this.state);
2695
- }
2696
- _cloneInto(to) {
2697
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2698
- to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
2699
- to.blockLen = blockLen;
2700
- to.state32.set(this.state32);
2701
- to.pos = this.pos;
2702
- to.posOut = this.posOut;
2703
- to.finished = this.finished;
2704
- to.rounds = rounds;
2705
- to.suffix = suffix;
2706
- to.outputLen = outputLen;
2707
- to.enableXOF = enableXOF;
2708
- to.canXOF = this.canXOF;
2709
- to.destroyed = this.destroyed;
2710
- return to;
2711
- }
2712
- }
2713
- var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
2714
- var sha3_256 = /* @__PURE__ */ genKeccak(6, 136, 32, /* @__PURE__ */ oidNist(8));
2715
- var sha3_512 = /* @__PURE__ */ genKeccak(6, 72, 64, /* @__PURE__ */ oidNist(10));
2716
- var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);
2717
- var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2718
- var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2719
-
2720
- // ../../node_modules/.bun/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/utils.js
2721
- /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
2722
- var abytesDoc = abytes;
2723
- var randomBytes3 = randomBytes;
2724
- function equalBytes2(a, b) {
2725
- if (a.length !== b.length)
2726
- return false;
2727
- let diff = 0;
2728
- for (let i = 0;i < a.length; i++)
2729
- diff |= a[i] ^ b[i];
2730
- return diff === 0;
2731
- }
2732
- function copyBytes2(bytes) {
2733
- return Uint8Array.from(abytes(bytes));
2734
- }
2735
- function validateOpts2(opts) {
2736
- if (Object.prototype.toString.call(opts) !== "[object Object]")
2737
- throw new TypeError("expected valid options object");
2738
- }
2739
- function validateVerOpts(opts) {
2740
- validateOpts2(opts);
2741
- if (opts.context !== undefined)
2742
- abytes(opts.context, undefined, "opts.context");
2743
- }
2744
- function validateSigOpts(opts) {
2745
- validateVerOpts(opts);
2746
- if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)
2747
- abytes(opts.extraEntropy, undefined, "opts.extraEntropy");
2748
- }
2749
- function splitCoder(label, ...lengths) {
2750
- const getLength = (c) => typeof c === "number" ? c : c.bytesLen;
2751
- const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);
2752
- return {
2753
- bytesLen,
2754
- encode: (bufs) => {
2755
- const res = new Uint8Array(bytesLen);
2756
- for (let i = 0, pos = 0;i < lengths.length; i++) {
2757
- const c = lengths[i];
2758
- const l = getLength(c);
2759
- const b = typeof c === "number" ? bufs[i] : c.encode(bufs[i]);
2760
- abytes(b, l, label);
2761
- res.set(b, pos);
2762
- if (typeof c !== "number")
2763
- b.fill(0);
2764
- pos += l;
2765
- }
2766
- return res;
2767
- },
2768
- decode: (buf) => {
2769
- abytes(buf, bytesLen, label);
2770
- const res = [];
2771
- for (const c of lengths) {
2772
- const l = getLength(c);
2773
- const b = buf.subarray(0, l);
2774
- res.push(typeof c === "number" ? b : c.decode(b));
2775
- buf = buf.subarray(l);
2776
- }
2777
- return res;
2778
- }
2779
- };
2780
- }
2781
- function vecCoder(c, vecLen) {
2782
- const coder = c;
2783
- const bytesLen = vecLen * coder.bytesLen;
2784
- return {
2785
- bytesLen,
2786
- encode: (u) => {
2787
- if (u.length !== vecLen)
2788
- throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
2789
- const res = new Uint8Array(bytesLen);
2790
- for (let i = 0, pos = 0;i < u.length; i++) {
2791
- const b = coder.encode(u[i]);
2792
- res.set(b, pos);
2793
- b.fill(0);
2794
- pos += b.length;
2795
- }
2796
- return res;
2797
- },
2798
- decode: (a) => {
2799
- abytes(a, bytesLen);
2800
- const r = [];
2801
- for (let i = 0;i < a.length; i += coder.bytesLen)
2802
- r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
2803
- return r;
2804
- }
2805
- };
2806
- }
2807
- function cleanBytes(...list) {
2808
- for (const t of list) {
2809
- if (Array.isArray(t))
2810
- for (const b of t)
2811
- b.fill(0);
2812
- else
2813
- t.fill(0);
2814
- }
2815
- }
2816
- function getMask(bits) {
2817
- if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
2818
- throw new RangeError(`expected bits in [0..32], got ${bits}`);
2819
- return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
2820
- }
2821
- var EMPTY = /* @__PURE__ */ Uint8Array.of();
2822
- function getMessage(msg, ctx = EMPTY) {
2823
- abytes(msg);
2824
- abytes(ctx);
2825
- if (ctx.length > 255)
2826
- throw new RangeError("context should be 255 bytes or less");
2827
- return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);
2828
- }
2829
- var oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2]);
2830
- function checkHash(hash, requiredStrength = 0) {
2831
- if (!hash.oid || !equalBytes2(hash.oid.subarray(0, 10), oidNistP))
2832
- throw new Error("hash.oid is invalid: expected NIST hash");
2833
- const collisionResistance = hash.outputLen * 8 / 2;
2834
- if (requiredStrength > collisionResistance) {
2835
- throw new Error("Pre-hash security strength too low: " + collisionResistance + ", required: " + requiredStrength);
2836
- }
2837
- }
2838
- function getMessagePrehash(hash, msg, ctx = EMPTY) {
2839
- abytes(msg);
2840
- abytes(ctx);
2841
- if (ctx.length > 255)
2842
- throw new RangeError("context should be 255 bytes or less");
2843
- const hashed = hash(msg);
2844
- return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed);
2845
- }
2846
-
2847
- // ../../node_modules/.bun/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/_crystals.js
2848
- /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
2849
- var genCrystals = (opts) => {
2850
- const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;
2851
- const mod2 = (a, modulo = Q) => {
2852
- const result = a % modulo | 0;
2853
- return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
2854
- };
2855
- const smod = (a, modulo = Q) => {
2856
- const r = mod2(a, modulo) | 0;
2857
- return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
2858
- };
2859
- function getZettas() {
2860
- const out = newPoly(N);
2861
- for (let i = 0;i < N; i++) {
2862
- const b = reverseBits(i, brvBits);
2863
- const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);
2864
- out[i] = Number(p) | 0;
2865
- }
2866
- return out;
2867
- }
2868
- const nttZetas = getZettas();
2869
- const field = {
2870
- add: (a, b) => mod2((a | 0) + (b | 0)) | 0,
2871
- sub: (a, b) => mod2((a | 0) - (b | 0)) | 0,
2872
- mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2873
- inv: (_a) => {
2874
- throw new Error("not implemented");
2875
- }
2876
- };
2877
- const nttOpts = {
2878
- N,
2879
- roots: nttZetas,
2880
- invertButterflies: true,
2881
- skipStages: isKyber ? 1 : 0,
2882
- brp: false
2883
- };
2884
- const dif = FFTCore(field, { dit: false, ...nttOpts });
2885
- const dit = FFTCore(field, { dit: true, ...nttOpts });
2886
- const NTT = {
2887
- encode: (r) => {
2888
- return dif(r);
2889
- },
2890
- decode: (r) => {
2891
- dit(r);
2892
- for (let i = 0;i < r.length; i++)
2893
- r[i] = mod2(F * r[i]);
2894
- return r;
2895
- }
2896
- };
2897
- const bitsCoder = (d, c) => {
2898
- const mask = getMask(d);
2899
- const bytesLen = d * (N / 8);
2900
- return {
2901
- bytesLen,
2902
- encode: (poly_) => {
2903
- const poly = poly_;
2904
- const r = new Uint8Array(bytesLen);
2905
- for (let i = 0, buf = 0, bufLen = 0, pos = 0;i < poly.length; i++) {
2906
- buf |= (c.encode(poly[i]) & mask) << bufLen;
2907
- bufLen += d;
2908
- for (;bufLen >= 8; bufLen -= 8, buf >>= 8)
2909
- r[pos++] = buf & getMask(bufLen);
2910
- }
2911
- return r;
2912
- },
2913
- decode: (bytes) => {
2914
- const r = newPoly(N);
2915
- for (let i = 0, buf = 0, bufLen = 0, pos = 0;i < bytes.length; i++) {
2916
- buf |= bytes[i] << bufLen;
2917
- bufLen += 8;
2918
- for (;bufLen >= d; bufLen -= d, buf >>= d)
2919
- r[pos++] = c.decode(buf & mask);
2920
- }
2921
- return r;
2922
- }
2923
- };
2924
- };
2925
- return {
2926
- mod: mod2,
2927
- smod,
2928
- nttZetas,
2929
- NTT: {
2930
- encode: (r) => NTT.encode(r),
2931
- decode: (r) => NTT.decode(r)
2932
- },
2933
- bitsCoder
2934
- };
2935
- };
2936
- var createXofShake = (shake) => (seed, blockLen) => {
2937
- if (!blockLen)
2938
- blockLen = shake.blockLen;
2939
- const _seed = new Uint8Array(seed.length + 2);
2940
- _seed.set(seed);
2941
- const seedLen = seed.length;
2942
- const buf = new Uint8Array(blockLen);
2943
- let h = shake.create({});
2944
- let calls = 0;
2945
- let xofs = 0;
2946
- return {
2947
- stats: () => ({ calls, xofs }),
2948
- get: (x, y) => {
2949
- _seed[seedLen + 0] = x;
2950
- _seed[seedLen + 1] = y;
2951
- h.destroy();
2952
- h = shake.create({}).update(_seed);
2953
- calls++;
2954
- return () => {
2955
- xofs++;
2956
- return h.xofInto(buf);
2957
- };
2958
- },
2959
- clean: () => {
2960
- h.destroy();
2961
- cleanBytes(buf, _seed);
2962
- }
2963
- };
2964
- };
2965
- var XOF128 = /* @__PURE__ */ createXofShake(shake128);
2966
- var XOF256 = /* @__PURE__ */ createXofShake(shake256);
2967
-
2968
- // ../../node_modules/.bun/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/ml-dsa.js
2969
- /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
2970
- function validateInternalOpts(opts) {
2971
- validateOpts2(opts);
2972
- if (opts.externalMu !== undefined)
2973
- abool(opts.externalMu, "opts.externalMu");
2974
- }
2975
- var N = 256;
2976
- var Q = 8380417;
2977
- var ROOT_OF_UNITY = 1753;
2978
- var F = 8347681;
2979
- var D = 13;
2980
- var GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;
2981
- var GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;
2982
- var PARAMS = /* @__PURE__ */ (() => Object.freeze({
2983
- 2: Object.freeze({
2984
- K: 4,
2985
- L: 4,
2986
- D,
2987
- GAMMA1: 2 ** 17,
2988
- GAMMA2: GAMMA2_1,
2989
- TAU: 39,
2990
- ETA: 2,
2991
- OMEGA: 80
2992
- }),
2993
- 3: Object.freeze({
2994
- K: 6,
2995
- L: 5,
2996
- D,
2997
- GAMMA1: 2 ** 19,
2998
- GAMMA2: GAMMA2_2,
2999
- TAU: 49,
3000
- ETA: 4,
3001
- OMEGA: 55
3002
- }),
3003
- 5: Object.freeze({
3004
- K: 8,
3005
- L: 7,
3006
- D,
3007
- GAMMA1: 2 ** 19,
3008
- GAMMA2: GAMMA2_2,
3009
- TAU: 60,
3010
- ETA: 2,
3011
- OMEGA: 75
3012
- })
3013
- }))();
3014
- var newPoly = (n) => new Int32Array(n);
3015
- var crystals = /* @__PURE__ */ genCrystals({
3016
- N,
3017
- Q,
3018
- F,
3019
- ROOT_OF_UNITY,
3020
- newPoly,
3021
- isKyber: false,
3022
- brvBits: 8
3023
- });
3024
- var id = (n) => n;
3025
- var polyCoder = (d, compress = id, verify = id) => crystals.bitsCoder(d, {
3026
- encode: (i) => compress(verify(i)),
3027
- decode: (i) => verify(compress(i))
3028
- });
3029
- var polyAdd = (a_, b_) => {
3030
- const a = a_;
3031
- const b = b_;
3032
- for (let i = 0;i < a.length; i++)
3033
- a[i] = crystals.mod(a[i] + b[i]);
3034
- return a;
3035
- };
3036
- var polySub = (a_, b_) => {
3037
- const a = a_;
3038
- const b = b_;
3039
- for (let i = 0;i < a.length; i++)
3040
- a[i] = crystals.mod(a[i] - b[i]);
3041
- return a;
3042
- };
3043
- var polyShiftl = (p_) => {
3044
- const p = p_;
3045
- for (let i = 0;i < N; i++)
3046
- p[i] <<= D;
3047
- return p;
3048
- };
3049
- var polyChknorm = (p_, B) => {
3050
- const p = p_;
3051
- for (let i = 0;i < N; i++)
3052
- if (Math.abs(crystals.smod(p[i])) >= B)
3053
- return true;
3054
- return false;
3055
- };
3056
- var MultiplyNTTs = (a_, b_) => {
3057
- const a = a_;
3058
- const b = b_;
3059
- const c = newPoly(N);
3060
- for (let i = 0;i < a.length; i++)
3061
- c[i] = crystals.mod(a[i] * b[i]);
3062
- return c;
3063
- };
3064
- function RejNTTPoly(xof_) {
3065
- const xof = xof_;
3066
- const r = newPoly(N);
3067
- for (let j = 0;j < N; ) {
3068
- const b = xof();
3069
- if (b.length % 3)
3070
- throw new Error("RejNTTPoly: unaligned block");
3071
- for (let i = 0;j < N && i <= b.length - 3; i += 3) {
3072
- const t = (b[i + 0] | b[i + 1] << 8 | b[i + 2] << 16) & 8388607;
3073
- if (t < Q)
3074
- r[j++] = t;
3075
- }
3076
- }
3077
- return r;
3078
- }
3079
- function getDilithium(opts_) {
3080
- const opts = opts_;
3081
- const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;
3082
- const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128: XOF1282, XOF256: XOF2562, securityLevel } = opts;
3083
- if (![2, 4].includes(ETA))
3084
- throw new Error("Wrong ETA");
3085
- if (![1 << 17, 1 << 19].includes(GAMMA1))
3086
- throw new Error("Wrong GAMMA1");
3087
- if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))
3088
- throw new Error("Wrong GAMMA2");
3089
- const BETA = TAU * ETA;
3090
- const decompose = (r) => {
3091
- const rPlus = crystals.mod(r);
3092
- const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0;
3093
- if (rPlus - r0 === Q - 1)
3094
- return { r1: 0 | 0, r0: r0 - 1 | 0 };
3095
- const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;
3096
- return { r1, r0 };
3097
- };
3098
- const HighBits = (r) => decompose(r).r1;
3099
- const LowBits = (r) => decompose(r).r0;
3100
- const MakeHint = (z, r) => {
3101
- const res0 = z <= GAMMA2 || z > Q - GAMMA2 || z === Q - GAMMA2 && r === 0 ? 0 : 1;
3102
- return res0;
3103
- };
3104
- const UseHint = (h, r) => {
3105
- const m = Math.floor((Q - 1) / (2 * GAMMA2));
3106
- const { r1, r0 } = decompose(r);
3107
- if (h === 1)
3108
- return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0;
3109
- return r1 | 0;
3110
- };
3111
- const Power2Round = (r) => {
3112
- const rPlus = crystals.mod(r);
3113
- const r0 = crystals.smod(rPlus, 2 ** D) | 0;
3114
- return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };
3115
- };
3116
- const hintCoder = {
3117
- bytesLen: OMEGA + K,
3118
- encode: (h_) => {
3119
- const h = h_;
3120
- if (h === false)
3121
- throw new Error("hint.encode: hint is false");
3122
- const res = new Uint8Array(OMEGA + K);
3123
- for (let i = 0, k = 0;i < K; i++) {
3124
- for (let j = 0;j < N; j++)
3125
- if (h[i][j] !== 0)
3126
- res[k++] = j;
3127
- res[OMEGA + i] = k;
3128
- }
3129
- return res;
3130
- },
3131
- decode: (buf) => {
3132
- const h = [];
3133
- let k = 0;
3134
- for (let i = 0;i < K; i++) {
3135
- const hi = newPoly(N);
3136
- if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)
3137
- return false;
3138
- for (let j = k;j < buf[OMEGA + i]; j++) {
3139
- if (j > k && buf[j] <= buf[j - 1])
3140
- return false;
3141
- hi[buf[j]] = 1;
3142
- }
3143
- k = buf[OMEGA + i];
3144
- h.push(hi);
3145
- }
3146
- for (let j = k;j < OMEGA; j++)
3147
- if (buf[j] !== 0)
3148
- return false;
3149
- return h;
3150
- }
3151
- };
3152
- const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {
3153
- if (!(-ETA <= i && i <= ETA))
3154
- throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);
3155
- return i;
3156
- });
3157
- const T0Coder = polyCoder(13, (i) => (1 << D - 1) - i);
3158
- const T1Coder = polyCoder(10);
3159
- const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i));
3160
- const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);
3161
- const W1Vec = vecCoder(W1Coder, K);
3162
- const publicCoder = splitCoder("publicKey", 32, vecCoder(T1Coder, K));
3163
- const secretCoder = splitCoder("secretKey", 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));
3164
- const sigCoder = splitCoder("signature", C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);
3165
- const CoefFromHalfByte = ETA === 2 ? (n) => n < 15 ? 2 - n % 5 : false : (n) => n < 9 ? 4 - n : false;
3166
- function RejBoundedPoly(xof_) {
3167
- const xof = xof_;
3168
- const r = newPoly(N);
3169
- for (let j = 0;j < N; ) {
3170
- const b = xof();
3171
- for (let i = 0;j < N && i < b.length; i += 1) {
3172
- const d1 = CoefFromHalfByte(b[i] & 15);
3173
- const d2 = CoefFromHalfByte(b[i] >> 4 & 15);
3174
- if (d1 !== false)
3175
- r[j++] = d1;
3176
- if (j < N && d2 !== false)
3177
- r[j++] = d2;
3178
- }
3179
- }
3180
- return r;
3181
- }
3182
- const SampleInBall = (seed) => {
3183
- const pre = newPoly(N);
3184
- const s = shake256.create({}).update(seed);
3185
- const buf = new Uint8Array(shake256.blockLen);
3186
- s.xofInto(buf);
3187
- const masks = buf.slice(0, 8);
3188
- for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0;i < N; i++) {
3189
- let b = i + 1;
3190
- for (;b > i; ) {
3191
- b = buf[pos++];
3192
- if (pos < shake256.blockLen)
3193
- continue;
3194
- s.xofInto(buf);
3195
- pos = 0;
3196
- }
3197
- pre[i] = pre[b];
3198
- pre[b] = 1 - ((masks[maskPos] >> maskBit++ & 1) << 1);
3199
- if (maskBit >= 8) {
3200
- maskPos++;
3201
- maskBit = 0;
3202
- }
3203
- }
3204
- return pre;
3205
- };
3206
- const polyPowerRound = (p_) => {
3207
- const p = p_;
3208
- const res0 = newPoly(N);
3209
- const res1 = newPoly(N);
3210
- for (let i = 0;i < p.length; i++) {
3211
- const { r0, r1 } = Power2Round(p[i]);
3212
- res0[i] = r0;
3213
- res1[i] = r1;
3214
- }
3215
- return { r0: res0, r1: res1 };
3216
- };
3217
- const polyUseHint = (u_, h_) => {
3218
- const u = u_;
3219
- const h = h_;
3220
- for (let i = 0;i < N; i++)
3221
- u[i] = UseHint(h[i], u[i]);
3222
- return u;
3223
- };
3224
- const polyMakeHint = (a_, b_) => {
3225
- const a = a_;
3226
- const b = b_;
3227
- const v = newPoly(N);
3228
- let cnt = 0;
3229
- for (let i = 0;i < N; i++) {
3230
- const h = MakeHint(a[i], b[i]);
3231
- v[i] = h;
3232
- cnt += h;
3233
- }
3234
- return { v, cnt };
3235
- };
3236
- const signRandBytes = 32;
3237
- const seedCoder = splitCoder("seed", 32, 64, 32);
3238
- const internal = Object.freeze({
3239
- info: Object.freeze({ type: "internal-ml-dsa" }),
3240
- lengths: Object.freeze({
3241
- secretKey: secretCoder.bytesLen,
3242
- publicKey: publicCoder.bytesLen,
3243
- seed: 32,
3244
- signature: sigCoder.bytesLen,
3245
- signRand: signRandBytes
3246
- }),
3247
- keygen: (seed) => {
3248
- const seedDst = new Uint8Array(32 + 2);
3249
- const randSeed = seed === undefined;
3250
- if (randSeed)
3251
- seed = randomBytes3(32);
3252
- abytesDoc(seed, 32, "seed");
3253
- seedDst.set(seed);
3254
- if (randSeed)
3255
- cleanBytes(seed);
3256
- seedDst[32] = K;
3257
- seedDst[33] = L;
3258
- const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));
3259
- const xofPrime = XOF2562(rhoPrime);
3260
- const s1 = [];
3261
- for (let i = 0;i < L; i++)
3262
- s1.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255)));
3263
- const s2 = [];
3264
- for (let i = L;i < L + K; i++)
3265
- s2.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255)));
3266
- const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice()));
3267
- const t0 = [];
3268
- const t1 = [];
3269
- const xof = XOF1282(rho);
3270
- const t = newPoly(N);
3271
- for (let i = 0;i < K; i++) {
3272
- cleanBytes(t);
3273
- for (let j = 0;j < L; j++) {
3274
- const aij = RejNTTPoly(xof.get(j, i));
3275
- polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));
3276
- }
3277
- crystals.NTT.decode(t);
3278
- const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i]));
3279
- t0.push(r0);
3280
- t1.push(r1);
3281
- }
3282
- const publicKey = publicCoder.encode([rho, t1]);
3283
- const tr = shake256(publicKey, { dkLen: TR_BYTES });
3284
- const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);
3285
- xof.clean();
3286
- xofPrime.clean();
3287
- cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);
3288
- return {
3289
- publicKey,
3290
- secretKey
3291
- };
3292
- },
3293
- getPublicKey: (secretKey) => {
3294
- const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey);
3295
- const xof = XOF1282(rho);
3296
- const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice()));
3297
- const t1 = [];
3298
- const tmp = newPoly(N);
3299
- for (let i = 0;i < K; i++) {
3300
- tmp.fill(0);
3301
- for (let j = 0;j < L; j++) {
3302
- const aij = RejNTTPoly(xof.get(j, i));
3303
- polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j]));
3304
- }
3305
- crystals.NTT.decode(tmp);
3306
- polyAdd(tmp, s2[i]);
3307
- const { r1 } = polyPowerRound(tmp);
3308
- t1.push(r1);
3309
- }
3310
- xof.clean();
3311
- cleanBytes(tmp, s1Hat, _t0, s1, s2);
3312
- return publicCoder.encode([rho, t1]);
3313
- },
3314
- sign: (msg, secretKey, opts2 = {}) => {
3315
- validateSigOpts(opts2);
3316
- validateInternalOpts(opts2);
3317
- let { extraEntropy: random, externalMu = false } = opts2;
3318
- const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey);
3319
- const A = [];
3320
- const xof = XOF1282(rho);
3321
- for (let i = 0;i < K; i++) {
3322
- const pv = [];
3323
- for (let j = 0;j < L; j++)
3324
- pv.push(RejNTTPoly(xof.get(j, i)));
3325
- A.push(pv);
3326
- }
3327
- xof.clean();
3328
- for (let i = 0;i < L; i++)
3329
- crystals.NTT.encode(s1[i]);
3330
- for (let i = 0;i < K; i++) {
3331
- crystals.NTT.encode(s2[i]);
3332
- crystals.NTT.encode(t0[i]);
3333
- }
3334
- const mu = externalMu ? msg : shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();
3335
- const rnd = random === false ? new Uint8Array(32) : random === undefined ? randomBytes3(signRandBytes) : random;
3336
- abytesDoc(rnd, 32, "extraEntropy");
3337
- const rhoprime = shake256.create({ dkLen: CRH_BYTES }).update(_K).update(rnd).update(mu).digest();
3338
- abytesDoc(rhoprime, CRH_BYTES);
3339
- const x256 = XOF2562(rhoprime, ZCoder.bytesLen);
3340
- main_loop:
3341
- for (let kappa = 0;; ) {
3342
- const y = [];
3343
- for (let i = 0;i < L; i++, kappa++)
3344
- y.push(ZCoder.decode(x256.get(kappa & 255, kappa >> 8)()));
3345
- const z = y.map((i) => crystals.NTT.encode(i.slice()));
3346
- const w = [];
3347
- for (let i = 0;i < K; i++) {
3348
- const wi = newPoly(N);
3349
- for (let j = 0;j < L; j++)
3350
- polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));
3351
- crystals.NTT.decode(wi);
3352
- w.push(wi);
3353
- }
3354
- const w1 = w.map((j) => j.map(HighBits));
3355
- const cTilde = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(w1)).digest();
3356
- const cHat = crystals.NTT.encode(SampleInBall(cTilde));
3357
- const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));
3358
- for (let i = 0;i < L; i++) {
3359
- polyAdd(crystals.NTT.decode(cs1[i]), y[i]);
3360
- if (polyChknorm(cs1[i], GAMMA1 - BETA))
3361
- continue main_loop;
3362
- }
3363
- let cnt = 0;
3364
- const h = [];
3365
- for (let i = 0;i < K; i++) {
3366
- const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat));
3367
- const r0 = polySub(w[i], cs2).map(LowBits);
3368
- if (polyChknorm(r0, GAMMA2 - BETA))
3369
- continue main_loop;
3370
- const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat));
3371
- if (polyChknorm(ct0, GAMMA2))
3372
- continue main_loop;
3373
- polyAdd(r0, ct0);
3374
- const hint = polyMakeHint(r0, w1[i]);
3375
- h.push(hint.v);
3376
- cnt += hint.cnt;
3377
- }
3378
- if (cnt > OMEGA)
3379
- continue;
3380
- x256.clean();
3381
- const res = sigCoder.encode([cTilde, cs1, h]);
3382
- cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A);
3383
- if (!externalMu)
3384
- cleanBytes(mu);
3385
- return res;
3386
- }
3387
- throw new Error("Unreachable code path reached, report this error");
3388
- },
3389
- verify: (sig, msg, publicKey, opts2 = {}) => {
3390
- validateInternalOpts(opts2);
3391
- const { externalMu = false } = opts2;
3392
- const [rho, t1] = publicCoder.decode(publicKey);
3393
- const tr = shake256(publicKey, { dkLen: TR_BYTES });
3394
- if (sig.length !== sigCoder.bytesLen)
3395
- return false;
3396
- const [cTilde, z, h] = sigCoder.decode(sig);
3397
- if (h === false)
3398
- return false;
3399
- for (let i = 0;i < L; i++)
3400
- if (polyChknorm(z[i], GAMMA1 - BETA))
3401
- return false;
3402
- const mu = externalMu ? msg : shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();
3403
- const c = crystals.NTT.encode(SampleInBall(cTilde));
3404
- const zNtt = z.map((i) => i.slice());
3405
- for (let i = 0;i < L; i++)
3406
- crystals.NTT.encode(zNtt[i]);
3407
- const wTick1 = [];
3408
- const xof = XOF1282(rho);
3409
- for (let i = 0;i < K; i++) {
3410
- const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c);
3411
- const Az = newPoly(N);
3412
- for (let j = 0;j < L; j++) {
3413
- const aij = RejNTTPoly(xof.get(j, i));
3414
- polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));
3415
- }
3416
- const wApprox = crystals.NTT.decode(polySub(Az, ct12d));
3417
- wTick1.push(polyUseHint(wApprox, h[i]));
3418
- }
3419
- xof.clean();
3420
- const c2 = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(wTick1)).digest();
3421
- for (const t of h) {
3422
- const sum = t.reduce((acc, i) => acc + i, 0);
3423
- if (!(sum <= OMEGA))
3424
- return false;
3425
- }
3426
- for (const t of z)
3427
- if (polyChknorm(t, GAMMA1 - BETA))
3428
- return false;
3429
- return equalBytes2(cTilde, c2);
3430
- }
3431
- });
3432
- return Object.freeze({
3433
- info: Object.freeze({ type: "ml-dsa" }),
3434
- internal,
3435
- securityLevel,
3436
- keygen: internal.keygen,
3437
- lengths: internal.lengths,
3438
- getPublicKey: internal.getPublicKey,
3439
- sign: (msg, secretKey, opts2 = {}) => {
3440
- validateSigOpts(opts2);
3441
- const M = getMessage(msg, opts2.context);
3442
- const res = internal.sign(M, secretKey, opts2);
3443
- cleanBytes(M);
3444
- return res;
3445
- },
3446
- verify: (sig, msg, publicKey, opts2 = {}) => {
3447
- validateVerOpts(opts2);
3448
- return internal.verify(sig, getMessage(msg, opts2.context), publicKey);
3449
- },
3450
- prehash: (hash) => {
3451
- checkHash(hash, securityLevel);
3452
- return Object.freeze({
3453
- info: Object.freeze({ type: "hashml-dsa" }),
3454
- securityLevel,
3455
- lengths: internal.lengths,
3456
- keygen: internal.keygen,
3457
- getPublicKey: internal.getPublicKey,
3458
- sign: (msg, secretKey, opts2 = {}) => {
3459
- validateSigOpts(opts2);
3460
- const M = getMessagePrehash(hash, msg, opts2.context);
3461
- const res = internal.sign(M, secretKey, opts2);
3462
- cleanBytes(M);
3463
- return res;
3464
- },
3465
- verify: (sig, msg, publicKey, opts2 = {}) => {
3466
- validateVerOpts(opts2);
3467
- return internal.verify(sig, getMessagePrehash(hash, msg, opts2.context), publicKey);
3468
- }
3469
- });
3470
- }
3471
- });
3472
- }
3473
- var ml_dsa65 = /* @__PURE__ */ (() => getDilithium({
3474
- ...PARAMS[3],
3475
- CRH_BYTES: 64,
3476
- TR_BYTES: 64,
3477
- C_TILDE_BYTES: 48,
3478
- XOF128,
3479
- XOF256,
3480
- securityLevel: 192
3481
- }))();
3482
-
3483
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js
3484
- class _HMAC {
3485
- oHash;
3486
- iHash;
3487
- blockLen;
3488
- outputLen;
3489
- canXOF = false;
3490
- finished = false;
3491
- destroyed = false;
3492
- constructor(hash, key) {
3493
- ahash(hash);
3494
- abytes(key, undefined, "key");
3495
- this.iHash = hash.create();
3496
- if (typeof this.iHash.update !== "function")
3497
- throw new Error("Expected instance of class which extends utils.Hash");
3498
- this.blockLen = this.iHash.blockLen;
3499
- this.outputLen = this.iHash.outputLen;
3500
- const blockLen = this.blockLen;
3501
- const pad = new Uint8Array(blockLen);
3502
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
3503
- for (let i = 0;i < pad.length; i++)
3504
- pad[i] ^= 54;
3505
- this.iHash.update(pad);
3506
- this.oHash = hash.create();
3507
- for (let i = 0;i < pad.length; i++)
3508
- pad[i] ^= 54 ^ 92;
3509
- this.oHash.update(pad);
3510
- clean(pad);
3511
- }
3512
- update(buf) {
3513
- aexists(this);
3514
- this.iHash.update(buf);
3515
- return this;
3516
- }
3517
- digestInto(out) {
3518
- aexists(this);
3519
- aoutput(out, this);
3520
- this.finished = true;
3521
- const buf = out.subarray(0, this.outputLen);
3522
- this.iHash.digestInto(buf);
3523
- this.oHash.update(buf);
3524
- this.oHash.digestInto(buf);
3525
- this.destroy();
3526
- }
3527
- digest() {
3528
- const out = new Uint8Array(this.oHash.outputLen);
3529
- this.digestInto(out);
3530
- return out;
3531
- }
3532
- _cloneInto(to) {
3533
- to ||= Object.create(Object.getPrototypeOf(this), {});
3534
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
3535
- to = to;
3536
- to.finished = finished;
3537
- to.destroyed = destroyed;
3538
- to.blockLen = blockLen;
3539
- to.outputLen = outputLen;
3540
- to.oHash = oHash._cloneInto(to.oHash);
3541
- to.iHash = iHash._cloneInto(to.iHash);
3542
- return to;
3543
- }
3544
- clone() {
3545
- return this._cloneInto();
3546
- }
3547
- destroy() {
3548
- this.destroyed = true;
3549
- this.oHash.destroy();
3550
- this.iHash.destroy();
3551
- }
3552
- }
3553
- var hmac = /* @__PURE__ */ (() => {
3554
- const hmac_ = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
3555
- hmac_.create = (hash, key) => new _HMAC(hash, key);
3556
- return hmac_;
3557
- })();
3558
-
3559
- // ../../node_modules/.bun/@noble+hashes@2.2.0/node_modules/@noble/hashes/hkdf.js
3560
- function extract(hash, ikm, salt) {
3561
- ahash(hash);
3562
- if (salt === undefined)
3563
- salt = new Uint8Array(hash.outputLen);
3564
- return hmac(hash, salt, ikm);
3565
- }
3566
- var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
3567
- var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
3568
- function expand(hash, prk, info, length = 32) {
3569
- ahash(hash);
3570
- anumber(length, "length");
3571
- abytes(prk, undefined, "prk");
3572
- const olen = hash.outputLen;
3573
- if (prk.length < olen)
3574
- throw new Error('"prk" must be at least HashLen octets');
3575
- if (length > 255 * olen)
3576
- throw new Error("Length must be <= 255*HashLen");
3577
- const blocks = Math.ceil(length / olen);
3578
- if (info === undefined)
3579
- info = EMPTY_BUFFER;
3580
- else
3581
- abytes(info, undefined, "info");
3582
- const okm = new Uint8Array(blocks * olen);
3583
- const HMAC = hmac.create(hash, prk);
3584
- const HMACTmp = HMAC._cloneInto();
3585
- const T = new Uint8Array(HMAC.outputLen);
3586
- for (let counter = 0;counter < blocks; counter++) {
3587
- HKDF_COUNTER[0] = counter + 1;
3588
- HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
3589
- okm.set(T, olen * counter);
3590
- HMAC._cloneInto(HMACTmp);
3591
- }
3592
- HMAC.destroy();
3593
- HMACTmp.destroy();
3594
- clean(T, HKDF_COUNTER);
3595
- return okm.slice(0, length);
3596
- }
3597
- var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
3598
-
3599
- // ../../node_modules/.bun/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/ml-kem.js
3600
- /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
3601
- var N2 = 256;
3602
- var Q2 = 3329;
3603
- var F2 = 3303;
3604
- var ROOT_OF_UNITY2 = 17;
3605
- var crystals2 = /* @__PURE__ */ genCrystals({
3606
- N: N2,
3607
- Q: Q2,
3608
- F: F2,
3609
- ROOT_OF_UNITY: ROOT_OF_UNITY2,
3610
- newPoly: (n) => new Uint16Array(n),
3611
- brvBits: 7,
3612
- isKyber: true
3613
- });
3614
- var PARAMS2 = /* @__PURE__ */ (() => Object.freeze({
3615
- 512: Object.freeze({ N: N2, Q: Q2, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
3616
- 768: Object.freeze({ N: N2, Q: Q2, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
3617
- 1024: Object.freeze({ N: N2, Q: Q2, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
3618
- }))();
3619
- var compress = (d) => {
3620
- if (d >= 12)
3621
- return { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i };
3622
- const a = 2 ** (d - 1);
3623
- return {
3624
- encode: (i) => ((i << d) + Q2 / 2) / Q2,
3625
- decode: (i) => i * Q2 + a >>> d
3626
- };
3627
- };
3628
- var byteCoder = (d) => crystals2.bitsCoder(d, d === 12 ? { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i } : { encode: (i) => i, decode: (i) => i });
3629
- var polyCoder2 = (d) => d === 12 ? byteCoder(12) : crystals2.bitsCoder(d, compress(d));
3630
- function polyAdd2(a_, b_) {
3631
- const a = a_;
3632
- const b = b_;
3633
- for (let i = 0;i < N2; i++)
3634
- a[i] = crystals2.mod(a[i] + b[i]);
3635
- }
3636
- function polySub2(a_, b_) {
3637
- const a = a_;
3638
- const b = b_;
3639
- for (let i = 0;i < N2; i++)
3640
- a[i] = crystals2.mod(a[i] - b[i]);
3641
- }
3642
- function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
3643
- const c0 = crystals2.mod(a1 * b1 * zeta + a0 * b0);
3644
- const c1 = crystals2.mod(a0 * b1 + a1 * b0);
3645
- return { c0, c1 };
3646
- }
3647
- function MultiplyNTTs2(f_, g_) {
3648
- const f = f_;
3649
- const g = g_;
3650
- for (let i = 0;i < N2 / 2; i++) {
3651
- let z = crystals2.nttZetas[64 + (i >> 1)];
3652
- if (i & 1)
3653
- z = -z;
3654
- const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);
3655
- f[2 * i + 0] = c0;
3656
- f[2 * i + 1] = c1;
3657
- }
3658
- return f;
3659
- }
3660
- function SampleNTT(xof_) {
3661
- const xof = xof_;
3662
- const r = new Uint16Array(N2);
3663
- for (let j = 0;j < N2; ) {
3664
- const b = xof();
3665
- if (b.length % 3)
3666
- throw new Error("SampleNTT: unaligned block");
3667
- for (let i = 0;j < N2 && i + 3 <= b.length; i += 3) {
3668
- const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095;
3669
- const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095;
3670
- if (d1 < Q2)
3671
- r[j++] = d1;
3672
- if (j < N2 && d2 < Q2)
3673
- r[j++] = d2;
3674
- }
3675
- }
3676
- return r;
3677
- }
3678
- var sampleCBDBytes = (buf, eta) => {
3679
- const r = new Uint16Array(N2);
3680
- const b32 = u32(buf);
3681
- swap32IfBE(b32);
3682
- let len = 0;
3683
- for (let i = 0, p = 0, bb = 0, t0 = 0;i < b32.length; i++) {
3684
- let b = b32[i];
3685
- for (let j = 0;j < 32; j++) {
3686
- bb += b & 1;
3687
- b >>= 1;
3688
- len += 1;
3689
- if (len === eta) {
3690
- t0 = bb;
3691
- bb = 0;
3692
- } else if (len === 2 * eta) {
3693
- r[p++] = crystals2.mod(t0 - bb);
3694
- bb = 0;
3695
- len = 0;
3696
- }
3697
- }
3698
- }
3699
- swap32IfBE(b32);
3700
- if (len)
3701
- throw new Error(`sampleCBD: leftover bits: ${len}`);
3702
- return r;
3703
- };
3704
- function sampleCBD(PRF_, seed, nonce, eta) {
3705
- const PRF = PRF_;
3706
- return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta);
3707
- }
3708
- var genKPKE = (opts_) => {
3709
- const opts = opts_;
3710
- const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;
3711
- const poly1 = polyCoder2(1);
3712
- const polyV = polyCoder2(dv);
3713
- const polyU = polyCoder2(du);
3714
- const publicCoder = splitCoder("publicKey", vecCoder(polyCoder2(12), K), 32);
3715
- const secretCoder = vecCoder(polyCoder2(12), K);
3716
- const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
3717
- const seedCoder = splitCoder("seed", 32, 32);
3718
- return {
3719
- secretCoder,
3720
- lengths: {
3721
- secretKey: secretCoder.bytesLen,
3722
- publicKey: publicCoder.bytesLen,
3723
- cipherText: cipherCoder.bytesLen
3724
- },
3725
- keygen: (seed) => {
3726
- abytesDoc(seed, 32, "seed");
3727
- const seedDst = new Uint8Array(33);
3728
- seedDst.set(seed);
3729
- seedDst[32] = K;
3730
- const seedHash = HASH512(seedDst);
3731
- const [rho, sigma] = seedCoder.decode(seedHash);
3732
- const sHat = [];
3733
- const tHat = [];
3734
- for (let i = 0;i < K; i++)
3735
- sHat.push(crystals2.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));
3736
- const x = XOF(rho);
3737
- for (let i = 0;i < K; i++) {
3738
- const e = crystals2.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));
3739
- for (let j = 0;j < K; j++) {
3740
- const aji = SampleNTT(x.get(j, i));
3741
- polyAdd2(e, MultiplyNTTs2(aji, sHat[j]));
3742
- }
3743
- tHat.push(e);
3744
- }
3745
- x.clean();
3746
- const res = {
3747
- publicKey: publicCoder.encode([tHat, rho]),
3748
- secretKey: secretCoder.encode(sHat)
3749
- };
3750
- cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);
3751
- return res;
3752
- },
3753
- encrypt: (publicKey, msg, seed) => {
3754
- const [tHat, rho] = publicCoder.decode(publicKey);
3755
- const rHat = [];
3756
- for (let i = 0;i < K; i++)
3757
- rHat.push(crystals2.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
3758
- const x = XOF(rho);
3759
- const tmp2 = new Uint16Array(N2);
3760
- const u = [];
3761
- for (let i = 0;i < K; i++) {
3762
- const e1 = sampleCBD(PRF, seed, K + i, ETA2);
3763
- const tmp = new Uint16Array(N2);
3764
- for (let j = 0;j < K; j++) {
3765
- const aij = SampleNTT(x.get(i, j));
3766
- polyAdd2(tmp, MultiplyNTTs2(aij, rHat[j]));
3767
- }
3768
- polyAdd2(e1, crystals2.NTT.decode(tmp));
3769
- u.push(e1);
3770
- polyAdd2(tmp2, MultiplyNTTs2(tHat[i], rHat[i]));
3771
- cleanBytes(tmp);
3772
- }
3773
- x.clean();
3774
- const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
3775
- polyAdd2(e2, crystals2.NTT.decode(tmp2));
3776
- const v = poly1.decode(msg);
3777
- polyAdd2(v, e2);
3778
- cleanBytes(tHat, rHat, tmp2, e2);
3779
- return cipherCoder.encode([u, v]);
3780
- },
3781
- decrypt: (cipherText, privateKey) => {
3782
- const [u, v] = cipherCoder.decode(cipherText);
3783
- const sk = secretCoder.decode(privateKey);
3784
- const tmp = new Uint16Array(N2);
3785
- for (let i = 0;i < K; i++)
3786
- polyAdd2(tmp, MultiplyNTTs2(sk[i], crystals2.NTT.encode(u[i])));
3787
- polySub2(v, crystals2.NTT.decode(tmp));
3788
- cleanBytes(tmp, sk, u);
3789
- return poly1.encode(v);
3790
- }
3791
- };
3792
- };
3793
- function createKyber(opts) {
3794
- const rawOpts = opts;
3795
- const KPKE = genKPKE(rawOpts);
3796
- const { HASH256, HASH512, KDF } = rawOpts;
3797
- const { secretCoder: KPKESecretCoder, lengths } = KPKE;
3798
- const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
3799
- const msgLen = 32;
3800
- const seedLen = 64;
3801
- const kemLengths = Object.freeze({
3802
- ...lengths,
3803
- seed: 64,
3804
- msg: msgLen,
3805
- msgRand: msgLen,
3806
- secretKey: secretCoder.bytesLen
3807
- });
3808
- return Object.freeze({
3809
- info: Object.freeze({ type: "ml-kem" }),
3810
- lengths: kemLengths,
3811
- keygen: (seed = randomBytes3(seedLen)) => {
3812
- abytesDoc(seed, seedLen, "seed");
3813
- const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
3814
- const publicKeyHash = HASH256(publicKey);
3815
- const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
3816
- cleanBytes(sk, publicKeyHash);
3817
- return {
3818
- publicKey,
3819
- secretKey
3820
- };
3821
- },
3822
- getPublicKey: (secretKey) => {
3823
- const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
3824
- return Uint8Array.from(publicKey);
3825
- },
3826
- encapsulate: (publicKey, msg = randomBytes3(msgLen)) => {
3827
- abytesDoc(publicKey, lengths.publicKey, "publicKey");
3828
- abytesDoc(msg, msgLen, "message");
3829
- const eke = publicKey.subarray(0, 384 * opts.K);
3830
- const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
3831
- if (!equalBytes2(ek, eke)) {
3832
- cleanBytes(ek);
3833
- throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
3834
- }
3835
- cleanBytes(ek);
3836
- const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
3837
- const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
3838
- cleanBytes(kr.subarray(32));
3839
- return {
3840
- cipherText,
3841
- sharedSecret: kr.subarray(0, 32)
3842
- };
3843
- },
3844
- decapsulate: (cipherText, secretKey) => {
3845
- abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
3846
- abytesDoc(cipherText, lengths.cipherText, "cipherText");
3847
- const k768 = secretCoder.bytesLen - 96;
3848
- const start = k768 + 32;
3849
- const test = HASH256(secretKey.subarray(k768 / 2, start));
3850
- if (!equalBytes2(test, secretKey.subarray(start, start + 32)))
3851
- throw new Error("invalid secretKey: hash check failed");
3852
- const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
3853
- const msg = KPKE.decrypt(cipherText, sk);
3854
- const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
3855
- const Khat = kr.subarray(0, 32);
3856
- const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
3857
- const isValid = equalBytes2(cipherText, cipherText2);
3858
- const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
3859
- cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
3860
- return isValid ? Khat : Kbar;
3861
- }
3862
- });
3863
- }
3864
- function shakePRF(dkLen, key, nonce) {
3865
- return shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
3866
- }
3867
- var opts = /* @__PURE__ */ (() => ({
3868
- HASH256: sha3_256,
3869
- HASH512: sha3_512,
3870
- KDF: shake256,
3871
- XOF: XOF128,
3872
- PRF: shakePRF
3873
- }))();
3874
- var mk = (params) => createKyber({
3875
- ...opts,
3876
- ...params
3877
- });
3878
- var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS2[768]))();
3879
-
3880
- // ../../node_modules/.bun/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/hybrid.js
3881
- /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
3882
- function ecKeygen(curve, allowZeroKey = false) {
3883
- const lengths = curve.lengths;
3884
- let keygen = curve.keygen;
3885
- if (allowZeroKey) {
3886
- if (!(("getSharedSecret" in curve) && ("sign" in curve) && ("verify" in curve)))
3887
- throw new Error("allowZeroKey requires a Weierstrass curve");
3888
- const wCurve = curve;
3889
- const Fn2 = wCurve.Point.Fn;
3890
- keygen = (seed = randomBytes3(lengths.seed)) => {
3891
- abytes(seed, lengths.seed, "seed");
3892
- const seedScalar = Fn2.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
3893
- const secretKey = Fn2.toBytes(Fn2.create(seedScalar));
3894
- return {
3895
- secretKey,
3896
- publicKey: curve.getPublicKey(secretKey)
3897
- };
3898
- };
3899
- }
3900
- return {
3901
- lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },
3902
- keygen: (seed) => keygen(seed),
3903
- getPublicKey: (secretKey) => curve.getPublicKey(secretKey)
3904
- };
3905
- }
3906
- function ecdhKem(curve, allowZeroKey = false) {
3907
- const kg = ecKeygen(curve, allowZeroKey);
3908
- if (!curve.getSharedSecret)
3909
- throw new Error("wrong curve");
3910
- return {
3911
- lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },
3912
- keygen: kg.keygen,
3913
- getPublicKey: kg.getPublicKey,
3914
- encapsulate(publicKey, rand = randomBytes3(curve.lengths.seed)) {
3915
- const seed = copyBytes2(rand);
3916
- let ek = undefined;
3917
- try {
3918
- ek = this.keygen(seed).secretKey;
3919
- const sharedSecret = this.decapsulate(publicKey, ek);
3920
- const cipherText = curve.getPublicKey(ek);
3921
- return { sharedSecret, cipherText };
3922
- } finally {
3923
- cleanBytes(seed);
3924
- if (ek)
3925
- cleanBytes(ek);
3926
- }
3927
- },
3928
- decapsulate(cipherText, secretKey) {
3929
- const res = curve.getSharedSecret(secretKey, cipherText);
3930
- return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
3931
- }
3932
- };
3933
- }
3934
- function splitLengths(lst, name) {
3935
- return splitCoder(name, ...lst.map((i) => {
3936
- if (typeof i.lengths[name] !== "number")
3937
- throw new Error("wrong length: " + name);
3938
- return i.lengths[name];
3939
- }));
3940
- }
3941
- function expandSeedXof(xof) {
3942
- return (seed, seedLen) => xof(seed, { dkLen: seedLen });
3943
- }
3944
- function combineKeys(realSeedLen, expandSeed_, ...ck_) {
3945
- const expandSeed = expandSeed_;
3946
- const ck = ck_;
3947
- const seedCoder = splitLengths(ck, "seed");
3948
- const pkCoder = splitLengths(ck, "publicKey");
3949
- if (realSeedLen === undefined)
3950
- realSeedLen = seedCoder.bytesLen;
3951
- anumber(realSeedLen);
3952
- function expandDecapsulationKey(seed) {
3953
- abytes(seed, realSeedLen);
3954
- const expandedRaw = expandSeed(seed, seedCoder.bytesLen);
3955
- const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes2(expandedRaw) : expandedRaw;
3956
- const expanded = [];
3957
- const keySecret = [];
3958
- const secretKey = [];
3959
- const publicKey = [];
3960
- let ok = false;
3961
- try {
3962
- for (const part of seedCoder.decode(expandedSeed))
3963
- expanded.push(copyBytes2(part));
3964
- for (let i = 0;i < ck.length; i++) {
3965
- const keys = ck[i].keygen(expanded[i]);
3966
- keySecret.push(keys.secretKey);
3967
- secretKey.push(copyBytes2(keys.secretKey));
3968
- publicKey.push(keys.publicKey);
3969
- }
3970
- ok = true;
3971
- return { secretKey, publicKey };
3972
- } finally {
3973
- cleanBytes(expandedSeed, expanded, keySecret);
3974
- if (!ok)
3975
- cleanBytes(secretKey);
3976
- }
3977
- }
3978
- return {
3979
- info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },
3980
- getPublicKey(secretKey) {
3981
- return this.keygen(secretKey).publicKey;
3982
- },
3983
- keygen(seed = randomBytes3(realSeedLen)) {
3984
- const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);
3985
- try {
3986
- const publicKey = pkCoder.encode(pk);
3987
- return { secretKey: seed, publicKey };
3988
- } finally {
3989
- cleanBytes(pk);
3990
- cleanBytes(secretKey);
3991
- }
3992
- },
3993
- expandDecapsulationKey,
3994
- realSeedLen
3995
- };
3996
- }
3997
- function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3998
- const rawCombiner = combiner;
3999
- const rawKems = kems;
4000
- const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);
4001
- const ctCoder = splitLengths(rawKems, "cipherText");
4002
- const pkCoder = splitLengths(rawKems, "publicKey");
4003
- const msgCoder = splitLengths(rawKems, "msg");
4004
- if (realMsgLen === undefined)
4005
- realMsgLen = msgCoder.bytesLen;
4006
- anumber(realMsgLen);
4007
- const lengths = Object.freeze({
4008
- ...keys.info.lengths,
4009
- msg: realMsgLen,
4010
- msgRand: msgCoder.bytesLen,
4011
- cipherText: ctCoder.bytesLen
4012
- });
4013
- return Object.freeze({
4014
- lengths,
4015
- getPublicKey: keys.getPublicKey,
4016
- keygen: keys.keygen,
4017
- encapsulate(pk, randomness = randomBytes3(msgCoder.bytesLen)) {
4018
- const pks = pkCoder.decode(pk);
4019
- const rand = msgCoder.decode(randomness);
4020
- const sharedSecret = [];
4021
- const cipherText = [];
4022
- try {
4023
- for (let i = 0;i < rawKems.length; i++) {
4024
- const enc = rawKems[i].encapsulate(pks[i], rand[i]);
4025
- sharedSecret.push(enc.sharedSecret);
4026
- cipherText.push(enc.cipherText);
4027
- }
4028
- return {
4029
- sharedSecret: copyBytes2(rawCombiner(pks, cipherText, sharedSecret)),
4030
- cipherText: ctCoder.encode(cipherText)
4031
- };
4032
- } finally {
4033
- cleanBytes(sharedSecret, cipherText);
4034
- }
4035
- },
4036
- decapsulate(ct, seed) {
4037
- const cts = ctCoder.decode(ct);
4038
- const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);
4039
- const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
4040
- try {
4041
- return copyBytes2(rawCombiner(publicKey, cts, sharedSecret));
4042
- } finally {
4043
- cleanBytes(secretKey, sharedSecret);
4044
- }
4045
- }
4046
- });
4047
- }
4048
- var x25519kem = /* @__PURE__ */ ecdhKem(x25519);
4049
- var ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(32, 32, expandSeedXof(shake256), (pk, ct, ss) => sha3_256(concatBytes2(ss[0], ss[1], ct[1], pk[1], asciiToBytes("\\.//^\\"))), ml_kem768, x25519kem))();
4050
-
4051
- // ../runtime/dist/identity.js
4052
- var ENCODER = new TextEncoder;
4053
- var b64 = toBase64Url;
4054
- var un64 = fromBase64Url;
4055
- var randomBytes4 = (length) => crypto.getRandomValues(new Uint8Array(length));
4056
- function deriveKeysFromSeed(seed) {
4057
- if (seed.length < 32)
4058
- throw new Error("identity: seed must be at least 32 bytes");
4059
- const sub = (label) => hkdf(sha256, seed, undefined, ENCODER.encode(label), 32);
4060
- const edSecret = sub("forgezero/identity/ed25519/v1");
4061
- const mlSeed = sub("forgezero/identity/ml-dsa-65/v1");
4062
- const edPublic = ed25519.getPublicKey(edSecret);
4063
- const mlKeys = ml_dsa65.keygen(mlSeed);
4064
- mlSeed.fill(0);
4065
- return {
4066
- ed25519: { publicKey: b64(edPublic), secretKey: b64(edSecret) },
4067
- mlDsa: { publicKey: b64(mlKeys.publicKey), secretKey: b64(mlKeys.secretKey) }
4068
- };
4069
- }
4070
- var RESPONSE_KEY_HEADER = "x-fz-response-key";
4071
- function generateResponseRecipient() {
4072
- const pair = ml_kem768_x25519.keygen();
4073
- return { publicKey: b64(pair.publicKey), secretKey: b64(pair.secretKey) };
4074
- }
4075
- var responseKey = (sharedSecret) => hkdf(sha256, sharedSecret, undefined, ENCODER.encode("forgezero/response/ml-kem-768+x25519/v1"), 32);
4076
- async function openResponse(recipientSecretKey, requestBinding, envelope) {
4077
- if (envelope?.version !== 1)
4078
- throw new Error("response: unsupported sealed response");
4079
- const sharedSecret = ml_kem768_x25519.decapsulate(un64(envelope.kemCiphertext), un64(recipientSecretKey));
4080
- const rawKey = responseKey(sharedSecret);
4081
- sharedSecret.fill(0);
4082
- const key = await crypto.subtle.importKey("raw", new Uint8Array(rawKey), "AES-GCM", false, ["decrypt"]);
4083
- rawKey.fill(0);
4084
- const decrypted = new Uint8Array(await crypto.subtle.decrypt({
4085
- name: "AES-GCM",
4086
- iv: new Uint8Array(un64(envelope.nonce)),
4087
- additionalData: new Uint8Array(ENCODER.encode(requestBinding)),
4088
- tagLength: 128
4089
- }, key, new Uint8Array(un64(envelope.ciphertext))));
4090
- try {
4091
- return JSON.parse(new TextDecoder().decode(decrypted));
4092
- } finally {
4093
- decrypted.fill(0);
4094
- }
4095
- }
4096
- var SIGNATURE_FIELDS = (envelope) => ({
4097
- timestamp: envelope.timestamp,
4098
- nonce: envelope.nonce,
4099
- edSignature: envelope.edSignature,
4100
- mlDsaSignature: envelope.mlDsaSignature
4101
- });
4102
- function encodeSignatureHeader(envelope) {
4103
- return b64(ENCODER.encode(JSON.stringify(SIGNATURE_FIELDS(envelope))));
4104
- }
4105
- function canonicalString(args) {
4106
- const body = typeof args.body === "string" ? ENCODER.encode(args.body) : args.body;
4107
- const digest = Array.from(sha256(body), (byte) => byte.toString(16).padStart(2, "0")).join("");
4108
- const fields = [
4109
- args.method.toUpperCase(),
4110
- args.path,
4111
- args.query ?? "",
4112
- String(args.timestamp),
4113
- args.nonce,
4114
- digest
4115
- ];
4116
- if (args.responseKey)
4117
- fields.push(args.responseKey);
4118
- return fields.join(`
4119
- `);
4120
- }
4121
- function signRequest(keys, nodeKey, args) {
4122
- const timestamp = Math.floor(Date.now() / 1000);
4123
- const nonce = b64(randomBytes4(16));
4124
- const message = ENCODER.encode(canonicalString({ ...args, query: args.query ?? "", timestamp, nonce }));
4125
- return {
4126
- nodeKey,
4127
- timestamp,
4128
- nonce,
4129
- edSignature: b64(ed25519.sign(message, un64(keys.ed25519.secretKey))),
4130
- mlDsaSignature: b64(ml_dsa65.sign(message, un64(keys.mlDsa.secretKey)))
4131
- };
4132
- }
4133
-
4134
- // ../vault/dist/index.js
4135
- var DEFAULT_SOCKET = "/run/forgezero/vault.sock";
8
+ import { deriveKeysFromSeed } from "@forgezero/runtime/identity";
9
+ import { DEFAULT_SOCKET as DEFAULT_SOCKET2 } from "@forgezero/vault";
4136
10
 
4137
11
  // src/socket.ts
4138
12
  import { createServer } from "net";
4139
13
  import { chmodSync, existsSync, unlinkSync } from "fs";
14
+ import { signRequest as signRequest2 } from "@forgezero/runtime/identity";
4140
15
 
4141
16
  // src/cache.ts
4142
17
  class CacheError extends Error {
@@ -4259,6 +134,14 @@ function createSecretCache(options) {
4259
134
  }
4260
135
 
4261
136
  // src/signed-node-http.ts
137
+ import {
138
+ encodeSignatureHeader,
139
+ generateResponseRecipient,
140
+ openResponse,
141
+ RESPONSE_KEY_HEADER,
142
+ signRequest
143
+ } from "@forgezero/runtime/identity";
144
+
4262
145
  class SignedNodeHttpError extends Error {
4263
146
  status;
4264
147
  constructor(status, message) {
@@ -4438,7 +321,7 @@ function handleRequest(options, request) {
4438
321
  return Promise.resolve({
4439
322
  ok: true,
4440
323
  op: "sign",
4441
- envelope: signRequest(options.keys, options.nodeKey, {
324
+ envelope: signRequest2(options.keys, options.nodeKey, {
4442
325
  method: request.method,
4443
326
  path: request.path,
4444
327
  query: request.query ?? "",
@@ -4579,308 +462,7 @@ function safeOp(line) {
4579
462
  import { chmodSync as chmodSync2, existsSync as existsSync2, lstatSync, mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
4580
463
  import { createHash as createHash2, randomUUID } from "crypto";
4581
464
  import { dirname, isAbsolute as isAbsolute2, join } from "path";
4582
-
4583
- // ../runtime/dist/queue.js
4584
- class QueueStoppedError extends Error {
4585
- constructor() {
4586
- super("queue: stopped before this task could run");
4587
- this.name = "QueueStoppedError";
4588
- }
4589
- }
4590
-
4591
- class QueueKeyStoppedError extends Error {
4592
- key;
4593
- constructor(key) {
4594
- super(`queue: key ${key} is stopped`);
4595
- this.key = key;
4596
- this.name = "QueueKeyStoppedError";
4597
- }
4598
- }
4599
-
4600
- class TaskCancelledError extends Error {
4601
- constructor() {
4602
- super("queue: task cancelled");
4603
- this.name = "TaskCancelledError";
4604
- }
4605
- }
4606
- var DEFAULT_RETRY = {
4607
- attempts: 1,
4608
- backoffMs: (attempt) => Math.min(30000, 2 ** attempt * 100)
4609
- };
4610
- var reportedParallelism = () => {
4611
- const reported = globalThis.navigator?.hardwareConcurrency;
4612
- return Number.isSafeInteger(reported) && reported > 0 ? reported : 1;
4613
- };
4614
- function queueWidthFor(policy = {}) {
4615
- const percent = policy.percent ?? 60;
4616
- const reserve = policy.reserve ?? 1;
4617
- const min = policy.min ?? 1;
4618
- const max = policy.max ?? Number.MAX_SAFE_INTEGER;
4619
- const available = (policy.available ?? reportedParallelism)();
4620
- if (!Number.isFinite(percent) || percent <= 0 || percent > 100) {
4621
- throw new RangeError("queue: resource percent must be greater than 0 and at most 100");
4622
- }
4623
- for (const [name, value] of [["reserve", reserve], ["min", min], ["max", max]]) {
4624
- if (!Number.isSafeInteger(value) || value < (name === "reserve" ? 0 : 1)) {
4625
- throw new RangeError(`queue: resource ${name} must be ${name === "reserve" ? "a non-negative" : "a positive"} integer`);
4626
- }
4627
- }
4628
- if (!Number.isSafeInteger(available) || available < 1) {
4629
- throw new RangeError("queue: available parallelism must be a positive integer");
4630
- }
4631
- if (min > max)
4632
- throw new RangeError("queue: resource min cannot exceed max");
4633
- const usable = Math.max(1, available - reserve);
4634
- return Math.min(max, Math.max(min, Math.floor(usable * percent / 100)));
4635
- }
4636
- function createQueue(options = {}) {
4637
- if (options.width !== undefined && options.resources !== undefined) {
4638
- throw new Error("queue: choose either width or resources, not both");
4639
- }
4640
- const configuredWidth = options.width;
4641
- const widthNow = () => configuredWidth ?? queueWidthFor(options.resources);
4642
- const initialWidth = widthNow();
4643
- const retry = { ...DEFAULT_RETRY, ...options.retry };
4644
- if (!Number.isSafeInteger(initialWidth) || initialWidth < 1) {
4645
- throw new RangeError("queue: width must be a positive integer");
4646
- }
4647
- if (!Number.isSafeInteger(retry.attempts) || retry.attempts < 1) {
4648
- throw new RangeError("queue: retry attempts must be a positive integer");
4649
- }
4650
- const sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
4651
- const lanes = new Map;
4652
- const running = new Set;
4653
- const paused = new Set;
4654
- const stoppedKeys = new Set;
4655
- let sequence = 0;
4656
- let globallyPaused = false;
4657
- let accepting = true;
4658
- let aborted = false;
4659
- let completed = 0;
4660
- let failed = 0;
4661
- const idle = [];
4662
- const announceIdle = () => {
4663
- if (running.size > 0)
4664
- return;
4665
- for (const lane of lanes.values())
4666
- if (lane.length > 0)
4667
- return;
4668
- while (idle.length > 0)
4669
- idle.shift()();
4670
- };
4671
- function pump() {
4672
- if (globallyPaused || aborted) {
4673
- announceIdle();
4674
- return;
4675
- }
4676
- const width = widthNow();
4677
- for (const [key, lane] of lanes) {
4678
- if (running.size >= width)
4679
- break;
4680
- if (running.has(key) || paused.has(key) || lane.length === 0)
4681
- continue;
4682
- execute(key);
4683
- }
4684
- announceIdle();
4685
- }
4686
- async function execute(key) {
4687
- running.add(key);
4688
- try {
4689
- const lane = lanes.get(key);
4690
- const entry = lane?.[0];
4691
- if (entry && !globallyPaused && !paused.has(key) && !aborted) {
4692
- lane.shift();
4693
- await attempt(entry);
4694
- }
4695
- } finally {
4696
- running.delete(key);
4697
- const remaining = lanes.get(key);
4698
- if (remaining?.length === 0)
4699
- lanes.delete(key);
4700
- else if (remaining) {
4701
- lanes.delete(key);
4702
- lanes.set(key, remaining);
4703
- }
4704
- pump();
4705
- }
4706
- }
4707
- async function attempt(entry) {
4708
- if (entry.cancelled) {
4709
- entry.reject(new TaskCancelledError);
4710
- return;
4711
- }
4712
- for (;; ) {
4713
- entry.attempt += 1;
4714
- try {
4715
- const value = await entry.run();
4716
- completed += 1;
4717
- entry.resolve(value);
4718
- return;
4719
- } catch (cause) {
4720
- if (entry.attempt >= retry.attempts || entry.cancelled || aborted) {
4721
- failed += 1;
4722
- entry.reject(cause);
4723
- return;
4724
- }
4725
- const delay = retry.backoffMs(entry.attempt);
4726
- if (!Number.isFinite(delay) || delay < 0) {
4727
- failed += 1;
4728
- entry.reject(new RangeError("queue: retry backoff must be a non-negative finite number"));
4729
- return;
4730
- }
4731
- await sleep(delay);
4732
- }
4733
- }
4734
- }
4735
- return {
4736
- run(key, handler, ...args) {
4737
- const id2 = `q_${++sequence}`;
4738
- if (!accepting || stoppedKeys.has(key)) {
4739
- const refused = Promise.reject(accepting ? new QueueKeyStoppedError(key) : new QueueStoppedError);
4740
- refused.catch(() => {
4741
- return;
4742
- });
4743
- return { id: id2, key, result: refused };
4744
- }
4745
- let resolve;
4746
- let reject;
4747
- const result = new Promise((ok, no) => {
4748
- resolve = ok;
4749
- reject = no;
4750
- });
4751
- const entry = {
4752
- id: id2,
4753
- key,
4754
- run: async () => handler(...args),
4755
- resolve,
4756
- reject,
4757
- attempt: 0,
4758
- cancelled: false
4759
- };
4760
- const lane = lanes.get(key);
4761
- if (lane)
4762
- lane.push(entry);
4763
- else
4764
- lanes.set(key, [entry]);
4765
- pump();
4766
- return { id: id2, key, result };
4767
- },
4768
- cancel(id2) {
4769
- for (const [key, lane] of lanes) {
4770
- const index = lane.findIndex((entry2) => entry2.id === id2);
4771
- if (index === -1)
4772
- continue;
4773
- const [entry] = lane.splice(index, 1);
4774
- entry.cancelled = true;
4775
- entry.reject(new TaskCancelledError);
4776
- if (lane.length === 0 && !running.has(key))
4777
- lanes.delete(key);
4778
- announceIdle();
4779
- return true;
4780
- }
4781
- return false;
4782
- },
4783
- pauseKey(key) {
4784
- paused.add(key);
4785
- },
4786
- resumeKey(key) {
4787
- paused.delete(key);
4788
- pump();
4789
- },
4790
- stopKey(key) {
4791
- stoppedKeys.add(key);
4792
- paused.delete(key);
4793
- const lane = lanes.get(key);
4794
- if (!lane)
4795
- return 0;
4796
- let removed = 0;
4797
- for (const entry of lane.splice(0)) {
4798
- removed += 1;
4799
- entry.cancelled = true;
4800
- entry.reject(new QueueKeyStoppedError(key));
4801
- }
4802
- if (!running.has(key))
4803
- lanes.delete(key);
4804
- announceIdle();
4805
- return removed;
4806
- },
4807
- startKey(key) {
4808
- const changed = stoppedKeys.delete(key);
4809
- pump();
4810
- return changed;
4811
- },
4812
- pause() {
4813
- globallyPaused = true;
4814
- },
4815
- resume() {
4816
- globallyPaused = false;
4817
- pump();
4818
- },
4819
- snapshot() {
4820
- let queued = 0;
4821
- for (const lane of lanes.values())
4822
- queued += lane.length;
4823
- return {
4824
- width: widthNow(),
4825
- running: running.size,
4826
- queued,
4827
- keys: lanes.size,
4828
- paused: globallyPaused,
4829
- pausedKeys: [...paused],
4830
- stoppedKeys: [...stoppedKeys],
4831
- completed,
4832
- failed
4833
- };
4834
- },
4835
- whenIdle() {
4836
- if (running.size === 0 && [...lanes.values()].every((lane) => lane.length === 0)) {
4837
- return Promise.resolve();
4838
- }
4839
- return new Promise((resolve) => idle.push(resolve));
4840
- },
4841
- async stop(deadlineMs = 30000) {
4842
- if (!Number.isSafeInteger(deadlineMs) || deadlineMs < 0) {
4843
- throw new RangeError("queue: stop deadline must be a non-negative integer");
4844
- }
4845
- accepting = false;
4846
- const before = { completed, failed };
4847
- globallyPaused = false;
4848
- paused.clear();
4849
- pump();
4850
- let timedOut = false;
4851
- let deadlineHandle;
4852
- const deadline = new Promise((resolve) => {
4853
- deadlineHandle = setTimeout(() => {
4854
- timedOut = true;
4855
- resolve();
4856
- }, deadlineMs);
4857
- });
4858
- await Promise.race([this.whenIdle(), deadline]);
4859
- if (!timedOut && deadlineHandle !== undefined)
4860
- clearTimeout(deadlineHandle);
4861
- if (timedOut)
4862
- aborted = true;
4863
- let abandoned = 0;
4864
- for (const lane of lanes.values()) {
4865
- abandoned += lane.length;
4866
- for (const entry of lane.splice(0))
4867
- entry.reject(new QueueStoppedError);
4868
- }
4869
- abandoned += running.size;
4870
- for (const [key, lane] of lanes) {
4871
- if (lane.length === 0 && !running.has(key))
4872
- lanes.delete(key);
4873
- }
4874
- announceIdle();
4875
- return {
4876
- completed: completed - before.completed,
4877
- failed: failed - before.failed,
4878
- abandoned,
4879
- timedOut
4880
- };
4881
- }
4882
- };
4883
- }
465
+ import { createQueue } from "@forgezero/runtime/queue";
4884
466
 
4885
467
  // src/software.ts
4886
468
  import { readFileSync } from "fs";
@@ -7858,11 +3440,7 @@ function requestDeploymentCommand(input, socketPath = DEFAULT_DEPLOYMENT_RUNNER_
7858
3440
 
7859
3441
  // src/snp-attestation.ts
7860
3442
  import { existsSync as existsSync8 } from "fs";
7861
-
7862
- // ../runtime/dist/snp.js
7863
- var REPORT_BYTES = 1184;
7864
-
7865
- // src/snp-attestation.ts
3443
+ import { REPORT_BYTES } from "@forgezero/runtime/snp";
7866
3444
  var SNP_REPORT_HELPER = String.raw`
7867
3445
  import base64
7868
3446
  import ctypes
@@ -8641,6 +4219,7 @@ import {
8641
4219
  } from "fs";
8642
4220
  import { connect as connect5, createServer as createServer6 } from "net";
8643
4221
  import { dirname as dirname5, join as join6, resolve as resolve3 } from "path";
4222
+ import { DEFAULT_SOCKET } from "@forgezero/vault";
8644
4223
  var AGENT_UPDATE_GROUP = "forgezero-update";
8645
4224
  var AGENT_UPDATE_HELPER_UNIT_PATH = "/etc/systemd/system/forgezero-agent-update-helper.service";
8646
4225
  var AGENT_UPDATE_JOURNAL = "/var/lib/forgezero/agent-update.json";
@@ -9093,7 +4672,7 @@ function requestAgentUpdate(request, socketPath = DEFAULT_AGENT_UPDATE_SOCKET, t
9093
4672
  import { readFileSync as readFileSync9 } from "fs";
9094
4673
 
9095
4674
  // src/version.ts
9096
- var VERSION3 = "0.1.36";
4675
+ var VERSION3 = "0.1.37";
9097
4676
 
9098
4677
  // src/agent-heartbeat.ts
9099
4678
  var unquote = (value) => value.replace(/^['"]|['"]$/g, "");
@@ -10204,12 +5783,12 @@ function loadOrCreateSeed(path) {
10204
5783
  return seed2;
10205
5784
  }
10206
5785
  mkdirSync9(dirname7(path), { recursive: true });
10207
- const seed = new Uint8Array(randomBytes5(32));
5786
+ const seed = new Uint8Array(randomBytes(32));
10208
5787
  writeFileSync9(path, Buffer.from(seed).toString("base64url"), { mode: 384 });
10209
5788
  chmodSync13(path, 384);
10210
5789
  return seed;
10211
5790
  }
10212
- var DEFAULT_SOCKET_PATH = DEFAULT_SOCKET;
5791
+ var DEFAULT_SOCKET_PATH = DEFAULT_SOCKET2;
10213
5792
  var DEFAULT_SEED_PATH = "/var/lib/forgezero/node.seed";
10214
5793
  var DEFAULT_SEED_CREDENTIAL = "agent-seed";
10215
5794
  function configuredAgentSeed(options) {