protect-mcp 0.1.1 → 0.2.1

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/cli.js CHANGED
@@ -1,5 +1,2642 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
30
+ mod2
31
+ ));
32
+
33
+ // node_modules/@noble/hashes/esm/cryptoNode.js
34
+ var nc, crypto;
35
+ var init_cryptoNode = __esm({
36
+ "node_modules/@noble/hashes/esm/cryptoNode.js"() {
37
+ "use strict";
38
+ nc = __toESM(require("crypto"), 1);
39
+ crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
40
+ }
41
+ });
42
+
43
+ // node_modules/@noble/hashes/esm/utils.js
44
+ var utils_exports = {};
45
+ __export(utils_exports, {
46
+ Hash: () => Hash,
47
+ abytes: () => abytes,
48
+ aexists: () => aexists,
49
+ ahash: () => ahash,
50
+ anumber: () => anumber,
51
+ aoutput: () => aoutput,
52
+ asyncLoop: () => asyncLoop,
53
+ byteSwap: () => byteSwap,
54
+ byteSwap32: () => byteSwap32,
55
+ byteSwapIfBE: () => byteSwapIfBE,
56
+ bytesToHex: () => bytesToHex,
57
+ bytesToUtf8: () => bytesToUtf8,
58
+ checkOpts: () => checkOpts,
59
+ clean: () => clean,
60
+ concatBytes: () => concatBytes,
61
+ createHasher: () => createHasher,
62
+ createOptHasher: () => createOptHasher,
63
+ createView: () => createView,
64
+ createXOFer: () => createXOFer,
65
+ hexToBytes: () => hexToBytes,
66
+ isBytes: () => isBytes,
67
+ isLE: () => isLE,
68
+ kdfInputToBytes: () => kdfInputToBytes,
69
+ nextTick: () => nextTick,
70
+ randomBytes: () => randomBytes,
71
+ rotl: () => rotl,
72
+ rotr: () => rotr,
73
+ swap32IfBE: () => swap32IfBE,
74
+ swap8IfBE: () => swap8IfBE,
75
+ toBytes: () => toBytes,
76
+ u32: () => u32,
77
+ u8: () => u8,
78
+ utf8ToBytes: () => utf8ToBytes,
79
+ wrapConstructor: () => wrapConstructor,
80
+ wrapConstructorWithOpts: () => wrapConstructorWithOpts,
81
+ wrapXOFConstructorWithOpts: () => wrapXOFConstructorWithOpts
82
+ });
83
+ function isBytes(a) {
84
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
85
+ }
86
+ function anumber(n) {
87
+ if (!Number.isSafeInteger(n) || n < 0)
88
+ throw new Error("positive integer expected, got " + n);
89
+ }
90
+ function abytes(b, ...lengths) {
91
+ if (!isBytes(b))
92
+ throw new Error("Uint8Array expected");
93
+ if (lengths.length > 0 && !lengths.includes(b.length))
94
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
95
+ }
96
+ function ahash(h) {
97
+ if (typeof h !== "function" || typeof h.create !== "function")
98
+ throw new Error("Hash should be wrapped by utils.createHasher");
99
+ anumber(h.outputLen);
100
+ anumber(h.blockLen);
101
+ }
102
+ function aexists(instance, checkFinished = true) {
103
+ if (instance.destroyed)
104
+ throw new Error("Hash instance has been destroyed");
105
+ if (checkFinished && instance.finished)
106
+ throw new Error("Hash#digest() has already been called");
107
+ }
108
+ function aoutput(out, instance) {
109
+ abytes(out);
110
+ const min = instance.outputLen;
111
+ if (out.length < min) {
112
+ throw new Error("digestInto() expects output buffer of length at least " + min);
113
+ }
114
+ }
115
+ function u8(arr) {
116
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
117
+ }
118
+ function u32(arr) {
119
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
120
+ }
121
+ function clean(...arrays) {
122
+ for (let i = 0; i < arrays.length; i++) {
123
+ arrays[i].fill(0);
124
+ }
125
+ }
126
+ function createView(arr) {
127
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
128
+ }
129
+ function rotr(word, shift) {
130
+ return word << 32 - shift | word >>> shift;
131
+ }
132
+ function rotl(word, shift) {
133
+ return word << shift | word >>> 32 - shift >>> 0;
134
+ }
135
+ function byteSwap(word) {
136
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
137
+ }
138
+ function byteSwap32(arr) {
139
+ for (let i = 0; i < arr.length; i++) {
140
+ arr[i] = byteSwap(arr[i]);
141
+ }
142
+ return arr;
143
+ }
144
+ function bytesToHex(bytes) {
145
+ abytes(bytes);
146
+ if (hasHexBuiltin)
147
+ return bytes.toHex();
148
+ let hex = "";
149
+ for (let i = 0; i < bytes.length; i++) {
150
+ hex += hexes[bytes[i]];
151
+ }
152
+ return hex;
153
+ }
154
+ function asciiToBase16(ch) {
155
+ if (ch >= asciis._0 && ch <= asciis._9)
156
+ return ch - asciis._0;
157
+ if (ch >= asciis.A && ch <= asciis.F)
158
+ return ch - (asciis.A - 10);
159
+ if (ch >= asciis.a && ch <= asciis.f)
160
+ return ch - (asciis.a - 10);
161
+ return;
162
+ }
163
+ function hexToBytes(hex) {
164
+ if (typeof hex !== "string")
165
+ throw new Error("hex string expected, got " + typeof hex);
166
+ if (hasHexBuiltin)
167
+ return Uint8Array.fromHex(hex);
168
+ const hl = hex.length;
169
+ const al = hl / 2;
170
+ if (hl % 2)
171
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
172
+ const array = new Uint8Array(al);
173
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
174
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
175
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
176
+ if (n1 === void 0 || n2 === void 0) {
177
+ const char = hex[hi] + hex[hi + 1];
178
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
179
+ }
180
+ array[ai] = n1 * 16 + n2;
181
+ }
182
+ return array;
183
+ }
184
+ async function asyncLoop(iters, tick, cb) {
185
+ let ts = Date.now();
186
+ for (let i = 0; i < iters; i++) {
187
+ cb(i);
188
+ const diff = Date.now() - ts;
189
+ if (diff >= 0 && diff < tick)
190
+ continue;
191
+ await nextTick();
192
+ ts += diff;
193
+ }
194
+ }
195
+ function utf8ToBytes(str) {
196
+ if (typeof str !== "string")
197
+ throw new Error("string expected");
198
+ return new Uint8Array(new TextEncoder().encode(str));
199
+ }
200
+ function bytesToUtf8(bytes) {
201
+ return new TextDecoder().decode(bytes);
202
+ }
203
+ function toBytes(data) {
204
+ if (typeof data === "string")
205
+ data = utf8ToBytes(data);
206
+ abytes(data);
207
+ return data;
208
+ }
209
+ function kdfInputToBytes(data) {
210
+ if (typeof data === "string")
211
+ data = utf8ToBytes(data);
212
+ abytes(data);
213
+ return data;
214
+ }
215
+ function concatBytes(...arrays) {
216
+ let sum = 0;
217
+ for (let i = 0; i < arrays.length; i++) {
218
+ const a = arrays[i];
219
+ abytes(a);
220
+ sum += a.length;
221
+ }
222
+ const res = new Uint8Array(sum);
223
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
224
+ const a = arrays[i];
225
+ res.set(a, pad);
226
+ pad += a.length;
227
+ }
228
+ return res;
229
+ }
230
+ function checkOpts(defaults, opts) {
231
+ if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
232
+ throw new Error("options should be object or undefined");
233
+ const merged = Object.assign(defaults, opts);
234
+ return merged;
235
+ }
236
+ function createHasher(hashCons) {
237
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
238
+ const tmp = hashCons();
239
+ hashC.outputLen = tmp.outputLen;
240
+ hashC.blockLen = tmp.blockLen;
241
+ hashC.create = () => hashCons();
242
+ return hashC;
243
+ }
244
+ function createOptHasher(hashCons) {
245
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
246
+ const tmp = hashCons({});
247
+ hashC.outputLen = tmp.outputLen;
248
+ hashC.blockLen = tmp.blockLen;
249
+ hashC.create = (opts) => hashCons(opts);
250
+ return hashC;
251
+ }
252
+ function createXOFer(hashCons) {
253
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
254
+ const tmp = hashCons({});
255
+ hashC.outputLen = tmp.outputLen;
256
+ hashC.blockLen = tmp.blockLen;
257
+ hashC.create = (opts) => hashCons(opts);
258
+ return hashC;
259
+ }
260
+ function randomBytes(bytesLength = 32) {
261
+ if (crypto && typeof crypto.getRandomValues === "function") {
262
+ return crypto.getRandomValues(new Uint8Array(bytesLength));
263
+ }
264
+ if (crypto && typeof crypto.randomBytes === "function") {
265
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
266
+ }
267
+ throw new Error("crypto.getRandomValues must be defined");
268
+ }
269
+ var isLE, swap8IfBE, byteSwapIfBE, swap32IfBE, hasHexBuiltin, hexes, asciis, nextTick, Hash, wrapConstructor, wrapConstructorWithOpts, wrapXOFConstructorWithOpts;
270
+ var init_utils = __esm({
271
+ "node_modules/@noble/hashes/esm/utils.js"() {
272
+ "use strict";
273
+ init_cryptoNode();
274
+ isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
275
+ swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n);
276
+ byteSwapIfBE = swap8IfBE;
277
+ swap32IfBE = isLE ? (u) => u : byteSwap32;
278
+ hasHexBuiltin = /* @__PURE__ */ (() => (
279
+ // @ts-ignore
280
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
281
+ ))();
282
+ hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
283
+ asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
284
+ nextTick = async () => {
285
+ };
286
+ Hash = class {
287
+ };
288
+ wrapConstructor = createHasher;
289
+ wrapConstructorWithOpts = createOptHasher;
290
+ wrapXOFConstructorWithOpts = createXOFer;
291
+ }
292
+ });
293
+
294
+ // node_modules/@noble/hashes/esm/_md.js
295
+ function setBigUint64(view, byteOffset, value, isLE2) {
296
+ if (typeof view.setBigUint64 === "function")
297
+ return view.setBigUint64(byteOffset, value, isLE2);
298
+ const _32n2 = BigInt(32);
299
+ const _u32_max = BigInt(4294967295);
300
+ const wh = Number(value >> _32n2 & _u32_max);
301
+ const wl = Number(value & _u32_max);
302
+ const h = isLE2 ? 4 : 0;
303
+ const l = isLE2 ? 0 : 4;
304
+ view.setUint32(byteOffset + h, wh, isLE2);
305
+ view.setUint32(byteOffset + l, wl, isLE2);
306
+ }
307
+ var HashMD, SHA512_IV;
308
+ var init_md = __esm({
309
+ "node_modules/@noble/hashes/esm/_md.js"() {
310
+ "use strict";
311
+ init_utils();
312
+ HashMD = class extends Hash {
313
+ constructor(blockLen, outputLen, padOffset, isLE2) {
314
+ super();
315
+ this.finished = false;
316
+ this.length = 0;
317
+ this.pos = 0;
318
+ this.destroyed = false;
319
+ this.blockLen = blockLen;
320
+ this.outputLen = outputLen;
321
+ this.padOffset = padOffset;
322
+ this.isLE = isLE2;
323
+ this.buffer = new Uint8Array(blockLen);
324
+ this.view = createView(this.buffer);
325
+ }
326
+ update(data) {
327
+ aexists(this);
328
+ data = toBytes(data);
329
+ abytes(data);
330
+ const { view, buffer, blockLen } = this;
331
+ const len = data.length;
332
+ for (let pos = 0; pos < len; ) {
333
+ const take = Math.min(blockLen - this.pos, len - pos);
334
+ if (take === blockLen) {
335
+ const dataView = createView(data);
336
+ for (; blockLen <= len - pos; pos += blockLen)
337
+ this.process(dataView, pos);
338
+ continue;
339
+ }
340
+ buffer.set(data.subarray(pos, pos + take), this.pos);
341
+ this.pos += take;
342
+ pos += take;
343
+ if (this.pos === blockLen) {
344
+ this.process(view, 0);
345
+ this.pos = 0;
346
+ }
347
+ }
348
+ this.length += data.length;
349
+ this.roundClean();
350
+ return this;
351
+ }
352
+ digestInto(out) {
353
+ aexists(this);
354
+ aoutput(out, this);
355
+ this.finished = true;
356
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
357
+ let { pos } = this;
358
+ buffer[pos++] = 128;
359
+ clean(this.buffer.subarray(pos));
360
+ if (this.padOffset > blockLen - pos) {
361
+ this.process(view, 0);
362
+ pos = 0;
363
+ }
364
+ for (let i = pos; i < blockLen; i++)
365
+ buffer[i] = 0;
366
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
367
+ this.process(view, 0);
368
+ const oview = createView(out);
369
+ const len = this.outputLen;
370
+ if (len % 4)
371
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
372
+ const outLen = len / 4;
373
+ const state = this.get();
374
+ if (outLen > state.length)
375
+ throw new Error("_sha2: outputLen bigger than state");
376
+ for (let i = 0; i < outLen; i++)
377
+ oview.setUint32(4 * i, state[i], isLE2);
378
+ }
379
+ digest() {
380
+ const { buffer, outputLen } = this;
381
+ this.digestInto(buffer);
382
+ const res = buffer.slice(0, outputLen);
383
+ this.destroy();
384
+ return res;
385
+ }
386
+ _cloneInto(to) {
387
+ to || (to = new this.constructor());
388
+ to.set(...this.get());
389
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
390
+ to.destroyed = destroyed;
391
+ to.finished = finished;
392
+ to.length = length;
393
+ to.pos = pos;
394
+ if (length % blockLen)
395
+ to.buffer.set(buffer);
396
+ return to;
397
+ }
398
+ clone() {
399
+ return this._cloneInto();
400
+ }
401
+ };
402
+ SHA512_IV = /* @__PURE__ */ Uint32Array.from([
403
+ 1779033703,
404
+ 4089235720,
405
+ 3144134277,
406
+ 2227873595,
407
+ 1013904242,
408
+ 4271175723,
409
+ 2773480762,
410
+ 1595750129,
411
+ 1359893119,
412
+ 2917565137,
413
+ 2600822924,
414
+ 725511199,
415
+ 528734635,
416
+ 4215389547,
417
+ 1541459225,
418
+ 327033209
419
+ ]);
420
+ }
421
+ });
422
+
423
+ // node_modules/@noble/hashes/esm/_u64.js
424
+ function fromBig(n, le = false) {
425
+ if (le)
426
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
427
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
428
+ }
429
+ function split(lst, le = false) {
430
+ const len = lst.length;
431
+ let Ah = new Uint32Array(len);
432
+ let Al = new Uint32Array(len);
433
+ for (let i = 0; i < len; i++) {
434
+ const { h, l } = fromBig(lst[i], le);
435
+ [Ah[i], Al[i]] = [h, l];
436
+ }
437
+ return [Ah, Al];
438
+ }
439
+ function add(Ah, Al, Bh, Bl) {
440
+ const l = (Al >>> 0) + (Bl >>> 0);
441
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
442
+ }
443
+ var U32_MASK64, _32n, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, add3L, add3H, add4L, add4H, add5L, add5H;
444
+ var init_u64 = __esm({
445
+ "node_modules/@noble/hashes/esm/_u64.js"() {
446
+ "use strict";
447
+ U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
448
+ _32n = /* @__PURE__ */ BigInt(32);
449
+ shrSH = (h, _l, s) => h >>> s;
450
+ shrSL = (h, l, s) => h << 32 - s | l >>> s;
451
+ rotrSH = (h, l, s) => h >>> s | l << 32 - s;
452
+ rotrSL = (h, l, s) => h << 32 - s | l >>> s;
453
+ rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
454
+ rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
455
+ add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
456
+ add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
457
+ add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
458
+ add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
459
+ add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
460
+ add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
461
+ }
462
+ });
463
+
464
+ // node_modules/@noble/hashes/esm/sha2.js
465
+ var K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, sha512;
466
+ var init_sha2 = __esm({
467
+ "node_modules/@noble/hashes/esm/sha2.js"() {
468
+ "use strict";
469
+ init_md();
470
+ init_u64();
471
+ init_utils();
472
+ K512 = /* @__PURE__ */ (() => split([
473
+ "0x428a2f98d728ae22",
474
+ "0x7137449123ef65cd",
475
+ "0xb5c0fbcfec4d3b2f",
476
+ "0xe9b5dba58189dbbc",
477
+ "0x3956c25bf348b538",
478
+ "0x59f111f1b605d019",
479
+ "0x923f82a4af194f9b",
480
+ "0xab1c5ed5da6d8118",
481
+ "0xd807aa98a3030242",
482
+ "0x12835b0145706fbe",
483
+ "0x243185be4ee4b28c",
484
+ "0x550c7dc3d5ffb4e2",
485
+ "0x72be5d74f27b896f",
486
+ "0x80deb1fe3b1696b1",
487
+ "0x9bdc06a725c71235",
488
+ "0xc19bf174cf692694",
489
+ "0xe49b69c19ef14ad2",
490
+ "0xefbe4786384f25e3",
491
+ "0x0fc19dc68b8cd5b5",
492
+ "0x240ca1cc77ac9c65",
493
+ "0x2de92c6f592b0275",
494
+ "0x4a7484aa6ea6e483",
495
+ "0x5cb0a9dcbd41fbd4",
496
+ "0x76f988da831153b5",
497
+ "0x983e5152ee66dfab",
498
+ "0xa831c66d2db43210",
499
+ "0xb00327c898fb213f",
500
+ "0xbf597fc7beef0ee4",
501
+ "0xc6e00bf33da88fc2",
502
+ "0xd5a79147930aa725",
503
+ "0x06ca6351e003826f",
504
+ "0x142929670a0e6e70",
505
+ "0x27b70a8546d22ffc",
506
+ "0x2e1b21385c26c926",
507
+ "0x4d2c6dfc5ac42aed",
508
+ "0x53380d139d95b3df",
509
+ "0x650a73548baf63de",
510
+ "0x766a0abb3c77b2a8",
511
+ "0x81c2c92e47edaee6",
512
+ "0x92722c851482353b",
513
+ "0xa2bfe8a14cf10364",
514
+ "0xa81a664bbc423001",
515
+ "0xc24b8b70d0f89791",
516
+ "0xc76c51a30654be30",
517
+ "0xd192e819d6ef5218",
518
+ "0xd69906245565a910",
519
+ "0xf40e35855771202a",
520
+ "0x106aa07032bbd1b8",
521
+ "0x19a4c116b8d2d0c8",
522
+ "0x1e376c085141ab53",
523
+ "0x2748774cdf8eeb99",
524
+ "0x34b0bcb5e19b48a8",
525
+ "0x391c0cb3c5c95a63",
526
+ "0x4ed8aa4ae3418acb",
527
+ "0x5b9cca4f7763e373",
528
+ "0x682e6ff3d6b2b8a3",
529
+ "0x748f82ee5defb2fc",
530
+ "0x78a5636f43172f60",
531
+ "0x84c87814a1f0ab72",
532
+ "0x8cc702081a6439ec",
533
+ "0x90befffa23631e28",
534
+ "0xa4506cebde82bde9",
535
+ "0xbef9a3f7b2c67915",
536
+ "0xc67178f2e372532b",
537
+ "0xca273eceea26619c",
538
+ "0xd186b8c721c0c207",
539
+ "0xeada7dd6cde0eb1e",
540
+ "0xf57d4f7fee6ed178",
541
+ "0x06f067aa72176fba",
542
+ "0x0a637dc5a2c898a6",
543
+ "0x113f9804bef90dae",
544
+ "0x1b710b35131c471b",
545
+ "0x28db77f523047d84",
546
+ "0x32caab7b40c72493",
547
+ "0x3c9ebe0a15c9bebc",
548
+ "0x431d67c49c100d4c",
549
+ "0x4cc5d4becb3e42b6",
550
+ "0x597f299cfc657e2a",
551
+ "0x5fcb6fab3ad6faec",
552
+ "0x6c44198c4a475817"
553
+ ].map((n) => BigInt(n))))();
554
+ SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
555
+ SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
556
+ SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
557
+ SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
558
+ SHA512 = class extends HashMD {
559
+ constructor(outputLen = 64) {
560
+ super(128, outputLen, 16, false);
561
+ this.Ah = SHA512_IV[0] | 0;
562
+ this.Al = SHA512_IV[1] | 0;
563
+ this.Bh = SHA512_IV[2] | 0;
564
+ this.Bl = SHA512_IV[3] | 0;
565
+ this.Ch = SHA512_IV[4] | 0;
566
+ this.Cl = SHA512_IV[5] | 0;
567
+ this.Dh = SHA512_IV[6] | 0;
568
+ this.Dl = SHA512_IV[7] | 0;
569
+ this.Eh = SHA512_IV[8] | 0;
570
+ this.El = SHA512_IV[9] | 0;
571
+ this.Fh = SHA512_IV[10] | 0;
572
+ this.Fl = SHA512_IV[11] | 0;
573
+ this.Gh = SHA512_IV[12] | 0;
574
+ this.Gl = SHA512_IV[13] | 0;
575
+ this.Hh = SHA512_IV[14] | 0;
576
+ this.Hl = SHA512_IV[15] | 0;
577
+ }
578
+ // prettier-ignore
579
+ get() {
580
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
581
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
582
+ }
583
+ // prettier-ignore
584
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
585
+ this.Ah = Ah | 0;
586
+ this.Al = Al | 0;
587
+ this.Bh = Bh | 0;
588
+ this.Bl = Bl | 0;
589
+ this.Ch = Ch | 0;
590
+ this.Cl = Cl | 0;
591
+ this.Dh = Dh | 0;
592
+ this.Dl = Dl | 0;
593
+ this.Eh = Eh | 0;
594
+ this.El = El | 0;
595
+ this.Fh = Fh | 0;
596
+ this.Fl = Fl | 0;
597
+ this.Gh = Gh | 0;
598
+ this.Gl = Gl | 0;
599
+ this.Hh = Hh | 0;
600
+ this.Hl = Hl | 0;
601
+ }
602
+ process(view, offset) {
603
+ for (let i = 0; i < 16; i++, offset += 4) {
604
+ SHA512_W_H[i] = view.getUint32(offset);
605
+ SHA512_W_L[i] = view.getUint32(offset += 4);
606
+ }
607
+ for (let i = 16; i < 80; i++) {
608
+ const W15h = SHA512_W_H[i - 15] | 0;
609
+ const W15l = SHA512_W_L[i - 15] | 0;
610
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
611
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
612
+ const W2h = SHA512_W_H[i - 2] | 0;
613
+ const W2l = SHA512_W_L[i - 2] | 0;
614
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
615
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
616
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
617
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
618
+ SHA512_W_H[i] = SUMh | 0;
619
+ SHA512_W_L[i] = SUMl | 0;
620
+ }
621
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
622
+ for (let i = 0; i < 80; i++) {
623
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
624
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
625
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
626
+ const CHIl = El & Fl ^ ~El & Gl;
627
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
628
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
629
+ const T1l = T1ll | 0;
630
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
631
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
632
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
633
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
634
+ Hh = Gh | 0;
635
+ Hl = Gl | 0;
636
+ Gh = Fh | 0;
637
+ Gl = Fl | 0;
638
+ Fh = Eh | 0;
639
+ Fl = El | 0;
640
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
641
+ Dh = Ch | 0;
642
+ Dl = Cl | 0;
643
+ Ch = Bh | 0;
644
+ Cl = Bl | 0;
645
+ Bh = Ah | 0;
646
+ Bl = Al | 0;
647
+ const All = add3L(T1l, sigma0l, MAJl);
648
+ Ah = add3H(All, T1h, sigma0h, MAJh);
649
+ Al = All | 0;
650
+ }
651
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
652
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
653
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
654
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
655
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
656
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
657
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
658
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
659
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
660
+ }
661
+ roundClean() {
662
+ clean(SHA512_W_H, SHA512_W_L);
663
+ }
664
+ destroy() {
665
+ clean(this.buffer);
666
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
667
+ }
668
+ };
669
+ sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
670
+ }
671
+ });
672
+
673
+ // node_modules/@noble/curves/esm/utils.js
674
+ function _abool2(value, title = "") {
675
+ if (typeof value !== "boolean") {
676
+ const prefix = title && `"${title}"`;
677
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
678
+ }
679
+ return value;
680
+ }
681
+ function _abytes2(value, length, title = "") {
682
+ const bytes = isBytes(value);
683
+ const len = value?.length;
684
+ const needsLen = length !== void 0;
685
+ if (!bytes || needsLen && len !== length) {
686
+ const prefix = title && `"${title}" `;
687
+ const ofLen = needsLen ? ` of length ${length}` : "";
688
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
689
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
690
+ }
691
+ return value;
692
+ }
693
+ function hexToNumber(hex) {
694
+ if (typeof hex !== "string")
695
+ throw new Error("hex string expected, got " + typeof hex);
696
+ return hex === "" ? _0n : BigInt("0x" + hex);
697
+ }
698
+ function bytesToNumberBE(bytes) {
699
+ return hexToNumber(bytesToHex(bytes));
700
+ }
701
+ function bytesToNumberLE(bytes) {
702
+ abytes(bytes);
703
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
704
+ }
705
+ function numberToBytesBE(n, len) {
706
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
707
+ }
708
+ function numberToBytesLE(n, len) {
709
+ return numberToBytesBE(n, len).reverse();
710
+ }
711
+ function ensureBytes(title, hex, expectedLength) {
712
+ let res;
713
+ if (typeof hex === "string") {
714
+ try {
715
+ res = hexToBytes(hex);
716
+ } catch (e) {
717
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
718
+ }
719
+ } else if (isBytes(hex)) {
720
+ res = Uint8Array.from(hex);
721
+ } else {
722
+ throw new Error(title + " must be hex string or Uint8Array");
723
+ }
724
+ const len = res.length;
725
+ if (typeof expectedLength === "number" && len !== expectedLength)
726
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
727
+ return res;
728
+ }
729
+ function equalBytes(a, b) {
730
+ if (a.length !== b.length)
731
+ return false;
732
+ let diff = 0;
733
+ for (let i = 0; i < a.length; i++)
734
+ diff |= a[i] ^ b[i];
735
+ return diff === 0;
736
+ }
737
+ function copyBytes(bytes) {
738
+ return Uint8Array.from(bytes);
739
+ }
740
+ function inRange(n, min, max) {
741
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
742
+ }
743
+ function aInRange(title, n, min, max) {
744
+ if (!inRange(n, min, max))
745
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
746
+ }
747
+ function bitLen(n) {
748
+ let len;
749
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
750
+ ;
751
+ return len;
752
+ }
753
+ function isHash(val) {
754
+ return typeof val === "function" && Number.isSafeInteger(val.outputLen);
755
+ }
756
+ function _validateObject(object, fields, optFields = {}) {
757
+ if (!object || typeof object !== "object")
758
+ throw new Error("expected valid options object");
759
+ function checkField(fieldName, expectedType, isOpt) {
760
+ const val = object[fieldName];
761
+ if (isOpt && val === void 0)
762
+ return;
763
+ const current = typeof val;
764
+ if (current !== expectedType || val === null)
765
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
766
+ }
767
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
768
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
769
+ }
770
+ function memoized(fn) {
771
+ const map = /* @__PURE__ */ new WeakMap();
772
+ return (arg, ...args) => {
773
+ const val = map.get(arg);
774
+ if (val !== void 0)
775
+ return val;
776
+ const computed = fn(arg, ...args);
777
+ map.set(arg, computed);
778
+ return computed;
779
+ };
780
+ }
781
+ var _0n, _1n, isPosBig, bitMask, notImplemented;
782
+ var init_utils2 = __esm({
783
+ "node_modules/@noble/curves/esm/utils.js"() {
784
+ "use strict";
785
+ init_utils();
786
+ init_utils();
787
+ _0n = /* @__PURE__ */ BigInt(0);
788
+ _1n = /* @__PURE__ */ BigInt(1);
789
+ isPosBig = (n) => typeof n === "bigint" && _0n <= n;
790
+ bitMask = (n) => (_1n << BigInt(n)) - _1n;
791
+ notImplemented = () => {
792
+ throw new Error("not implemented");
793
+ };
794
+ }
795
+ });
796
+
797
+ // node_modules/@noble/curves/esm/abstract/modular.js
798
+ function mod(a, b) {
799
+ const result = a % b;
800
+ return result >= _0n2 ? result : b + result;
801
+ }
802
+ function pow2(x, power, modulo) {
803
+ let res = x;
804
+ while (power-- > _0n2) {
805
+ res *= res;
806
+ res %= modulo;
807
+ }
808
+ return res;
809
+ }
810
+ function invert(number, modulo) {
811
+ if (number === _0n2)
812
+ throw new Error("invert: expected non-zero number");
813
+ if (modulo <= _0n2)
814
+ throw new Error("invert: expected positive modulus, got " + modulo);
815
+ let a = mod(number, modulo);
816
+ let b = modulo;
817
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
818
+ while (a !== _0n2) {
819
+ const q = b / a;
820
+ const r = b % a;
821
+ const m = x - u * q;
822
+ const n = y - v * q;
823
+ b = a, a = r, x = u, y = v, u = m, v = n;
824
+ }
825
+ const gcd = b;
826
+ if (gcd !== _1n2)
827
+ throw new Error("invert: does not exist");
828
+ return mod(x, modulo);
829
+ }
830
+ function assertIsSquare(Fp2, root, n) {
831
+ if (!Fp2.eql(Fp2.sqr(root), n))
832
+ throw new Error("Cannot find square root");
833
+ }
834
+ function sqrt3mod4(Fp2, n) {
835
+ const p1div4 = (Fp2.ORDER + _1n2) / _4n;
836
+ const root = Fp2.pow(n, p1div4);
837
+ assertIsSquare(Fp2, root, n);
838
+ return root;
839
+ }
840
+ function sqrt5mod8(Fp2, n) {
841
+ const p5div8 = (Fp2.ORDER - _5n) / _8n;
842
+ const n2 = Fp2.mul(n, _2n);
843
+ const v = Fp2.pow(n2, p5div8);
844
+ const nv = Fp2.mul(n, v);
845
+ const i = Fp2.mul(Fp2.mul(nv, _2n), v);
846
+ const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
847
+ assertIsSquare(Fp2, root, n);
848
+ return root;
849
+ }
850
+ function sqrt9mod16(P) {
851
+ const Fp_ = Field(P);
852
+ const tn = tonelliShanks(P);
853
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
854
+ const c2 = tn(Fp_, c1);
855
+ const c3 = tn(Fp_, Fp_.neg(c1));
856
+ const c4 = (P + _7n) / _16n;
857
+ return (Fp2, n) => {
858
+ let tv1 = Fp2.pow(n, c4);
859
+ let tv2 = Fp2.mul(tv1, c1);
860
+ const tv3 = Fp2.mul(tv1, c2);
861
+ const tv4 = Fp2.mul(tv1, c3);
862
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
863
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
864
+ tv1 = Fp2.cmov(tv1, tv2, e1);
865
+ tv2 = Fp2.cmov(tv4, tv3, e2);
866
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
867
+ const root = Fp2.cmov(tv1, tv2, e3);
868
+ assertIsSquare(Fp2, root, n);
869
+ return root;
870
+ };
871
+ }
872
+ function tonelliShanks(P) {
873
+ if (P < _3n)
874
+ throw new Error("sqrt is not defined for small field");
875
+ let Q = P - _1n2;
876
+ let S = 0;
877
+ while (Q % _2n === _0n2) {
878
+ Q /= _2n;
879
+ S++;
880
+ }
881
+ let Z = _2n;
882
+ const _Fp = Field(P);
883
+ while (FpLegendre(_Fp, Z) === 1) {
884
+ if (Z++ > 1e3)
885
+ throw new Error("Cannot find square root: probably non-prime P");
886
+ }
887
+ if (S === 1)
888
+ return sqrt3mod4;
889
+ let cc = _Fp.pow(Z, Q);
890
+ const Q1div2 = (Q + _1n2) / _2n;
891
+ return function tonelliSlow(Fp2, n) {
892
+ if (Fp2.is0(n))
893
+ return n;
894
+ if (FpLegendre(Fp2, n) !== 1)
895
+ throw new Error("Cannot find square root");
896
+ let M = S;
897
+ let c = Fp2.mul(Fp2.ONE, cc);
898
+ let t = Fp2.pow(n, Q);
899
+ let R = Fp2.pow(n, Q1div2);
900
+ while (!Fp2.eql(t, Fp2.ONE)) {
901
+ if (Fp2.is0(t))
902
+ return Fp2.ZERO;
903
+ let i = 1;
904
+ let t_tmp = Fp2.sqr(t);
905
+ while (!Fp2.eql(t_tmp, Fp2.ONE)) {
906
+ i++;
907
+ t_tmp = Fp2.sqr(t_tmp);
908
+ if (i === M)
909
+ throw new Error("Cannot find square root");
910
+ }
911
+ const exponent = _1n2 << BigInt(M - i - 1);
912
+ const b = Fp2.pow(c, exponent);
913
+ M = i;
914
+ c = Fp2.sqr(b);
915
+ t = Fp2.mul(t, c);
916
+ R = Fp2.mul(R, b);
917
+ }
918
+ return R;
919
+ };
920
+ }
921
+ function FpSqrt(P) {
922
+ if (P % _4n === _3n)
923
+ return sqrt3mod4;
924
+ if (P % _8n === _5n)
925
+ return sqrt5mod8;
926
+ if (P % _16n === _9n)
927
+ return sqrt9mod16(P);
928
+ return tonelliShanks(P);
929
+ }
930
+ function validateField(field) {
931
+ const initial = {
932
+ ORDER: "bigint",
933
+ MASK: "bigint",
934
+ BYTES: "number",
935
+ BITS: "number"
936
+ };
937
+ const opts = FIELD_FIELDS.reduce((map, val) => {
938
+ map[val] = "function";
939
+ return map;
940
+ }, initial);
941
+ _validateObject(field, opts);
942
+ return field;
943
+ }
944
+ function FpPow(Fp2, num, power) {
945
+ if (power < _0n2)
946
+ throw new Error("invalid exponent, negatives unsupported");
947
+ if (power === _0n2)
948
+ return Fp2.ONE;
949
+ if (power === _1n2)
950
+ return num;
951
+ let p = Fp2.ONE;
952
+ let d = num;
953
+ while (power > _0n2) {
954
+ if (power & _1n2)
955
+ p = Fp2.mul(p, d);
956
+ d = Fp2.sqr(d);
957
+ power >>= _1n2;
958
+ }
959
+ return p;
960
+ }
961
+ function FpInvertBatch(Fp2, nums, passZero = false) {
962
+ const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
963
+ const multipliedAcc = nums.reduce((acc, num, i) => {
964
+ if (Fp2.is0(num))
965
+ return acc;
966
+ inverted[i] = acc;
967
+ return Fp2.mul(acc, num);
968
+ }, Fp2.ONE);
969
+ const invertedAcc = Fp2.inv(multipliedAcc);
970
+ nums.reduceRight((acc, num, i) => {
971
+ if (Fp2.is0(num))
972
+ return acc;
973
+ inverted[i] = Fp2.mul(acc, inverted[i]);
974
+ return Fp2.mul(acc, num);
975
+ }, invertedAcc);
976
+ return inverted;
977
+ }
978
+ function FpLegendre(Fp2, n) {
979
+ const p1mod2 = (Fp2.ORDER - _1n2) / _2n;
980
+ const powered = Fp2.pow(n, p1mod2);
981
+ const yes = Fp2.eql(powered, Fp2.ONE);
982
+ const zero = Fp2.eql(powered, Fp2.ZERO);
983
+ const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
984
+ if (!yes && !zero && !no)
985
+ throw new Error("invalid Legendre symbol result");
986
+ return yes ? 1 : zero ? 0 : -1;
987
+ }
988
+ function nLength(n, nBitLength) {
989
+ if (nBitLength !== void 0)
990
+ anumber(nBitLength);
991
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
992
+ const nByteLength = Math.ceil(_nBitLength / 8);
993
+ return { nBitLength: _nBitLength, nByteLength };
994
+ }
995
+ function Field(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
996
+ if (ORDER <= _0n2)
997
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
998
+ let _nbitLength = void 0;
999
+ let _sqrt = void 0;
1000
+ let modFromBytes = false;
1001
+ let allowedLengths = void 0;
1002
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
1003
+ if (opts.sqrt || isLE2)
1004
+ throw new Error("cannot specify opts in two arguments");
1005
+ const _opts = bitLenOrOpts;
1006
+ if (_opts.BITS)
1007
+ _nbitLength = _opts.BITS;
1008
+ if (_opts.sqrt)
1009
+ _sqrt = _opts.sqrt;
1010
+ if (typeof _opts.isLE === "boolean")
1011
+ isLE2 = _opts.isLE;
1012
+ if (typeof _opts.modFromBytes === "boolean")
1013
+ modFromBytes = _opts.modFromBytes;
1014
+ allowedLengths = _opts.allowedLengths;
1015
+ } else {
1016
+ if (typeof bitLenOrOpts === "number")
1017
+ _nbitLength = bitLenOrOpts;
1018
+ if (opts.sqrt)
1019
+ _sqrt = opts.sqrt;
1020
+ }
1021
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
1022
+ if (BYTES > 2048)
1023
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1024
+ let sqrtP;
1025
+ const f = Object.freeze({
1026
+ ORDER,
1027
+ isLE: isLE2,
1028
+ BITS,
1029
+ BYTES,
1030
+ MASK: bitMask(BITS),
1031
+ ZERO: _0n2,
1032
+ ONE: _1n2,
1033
+ allowedLengths,
1034
+ create: (num) => mod(num, ORDER),
1035
+ isValid: (num) => {
1036
+ if (typeof num !== "bigint")
1037
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
1038
+ return _0n2 <= num && num < ORDER;
1039
+ },
1040
+ is0: (num) => num === _0n2,
1041
+ // is valid and invertible
1042
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
1043
+ isOdd: (num) => (num & _1n2) === _1n2,
1044
+ neg: (num) => mod(-num, ORDER),
1045
+ eql: (lhs, rhs) => lhs === rhs,
1046
+ sqr: (num) => mod(num * num, ORDER),
1047
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
1048
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
1049
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
1050
+ pow: (num, power) => FpPow(f, num, power),
1051
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
1052
+ // Same as above, but doesn't normalize
1053
+ sqrN: (num) => num * num,
1054
+ addN: (lhs, rhs) => lhs + rhs,
1055
+ subN: (lhs, rhs) => lhs - rhs,
1056
+ mulN: (lhs, rhs) => lhs * rhs,
1057
+ inv: (num) => invert(num, ORDER),
1058
+ sqrt: _sqrt || ((n) => {
1059
+ if (!sqrtP)
1060
+ sqrtP = FpSqrt(ORDER);
1061
+ return sqrtP(f, n);
1062
+ }),
1063
+ toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
1064
+ fromBytes: (bytes, skipValidation = true) => {
1065
+ if (allowedLengths) {
1066
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1067
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1068
+ }
1069
+ const padded = new Uint8Array(BYTES);
1070
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
1071
+ bytes = padded;
1072
+ }
1073
+ if (bytes.length !== BYTES)
1074
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1075
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1076
+ if (modFromBytes)
1077
+ scalar = mod(scalar, ORDER);
1078
+ if (!skipValidation) {
1079
+ if (!f.isValid(scalar))
1080
+ throw new Error("invalid field element: outside of range 0..ORDER");
1081
+ }
1082
+ return scalar;
1083
+ },
1084
+ // TODO: we don't need it here, move out to separate fn
1085
+ invertBatch: (lst) => FpInvertBatch(f, lst),
1086
+ // We can't move this out because Fp6, Fp12 implement it
1087
+ // and it's unclear what to return in there.
1088
+ cmov: (a, b, c) => c ? b : a
1089
+ });
1090
+ return Object.freeze(f);
1091
+ }
1092
+ function FpSqrtEven(Fp2, elm) {
1093
+ if (!Fp2.isOdd)
1094
+ throw new Error("Field doesn't have isOdd");
1095
+ const root = Fp2.sqrt(elm);
1096
+ return Fp2.isOdd(root) ? Fp2.neg(root) : root;
1097
+ }
1098
+ var _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _16n, isNegativeLE, FIELD_FIELDS;
1099
+ var init_modular = __esm({
1100
+ "node_modules/@noble/curves/esm/abstract/modular.js"() {
1101
+ "use strict";
1102
+ init_utils2();
1103
+ _0n2 = BigInt(0);
1104
+ _1n2 = BigInt(1);
1105
+ _2n = /* @__PURE__ */ BigInt(2);
1106
+ _3n = /* @__PURE__ */ BigInt(3);
1107
+ _4n = /* @__PURE__ */ BigInt(4);
1108
+ _5n = /* @__PURE__ */ BigInt(5);
1109
+ _7n = /* @__PURE__ */ BigInt(7);
1110
+ _8n = /* @__PURE__ */ BigInt(8);
1111
+ _9n = /* @__PURE__ */ BigInt(9);
1112
+ _16n = /* @__PURE__ */ BigInt(16);
1113
+ isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
1114
+ FIELD_FIELDS = [
1115
+ "create",
1116
+ "isValid",
1117
+ "is0",
1118
+ "neg",
1119
+ "inv",
1120
+ "sqrt",
1121
+ "sqr",
1122
+ "eql",
1123
+ "add",
1124
+ "sub",
1125
+ "mul",
1126
+ "pow",
1127
+ "div",
1128
+ "addN",
1129
+ "subN",
1130
+ "mulN",
1131
+ "sqrN"
1132
+ ];
1133
+ }
1134
+ });
1135
+
1136
+ // node_modules/@noble/curves/esm/abstract/curve.js
1137
+ function negateCt(condition, item) {
1138
+ const neg = item.negate();
1139
+ return condition ? neg : item;
1140
+ }
1141
+ function normalizeZ(c, points) {
1142
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1143
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1144
+ }
1145
+ function validateW(W, bits) {
1146
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1147
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1148
+ }
1149
+ function calcWOpts(W, scalarBits) {
1150
+ validateW(W, scalarBits);
1151
+ const windows = Math.ceil(scalarBits / W) + 1;
1152
+ const windowSize = 2 ** (W - 1);
1153
+ const maxNumber = 2 ** W;
1154
+ const mask = bitMask(W);
1155
+ const shiftBy = BigInt(W);
1156
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1157
+ }
1158
+ function calcOffsets(n, window, wOpts) {
1159
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1160
+ let wbits = Number(n & mask);
1161
+ let nextN = n >> shiftBy;
1162
+ if (wbits > windowSize) {
1163
+ wbits -= maxNumber;
1164
+ nextN += _1n3;
1165
+ }
1166
+ const offsetStart = window * windowSize;
1167
+ const offset = offsetStart + Math.abs(wbits) - 1;
1168
+ const isZero = wbits === 0;
1169
+ const isNeg = wbits < 0;
1170
+ const isNegF = window % 2 !== 0;
1171
+ const offsetF = offsetStart;
1172
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1173
+ }
1174
+ function validateMSMPoints(points, c) {
1175
+ if (!Array.isArray(points))
1176
+ throw new Error("array expected");
1177
+ points.forEach((p, i) => {
1178
+ if (!(p instanceof c))
1179
+ throw new Error("invalid point at index " + i);
1180
+ });
1181
+ }
1182
+ function validateMSMScalars(scalars, field) {
1183
+ if (!Array.isArray(scalars))
1184
+ throw new Error("array of scalars expected");
1185
+ scalars.forEach((s, i) => {
1186
+ if (!field.isValid(s))
1187
+ throw new Error("invalid scalar at index " + i);
1188
+ });
1189
+ }
1190
+ function getW(P) {
1191
+ return pointWindowSizes.get(P) || 1;
1192
+ }
1193
+ function assert0(n) {
1194
+ if (n !== _0n3)
1195
+ throw new Error("invalid wNAF");
1196
+ }
1197
+ function pippenger(c, fieldN, points, scalars) {
1198
+ validateMSMPoints(points, c);
1199
+ validateMSMScalars(scalars, fieldN);
1200
+ const plength = points.length;
1201
+ const slength = scalars.length;
1202
+ if (plength !== slength)
1203
+ throw new Error("arrays of points and scalars must have equal length");
1204
+ const zero = c.ZERO;
1205
+ const wbits = bitLen(BigInt(plength));
1206
+ let windowSize = 1;
1207
+ if (wbits > 12)
1208
+ windowSize = wbits - 3;
1209
+ else if (wbits > 4)
1210
+ windowSize = wbits - 2;
1211
+ else if (wbits > 0)
1212
+ windowSize = 2;
1213
+ const MASK = bitMask(windowSize);
1214
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
1215
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1216
+ let sum = zero;
1217
+ for (let i = lastBits; i >= 0; i -= windowSize) {
1218
+ buckets.fill(zero);
1219
+ for (let j = 0; j < slength; j++) {
1220
+ const scalar = scalars[j];
1221
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
1222
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
1223
+ }
1224
+ let resI = zero;
1225
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1226
+ sumI = sumI.add(buckets[j]);
1227
+ resI = resI.add(sumI);
1228
+ }
1229
+ sum = sum.add(resI);
1230
+ if (i !== 0)
1231
+ for (let j = 0; j < windowSize; j++)
1232
+ sum = sum.double();
1233
+ }
1234
+ return sum;
1235
+ }
1236
+ function createField(order, field, isLE2) {
1237
+ if (field) {
1238
+ if (field.ORDER !== order)
1239
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1240
+ validateField(field);
1241
+ return field;
1242
+ } else {
1243
+ return Field(order, { isLE: isLE2 });
1244
+ }
1245
+ }
1246
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1247
+ if (FpFnLE === void 0)
1248
+ FpFnLE = type === "edwards";
1249
+ if (!CURVE || typeof CURVE !== "object")
1250
+ throw new Error(`expected valid ${type} CURVE object`);
1251
+ for (const p of ["p", "n", "h"]) {
1252
+ const val = CURVE[p];
1253
+ if (!(typeof val === "bigint" && val > _0n3))
1254
+ throw new Error(`CURVE.${p} must be positive bigint`);
1255
+ }
1256
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1257
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1258
+ const _b = type === "weierstrass" ? "b" : "d";
1259
+ const params = ["Gx", "Gy", "a", _b];
1260
+ for (const p of params) {
1261
+ if (!Fp2.isValid(CURVE[p]))
1262
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1263
+ }
1264
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1265
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
1266
+ }
1267
+ var _0n3, _1n3, pointPrecomputes, pointWindowSizes, wNAF;
1268
+ var init_curve = __esm({
1269
+ "node_modules/@noble/curves/esm/abstract/curve.js"() {
1270
+ "use strict";
1271
+ init_utils2();
1272
+ init_modular();
1273
+ _0n3 = BigInt(0);
1274
+ _1n3 = BigInt(1);
1275
+ pointPrecomputes = /* @__PURE__ */ new WeakMap();
1276
+ pointWindowSizes = /* @__PURE__ */ new WeakMap();
1277
+ wNAF = class {
1278
+ // Parametrized with a given Point class (not individual point)
1279
+ constructor(Point, bits) {
1280
+ this.BASE = Point.BASE;
1281
+ this.ZERO = Point.ZERO;
1282
+ this.Fn = Point.Fn;
1283
+ this.bits = bits;
1284
+ }
1285
+ // non-const time multiplication ladder
1286
+ _unsafeLadder(elm, n, p = this.ZERO) {
1287
+ let d = elm;
1288
+ while (n > _0n3) {
1289
+ if (n & _1n3)
1290
+ p = p.add(d);
1291
+ d = d.double();
1292
+ n >>= _1n3;
1293
+ }
1294
+ return p;
1295
+ }
1296
+ /**
1297
+ * Creates a wNAF precomputation window. Used for caching.
1298
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1299
+ * Number of precomputed points depends on the curve size:
1300
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1301
+ * - 𝑊 is the window size
1302
+ * - 𝑛 is the bitlength of the curve order.
1303
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1304
+ * @param point Point instance
1305
+ * @param W window size
1306
+ * @returns precomputed point tables flattened to a single array
1307
+ */
1308
+ precomputeWindow(point, W) {
1309
+ const { windows, windowSize } = calcWOpts(W, this.bits);
1310
+ const points = [];
1311
+ let p = point;
1312
+ let base = p;
1313
+ for (let window = 0; window < windows; window++) {
1314
+ base = p;
1315
+ points.push(base);
1316
+ for (let i = 1; i < windowSize; i++) {
1317
+ base = base.add(p);
1318
+ points.push(base);
1319
+ }
1320
+ p = base.double();
1321
+ }
1322
+ return points;
1323
+ }
1324
+ /**
1325
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1326
+ * More compact implementation:
1327
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1328
+ * @returns real and fake (for const-time) points
1329
+ */
1330
+ wNAF(W, precomputes, n) {
1331
+ if (!this.Fn.isValid(n))
1332
+ throw new Error("invalid scalar");
1333
+ let p = this.ZERO;
1334
+ let f = this.BASE;
1335
+ const wo = calcWOpts(W, this.bits);
1336
+ for (let window = 0; window < wo.windows; window++) {
1337
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1338
+ n = nextN;
1339
+ if (isZero) {
1340
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
1341
+ } else {
1342
+ p = p.add(negateCt(isNeg, precomputes[offset]));
1343
+ }
1344
+ }
1345
+ assert0(n);
1346
+ return { p, f };
1347
+ }
1348
+ /**
1349
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1350
+ * @param acc accumulator point to add result of multiplication
1351
+ * @returns point
1352
+ */
1353
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1354
+ const wo = calcWOpts(W, this.bits);
1355
+ for (let window = 0; window < wo.windows; window++) {
1356
+ if (n === _0n3)
1357
+ break;
1358
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1359
+ n = nextN;
1360
+ if (isZero) {
1361
+ continue;
1362
+ } else {
1363
+ const item = precomputes[offset];
1364
+ acc = acc.add(isNeg ? item.negate() : item);
1365
+ }
1366
+ }
1367
+ assert0(n);
1368
+ return acc;
1369
+ }
1370
+ getPrecomputes(W, point, transform) {
1371
+ let comp = pointPrecomputes.get(point);
1372
+ if (!comp) {
1373
+ comp = this.precomputeWindow(point, W);
1374
+ if (W !== 1) {
1375
+ if (typeof transform === "function")
1376
+ comp = transform(comp);
1377
+ pointPrecomputes.set(point, comp);
1378
+ }
1379
+ }
1380
+ return comp;
1381
+ }
1382
+ cached(point, scalar, transform) {
1383
+ const W = getW(point);
1384
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1385
+ }
1386
+ unsafe(point, scalar, transform, prev) {
1387
+ const W = getW(point);
1388
+ if (W === 1)
1389
+ return this._unsafeLadder(point, scalar, prev);
1390
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1391
+ }
1392
+ // We calculate precomputes for elliptic curve point multiplication
1393
+ // using windowed method. This specifies window size and
1394
+ // stores precomputed values. Usually only base point would be precomputed.
1395
+ createCache(P, W) {
1396
+ validateW(W, this.bits);
1397
+ pointWindowSizes.set(P, W);
1398
+ pointPrecomputes.delete(P);
1399
+ }
1400
+ hasCache(elm) {
1401
+ return getW(elm) !== 1;
1402
+ }
1403
+ };
1404
+ }
1405
+ });
1406
+
1407
+ // node_modules/@noble/curves/esm/abstract/edwards.js
1408
+ function isEdValidXY(Fp2, CURVE, x, y) {
1409
+ const x2 = Fp2.sqr(x);
1410
+ const y2 = Fp2.sqr(y);
1411
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
1412
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
1413
+ return Fp2.eql(left, right);
1414
+ }
1415
+ function edwards(params, extraOpts = {}) {
1416
+ const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
1417
+ const { Fp: Fp2, Fn: Fn2 } = validated;
1418
+ let CURVE = validated.CURVE;
1419
+ const { h: cofactor } = CURVE;
1420
+ _validateObject(extraOpts, {}, { uvRatio: "function" });
1421
+ const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
1422
+ const modP = (n) => Fp2.create(n);
1423
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
1424
+ try {
1425
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
1426
+ } catch (e) {
1427
+ return { isValid: false, value: _0n4 };
1428
+ }
1429
+ });
1430
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1431
+ throw new Error("bad curve params: generator point");
1432
+ function acoord(title, n, banZero = false) {
1433
+ const min = banZero ? _1n4 : _0n4;
1434
+ aInRange("coordinate " + title, n, min, MASK);
1435
+ return n;
1436
+ }
1437
+ function aextpoint(other) {
1438
+ if (!(other instanceof Point))
1439
+ throw new Error("ExtendedPoint expected");
1440
+ }
1441
+ const toAffineMemo = memoized((p, iz) => {
1442
+ const { X, Y, Z } = p;
1443
+ const is0 = p.is0();
1444
+ if (iz == null)
1445
+ iz = is0 ? _8n2 : Fp2.inv(Z);
1446
+ const x = modP(X * iz);
1447
+ const y = modP(Y * iz);
1448
+ const zz = Fp2.mul(Z, iz);
1449
+ if (is0)
1450
+ return { x: _0n4, y: _1n4 };
1451
+ if (zz !== _1n4)
1452
+ throw new Error("invZ was invalid");
1453
+ return { x, y };
1454
+ });
1455
+ const assertValidMemo = memoized((p) => {
1456
+ const { a, d } = CURVE;
1457
+ if (p.is0())
1458
+ throw new Error("bad point: ZERO");
1459
+ const { X, Y, Z, T } = p;
1460
+ const X2 = modP(X * X);
1461
+ const Y2 = modP(Y * Y);
1462
+ const Z2 = modP(Z * Z);
1463
+ const Z4 = modP(Z2 * Z2);
1464
+ const aX2 = modP(X2 * a);
1465
+ const left = modP(Z2 * modP(aX2 + Y2));
1466
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1467
+ if (left !== right)
1468
+ throw new Error("bad point: equation left != right (1)");
1469
+ const XY = modP(X * Y);
1470
+ const ZT = modP(Z * T);
1471
+ if (XY !== ZT)
1472
+ throw new Error("bad point: equation left != right (2)");
1473
+ return true;
1474
+ });
1475
+ class Point {
1476
+ constructor(X, Y, Z, T) {
1477
+ this.X = acoord("x", X);
1478
+ this.Y = acoord("y", Y);
1479
+ this.Z = acoord("z", Z, true);
1480
+ this.T = acoord("t", T);
1481
+ Object.freeze(this);
1482
+ }
1483
+ static CURVE() {
1484
+ return CURVE;
1485
+ }
1486
+ static fromAffine(p) {
1487
+ if (p instanceof Point)
1488
+ throw new Error("extended point not allowed");
1489
+ const { x, y } = p || {};
1490
+ acoord("x", x);
1491
+ acoord("y", y);
1492
+ return new Point(x, y, _1n4, modP(x * y));
1493
+ }
1494
+ // Uses algo from RFC8032 5.1.3.
1495
+ static fromBytes(bytes, zip215 = false) {
1496
+ const len = Fp2.BYTES;
1497
+ const { a, d } = CURVE;
1498
+ bytes = copyBytes(_abytes2(bytes, len, "point"));
1499
+ _abool2(zip215, "zip215");
1500
+ const normed = copyBytes(bytes);
1501
+ const lastByte = bytes[len - 1];
1502
+ normed[len - 1] = lastByte & ~128;
1503
+ const y = bytesToNumberLE(normed);
1504
+ const max = zip215 ? MASK : Fp2.ORDER;
1505
+ aInRange("point.y", y, _0n4, max);
1506
+ const y2 = modP(y * y);
1507
+ const u = modP(y2 - _1n4);
1508
+ const v = modP(d * y2 - a);
1509
+ let { isValid, value: x } = uvRatio2(u, v);
1510
+ if (!isValid)
1511
+ throw new Error("bad point: invalid y coordinate");
1512
+ const isXOdd = (x & _1n4) === _1n4;
1513
+ const isLastByteOdd = (lastByte & 128) !== 0;
1514
+ if (!zip215 && x === _0n4 && isLastByteOdd)
1515
+ throw new Error("bad point: x=0 and x_0=1");
1516
+ if (isLastByteOdd !== isXOdd)
1517
+ x = modP(-x);
1518
+ return Point.fromAffine({ x, y });
1519
+ }
1520
+ static fromHex(bytes, zip215 = false) {
1521
+ return Point.fromBytes(ensureBytes("point", bytes), zip215);
1522
+ }
1523
+ get x() {
1524
+ return this.toAffine().x;
1525
+ }
1526
+ get y() {
1527
+ return this.toAffine().y;
1528
+ }
1529
+ precompute(windowSize = 8, isLazy = true) {
1530
+ wnaf.createCache(this, windowSize);
1531
+ if (!isLazy)
1532
+ this.multiply(_2n2);
1533
+ return this;
1534
+ }
1535
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
1536
+ assertValidity() {
1537
+ assertValidMemo(this);
1538
+ }
1539
+ // Compare one point to another.
1540
+ equals(other) {
1541
+ aextpoint(other);
1542
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1543
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1544
+ const X1Z2 = modP(X1 * Z2);
1545
+ const X2Z1 = modP(X2 * Z1);
1546
+ const Y1Z2 = modP(Y1 * Z2);
1547
+ const Y2Z1 = modP(Y2 * Z1);
1548
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1549
+ }
1550
+ is0() {
1551
+ return this.equals(Point.ZERO);
1552
+ }
1553
+ negate() {
1554
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1555
+ }
1556
+ // Fast algo for doubling Extended Point.
1557
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1558
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1559
+ double() {
1560
+ const { a } = CURVE;
1561
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1562
+ const A = modP(X1 * X1);
1563
+ const B = modP(Y1 * Y1);
1564
+ const C = modP(_2n2 * modP(Z1 * Z1));
1565
+ const D = modP(a * A);
1566
+ const x1y1 = X1 + Y1;
1567
+ const E = modP(modP(x1y1 * x1y1) - A - B);
1568
+ const G = D + B;
1569
+ const F = G - C;
1570
+ const H = D - B;
1571
+ const X3 = modP(E * F);
1572
+ const Y3 = modP(G * H);
1573
+ const T3 = modP(E * H);
1574
+ const Z3 = modP(F * G);
1575
+ return new Point(X3, Y3, Z3, T3);
1576
+ }
1577
+ // Fast algo for adding 2 Extended Points.
1578
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1579
+ // Cost: 9M + 1*a + 1*d + 7add.
1580
+ add(other) {
1581
+ aextpoint(other);
1582
+ const { a, d } = CURVE;
1583
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1584
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1585
+ const A = modP(X1 * X2);
1586
+ const B = modP(Y1 * Y2);
1587
+ const C = modP(T1 * d * T2);
1588
+ const D = modP(Z1 * Z2);
1589
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1590
+ const F = D - C;
1591
+ const G = D + C;
1592
+ const H = modP(B - a * A);
1593
+ const X3 = modP(E * F);
1594
+ const Y3 = modP(G * H);
1595
+ const T3 = modP(E * H);
1596
+ const Z3 = modP(F * G);
1597
+ return new Point(X3, Y3, Z3, T3);
1598
+ }
1599
+ subtract(other) {
1600
+ return this.add(other.negate());
1601
+ }
1602
+ // Constant-time multiplication.
1603
+ multiply(scalar) {
1604
+ if (!Fn2.isValidNot0(scalar))
1605
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
1606
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1607
+ return normalizeZ(Point, [p, f])[0];
1608
+ }
1609
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1610
+ // It's faster, but should only be used when you don't care about
1611
+ // an exposed private key e.g. sig verification.
1612
+ // Does NOT allow scalars higher than CURVE.n.
1613
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
1614
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
1615
+ if (!Fn2.isValid(scalar))
1616
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
1617
+ if (scalar === _0n4)
1618
+ return Point.ZERO;
1619
+ if (this.is0() || scalar === _1n4)
1620
+ return this;
1621
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
1622
+ }
1623
+ // Checks if point is of small order.
1624
+ // If you add something to small order point, you will have "dirty"
1625
+ // point with torsion component.
1626
+ // Multiplies point by cofactor and checks if the result is 0.
1627
+ isSmallOrder() {
1628
+ return this.multiplyUnsafe(cofactor).is0();
1629
+ }
1630
+ // Multiplies point by curve order and checks if the result is 0.
1631
+ // Returns `false` is the point is dirty.
1632
+ isTorsionFree() {
1633
+ return wnaf.unsafe(this, CURVE.n).is0();
1634
+ }
1635
+ // Converts Extended point to default (x, y) coordinates.
1636
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1637
+ toAffine(invertedZ) {
1638
+ return toAffineMemo(this, invertedZ);
1639
+ }
1640
+ clearCofactor() {
1641
+ if (cofactor === _1n4)
1642
+ return this;
1643
+ return this.multiplyUnsafe(cofactor);
1644
+ }
1645
+ toBytes() {
1646
+ const { x, y } = this.toAffine();
1647
+ const bytes = Fp2.toBytes(y);
1648
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1649
+ return bytes;
1650
+ }
1651
+ toHex() {
1652
+ return bytesToHex(this.toBytes());
1653
+ }
1654
+ toString() {
1655
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1656
+ }
1657
+ // TODO: remove
1658
+ get ex() {
1659
+ return this.X;
1660
+ }
1661
+ get ey() {
1662
+ return this.Y;
1663
+ }
1664
+ get ez() {
1665
+ return this.Z;
1666
+ }
1667
+ get et() {
1668
+ return this.T;
1669
+ }
1670
+ static normalizeZ(points) {
1671
+ return normalizeZ(Point, points);
1672
+ }
1673
+ static msm(points, scalars) {
1674
+ return pippenger(Point, Fn2, points, scalars);
1675
+ }
1676
+ _setWindowSize(windowSize) {
1677
+ this.precompute(windowSize);
1678
+ }
1679
+ toRawBytes() {
1680
+ return this.toBytes();
1681
+ }
1682
+ }
1683
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
1684
+ Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
1685
+ Point.Fp = Fp2;
1686
+ Point.Fn = Fn2;
1687
+ const wnaf = new wNAF(Point, Fn2.BITS);
1688
+ Point.BASE.precompute(8);
1689
+ return Point;
1690
+ }
1691
+ function eddsa(Point, cHash, eddsaOpts = {}) {
1692
+ if (typeof cHash !== "function")
1693
+ throw new Error('"hash" function param is required');
1694
+ _validateObject(eddsaOpts, {}, {
1695
+ adjustScalarBytes: "function",
1696
+ randomBytes: "function",
1697
+ domain: "function",
1698
+ prehash: "function",
1699
+ mapToCurve: "function"
1700
+ });
1701
+ const { prehash } = eddsaOpts;
1702
+ const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
1703
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
1704
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
1705
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
1706
+ _abool2(phflag, "phflag");
1707
+ if (ctx.length || phflag)
1708
+ throw new Error("Contexts/pre-hash are not supported");
1709
+ return data;
1710
+ });
1711
+ function modN_LE(hash) {
1712
+ return Fn2.create(bytesToNumberLE(hash));
1713
+ }
1714
+ function getPrivateScalar(key) {
1715
+ const len = lengths.secretKey;
1716
+ key = ensureBytes("private key", key, len);
1717
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
1718
+ const head = adjustScalarBytes2(hashed.slice(0, len));
1719
+ const prefix = hashed.slice(len, 2 * len);
1720
+ const scalar = modN_LE(head);
1721
+ return { head, prefix, scalar };
1722
+ }
1723
+ function getExtendedPublicKey(secretKey) {
1724
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
1725
+ const point = BASE.multiply(scalar);
1726
+ const pointBytes = point.toBytes();
1727
+ return { head, prefix, scalar, point, pointBytes };
1728
+ }
1729
+ function getPublicKey(secretKey) {
1730
+ return getExtendedPublicKey(secretKey).pointBytes;
1731
+ }
1732
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
1733
+ const msg = concatBytes(...msgs);
1734
+ return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
1735
+ }
1736
+ function sign(msg, secretKey, options = {}) {
1737
+ msg = ensureBytes("message", msg);
1738
+ if (prehash)
1739
+ msg = prehash(msg);
1740
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
1741
+ const r = hashDomainToScalar(options.context, prefix, msg);
1742
+ const R = BASE.multiply(r).toBytes();
1743
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
1744
+ const s = Fn2.create(r + k * scalar);
1745
+ if (!Fn2.isValid(s))
1746
+ throw new Error("sign failed: invalid s");
1747
+ const rs = concatBytes(R, Fn2.toBytes(s));
1748
+ return _abytes2(rs, lengths.signature, "result");
1749
+ }
1750
+ const verifyOpts = { zip215: true };
1751
+ function verify(sig, msg, publicKey, options = verifyOpts) {
1752
+ const { context, zip215 } = options;
1753
+ const len = lengths.signature;
1754
+ sig = ensureBytes("signature", sig, len);
1755
+ msg = ensureBytes("message", msg);
1756
+ publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
1757
+ if (zip215 !== void 0)
1758
+ _abool2(zip215, "zip215");
1759
+ if (prehash)
1760
+ msg = prehash(msg);
1761
+ const mid = len / 2;
1762
+ const r = sig.subarray(0, mid);
1763
+ const s = bytesToNumberLE(sig.subarray(mid, len));
1764
+ let A, R, SB;
1765
+ try {
1766
+ A = Point.fromBytes(publicKey, zip215);
1767
+ R = Point.fromBytes(r, zip215);
1768
+ SB = BASE.multiplyUnsafe(s);
1769
+ } catch (error) {
1770
+ return false;
1771
+ }
1772
+ if (!zip215 && A.isSmallOrder())
1773
+ return false;
1774
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
1775
+ const RkA = R.add(A.multiplyUnsafe(k));
1776
+ return RkA.subtract(SB).clearCofactor().is0();
1777
+ }
1778
+ const _size = Fp2.BYTES;
1779
+ const lengths = {
1780
+ secretKey: _size,
1781
+ publicKey: _size,
1782
+ signature: 2 * _size,
1783
+ seed: _size
1784
+ };
1785
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
1786
+ return _abytes2(seed, lengths.seed, "seed");
1787
+ }
1788
+ function keygen(seed) {
1789
+ const secretKey = utils.randomSecretKey(seed);
1790
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1791
+ }
1792
+ function isValidSecretKey(key) {
1793
+ return isBytes(key) && key.length === Fn2.BYTES;
1794
+ }
1795
+ function isValidPublicKey(key, zip215) {
1796
+ try {
1797
+ return !!Point.fromBytes(key, zip215);
1798
+ } catch (error) {
1799
+ return false;
1800
+ }
1801
+ }
1802
+ const utils = {
1803
+ getExtendedPublicKey,
1804
+ randomSecretKey,
1805
+ isValidSecretKey,
1806
+ isValidPublicKey,
1807
+ /**
1808
+ * Converts ed public key to x public key. Uses formula:
1809
+ * - ed25519:
1810
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
1811
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
1812
+ * - ed448:
1813
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
1814
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
1815
+ */
1816
+ toMontgomery(publicKey) {
1817
+ const { y } = Point.fromBytes(publicKey);
1818
+ const size = lengths.publicKey;
1819
+ const is25519 = size === 32;
1820
+ if (!is25519 && size !== 57)
1821
+ throw new Error("only defined for 25519 and 448");
1822
+ const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
1823
+ return Fp2.toBytes(u);
1824
+ },
1825
+ toMontgomerySecret(secretKey) {
1826
+ const size = lengths.secretKey;
1827
+ _abytes2(secretKey, size);
1828
+ const hashed = cHash(secretKey.subarray(0, size));
1829
+ return adjustScalarBytes2(hashed).subarray(0, size);
1830
+ },
1831
+ /** @deprecated */
1832
+ randomPrivateKey: randomSecretKey,
1833
+ /** @deprecated */
1834
+ precompute(windowSize = 8, point = Point.BASE) {
1835
+ return point.precompute(windowSize, false);
1836
+ }
1837
+ };
1838
+ return Object.freeze({
1839
+ keygen,
1840
+ getPublicKey,
1841
+ sign,
1842
+ verify,
1843
+ utils,
1844
+ Point,
1845
+ lengths
1846
+ });
1847
+ }
1848
+ function _eddsa_legacy_opts_to_new(c) {
1849
+ const CURVE = {
1850
+ a: c.a,
1851
+ d: c.d,
1852
+ p: c.Fp.ORDER,
1853
+ n: c.n,
1854
+ h: c.h,
1855
+ Gx: c.Gx,
1856
+ Gy: c.Gy
1857
+ };
1858
+ const Fp2 = c.Fp;
1859
+ const Fn2 = Field(CURVE.n, c.nBitLength, true);
1860
+ const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
1861
+ const eddsaOpts = {
1862
+ randomBytes: c.randomBytes,
1863
+ adjustScalarBytes: c.adjustScalarBytes,
1864
+ domain: c.domain,
1865
+ prehash: c.prehash,
1866
+ mapToCurve: c.mapToCurve
1867
+ };
1868
+ return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
1869
+ }
1870
+ function _eddsa_new_output_to_legacy(c, eddsa2) {
1871
+ const Point = eddsa2.Point;
1872
+ const legacy = Object.assign({}, eddsa2, {
1873
+ ExtendedPoint: Point,
1874
+ CURVE: c,
1875
+ nBitLength: Point.Fn.BITS,
1876
+ nByteLength: Point.Fn.BYTES
1877
+ });
1878
+ return legacy;
1879
+ }
1880
+ function twistedEdwards(c) {
1881
+ const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
1882
+ const Point = edwards(CURVE, curveOpts);
1883
+ const EDDSA = eddsa(Point, hash, eddsaOpts);
1884
+ return _eddsa_new_output_to_legacy(c, EDDSA);
1885
+ }
1886
+ var _0n4, _1n4, _2n2, _8n2, PrimeEdwardsPoint;
1887
+ var init_edwards = __esm({
1888
+ "node_modules/@noble/curves/esm/abstract/edwards.js"() {
1889
+ "use strict";
1890
+ init_utils2();
1891
+ init_curve();
1892
+ init_modular();
1893
+ _0n4 = BigInt(0);
1894
+ _1n4 = BigInt(1);
1895
+ _2n2 = BigInt(2);
1896
+ _8n2 = BigInt(8);
1897
+ PrimeEdwardsPoint = class {
1898
+ constructor(ep) {
1899
+ this.ep = ep;
1900
+ }
1901
+ // Static methods that must be implemented by subclasses
1902
+ static fromBytes(_bytes) {
1903
+ notImplemented();
1904
+ }
1905
+ static fromHex(_hex) {
1906
+ notImplemented();
1907
+ }
1908
+ get x() {
1909
+ return this.toAffine().x;
1910
+ }
1911
+ get y() {
1912
+ return this.toAffine().y;
1913
+ }
1914
+ // Common implementations
1915
+ clearCofactor() {
1916
+ return this;
1917
+ }
1918
+ assertValidity() {
1919
+ this.ep.assertValidity();
1920
+ }
1921
+ toAffine(invertedZ) {
1922
+ return this.ep.toAffine(invertedZ);
1923
+ }
1924
+ toHex() {
1925
+ return bytesToHex(this.toBytes());
1926
+ }
1927
+ toString() {
1928
+ return this.toHex();
1929
+ }
1930
+ isTorsionFree() {
1931
+ return true;
1932
+ }
1933
+ isSmallOrder() {
1934
+ return false;
1935
+ }
1936
+ add(other) {
1937
+ this.assertSame(other);
1938
+ return this.init(this.ep.add(other.ep));
1939
+ }
1940
+ subtract(other) {
1941
+ this.assertSame(other);
1942
+ return this.init(this.ep.subtract(other.ep));
1943
+ }
1944
+ multiply(scalar) {
1945
+ return this.init(this.ep.multiply(scalar));
1946
+ }
1947
+ multiplyUnsafe(scalar) {
1948
+ return this.init(this.ep.multiplyUnsafe(scalar));
1949
+ }
1950
+ double() {
1951
+ return this.init(this.ep.double());
1952
+ }
1953
+ negate() {
1954
+ return this.init(this.ep.negate());
1955
+ }
1956
+ precompute(windowSize, isLazy) {
1957
+ return this.init(this.ep.precompute(windowSize, isLazy));
1958
+ }
1959
+ /** @deprecated use `toBytes` */
1960
+ toRawBytes() {
1961
+ return this.toBytes();
1962
+ }
1963
+ };
1964
+ }
1965
+ });
1966
+
1967
+ // node_modules/@noble/curves/esm/abstract/hash-to-curve.js
1968
+ function i2osp(value, length) {
1969
+ anum(value);
1970
+ anum(length);
1971
+ if (value < 0 || value >= 1 << 8 * length)
1972
+ throw new Error("invalid I2OSP input: " + value);
1973
+ const res = Array.from({ length }).fill(0);
1974
+ for (let i = length - 1; i >= 0; i--) {
1975
+ res[i] = value & 255;
1976
+ value >>>= 8;
1977
+ }
1978
+ return new Uint8Array(res);
1979
+ }
1980
+ function strxor(a, b) {
1981
+ const arr = new Uint8Array(a.length);
1982
+ for (let i = 0; i < a.length; i++) {
1983
+ arr[i] = a[i] ^ b[i];
1984
+ }
1985
+ return arr;
1986
+ }
1987
+ function anum(item) {
1988
+ if (!Number.isSafeInteger(item))
1989
+ throw new Error("number expected");
1990
+ }
1991
+ function normDST(DST) {
1992
+ if (!isBytes(DST) && typeof DST !== "string")
1993
+ throw new Error("DST must be Uint8Array or string");
1994
+ return typeof DST === "string" ? utf8ToBytes(DST) : DST;
1995
+ }
1996
+ function expand_message_xmd(msg, DST, lenInBytes, H) {
1997
+ abytes(msg);
1998
+ anum(lenInBytes);
1999
+ DST = normDST(DST);
2000
+ if (DST.length > 255)
2001
+ DST = H(concatBytes(utf8ToBytes("H2C-OVERSIZE-DST-"), DST));
2002
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
2003
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
2004
+ if (lenInBytes > 65535 || ell > 255)
2005
+ throw new Error("expand_message_xmd: invalid lenInBytes");
2006
+ const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
2007
+ const Z_pad = i2osp(0, r_in_bytes);
2008
+ const l_i_b_str = i2osp(lenInBytes, 2);
2009
+ const b = new Array(ell);
2010
+ const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
2011
+ b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
2012
+ for (let i = 1; i <= ell; i++) {
2013
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
2014
+ b[i] = H(concatBytes(...args));
2015
+ }
2016
+ const pseudo_random_bytes = concatBytes(...b);
2017
+ return pseudo_random_bytes.slice(0, lenInBytes);
2018
+ }
2019
+ function expand_message_xof(msg, DST, lenInBytes, k, H) {
2020
+ abytes(msg);
2021
+ anum(lenInBytes);
2022
+ DST = normDST(DST);
2023
+ if (DST.length > 255) {
2024
+ const dkLen = Math.ceil(2 * k / 8);
2025
+ DST = H.create({ dkLen }).update(utf8ToBytes("H2C-OVERSIZE-DST-")).update(DST).digest();
2026
+ }
2027
+ if (lenInBytes > 65535 || DST.length > 255)
2028
+ throw new Error("expand_message_xof: invalid lenInBytes");
2029
+ return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
2030
+ }
2031
+ function hash_to_field(msg, count, options) {
2032
+ _validateObject(options, {
2033
+ p: "bigint",
2034
+ m: "number",
2035
+ k: "number",
2036
+ hash: "function"
2037
+ });
2038
+ const { p, k, m, hash, expand, DST } = options;
2039
+ if (!isHash(options.hash))
2040
+ throw new Error("expected valid hash");
2041
+ abytes(msg);
2042
+ anum(count);
2043
+ const log2p = p.toString(2).length;
2044
+ const L = Math.ceil((log2p + k) / 8);
2045
+ const len_in_bytes = count * m * L;
2046
+ let prb;
2047
+ if (expand === "xmd") {
2048
+ prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
2049
+ } else if (expand === "xof") {
2050
+ prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
2051
+ } else if (expand === "_internal_pass") {
2052
+ prb = msg;
2053
+ } else {
2054
+ throw new Error('expand must be "xmd" or "xof"');
2055
+ }
2056
+ const u = new Array(count);
2057
+ for (let i = 0; i < count; i++) {
2058
+ const e = new Array(m);
2059
+ for (let j = 0; j < m; j++) {
2060
+ const elm_offset = L * (j + i * m);
2061
+ const tv = prb.subarray(elm_offset, elm_offset + L);
2062
+ e[j] = mod(os2ip(tv), p);
2063
+ }
2064
+ u[i] = e;
2065
+ }
2066
+ return u;
2067
+ }
2068
+ function createHasher2(Point, mapToCurve, defaults) {
2069
+ if (typeof mapToCurve !== "function")
2070
+ throw new Error("mapToCurve() must be defined");
2071
+ function map(num) {
2072
+ return Point.fromAffine(mapToCurve(num));
2073
+ }
2074
+ function clear(initial) {
2075
+ const P = initial.clearCofactor();
2076
+ if (P.equals(Point.ZERO))
2077
+ return Point.ZERO;
2078
+ P.assertValidity();
2079
+ return P;
2080
+ }
2081
+ return {
2082
+ defaults,
2083
+ hashToCurve(msg, options) {
2084
+ const opts = Object.assign({}, defaults, options);
2085
+ const u = hash_to_field(msg, 2, opts);
2086
+ const u0 = map(u[0]);
2087
+ const u1 = map(u[1]);
2088
+ return clear(u0.add(u1));
2089
+ },
2090
+ encodeToCurve(msg, options) {
2091
+ const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
2092
+ const opts = Object.assign({}, defaults, optsDst, options);
2093
+ const u = hash_to_field(msg, 1, opts);
2094
+ const u0 = map(u[0]);
2095
+ return clear(u0);
2096
+ },
2097
+ /** See {@link H2CHasher} */
2098
+ mapToCurve(scalars) {
2099
+ if (!Array.isArray(scalars))
2100
+ throw new Error("expected array of bigints");
2101
+ for (const i of scalars)
2102
+ if (typeof i !== "bigint")
2103
+ throw new Error("expected array of bigints");
2104
+ return clear(map(scalars));
2105
+ },
2106
+ // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
2107
+ // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
2108
+ hashToScalar(msg, options) {
2109
+ const N = Point.Fn.ORDER;
2110
+ const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
2111
+ return hash_to_field(msg, 1, opts)[0][0];
2112
+ }
2113
+ };
2114
+ }
2115
+ var os2ip, _DST_scalar;
2116
+ var init_hash_to_curve = __esm({
2117
+ "node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() {
2118
+ "use strict";
2119
+ init_utils2();
2120
+ init_modular();
2121
+ os2ip = bytesToNumberBE;
2122
+ _DST_scalar = utf8ToBytes("HashToScalar-");
2123
+ }
2124
+ });
2125
+
2126
+ // node_modules/@noble/curves/esm/abstract/montgomery.js
2127
+ function validateOpts(curve) {
2128
+ _validateObject(curve, {
2129
+ adjustScalarBytes: "function",
2130
+ powPminus2: "function"
2131
+ });
2132
+ return Object.freeze({ ...curve });
2133
+ }
2134
+ function montgomery(curveDef) {
2135
+ const CURVE = validateOpts(curveDef);
2136
+ const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
2137
+ const is25519 = type === "x25519";
2138
+ if (!is25519 && type !== "x448")
2139
+ throw new Error("invalid type");
2140
+ const randomBytes_ = rand || randomBytes;
2141
+ const montgomeryBits = is25519 ? 255 : 448;
2142
+ const fieldLen = is25519 ? 32 : 56;
2143
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
2144
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
2145
+ const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
2146
+ const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
2147
+ const maxScalar = minScalar + maxAdded + _1n5;
2148
+ const modP = (n) => mod(n, P);
2149
+ const GuBytes = encodeU(Gu);
2150
+ function encodeU(u) {
2151
+ return numberToBytesLE(modP(u), fieldLen);
2152
+ }
2153
+ function decodeU(u) {
2154
+ const _u = ensureBytes("u coordinate", u, fieldLen);
2155
+ if (is25519)
2156
+ _u[31] &= 127;
2157
+ return modP(bytesToNumberLE(_u));
2158
+ }
2159
+ function decodeScalar(scalar) {
2160
+ return bytesToNumberLE(adjustScalarBytes2(ensureBytes("scalar", scalar, fieldLen)));
2161
+ }
2162
+ function scalarMult(scalar, u) {
2163
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
2164
+ if (pu === _0n5)
2165
+ throw new Error("invalid private or public key received");
2166
+ return encodeU(pu);
2167
+ }
2168
+ function scalarMultBase(scalar) {
2169
+ return scalarMult(scalar, GuBytes);
2170
+ }
2171
+ function cswap(swap, x_2, x_3) {
2172
+ const dummy = modP(swap * (x_2 - x_3));
2173
+ x_2 = modP(x_2 - dummy);
2174
+ x_3 = modP(x_3 + dummy);
2175
+ return { x_2, x_3 };
2176
+ }
2177
+ function montgomeryLadder(u, scalar) {
2178
+ aInRange("u", u, _0n5, P);
2179
+ aInRange("scalar", scalar, minScalar, maxScalar);
2180
+ const k = scalar;
2181
+ const x_1 = u;
2182
+ let x_2 = _1n5;
2183
+ let z_2 = _0n5;
2184
+ let x_3 = u;
2185
+ let z_3 = _1n5;
2186
+ let swap = _0n5;
2187
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
2188
+ const k_t = k >> t & _1n5;
2189
+ swap ^= k_t;
2190
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
2191
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
2192
+ swap = k_t;
2193
+ const A = x_2 + z_2;
2194
+ const AA = modP(A * A);
2195
+ const B = x_2 - z_2;
2196
+ const BB = modP(B * B);
2197
+ const E = AA - BB;
2198
+ const C = x_3 + z_3;
2199
+ const D = x_3 - z_3;
2200
+ const DA = modP(D * A);
2201
+ const CB = modP(C * B);
2202
+ const dacb = DA + CB;
2203
+ const da_cb = DA - CB;
2204
+ x_3 = modP(dacb * dacb);
2205
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
2206
+ x_2 = modP(AA * BB);
2207
+ z_2 = modP(E * (AA + modP(a24 * E)));
2208
+ }
2209
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
2210
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
2211
+ const z2 = powPminus2(z_2);
2212
+ return modP(x_2 * z2);
2213
+ }
2214
+ const lengths = {
2215
+ secretKey: fieldLen,
2216
+ publicKey: fieldLen,
2217
+ seed: fieldLen
2218
+ };
2219
+ const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
2220
+ abytes(seed, lengths.seed);
2221
+ return seed;
2222
+ };
2223
+ function keygen(seed) {
2224
+ const secretKey = randomSecretKey(seed);
2225
+ return { secretKey, publicKey: scalarMultBase(secretKey) };
2226
+ }
2227
+ const utils = {
2228
+ randomSecretKey,
2229
+ randomPrivateKey: randomSecretKey
2230
+ };
2231
+ return {
2232
+ keygen,
2233
+ getSharedSecret: (secretKey, publicKey) => scalarMult(secretKey, publicKey),
2234
+ getPublicKey: (secretKey) => scalarMultBase(secretKey),
2235
+ scalarMult,
2236
+ scalarMultBase,
2237
+ utils,
2238
+ GuBytes: GuBytes.slice(),
2239
+ lengths
2240
+ };
2241
+ }
2242
+ var _0n5, _1n5, _2n3;
2243
+ var init_montgomery = __esm({
2244
+ "node_modules/@noble/curves/esm/abstract/montgomery.js"() {
2245
+ "use strict";
2246
+ init_utils2();
2247
+ init_modular();
2248
+ _0n5 = BigInt(0);
2249
+ _1n5 = BigInt(1);
2250
+ _2n3 = BigInt(2);
2251
+ }
2252
+ });
2253
+
2254
+ // node_modules/@noble/curves/esm/ed25519.js
2255
+ var ed25519_exports = {};
2256
+ __export(ed25519_exports, {
2257
+ ED25519_TORSION_SUBGROUP: () => ED25519_TORSION_SUBGROUP,
2258
+ RistrettoPoint: () => RistrettoPoint,
2259
+ ed25519: () => ed25519,
2260
+ ed25519_hasher: () => ed25519_hasher,
2261
+ ed25519ctx: () => ed25519ctx,
2262
+ ed25519ph: () => ed25519ph,
2263
+ edwardsToMontgomery: () => edwardsToMontgomery,
2264
+ edwardsToMontgomeryPriv: () => edwardsToMontgomeryPriv,
2265
+ edwardsToMontgomeryPub: () => edwardsToMontgomeryPub,
2266
+ encodeToCurve: () => encodeToCurve,
2267
+ hashToCurve: () => hashToCurve,
2268
+ hashToRistretto255: () => hashToRistretto255,
2269
+ hash_to_ristretto255: () => hash_to_ristretto255,
2270
+ ristretto255: () => ristretto255,
2271
+ ristretto255_hasher: () => ristretto255_hasher,
2272
+ x25519: () => x25519
2273
+ });
2274
+ function ed25519_pow_2_252_3(x) {
2275
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2276
+ const P = ed25519_CURVE_p;
2277
+ const x2 = x * x % P;
2278
+ const b2 = x2 * x % P;
2279
+ const b4 = pow2(b2, _2n4, P) * b2 % P;
2280
+ const b5 = pow2(b4, _1n6, P) * x % P;
2281
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
2282
+ const b20 = pow2(b10, _10n, P) * b10 % P;
2283
+ const b40 = pow2(b20, _20n, P) * b20 % P;
2284
+ const b80 = pow2(b40, _40n, P) * b40 % P;
2285
+ const b160 = pow2(b80, _80n, P) * b80 % P;
2286
+ const b240 = pow2(b160, _80n, P) * b80 % P;
2287
+ const b250 = pow2(b240, _10n, P) * b10 % P;
2288
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
2289
+ return { pow_p_5_8, b2 };
2290
+ }
2291
+ function adjustScalarBytes(bytes) {
2292
+ bytes[0] &= 248;
2293
+ bytes[31] &= 127;
2294
+ bytes[31] |= 64;
2295
+ return bytes;
2296
+ }
2297
+ function uvRatio(u, v) {
2298
+ const P = ed25519_CURVE_p;
2299
+ const v3 = mod(v * v * v, P);
2300
+ const v7 = mod(v3 * v3 * v, P);
2301
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2302
+ let x = mod(u * v3 * pow, P);
2303
+ const vx2 = mod(v * x * x, P);
2304
+ const root1 = x;
2305
+ const root2 = mod(x * ED25519_SQRT_M1, P);
2306
+ const useRoot1 = vx2 === u;
2307
+ const useRoot2 = vx2 === mod(-u, P);
2308
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2309
+ if (useRoot1)
2310
+ x = root1;
2311
+ if (useRoot2 || noRoot)
2312
+ x = root2;
2313
+ if (isNegativeLE(x, P))
2314
+ x = mod(-x, P);
2315
+ return { isValid: useRoot1 || useRoot2, value: x };
2316
+ }
2317
+ function ed25519_domain(data, ctx, phflag) {
2318
+ if (ctx.length > 255)
2319
+ throw new Error("Context is too big");
2320
+ return concatBytes(utf8ToBytes("SigEd25519 no Ed25519 collisions"), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
2321
+ }
2322
+ function map_to_curve_elligator2_curve25519(u) {
2323
+ const ELL2_C4 = (ed25519_CURVE_p - _5n2) / _8n3;
2324
+ const ELL2_J = BigInt(486662);
2325
+ let tv1 = Fp.sqr(u);
2326
+ tv1 = Fp.mul(tv1, _2n4);
2327
+ let xd = Fp.add(tv1, Fp.ONE);
2328
+ let x1n = Fp.neg(ELL2_J);
2329
+ let tv2 = Fp.sqr(xd);
2330
+ let gxd = Fp.mul(tv2, xd);
2331
+ let gx1 = Fp.mul(tv1, ELL2_J);
2332
+ gx1 = Fp.mul(gx1, x1n);
2333
+ gx1 = Fp.add(gx1, tv2);
2334
+ gx1 = Fp.mul(gx1, x1n);
2335
+ let tv3 = Fp.sqr(gxd);
2336
+ tv2 = Fp.sqr(tv3);
2337
+ tv3 = Fp.mul(tv3, gxd);
2338
+ tv3 = Fp.mul(tv3, gx1);
2339
+ tv2 = Fp.mul(tv2, tv3);
2340
+ let y11 = Fp.pow(tv2, ELL2_C4);
2341
+ y11 = Fp.mul(y11, tv3);
2342
+ let y12 = Fp.mul(y11, ELL2_C3);
2343
+ tv2 = Fp.sqr(y11);
2344
+ tv2 = Fp.mul(tv2, gxd);
2345
+ let e1 = Fp.eql(tv2, gx1);
2346
+ let y1 = Fp.cmov(y12, y11, e1);
2347
+ let x2n = Fp.mul(x1n, tv1);
2348
+ let y21 = Fp.mul(y11, u);
2349
+ y21 = Fp.mul(y21, ELL2_C2);
2350
+ let y22 = Fp.mul(y21, ELL2_C3);
2351
+ let gx2 = Fp.mul(gx1, tv1);
2352
+ tv2 = Fp.sqr(y21);
2353
+ tv2 = Fp.mul(tv2, gxd);
2354
+ let e2 = Fp.eql(tv2, gx2);
2355
+ let y2 = Fp.cmov(y22, y21, e2);
2356
+ tv2 = Fp.sqr(y1);
2357
+ tv2 = Fp.mul(tv2, gxd);
2358
+ let e3 = Fp.eql(tv2, gx1);
2359
+ let xn = Fp.cmov(x2n, x1n, e3);
2360
+ let y = Fp.cmov(y2, y1, e3);
2361
+ let e4 = Fp.isOdd(y);
2362
+ y = Fp.cmov(y, Fp.neg(y), e3 !== e4);
2363
+ return { xMn: xn, xMd: xd, yMn: y, yMd: _1n6 };
2364
+ }
2365
+ function map_to_curve_elligator2_edwards25519(u) {
2366
+ const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u);
2367
+ let xn = Fp.mul(xMn, yMd);
2368
+ xn = Fp.mul(xn, ELL2_C1_EDWARDS);
2369
+ let xd = Fp.mul(xMd, yMn);
2370
+ let yn = Fp.sub(xMn, xMd);
2371
+ let yd = Fp.add(xMn, xMd);
2372
+ let tv1 = Fp.mul(xd, yd);
2373
+ let e = Fp.eql(tv1, Fp.ZERO);
2374
+ xn = Fp.cmov(xn, Fp.ZERO, e);
2375
+ xd = Fp.cmov(xd, Fp.ONE, e);
2376
+ yn = Fp.cmov(yn, Fp.ONE, e);
2377
+ yd = Fp.cmov(yd, Fp.ONE, e);
2378
+ const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true);
2379
+ return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) };
2380
+ }
2381
+ function calcElligatorRistrettoMap(r0) {
2382
+ const { d } = ed25519_CURVE;
2383
+ const P = ed25519_CURVE_p;
2384
+ const mod2 = (n) => Fp.create(n);
2385
+ const r = mod2(SQRT_M1 * r0 * r0);
2386
+ const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2387
+ let c = BigInt(-1);
2388
+ const D = mod2((c - d * r) * mod2(r + d));
2389
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2390
+ let s_ = mod2(s * r0);
2391
+ if (!isNegativeLE(s_, P))
2392
+ s_ = mod2(-s_);
2393
+ if (!Ns_D_is_sq)
2394
+ s = s_;
2395
+ if (!Ns_D_is_sq)
2396
+ c = r;
2397
+ const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2398
+ const s2 = s * s;
2399
+ const W0 = mod2((s + s) * D);
2400
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2401
+ const W2 = mod2(_1n6 - s2);
2402
+ const W3 = mod2(_1n6 + s2);
2403
+ return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2404
+ }
2405
+ function ristretto255_map(bytes) {
2406
+ abytes(bytes, 64);
2407
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2408
+ const R1 = calcElligatorRistrettoMap(r1);
2409
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2410
+ const R2 = calcElligatorRistrettoMap(r2);
2411
+ return new _RistrettoPoint(R1.add(R2));
2412
+ }
2413
+ function edwardsToMontgomeryPub(edwardsPub) {
2414
+ return ed25519.utils.toMontgomery(ensureBytes("pub", edwardsPub));
2415
+ }
2416
+ function edwardsToMontgomeryPriv(edwardsPriv) {
2417
+ return ed25519.utils.toMontgomerySecret(ensureBytes("pub", edwardsPriv));
2418
+ }
2419
+ var _0n6, _1n6, _2n4, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, Fp, Fn, ed25519Defaults, ed25519, ed25519ctx, ed25519ph, x25519, ELL2_C1, ELL2_C2, ELL2_C3, ELL2_C1_EDWARDS, ed25519_hasher, SQRT_M1, SQRT_AD_MINUS_ONE, INVSQRT_A_MINUS_D, ONE_MINUS_D_SQ, D_MINUS_ONE_SQ, invertSqrt, MAX_255B, bytes255ToNumberLE, _RistrettoPoint, ristretto255, ristretto255_hasher, ED25519_TORSION_SUBGROUP, edwardsToMontgomery, RistrettoPoint, hashToCurve, encodeToCurve, hashToRistretto255, hash_to_ristretto255;
2420
+ var init_ed25519 = __esm({
2421
+ "node_modules/@noble/curves/esm/ed25519.js"() {
2422
+ "use strict";
2423
+ init_sha2();
2424
+ init_utils();
2425
+ init_curve();
2426
+ init_edwards();
2427
+ init_hash_to_curve();
2428
+ init_modular();
2429
+ init_montgomery();
2430
+ init_utils2();
2431
+ _0n6 = /* @__PURE__ */ BigInt(0);
2432
+ _1n6 = BigInt(1);
2433
+ _2n4 = BigInt(2);
2434
+ _3n2 = BigInt(3);
2435
+ _5n2 = BigInt(5);
2436
+ _8n3 = BigInt(8);
2437
+ ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2438
+ ed25519_CURVE = /* @__PURE__ */ (() => ({
2439
+ p: ed25519_CURVE_p,
2440
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2441
+ h: _8n3,
2442
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2443
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2444
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2445
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2446
+ }))();
2447
+ ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2448
+ Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
2449
+ Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
2450
+ ed25519Defaults = /* @__PURE__ */ (() => ({
2451
+ ...ed25519_CURVE,
2452
+ Fp,
2453
+ hash: sha512,
2454
+ adjustScalarBytes,
2455
+ // dom2
2456
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
2457
+ // Constant-time, u/√v
2458
+ uvRatio
2459
+ }))();
2460
+ ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
2461
+ ed25519ctx = /* @__PURE__ */ (() => twistedEdwards({
2462
+ ...ed25519Defaults,
2463
+ domain: ed25519_domain
2464
+ }))();
2465
+ ed25519ph = /* @__PURE__ */ (() => twistedEdwards(Object.assign({}, ed25519Defaults, {
2466
+ domain: ed25519_domain,
2467
+ prehash: sha512
2468
+ })))();
2469
+ x25519 = /* @__PURE__ */ (() => {
2470
+ const P = Fp.ORDER;
2471
+ return montgomery({
2472
+ P,
2473
+ type: "x25519",
2474
+ powPminus2: (x) => {
2475
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2476
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2477
+ },
2478
+ adjustScalarBytes
2479
+ });
2480
+ })();
2481
+ ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n2) / _8n3)();
2482
+ ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n4, ELL2_C1))();
2483
+ ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))();
2484
+ ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();
2485
+ ed25519_hasher = /* @__PURE__ */ (() => createHasher2(ed25519.Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
2486
+ DST: "edwards25519_XMD:SHA-512_ELL2_RO_",
2487
+ encodeDST: "edwards25519_XMD:SHA-512_ELL2_NU_",
2488
+ p: ed25519_CURVE_p,
2489
+ m: 1,
2490
+ k: 128,
2491
+ expand: "xmd",
2492
+ hash: sha512
2493
+ }))();
2494
+ SQRT_M1 = ED25519_SQRT_M1;
2495
+ SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2496
+ INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2497
+ ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2498
+ D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2499
+ invertSqrt = (number) => uvRatio(_1n6, number);
2500
+ MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2501
+ bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
2502
+ _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2503
+ constructor(ep) {
2504
+ super(ep);
2505
+ }
2506
+ static fromAffine(ap) {
2507
+ return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
2508
+ }
2509
+ assertSame(other) {
2510
+ if (!(other instanceof __RistrettoPoint))
2511
+ throw new Error("RistrettoPoint expected");
2512
+ }
2513
+ init(ep) {
2514
+ return new __RistrettoPoint(ep);
2515
+ }
2516
+ /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
2517
+ static hashToCurve(hex) {
2518
+ return ristretto255_map(ensureBytes("ristrettoHash", hex, 64));
2519
+ }
2520
+ static fromBytes(bytes) {
2521
+ abytes(bytes, 32);
2522
+ const { a, d } = ed25519_CURVE;
2523
+ const P = ed25519_CURVE_p;
2524
+ const mod2 = (n) => Fp.create(n);
2525
+ const s = bytes255ToNumberLE(bytes);
2526
+ if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2527
+ throw new Error("invalid ristretto255 encoding 1");
2528
+ const s2 = mod2(s * s);
2529
+ const u1 = mod2(_1n6 + a * s2);
2530
+ const u2 = mod2(_1n6 - a * s2);
2531
+ const u1_2 = mod2(u1 * u1);
2532
+ const u2_2 = mod2(u2 * u2);
2533
+ const v = mod2(a * d * u1_2 - u2_2);
2534
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2535
+ const Dx = mod2(I * u2);
2536
+ const Dy = mod2(I * Dx * v);
2537
+ let x = mod2((s + s) * Dx);
2538
+ if (isNegativeLE(x, P))
2539
+ x = mod2(-x);
2540
+ const y = mod2(u1 * Dy);
2541
+ const t = mod2(x * y);
2542
+ if (!isValid || isNegativeLE(t, P) || y === _0n6)
2543
+ throw new Error("invalid ristretto255 encoding 2");
2544
+ return new __RistrettoPoint(new ed25519.Point(x, y, _1n6, t));
2545
+ }
2546
+ /**
2547
+ * Converts ristretto-encoded string to ristretto point.
2548
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2549
+ * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2550
+ */
2551
+ static fromHex(hex) {
2552
+ return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex, 32));
2553
+ }
2554
+ static msm(points, scalars) {
2555
+ return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
2556
+ }
2557
+ /**
2558
+ * Encodes ristretto point to Uint8Array.
2559
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2560
+ */
2561
+ toBytes() {
2562
+ let { X, Y, Z, T } = this.ep;
2563
+ const P = ed25519_CURVE_p;
2564
+ const mod2 = (n) => Fp.create(n);
2565
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2566
+ const u2 = mod2(X * Y);
2567
+ const u2sq = mod2(u2 * u2);
2568
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2569
+ const D1 = mod2(invsqrt * u1);
2570
+ const D2 = mod2(invsqrt * u2);
2571
+ const zInv = mod2(D1 * D2 * T);
2572
+ let D;
2573
+ if (isNegativeLE(T * zInv, P)) {
2574
+ let _x = mod2(Y * SQRT_M1);
2575
+ let _y = mod2(X * SQRT_M1);
2576
+ X = _x;
2577
+ Y = _y;
2578
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
2579
+ } else {
2580
+ D = D2;
2581
+ }
2582
+ if (isNegativeLE(X * zInv, P))
2583
+ Y = mod2(-Y);
2584
+ let s = mod2((Z - Y) * D);
2585
+ if (isNegativeLE(s, P))
2586
+ s = mod2(-s);
2587
+ return Fp.toBytes(s);
2588
+ }
2589
+ /**
2590
+ * Compares two Ristretto points.
2591
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2592
+ */
2593
+ equals(other) {
2594
+ this.assertSame(other);
2595
+ const { X: X1, Y: Y1 } = this.ep;
2596
+ const { X: X2, Y: Y2 } = other.ep;
2597
+ const mod2 = (n) => Fp.create(n);
2598
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2599
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2600
+ return one || two;
2601
+ }
2602
+ is0() {
2603
+ return this.equals(__RistrettoPoint.ZERO);
2604
+ }
2605
+ };
2606
+ _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
2607
+ _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
2608
+ _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
2609
+ _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
2610
+ ristretto255 = { Point: _RistrettoPoint };
2611
+ ristretto255_hasher = {
2612
+ hashToCurve(msg, options) {
2613
+ const DST = options?.DST || "ristretto255_XMD:SHA-512_R255MAP_RO_";
2614
+ const xmd = expand_message_xmd(msg, DST, 64, sha512);
2615
+ return ristretto255_map(xmd);
2616
+ },
2617
+ hashToScalar(msg, options = { DST: _DST_scalar }) {
2618
+ const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2619
+ return Fn.create(bytesToNumberLE(xmd));
2620
+ }
2621
+ };
2622
+ ED25519_TORSION_SUBGROUP = [
2623
+ "0100000000000000000000000000000000000000000000000000000000000000",
2624
+ "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
2625
+ "0000000000000000000000000000000000000000000000000000000000000080",
2626
+ "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
2627
+ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
2628
+ "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
2629
+ "0000000000000000000000000000000000000000000000000000000000000000",
2630
+ "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"
2631
+ ];
2632
+ edwardsToMontgomery = edwardsToMontgomeryPub;
2633
+ RistrettoPoint = _RistrettoPoint;
2634
+ hashToCurve = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();
2635
+ encodeToCurve = /* @__PURE__ */ (() => ed25519_hasher.encodeToCurve)();
2636
+ hashToRistretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();
2637
+ hash_to_ristretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();
2638
+ }
2639
+ });
3
2640
 
4
2641
  // src/gateway.ts
5
2642
  var import_node_child_process = require("child_process");
@@ -15,9 +2652,19 @@ function loadPolicy(path) {
15
2652
  if (!parsed.tools || typeof parsed.tools !== "object") {
16
2653
  throw new Error(`Invalid policy file: missing "tools" object in ${path}`);
17
2654
  }
18
- const policy = { tools: parsed.tools };
2655
+ const policy = {
2656
+ tools: parsed.tools,
2657
+ default_tier: parsed.default_tier || "unknown",
2658
+ policy_engine: parsed.policy_engine || "built-in",
2659
+ ...parsed.external ? { external: parsed.external } : {}
2660
+ };
19
2661
  const digest = computePolicyDigest(policy);
20
- return { policy, digest };
2662
+ return {
2663
+ policy,
2664
+ digest,
2665
+ credentials: parsed.credentials,
2666
+ signing: parsed.signing
2667
+ };
21
2668
  }
22
2669
  function computePolicyDigest(policy) {
23
2670
  const canonical = JSON.stringify(sortKeysDeep(policy));
@@ -72,12 +2719,200 @@ function checkRateLimit(key, limit, store) {
72
2719
  return { allowed: true, remaining: limit.count - timestamps.length };
73
2720
  }
74
2721
 
2722
+ // src/admission.ts
2723
+ function evaluateTier(manifest, overrides) {
2724
+ if (!manifest) {
2725
+ return {
2726
+ tier: "unknown",
2727
+ reason: "no_manifest_presented"
2728
+ };
2729
+ }
2730
+ if (overrides && manifest.agent_id && overrides[manifest.agent_id]) {
2731
+ return {
2732
+ tier: overrides[manifest.agent_id],
2733
+ agent_id: manifest.agent_id,
2734
+ manifest_hash: manifest.manifest_hash,
2735
+ reason: "operator_override"
2736
+ };
2737
+ }
2738
+ if (manifest.signature_valid === false) {
2739
+ return {
2740
+ tier: "unknown",
2741
+ agent_id: manifest.agent_id,
2742
+ manifest_hash: manifest.manifest_hash,
2743
+ reason: "invalid_manifest_signature"
2744
+ };
2745
+ }
2746
+ if (manifest.signature_valid === true) {
2747
+ if (manifest.evidence_summary) {
2748
+ const es = manifest.evidence_summary;
2749
+ if (es.receipt_count >= 10 && es.epoch_span >= 3 && es.issuer_count >= 2) {
2750
+ return {
2751
+ tier: "evidenced",
2752
+ agent_id: manifest.agent_id,
2753
+ manifest_hash: manifest.manifest_hash,
2754
+ reason: "evidence_threshold_met"
2755
+ };
2756
+ }
2757
+ }
2758
+ return {
2759
+ tier: "signed-known",
2760
+ agent_id: manifest.agent_id,
2761
+ manifest_hash: manifest.manifest_hash,
2762
+ reason: "valid_signed_manifest"
2763
+ };
2764
+ }
2765
+ return {
2766
+ tier: "unknown",
2767
+ agent_id: manifest.agent_id,
2768
+ manifest_hash: manifest.manifest_hash,
2769
+ reason: "manifest_unverified"
2770
+ };
2771
+ }
2772
+ function meetsMinTier(actual, required) {
2773
+ const order = ["unknown", "signed-known", "evidenced", "privileged"];
2774
+ return order.indexOf(actual) >= order.indexOf(required);
2775
+ }
2776
+
2777
+ // src/credentials.ts
2778
+ function resolveCredential(label, credentials) {
2779
+ if (!credentials || !credentials[label]) {
2780
+ return {
2781
+ resolved: false,
2782
+ label,
2783
+ error: `credential "${label}" not configured`
2784
+ };
2785
+ }
2786
+ const config = credentials[label];
2787
+ const value = process.env[config.value_env];
2788
+ if (!value) {
2789
+ return {
2790
+ resolved: false,
2791
+ label,
2792
+ error: `environment variable "${config.value_env}" for credential "${label}" is not set`
2793
+ };
2794
+ }
2795
+ return {
2796
+ resolved: true,
2797
+ label,
2798
+ value,
2799
+ inject: config.inject,
2800
+ name: config.name
2801
+ };
2802
+ }
2803
+ function validateCredentials(credentials) {
2804
+ const warnings = [];
2805
+ if (!credentials) return warnings;
2806
+ for (const [label, config] of Object.entries(credentials)) {
2807
+ if (!config.value_env) {
2808
+ warnings.push(`credential "${label}": missing value_env`);
2809
+ continue;
2810
+ }
2811
+ if (!config.inject) {
2812
+ warnings.push(`credential "${label}": missing inject type`);
2813
+ continue;
2814
+ }
2815
+ if (!process.env[config.value_env]) {
2816
+ warnings.push(`credential "${label}": env var "${config.value_env}" not set`);
2817
+ }
2818
+ }
2819
+ return warnings;
2820
+ }
2821
+
2822
+ // src/signing.ts
2823
+ var import_node_fs2 = require("fs");
2824
+ var signerState = null;
2825
+ var artifactsModule = null;
2826
+ async function initSigning(config) {
2827
+ const warnings = [];
2828
+ if (!config || config.enabled === false) {
2829
+ return warnings;
2830
+ }
2831
+ try {
2832
+ artifactsModule = await import("@veritasacta/artifacts");
2833
+ } catch {
2834
+ warnings.push("signing: @veritasacta/artifacts not available \u2014 receipts will be unsigned");
2835
+ return warnings;
2836
+ }
2837
+ if (config.key_path) {
2838
+ if (!(0, import_node_fs2.existsSync)(config.key_path)) {
2839
+ warnings.push(`signing: key file not found at ${config.key_path} \u2014 run "protect-mcp init" to generate`);
2840
+ return warnings;
2841
+ }
2842
+ try {
2843
+ const keyData = JSON.parse((0, import_node_fs2.readFileSync)(config.key_path, "utf-8"));
2844
+ if (!keyData.privateKey || !keyData.publicKey) {
2845
+ warnings.push("signing: key file missing privateKey or publicKey fields");
2846
+ return warnings;
2847
+ }
2848
+ signerState = {
2849
+ privateKey: keyData.privateKey,
2850
+ publicKey: keyData.publicKey,
2851
+ kid: artifactsModule.computeKid(keyData.publicKey),
2852
+ issuer: config.issuer || "protect-mcp"
2853
+ };
2854
+ } catch (err) {
2855
+ warnings.push(`signing: failed to load key file: ${err instanceof Error ? err.message : err}`);
2856
+ }
2857
+ }
2858
+ return warnings;
2859
+ }
2860
+ function signDecision(entry) {
2861
+ if (!signerState || !artifactsModule) {
2862
+ return { signed: null, artifact_type: "none" };
2863
+ }
2864
+ const artifactType = entry.decision === "deny" ? "gateway_restraint" : "decision_receipt";
2865
+ try {
2866
+ const payload = {
2867
+ tool: entry.tool,
2868
+ decision: entry.decision,
2869
+ reason_code: entry.reason_code,
2870
+ policy_digest: entry.policy_digest,
2871
+ scope: entry.request_id,
2872
+ // request scope
2873
+ mode: entry.mode,
2874
+ request_id: entry.request_id
2875
+ };
2876
+ if (entry.tier) payload.tier = entry.tier;
2877
+ if (entry.credential_ref) payload.credential_ref = entry.credential_ref;
2878
+ if (entry.rate_limit_remaining !== void 0) {
2879
+ payload.rate_limit_remaining = entry.rate_limit_remaining;
2880
+ }
2881
+ if (entry.policy_engine) payload.policy_engine = entry.policy_engine;
2882
+ const result = artifactsModule.createSignedArtifact(
2883
+ artifactType,
2884
+ payload,
2885
+ signerState.privateKey,
2886
+ {
2887
+ kid: signerState.kid,
2888
+ issuer: signerState.issuer
2889
+ }
2890
+ );
2891
+ return {
2892
+ signed: JSON.stringify(result.artifact),
2893
+ artifact_type: artifactType
2894
+ };
2895
+ } catch (err) {
2896
+ return {
2897
+ signed: null,
2898
+ artifact_type: artifactType,
2899
+ warning: `signing failed: ${err instanceof Error ? err.message : "unknown error"}`
2900
+ };
2901
+ }
2902
+ }
2903
+ function isSigningEnabled() {
2904
+ return signerState !== null && artifactsModule !== null;
2905
+ }
2906
+
75
2907
  // src/gateway.ts
76
2908
  var ProtectGateway = class {
77
2909
  child = null;
78
2910
  config;
79
2911
  rateLimitStore = /* @__PURE__ */ new Map();
80
2912
  clientReader = null;
2913
+ // Trust-tier state for the current session
2914
+ currentTier = "unknown";
2915
+ admissionResult = null;
81
2916
  constructor(config) {
82
2917
  this.config = config;
83
2918
  }
@@ -86,12 +2921,20 @@ var ProtectGateway = class {
86
2921
  */
87
2922
  async start() {
88
2923
  const { command, args, verbose } = this.config;
2924
+ const mode = this.config.enforce ? "enforce" : "shadow";
89
2925
  if (verbose) {
90
- this.log(`Starting gateway in ${this.config.enforce ? "enforce" : "observe"} mode`);
2926
+ this.log(`Starting gateway in ${mode} mode`);
91
2927
  this.log(`Wrapping: ${command} ${args.join(" ")}`);
92
2928
  if (this.config.policy) {
93
2929
  this.log(`Policy digest: ${this.config.policyDigest}`);
94
2930
  }
2931
+ if (isSigningEnabled()) {
2932
+ this.log("Signing: enabled (receipts will be signed)");
2933
+ }
2934
+ if (this.config.credentials) {
2935
+ const labels = Object.keys(this.config.credentials);
2936
+ this.log(`Credential vault: ${labels.length} credential(s) configured [${labels.join(", ")}]`);
2937
+ }
95
2938
  }
96
2939
  this.child = (0, import_node_child_process.spawn)(command, args, {
97
2940
  stdio: ["pipe", "pipe", "pipe"],
@@ -132,6 +2975,18 @@ var ProtectGateway = class {
132
2975
  }
133
2976
  });
134
2977
  }
2978
+ /**
2979
+ * Set the trust tier for this session.
2980
+ * Called at admission (first interaction) or by explicit manifest presentation.
2981
+ */
2982
+ setManifest(manifest) {
2983
+ this.admissionResult = evaluateTier(manifest);
2984
+ this.currentTier = this.admissionResult.tier;
2985
+ if (this.config.verbose) {
2986
+ this.log(`Admission: tier=${this.currentTier} agent=${this.admissionResult.agent_id || "none"} reason=${this.admissionResult.reason}`);
2987
+ }
2988
+ return this.admissionResult;
2989
+ }
135
2990
  /**
136
2991
  * Handle a message from the MCP client (stdin).
137
2992
  * Intercept tools/call requests; pass through everything else.
@@ -169,22 +3024,66 @@ var ProtectGateway = class {
169
3024
  const toolName = request.params?.name || "unknown";
170
3025
  const requestId = (0, import_node_crypto2.randomUUID)().slice(0, 12);
171
3026
  const toolPolicy = getToolPolicy(toolName, this.config.policy);
3027
+ const mode = this.config.enforce ? "enforce" : "shadow";
3028
+ let credentialRef;
3029
+ if (this.config.credentials) {
3030
+ const cred = resolveCredential(toolName, this.config.credentials);
3031
+ if (cred.resolved) {
3032
+ credentialRef = cred.label;
3033
+ } else if (cred.error && !cred.error.includes("not configured")) {
3034
+ this.emitDecisionLog({
3035
+ tool: toolName,
3036
+ decision: "deny",
3037
+ reason_code: "policy_block",
3038
+ request_id: requestId,
3039
+ credential_ref: toolName,
3040
+ tier: this.currentTier
3041
+ });
3042
+ if (this.config.enforce) {
3043
+ this.log(`Credential error for "${toolName}": ${cred.error}`);
3044
+ return this.makeErrorResponse(request.id, -32600, `Credential error for tool "${toolName}"`);
3045
+ }
3046
+ }
3047
+ }
3048
+ if (toolPolicy.min_tier) {
3049
+ if (!meetsMinTier(this.currentTier, toolPolicy.min_tier)) {
3050
+ this.emitDecisionLog({
3051
+ tool: toolName,
3052
+ decision: "deny",
3053
+ reason_code: "tier_insufficient",
3054
+ request_id: requestId,
3055
+ tier: this.currentTier,
3056
+ credential_ref: credentialRef
3057
+ });
3058
+ if (this.config.enforce) {
3059
+ return this.makeErrorResponse(
3060
+ request.id,
3061
+ -32600,
3062
+ `Tool "${toolName}" requires tier "${toolPolicy.min_tier}", agent has "${this.currentTier}"`
3063
+ );
3064
+ }
3065
+ return null;
3066
+ }
3067
+ }
172
3068
  if (toolPolicy.block) {
173
3069
  this.emitDecisionLog({
174
3070
  tool: toolName,
175
3071
  decision: "deny",
176
3072
  reason_code: "policy_block",
177
- request_id: requestId
3073
+ request_id: requestId,
3074
+ tier: this.currentTier,
3075
+ credential_ref: credentialRef
178
3076
  });
179
3077
  if (this.config.enforce) {
180
3078
  return this.makeErrorResponse(request.id, -32600, `Tool "${toolName}" is blocked by policy`);
181
3079
  }
182
3080
  return null;
183
3081
  }
184
- if (toolPolicy.rate_limit) {
3082
+ const rateSpec = this.getTierRateLimit(toolPolicy, this.currentTier);
3083
+ if (rateSpec) {
185
3084
  try {
186
- const limit = parseRateLimit(toolPolicy.rate_limit);
187
- const key = `tool:${toolName}`;
3085
+ const limit = parseRateLimit(rateSpec);
3086
+ const key = `tool:${toolName}:${this.currentTier}`;
188
3087
  const { allowed, remaining } = checkRateLimit(key, limit, this.rateLimitStore);
189
3088
  if (!allowed) {
190
3089
  this.emitDecisionLog({
@@ -192,13 +3091,15 @@ var ProtectGateway = class {
192
3091
  decision: "deny",
193
3092
  reason_code: "rate_limit_exceeded",
194
3093
  request_id: requestId,
195
- rate_limit_remaining: 0
3094
+ rate_limit_remaining: 0,
3095
+ tier: this.currentTier,
3096
+ credential_ref: credentialRef
196
3097
  });
197
3098
  if (this.config.enforce) {
198
3099
  return this.makeErrorResponse(
199
3100
  request.id,
200
3101
  -32600,
201
- `Tool "${toolName}" rate limit exceeded (${toolPolicy.rate_limit})`
3102
+ `Tool "${toolName}" rate limit exceeded (${rateSpec})`
202
3103
  );
203
3104
  }
204
3105
  return null;
@@ -208,14 +3109,18 @@ var ProtectGateway = class {
208
3109
  decision: "allow",
209
3110
  reason_code: "policy_allow",
210
3111
  request_id: requestId,
211
- rate_limit_remaining: remaining
3112
+ rate_limit_remaining: remaining,
3113
+ tier: this.currentTier,
3114
+ credential_ref: credentialRef
212
3115
  });
213
3116
  } catch {
214
3117
  this.emitDecisionLog({
215
3118
  tool: toolName,
216
3119
  decision: "allow",
217
3120
  reason_code: "default_allow",
218
- request_id: requestId
3121
+ request_id: requestId,
3122
+ tier: this.currentTier,
3123
+ credential_ref: credentialRef
219
3124
  });
220
3125
  }
221
3126
  } else {
@@ -224,28 +3129,55 @@ var ProtectGateway = class {
224
3129
  tool: toolName,
225
3130
  decision: "allow",
226
3131
  reason_code: reasonCode,
227
- request_id: requestId
3132
+ request_id: requestId,
3133
+ tier: this.currentTier,
3134
+ credential_ref: credentialRef
228
3135
  });
229
3136
  }
230
3137
  return null;
231
3138
  }
3139
+ /**
3140
+ * Get the applicable rate limit spec based on the agent's tier.
3141
+ */
3142
+ getTierRateLimit(policy, tier) {
3143
+ if (policy.rate_limits && policy.rate_limits[tier]) {
3144
+ const tierLimit = policy.rate_limits[tier];
3145
+ return `${tierLimit.max}/${tierLimit.window}`;
3146
+ }
3147
+ return policy.rate_limit;
3148
+ }
232
3149
  /**
233
3150
  * Emit a structured decision log to stderr.
3151
+ * If signing is enabled, also emits a signed artifact.
234
3152
  */
235
3153
  emitDecisionLog(entry) {
3154
+ const mode = this.config.enforce ? "enforce" : "shadow";
236
3155
  const log = {
237
- v: 1,
3156
+ v: 2,
238
3157
  tool: entry.tool || "unknown",
239
3158
  decision: entry.decision || "allow",
240
3159
  reason_code: entry.reason_code || "default_allow",
241
3160
  policy_digest: this.config.policyDigest,
3161
+ policy_engine: this.config.policy?.policy_engine || "built-in",
242
3162
  request_id: entry.request_id || (0, import_node_crypto2.randomUUID)().slice(0, 12),
243
3163
  timestamp: Date.now(),
244
- mode: this.config.enforce ? "enforce" : "observe",
245
- ...entry.rate_limit_remaining !== void 0 && { rate_limit_remaining: entry.rate_limit_remaining }
3164
+ mode,
3165
+ ...entry.rate_limit_remaining !== void 0 && { rate_limit_remaining: entry.rate_limit_remaining },
3166
+ ...entry.tier && { tier: entry.tier },
3167
+ ...entry.credential_ref && { credential_ref: entry.credential_ref }
246
3168
  };
247
3169
  process.stderr.write(`[PROTECT_MCP] ${JSON.stringify(log)}
248
3170
  `);
3171
+ if (isSigningEnabled()) {
3172
+ const signed = signDecision(log);
3173
+ if (signed.signed) {
3174
+ process.stderr.write(`[PROTECT_MCP_RECEIPT] ${signed.signed}
3175
+ `);
3176
+ } else if (signed.warning) {
3177
+ process.stderr.write(`[PROTECT_MCP] Warning: ${signed.warning}
3178
+ `);
3179
+ }
3180
+ }
249
3181
  }
250
3182
  /**
251
3183
  * Create a JSON-RPC error response.
@@ -296,21 +3228,27 @@ var ProtectGateway = class {
296
3228
  // src/cli.ts
297
3229
  function printHelp() {
298
3230
  process.stderr.write(`
299
- @scopeblind/protect-mcp \u2014 Security gateway for MCP servers
3231
+ protect-mcp \u2014 Shadow-mode security gateway for MCP servers
300
3232
 
301
3233
  Usage:
302
3234
  protect-mcp [options] -- <command> [args...]
3235
+ protect-mcp init [--dir <path>]
303
3236
 
304
3237
  Options:
305
- --policy <path> Policy JSON file (default: allow-all)
3238
+ --policy <path> Policy/config JSON file (default: allow-all)
306
3239
  --slug <slug> ScopeBlind tenant slug (optional)
307
- --enforce Enable enforcement mode (default: observe-only)
3240
+ --enforce Enable enforcement mode (default: shadow mode)
308
3241
  --verbose Enable debug logging to stderr
309
3242
  --help Show this help
310
3243
 
3244
+ Commands:
3245
+ init Generate config template, Ed25519 keypair, and sample policy
3246
+
311
3247
  Examples:
312
3248
  protect-mcp -- node my-server.js
313
- protect-mcp --policy policy.json --enforce -- node my-server.js
3249
+ protect-mcp --policy protect-mcp.json -- node my-server.js
3250
+ protect-mcp --policy protect-mcp.json --enforce -- node my-server.js
3251
+ protect-mcp init
314
3252
 
315
3253
  `);
316
3254
  }
@@ -353,20 +3291,133 @@ function parseArgs(argv) {
353
3291
  }
354
3292
  return { policyPath, slug, enforce, verbose, childCommand };
355
3293
  }
3294
+ async function handleInit(argv) {
3295
+ const { writeFileSync, existsSync: existsSync2, mkdirSync } = await import("fs");
3296
+ const { join } = await import("path");
3297
+ let dir = process.cwd();
3298
+ const dirIdx = argv.indexOf("--dir");
3299
+ if (dirIdx !== -1 && argv[dirIdx + 1]) {
3300
+ dir = argv[dirIdx + 1];
3301
+ }
3302
+ const configPath = join(dir, "protect-mcp.json");
3303
+ const keysDir = join(dir, "keys");
3304
+ const keyPath = join(keysDir, "gateway.json");
3305
+ if (existsSync2(configPath)) {
3306
+ process.stderr.write(`[PROTECT_MCP] Config already exists at ${configPath}
3307
+ `);
3308
+ process.stderr.write("[PROTECT_MCP] Delete it first if you want to regenerate.\n");
3309
+ process.exit(1);
3310
+ }
3311
+ let keypair;
3312
+ try {
3313
+ const artifacts = await import("@veritasacta/artifacts");
3314
+ keypair = artifacts.generateKeypair();
3315
+ } catch {
3316
+ const { randomBytes: randomBytes2 } = await import("crypto");
3317
+ const { ed25519: ed255192 } = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
3318
+ const { bytesToHex: bytesToHex2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));
3319
+ const privateKey = randomBytes2(32);
3320
+ const publicKey = ed255192.getPublicKey(privateKey);
3321
+ keypair = {
3322
+ privateKey: bytesToHex2(privateKey),
3323
+ publicKey: bytesToHex2(publicKey),
3324
+ kid: "generated"
3325
+ };
3326
+ }
3327
+ if (!existsSync2(keysDir)) {
3328
+ mkdirSync(keysDir, { recursive: true });
3329
+ }
3330
+ writeFileSync(keyPath, JSON.stringify({
3331
+ privateKey: keypair.privateKey,
3332
+ publicKey: keypair.publicKey,
3333
+ kid: keypair.kid,
3334
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
3335
+ warning: "KEEP THIS FILE SECRET. Never commit to version control."
3336
+ }, null, 2) + "\n");
3337
+ const gitignorePath = join(keysDir, ".gitignore");
3338
+ if (!existsSync2(gitignorePath)) {
3339
+ writeFileSync(gitignorePath, "# Never commit signing keys\n*.json\n");
3340
+ }
3341
+ const config = {
3342
+ tools: {
3343
+ "*": {
3344
+ rate_limit: "100/hour"
3345
+ },
3346
+ "delete_file": {
3347
+ block: true,
3348
+ min_tier: "privileged"
3349
+ },
3350
+ "write_file": {
3351
+ min_tier: "signed-known",
3352
+ rate_limit: "10/minute"
3353
+ },
3354
+ "read_file": {
3355
+ rate_limit: "50/minute"
3356
+ }
3357
+ },
3358
+ default_tier: "unknown",
3359
+ signing: {
3360
+ key_path: "./keys/gateway.json",
3361
+ issuer: "protect-mcp",
3362
+ enabled: true
3363
+ },
3364
+ credentials: {
3365
+ _example_api: {
3366
+ inject: "header",
3367
+ name: "Authorization",
3368
+ value_env: "EXAMPLE_API_KEY",
3369
+ _comment: "Remove the underscore prefix and set EXAMPLE_API_KEY in your environment"
3370
+ }
3371
+ }
3372
+ };
3373
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
3374
+ process.stderr.write(`
3375
+ ${bold("protect-mcp initialized!")}
3376
+
3377
+ Created:
3378
+ ${configPath} Config with shadow mode + optional local signing
3379
+ ${keyPath} Ed25519 signing keypair
3380
+
3381
+ ${bold("Next steps:")}
3382
+ 1. Edit protect-mcp.json to match your MCP server's tools
3383
+ 2. Set any credential environment variables
3384
+ 3. Run: protect-mcp --policy protect-mcp.json -- <your-mcp-server>
3385
+
3386
+ ${bold("Your gateway public key:")}
3387
+ ${keypair.publicKey}
3388
+
3389
+ ${bold("Key ID (kid):")}
3390
+ ${keypair.kid}
3391
+
3392
+ Shadow mode is the default \u2014 all tool calls are logged and nothing is blocked.
3393
+ Run with the generated policy file if you also want local signed receipts. Add --enforce when ready.
3394
+ `);
3395
+ }
3396
+ function bold(s) {
3397
+ return process.env.NO_COLOR ? s : `\x1B[1m${s}\x1B[0m`;
3398
+ }
356
3399
  async function main() {
357
3400
  const args = process.argv.slice(2);
358
3401
  if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
359
3402
  printHelp();
360
3403
  process.exit(0);
361
3404
  }
3405
+ if (args[0] === "init") {
3406
+ await handleInit(args.slice(1));
3407
+ process.exit(0);
3408
+ }
362
3409
  const { policyPath, slug, enforce, verbose, childCommand } = parseArgs(args);
363
3410
  let policy = null;
364
3411
  let policyDigest = "none";
3412
+ let credentials;
3413
+ let signing;
365
3414
  if (policyPath) {
366
3415
  try {
367
3416
  const loaded = loadPolicy(policyPath);
368
3417
  policy = loaded.policy;
369
3418
  policyDigest = loaded.digest;
3419
+ credentials = loaded.credentials;
3420
+ signing = loaded.signing;
370
3421
  if (verbose) {
371
3422
  process.stderr.write(`[PROTECT_MCP] Loaded policy from ${policyPath} (digest: ${policyDigest})
372
3423
  `);
@@ -377,6 +3428,20 @@ async function main() {
377
3428
  process.exit(1);
378
3429
  }
379
3430
  }
3431
+ if (signing) {
3432
+ const warnings = await initSigning(signing);
3433
+ for (const w of warnings) {
3434
+ process.stderr.write(`[PROTECT_MCP] Warning: ${w}
3435
+ `);
3436
+ }
3437
+ }
3438
+ if (credentials) {
3439
+ const warnings = validateCredentials(credentials);
3440
+ for (const w of warnings) {
3441
+ process.stderr.write(`[PROTECT_MCP] Warning: ${w}
3442
+ `);
3443
+ }
3444
+ }
380
3445
  const config = {
381
3446
  command: childCommand[0],
382
3447
  args: childCommand.slice(1),
@@ -384,7 +3449,9 @@ async function main() {
384
3449
  policyDigest,
385
3450
  slug,
386
3451
  enforce,
387
- verbose
3452
+ verbose,
3453
+ signing,
3454
+ credentials
388
3455
  };
389
3456
  const gateway = new ProtectGateway(config);
390
3457
  await gateway.start();
@@ -394,3 +3461,16 @@ main().catch((err) => {
394
3461
  `);
395
3462
  process.exit(1);
396
3463
  });
3464
+ /*! Bundled license information:
3465
+
3466
+ @noble/hashes/esm/utils.js:
3467
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3468
+
3469
+ @noble/curves/esm/utils.js:
3470
+ @noble/curves/esm/abstract/modular.js:
3471
+ @noble/curves/esm/abstract/curve.js:
3472
+ @noble/curves/esm/abstract/edwards.js:
3473
+ @noble/curves/esm/abstract/montgomery.js:
3474
+ @noble/curves/esm/ed25519.js:
3475
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3476
+ */