protect-mcp 0.6.0 → 0.6.3

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
@@ -21,13 +21,13 @@ var __copyProps = (to, from, except, desc) => {
21
21
  }
22
22
  return to;
23
23
  };
24
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
25
  // If the importer is in node compatibility mode or this is not an ESM
26
26
  // file that has been converted to a CommonJS file using a Babel-
27
27
  // compatible transform (i.e. "__esModule" has not been set), then set
28
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
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
31
  ));
32
32
 
33
33
  // src/policy.ts
@@ -361,9 +361,36 @@ var init_credentials = __esm({
361
361
  // src/signing.ts
362
362
  async function initSigning(config) {
363
363
  const warnings = [];
364
+ signerState = null;
365
+ artifactsModule = null;
366
+ signingConfigured = Boolean(config && config.enabled !== false);
367
+ signingInitError = null;
364
368
  if (!config || config.enabled === false) {
365
369
  return warnings;
366
370
  }
371
+ if (!config.key_path) {
372
+ signingInitError = "signing enabled but key_path is not configured";
373
+ warnings.push(`signing: ${signingInitError}`);
374
+ return warnings;
375
+ }
376
+ if (!(0, import_node_fs3.existsSync)(config.key_path)) {
377
+ signingInitError = `key file not found at ${config.key_path}`;
378
+ warnings.push(`signing: ${signingInitError} \u2014 run "protect-mcp init" to generate`);
379
+ return warnings;
380
+ }
381
+ let keyData;
382
+ try {
383
+ keyData = JSON.parse((0, import_node_fs3.readFileSync)(config.key_path, "utf-8"));
384
+ if (!keyData.privateKey || !keyData.publicKey) {
385
+ signingInitError = "key file missing privateKey or publicKey fields";
386
+ warnings.push(`signing: ${signingInitError}`);
387
+ return warnings;
388
+ }
389
+ } catch (err) {
390
+ signingInitError = `failed to load key file: ${err instanceof Error ? err.message : err}`;
391
+ warnings.push(`signing: ${signingInitError}`);
392
+ return warnings;
393
+ }
367
394
  try {
368
395
  const moduleName = "@veritasacta/artifacts";
369
396
  artifactsModule = await import(
@@ -371,37 +398,48 @@ async function initSigning(config) {
371
398
  moduleName
372
399
  );
373
400
  } catch {
374
- warnings.push("signing: @veritasacta/artifacts not available \u2014 receipts will be unsigned");
401
+ signingInitError = "@veritasacta/artifacts not available";
402
+ warnings.push(`signing: ${signingInitError} \u2014 enforce mode will fail closed`);
375
403
  return warnings;
376
404
  }
377
- if (config.key_path) {
378
- if (!(0, import_node_fs3.existsSync)(config.key_path)) {
379
- warnings.push(`signing: key file not found at ${config.key_path} \u2014 run "protect-mcp init" to generate`);
380
- return warnings;
381
- }
382
- try {
383
- const keyData = JSON.parse((0, import_node_fs3.readFileSync)(config.key_path, "utf-8"));
384
- if (!keyData.privateKey || !keyData.publicKey) {
385
- warnings.push("signing: key file missing privateKey or publicKey fields");
386
- return warnings;
387
- }
388
- signerState = {
389
- privateKey: keyData.privateKey,
390
- publicKey: keyData.publicKey,
391
- kid: keyData.kid || artifactsModule.computeKid(keyData.publicKey),
392
- issuer: config.issuer || keyData.issuer || "protect-mcp"
393
- };
394
- } catch (err) {
395
- warnings.push(`signing: failed to load key file: ${err instanceof Error ? err.message : err}`);
396
- }
405
+ try {
406
+ signerState = {
407
+ privateKey: keyData.privateKey,
408
+ publicKey: keyData.publicKey,
409
+ kid: keyData.kid || artifactsModule.computeKid(keyData.publicKey),
410
+ issuer: config.issuer || keyData.issuer || "protect-mcp"
411
+ };
412
+ } catch (err) {
413
+ signingInitError = `failed to initialize signer: ${err instanceof Error ? err.message : err}`;
414
+ artifactsModule = null;
415
+ warnings.push(`signing: ${signingInitError} \u2014 enforce mode will fail closed`);
397
416
  }
398
417
  return warnings;
399
418
  }
400
419
  function signDecision(entry) {
420
+ const artifactType = entry.decision === "deny" ? "gateway_restraint" : "decision_receipt";
421
+ if (signingConfigured && signingInitError) {
422
+ return {
423
+ ok: false,
424
+ signed: null,
425
+ artifact_type: artifactType,
426
+ warning: `signing initialization failed: ${signingInitError}`,
427
+ error: signingInitError
428
+ };
429
+ }
430
+ if (signingConfigured && (!signerState || !artifactsModule)) {
431
+ const error = "signing was configured but no signer is ready";
432
+ return {
433
+ ok: false,
434
+ signed: null,
435
+ artifact_type: artifactType,
436
+ warning: error,
437
+ error
438
+ };
439
+ }
401
440
  if (!signerState || !artifactsModule) {
402
- return { signed: null, artifact_type: "none" };
441
+ return { ok: false, signed: null, artifact_type: "none" };
403
442
  }
404
- const artifactType = entry.decision === "deny" ? "gateway_restraint" : "decision_receipt";
405
443
  try {
406
444
  const payload = {
407
445
  tool: entry.tool,
@@ -442,14 +480,18 @@ function signDecision(entry) {
442
480
  }
443
481
  );
444
482
  return {
483
+ ok: true,
445
484
  signed: JSON.stringify(result.artifact),
446
485
  artifact_type: artifactType
447
486
  };
448
487
  } catch (err) {
488
+ const message = err instanceof Error ? err.message : "unknown error";
449
489
  return {
490
+ ok: false,
450
491
  signed: null,
451
492
  artifact_type: artifactType,
452
- warning: `signing failed: ${err instanceof Error ? err.message : "unknown error"}`
493
+ warning: `signing failed: ${message}`,
494
+ error: message
453
495
  };
454
496
  }
455
497
  }
@@ -462,15 +504,17 @@ function getSignerInfo() {
462
504
  };
463
505
  }
464
506
  function isSigningEnabled() {
465
- return signerState !== null && artifactsModule !== null;
507
+ return signingConfigured && signingInitError === null && signerState !== null && artifactsModule !== null;
466
508
  }
467
- var import_node_fs3, signerState, artifactsModule;
509
+ var import_node_fs3, signerState, artifactsModule, signingConfigured, signingInitError;
468
510
  var init_signing = __esm({
469
511
  "src/signing.ts"() {
470
512
  "use strict";
471
513
  import_node_fs3 = require("fs");
472
514
  signerState = null;
473
515
  artifactsModule = null;
516
+ signingConfigured = false;
517
+ signingInitError = null;
474
518
  }
475
519
  });
476
520
 
@@ -1639,8 +1683,20 @@ var init_gateway = __esm({
1639
1683
  this.evidenceStore.save();
1640
1684
  }
1641
1685
  }
1642
- } else if (signed.warning) {
1643
- process.stderr.write(`[PROTECT_MCP] Warning: ${signed.warning}
1686
+ } else if (signed.error) {
1687
+ const tombstone = JSON.stringify({
1688
+ type: "scopeblind.signing_failure.v1",
1689
+ request_id: log.request_id,
1690
+ tool: log.tool,
1691
+ decision: log.decision,
1692
+ error: signed.error,
1693
+ at: new Date(log.timestamp).toISOString()
1694
+ });
1695
+ try {
1696
+ (0, import_node_fs6.appendFileSync)(this.receiptFilePath, tombstone + "\n");
1697
+ } catch {
1698
+ }
1699
+ process.stderr.write(`[PROTECT_MCP_SIGNING_FAILURE] ${tombstone}
1644
1700
  `);
1645
1701
  }
1646
1702
  }
@@ -1771,2614 +1827,6 @@ var init_gateway = __esm({
1771
1827
  }
1772
1828
  });
1773
1829
 
1774
- // node_modules/@noble/hashes/esm/cryptoNode.js
1775
- var nc, crypto;
1776
- var init_cryptoNode = __esm({
1777
- "node_modules/@noble/hashes/esm/cryptoNode.js"() {
1778
- "use strict";
1779
- nc = __toESM(require("crypto"), 1);
1780
- crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
1781
- }
1782
- });
1783
-
1784
- // node_modules/@noble/hashes/esm/utils.js
1785
- var utils_exports = {};
1786
- __export(utils_exports, {
1787
- Hash: () => Hash,
1788
- abytes: () => abytes,
1789
- aexists: () => aexists,
1790
- ahash: () => ahash,
1791
- anumber: () => anumber,
1792
- aoutput: () => aoutput,
1793
- asyncLoop: () => asyncLoop,
1794
- byteSwap: () => byteSwap,
1795
- byteSwap32: () => byteSwap32,
1796
- byteSwapIfBE: () => byteSwapIfBE,
1797
- bytesToHex: () => bytesToHex,
1798
- bytesToUtf8: () => bytesToUtf8,
1799
- checkOpts: () => checkOpts,
1800
- clean: () => clean,
1801
- concatBytes: () => concatBytes,
1802
- createHasher: () => createHasher,
1803
- createOptHasher: () => createOptHasher,
1804
- createView: () => createView,
1805
- createXOFer: () => createXOFer,
1806
- hexToBytes: () => hexToBytes,
1807
- isBytes: () => isBytes,
1808
- isLE: () => isLE,
1809
- kdfInputToBytes: () => kdfInputToBytes,
1810
- nextTick: () => nextTick,
1811
- randomBytes: () => randomBytes2,
1812
- rotl: () => rotl,
1813
- rotr: () => rotr,
1814
- swap32IfBE: () => swap32IfBE,
1815
- swap8IfBE: () => swap8IfBE,
1816
- toBytes: () => toBytes,
1817
- u32: () => u32,
1818
- u8: () => u8,
1819
- utf8ToBytes: () => utf8ToBytes,
1820
- wrapConstructor: () => wrapConstructor,
1821
- wrapConstructorWithOpts: () => wrapConstructorWithOpts,
1822
- wrapXOFConstructorWithOpts: () => wrapXOFConstructorWithOpts
1823
- });
1824
- function isBytes(a) {
1825
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1826
- }
1827
- function anumber(n) {
1828
- if (!Number.isSafeInteger(n) || n < 0)
1829
- throw new Error("positive integer expected, got " + n);
1830
- }
1831
- function abytes(b, ...lengths) {
1832
- if (!isBytes(b))
1833
- throw new Error("Uint8Array expected");
1834
- if (lengths.length > 0 && !lengths.includes(b.length))
1835
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
1836
- }
1837
- function ahash(h) {
1838
- if (typeof h !== "function" || typeof h.create !== "function")
1839
- throw new Error("Hash should be wrapped by utils.createHasher");
1840
- anumber(h.outputLen);
1841
- anumber(h.blockLen);
1842
- }
1843
- function aexists(instance, checkFinished = true) {
1844
- if (instance.destroyed)
1845
- throw new Error("Hash instance has been destroyed");
1846
- if (checkFinished && instance.finished)
1847
- throw new Error("Hash#digest() has already been called");
1848
- }
1849
- function aoutput(out, instance) {
1850
- abytes(out);
1851
- const min = instance.outputLen;
1852
- if (out.length < min) {
1853
- throw new Error("digestInto() expects output buffer of length at least " + min);
1854
- }
1855
- }
1856
- function u8(arr) {
1857
- return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
1858
- }
1859
- function u32(arr) {
1860
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
1861
- }
1862
- function clean(...arrays) {
1863
- for (let i = 0; i < arrays.length; i++) {
1864
- arrays[i].fill(0);
1865
- }
1866
- }
1867
- function createView(arr) {
1868
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1869
- }
1870
- function rotr(word, shift) {
1871
- return word << 32 - shift | word >>> shift;
1872
- }
1873
- function rotl(word, shift) {
1874
- return word << shift | word >>> 32 - shift >>> 0;
1875
- }
1876
- function byteSwap(word) {
1877
- return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
1878
- }
1879
- function byteSwap32(arr) {
1880
- for (let i = 0; i < arr.length; i++) {
1881
- arr[i] = byteSwap(arr[i]);
1882
- }
1883
- return arr;
1884
- }
1885
- function bytesToHex(bytes) {
1886
- abytes(bytes);
1887
- if (hasHexBuiltin)
1888
- return bytes.toHex();
1889
- let hex = "";
1890
- for (let i = 0; i < bytes.length; i++) {
1891
- hex += hexes[bytes[i]];
1892
- }
1893
- return hex;
1894
- }
1895
- function asciiToBase16(ch) {
1896
- if (ch >= asciis._0 && ch <= asciis._9)
1897
- return ch - asciis._0;
1898
- if (ch >= asciis.A && ch <= asciis.F)
1899
- return ch - (asciis.A - 10);
1900
- if (ch >= asciis.a && ch <= asciis.f)
1901
- return ch - (asciis.a - 10);
1902
- return;
1903
- }
1904
- function hexToBytes(hex) {
1905
- if (typeof hex !== "string")
1906
- throw new Error("hex string expected, got " + typeof hex);
1907
- if (hasHexBuiltin)
1908
- return Uint8Array.fromHex(hex);
1909
- const hl = hex.length;
1910
- const al = hl / 2;
1911
- if (hl % 2)
1912
- throw new Error("hex string expected, got unpadded hex of length " + hl);
1913
- const array = new Uint8Array(al);
1914
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1915
- const n1 = asciiToBase16(hex.charCodeAt(hi));
1916
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1917
- if (n1 === void 0 || n2 === void 0) {
1918
- const char = hex[hi] + hex[hi + 1];
1919
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1920
- }
1921
- array[ai] = n1 * 16 + n2;
1922
- }
1923
- return array;
1924
- }
1925
- async function asyncLoop(iters, tick, cb) {
1926
- let ts = Date.now();
1927
- for (let i = 0; i < iters; i++) {
1928
- cb(i);
1929
- const diff = Date.now() - ts;
1930
- if (diff >= 0 && diff < tick)
1931
- continue;
1932
- await nextTick();
1933
- ts += diff;
1934
- }
1935
- }
1936
- function utf8ToBytes(str) {
1937
- if (typeof str !== "string")
1938
- throw new Error("string expected");
1939
- return new Uint8Array(new TextEncoder().encode(str));
1940
- }
1941
- function bytesToUtf8(bytes) {
1942
- return new TextDecoder().decode(bytes);
1943
- }
1944
- function toBytes(data) {
1945
- if (typeof data === "string")
1946
- data = utf8ToBytes(data);
1947
- abytes(data);
1948
- return data;
1949
- }
1950
- function kdfInputToBytes(data) {
1951
- if (typeof data === "string")
1952
- data = utf8ToBytes(data);
1953
- abytes(data);
1954
- return data;
1955
- }
1956
- function concatBytes(...arrays) {
1957
- let sum = 0;
1958
- for (let i = 0; i < arrays.length; i++) {
1959
- const a = arrays[i];
1960
- abytes(a);
1961
- sum += a.length;
1962
- }
1963
- const res = new Uint8Array(sum);
1964
- for (let i = 0, pad = 0; i < arrays.length; i++) {
1965
- const a = arrays[i];
1966
- res.set(a, pad);
1967
- pad += a.length;
1968
- }
1969
- return res;
1970
- }
1971
- function checkOpts(defaults, opts) {
1972
- if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
1973
- throw new Error("options should be object or undefined");
1974
- const merged = Object.assign(defaults, opts);
1975
- return merged;
1976
- }
1977
- function createHasher(hashCons) {
1978
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
1979
- const tmp = hashCons();
1980
- hashC.outputLen = tmp.outputLen;
1981
- hashC.blockLen = tmp.blockLen;
1982
- hashC.create = () => hashCons();
1983
- return hashC;
1984
- }
1985
- function createOptHasher(hashCons) {
1986
- const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
1987
- const tmp = hashCons({});
1988
- hashC.outputLen = tmp.outputLen;
1989
- hashC.blockLen = tmp.blockLen;
1990
- hashC.create = (opts) => hashCons(opts);
1991
- return hashC;
1992
- }
1993
- function createXOFer(hashCons) {
1994
- const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
1995
- const tmp = hashCons({});
1996
- hashC.outputLen = tmp.outputLen;
1997
- hashC.blockLen = tmp.blockLen;
1998
- hashC.create = (opts) => hashCons(opts);
1999
- return hashC;
2000
- }
2001
- function randomBytes2(bytesLength = 32) {
2002
- if (crypto && typeof crypto.getRandomValues === "function") {
2003
- return crypto.getRandomValues(new Uint8Array(bytesLength));
2004
- }
2005
- if (crypto && typeof crypto.randomBytes === "function") {
2006
- return Uint8Array.from(crypto.randomBytes(bytesLength));
2007
- }
2008
- throw new Error("crypto.getRandomValues must be defined");
2009
- }
2010
- var isLE, swap8IfBE, byteSwapIfBE, swap32IfBE, hasHexBuiltin, hexes, asciis, nextTick, Hash, wrapConstructor, wrapConstructorWithOpts, wrapXOFConstructorWithOpts;
2011
- var init_utils = __esm({
2012
- "node_modules/@noble/hashes/esm/utils.js"() {
2013
- "use strict";
2014
- init_cryptoNode();
2015
- isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
2016
- swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n);
2017
- byteSwapIfBE = swap8IfBE;
2018
- swap32IfBE = isLE ? (u) => u : byteSwap32;
2019
- hasHexBuiltin = /* @__PURE__ */ (() => (
2020
- // @ts-ignore
2021
- typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
2022
- ))();
2023
- hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
2024
- asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
2025
- nextTick = async () => {
2026
- };
2027
- Hash = class {
2028
- };
2029
- wrapConstructor = createHasher;
2030
- wrapConstructorWithOpts = createOptHasher;
2031
- wrapXOFConstructorWithOpts = createXOFer;
2032
- }
2033
- });
2034
-
2035
- // node_modules/@noble/hashes/esm/_md.js
2036
- function setBigUint64(view, byteOffset, value, isLE2) {
2037
- if (typeof view.setBigUint64 === "function")
2038
- return view.setBigUint64(byteOffset, value, isLE2);
2039
- const _32n2 = BigInt(32);
2040
- const _u32_max = BigInt(4294967295);
2041
- const wh = Number(value >> _32n2 & _u32_max);
2042
- const wl = Number(value & _u32_max);
2043
- const h = isLE2 ? 4 : 0;
2044
- const l = isLE2 ? 0 : 4;
2045
- view.setUint32(byteOffset + h, wh, isLE2);
2046
- view.setUint32(byteOffset + l, wl, isLE2);
2047
- }
2048
- var HashMD, SHA512_IV;
2049
- var init_md = __esm({
2050
- "node_modules/@noble/hashes/esm/_md.js"() {
2051
- "use strict";
2052
- init_utils();
2053
- HashMD = class extends Hash {
2054
- constructor(blockLen, outputLen, padOffset, isLE2) {
2055
- super();
2056
- this.finished = false;
2057
- this.length = 0;
2058
- this.pos = 0;
2059
- this.destroyed = false;
2060
- this.blockLen = blockLen;
2061
- this.outputLen = outputLen;
2062
- this.padOffset = padOffset;
2063
- this.isLE = isLE2;
2064
- this.buffer = new Uint8Array(blockLen);
2065
- this.view = createView(this.buffer);
2066
- }
2067
- update(data) {
2068
- aexists(this);
2069
- data = toBytes(data);
2070
- abytes(data);
2071
- const { view, buffer, blockLen } = this;
2072
- const len = data.length;
2073
- for (let pos = 0; pos < len; ) {
2074
- const take = Math.min(blockLen - this.pos, len - pos);
2075
- if (take === blockLen) {
2076
- const dataView = createView(data);
2077
- for (; blockLen <= len - pos; pos += blockLen)
2078
- this.process(dataView, pos);
2079
- continue;
2080
- }
2081
- buffer.set(data.subarray(pos, pos + take), this.pos);
2082
- this.pos += take;
2083
- pos += take;
2084
- if (this.pos === blockLen) {
2085
- this.process(view, 0);
2086
- this.pos = 0;
2087
- }
2088
- }
2089
- this.length += data.length;
2090
- this.roundClean();
2091
- return this;
2092
- }
2093
- digestInto(out) {
2094
- aexists(this);
2095
- aoutput(out, this);
2096
- this.finished = true;
2097
- const { buffer, view, blockLen, isLE: isLE2 } = this;
2098
- let { pos } = this;
2099
- buffer[pos++] = 128;
2100
- clean(this.buffer.subarray(pos));
2101
- if (this.padOffset > blockLen - pos) {
2102
- this.process(view, 0);
2103
- pos = 0;
2104
- }
2105
- for (let i = pos; i < blockLen; i++)
2106
- buffer[i] = 0;
2107
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
2108
- this.process(view, 0);
2109
- const oview = createView(out);
2110
- const len = this.outputLen;
2111
- if (len % 4)
2112
- throw new Error("_sha2: outputLen should be aligned to 32bit");
2113
- const outLen = len / 4;
2114
- const state = this.get();
2115
- if (outLen > state.length)
2116
- throw new Error("_sha2: outputLen bigger than state");
2117
- for (let i = 0; i < outLen; i++)
2118
- oview.setUint32(4 * i, state[i], isLE2);
2119
- }
2120
- digest() {
2121
- const { buffer, outputLen } = this;
2122
- this.digestInto(buffer);
2123
- const res = buffer.slice(0, outputLen);
2124
- this.destroy();
2125
- return res;
2126
- }
2127
- _cloneInto(to) {
2128
- to || (to = new this.constructor());
2129
- to.set(...this.get());
2130
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
2131
- to.destroyed = destroyed;
2132
- to.finished = finished;
2133
- to.length = length;
2134
- to.pos = pos;
2135
- if (length % blockLen)
2136
- to.buffer.set(buffer);
2137
- return to;
2138
- }
2139
- clone() {
2140
- return this._cloneInto();
2141
- }
2142
- };
2143
- SHA512_IV = /* @__PURE__ */ Uint32Array.from([
2144
- 1779033703,
2145
- 4089235720,
2146
- 3144134277,
2147
- 2227873595,
2148
- 1013904242,
2149
- 4271175723,
2150
- 2773480762,
2151
- 1595750129,
2152
- 1359893119,
2153
- 2917565137,
2154
- 2600822924,
2155
- 725511199,
2156
- 528734635,
2157
- 4215389547,
2158
- 1541459225,
2159
- 327033209
2160
- ]);
2161
- }
2162
- });
2163
-
2164
- // node_modules/@noble/hashes/esm/_u64.js
2165
- function fromBig(n, le = false) {
2166
- if (le)
2167
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
2168
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
2169
- }
2170
- function split(lst, le = false) {
2171
- const len = lst.length;
2172
- let Ah = new Uint32Array(len);
2173
- let Al = new Uint32Array(len);
2174
- for (let i = 0; i < len; i++) {
2175
- const { h, l } = fromBig(lst[i], le);
2176
- [Ah[i], Al[i]] = [h, l];
2177
- }
2178
- return [Ah, Al];
2179
- }
2180
- function add(Ah, Al, Bh, Bl) {
2181
- const l = (Al >>> 0) + (Bl >>> 0);
2182
- return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
2183
- }
2184
- var U32_MASK64, _32n, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, add3L, add3H, add4L, add4H, add5L, add5H;
2185
- var init_u64 = __esm({
2186
- "node_modules/@noble/hashes/esm/_u64.js"() {
2187
- "use strict";
2188
- U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2189
- _32n = /* @__PURE__ */ BigInt(32);
2190
- shrSH = (h, _l, s) => h >>> s;
2191
- shrSL = (h, l, s) => h << 32 - s | l >>> s;
2192
- rotrSH = (h, l, s) => h >>> s | l << 32 - s;
2193
- rotrSL = (h, l, s) => h << 32 - s | l >>> s;
2194
- rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
2195
- rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
2196
- add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
2197
- add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
2198
- add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
2199
- add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
2200
- add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
2201
- add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
2202
- }
2203
- });
2204
-
2205
- // node_modules/@noble/hashes/esm/sha2.js
2206
- var K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, sha512;
2207
- var init_sha2 = __esm({
2208
- "node_modules/@noble/hashes/esm/sha2.js"() {
2209
- "use strict";
2210
- init_md();
2211
- init_u64();
2212
- init_utils();
2213
- K512 = /* @__PURE__ */ (() => split([
2214
- "0x428a2f98d728ae22",
2215
- "0x7137449123ef65cd",
2216
- "0xb5c0fbcfec4d3b2f",
2217
- "0xe9b5dba58189dbbc",
2218
- "0x3956c25bf348b538",
2219
- "0x59f111f1b605d019",
2220
- "0x923f82a4af194f9b",
2221
- "0xab1c5ed5da6d8118",
2222
- "0xd807aa98a3030242",
2223
- "0x12835b0145706fbe",
2224
- "0x243185be4ee4b28c",
2225
- "0x550c7dc3d5ffb4e2",
2226
- "0x72be5d74f27b896f",
2227
- "0x80deb1fe3b1696b1",
2228
- "0x9bdc06a725c71235",
2229
- "0xc19bf174cf692694",
2230
- "0xe49b69c19ef14ad2",
2231
- "0xefbe4786384f25e3",
2232
- "0x0fc19dc68b8cd5b5",
2233
- "0x240ca1cc77ac9c65",
2234
- "0x2de92c6f592b0275",
2235
- "0x4a7484aa6ea6e483",
2236
- "0x5cb0a9dcbd41fbd4",
2237
- "0x76f988da831153b5",
2238
- "0x983e5152ee66dfab",
2239
- "0xa831c66d2db43210",
2240
- "0xb00327c898fb213f",
2241
- "0xbf597fc7beef0ee4",
2242
- "0xc6e00bf33da88fc2",
2243
- "0xd5a79147930aa725",
2244
- "0x06ca6351e003826f",
2245
- "0x142929670a0e6e70",
2246
- "0x27b70a8546d22ffc",
2247
- "0x2e1b21385c26c926",
2248
- "0x4d2c6dfc5ac42aed",
2249
- "0x53380d139d95b3df",
2250
- "0x650a73548baf63de",
2251
- "0x766a0abb3c77b2a8",
2252
- "0x81c2c92e47edaee6",
2253
- "0x92722c851482353b",
2254
- "0xa2bfe8a14cf10364",
2255
- "0xa81a664bbc423001",
2256
- "0xc24b8b70d0f89791",
2257
- "0xc76c51a30654be30",
2258
- "0xd192e819d6ef5218",
2259
- "0xd69906245565a910",
2260
- "0xf40e35855771202a",
2261
- "0x106aa07032bbd1b8",
2262
- "0x19a4c116b8d2d0c8",
2263
- "0x1e376c085141ab53",
2264
- "0x2748774cdf8eeb99",
2265
- "0x34b0bcb5e19b48a8",
2266
- "0x391c0cb3c5c95a63",
2267
- "0x4ed8aa4ae3418acb",
2268
- "0x5b9cca4f7763e373",
2269
- "0x682e6ff3d6b2b8a3",
2270
- "0x748f82ee5defb2fc",
2271
- "0x78a5636f43172f60",
2272
- "0x84c87814a1f0ab72",
2273
- "0x8cc702081a6439ec",
2274
- "0x90befffa23631e28",
2275
- "0xa4506cebde82bde9",
2276
- "0xbef9a3f7b2c67915",
2277
- "0xc67178f2e372532b",
2278
- "0xca273eceea26619c",
2279
- "0xd186b8c721c0c207",
2280
- "0xeada7dd6cde0eb1e",
2281
- "0xf57d4f7fee6ed178",
2282
- "0x06f067aa72176fba",
2283
- "0x0a637dc5a2c898a6",
2284
- "0x113f9804bef90dae",
2285
- "0x1b710b35131c471b",
2286
- "0x28db77f523047d84",
2287
- "0x32caab7b40c72493",
2288
- "0x3c9ebe0a15c9bebc",
2289
- "0x431d67c49c100d4c",
2290
- "0x4cc5d4becb3e42b6",
2291
- "0x597f299cfc657e2a",
2292
- "0x5fcb6fab3ad6faec",
2293
- "0x6c44198c4a475817"
2294
- ].map((n) => BigInt(n))))();
2295
- SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
2296
- SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
2297
- SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
2298
- SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
2299
- SHA512 = class extends HashMD {
2300
- constructor(outputLen = 64) {
2301
- super(128, outputLen, 16, false);
2302
- this.Ah = SHA512_IV[0] | 0;
2303
- this.Al = SHA512_IV[1] | 0;
2304
- this.Bh = SHA512_IV[2] | 0;
2305
- this.Bl = SHA512_IV[3] | 0;
2306
- this.Ch = SHA512_IV[4] | 0;
2307
- this.Cl = SHA512_IV[5] | 0;
2308
- this.Dh = SHA512_IV[6] | 0;
2309
- this.Dl = SHA512_IV[7] | 0;
2310
- this.Eh = SHA512_IV[8] | 0;
2311
- this.El = SHA512_IV[9] | 0;
2312
- this.Fh = SHA512_IV[10] | 0;
2313
- this.Fl = SHA512_IV[11] | 0;
2314
- this.Gh = SHA512_IV[12] | 0;
2315
- this.Gl = SHA512_IV[13] | 0;
2316
- this.Hh = SHA512_IV[14] | 0;
2317
- this.Hl = SHA512_IV[15] | 0;
2318
- }
2319
- // prettier-ignore
2320
- get() {
2321
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
2322
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
2323
- }
2324
- // prettier-ignore
2325
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
2326
- this.Ah = Ah | 0;
2327
- this.Al = Al | 0;
2328
- this.Bh = Bh | 0;
2329
- this.Bl = Bl | 0;
2330
- this.Ch = Ch | 0;
2331
- this.Cl = Cl | 0;
2332
- this.Dh = Dh | 0;
2333
- this.Dl = Dl | 0;
2334
- this.Eh = Eh | 0;
2335
- this.El = El | 0;
2336
- this.Fh = Fh | 0;
2337
- this.Fl = Fl | 0;
2338
- this.Gh = Gh | 0;
2339
- this.Gl = Gl | 0;
2340
- this.Hh = Hh | 0;
2341
- this.Hl = Hl | 0;
2342
- }
2343
- process(view, offset) {
2344
- for (let i = 0; i < 16; i++, offset += 4) {
2345
- SHA512_W_H[i] = view.getUint32(offset);
2346
- SHA512_W_L[i] = view.getUint32(offset += 4);
2347
- }
2348
- for (let i = 16; i < 80; i++) {
2349
- const W15h = SHA512_W_H[i - 15] | 0;
2350
- const W15l = SHA512_W_L[i - 15] | 0;
2351
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
2352
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
2353
- const W2h = SHA512_W_H[i - 2] | 0;
2354
- const W2l = SHA512_W_L[i - 2] | 0;
2355
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
2356
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
2357
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
2358
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
2359
- SHA512_W_H[i] = SUMh | 0;
2360
- SHA512_W_L[i] = SUMl | 0;
2361
- }
2362
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
2363
- for (let i = 0; i < 80; i++) {
2364
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
2365
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
2366
- const CHIh = Eh & Fh ^ ~Eh & Gh;
2367
- const CHIl = El & Fl ^ ~El & Gl;
2368
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
2369
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
2370
- const T1l = T1ll | 0;
2371
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
2372
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
2373
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
2374
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
2375
- Hh = Gh | 0;
2376
- Hl = Gl | 0;
2377
- Gh = Fh | 0;
2378
- Gl = Fl | 0;
2379
- Fh = Eh | 0;
2380
- Fl = El | 0;
2381
- ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
2382
- Dh = Ch | 0;
2383
- Dl = Cl | 0;
2384
- Ch = Bh | 0;
2385
- Cl = Bl | 0;
2386
- Bh = Ah | 0;
2387
- Bl = Al | 0;
2388
- const All = add3L(T1l, sigma0l, MAJl);
2389
- Ah = add3H(All, T1h, sigma0h, MAJh);
2390
- Al = All | 0;
2391
- }
2392
- ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
2393
- ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
2394
- ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
2395
- ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
2396
- ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
2397
- ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
2398
- ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
2399
- ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
2400
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
2401
- }
2402
- roundClean() {
2403
- clean(SHA512_W_H, SHA512_W_L);
2404
- }
2405
- destroy() {
2406
- clean(this.buffer);
2407
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2408
- }
2409
- };
2410
- sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
2411
- }
2412
- });
2413
-
2414
- // node_modules/@noble/curves/esm/utils.js
2415
- function _abool2(value, title = "") {
2416
- if (typeof value !== "boolean") {
2417
- const prefix = title && `"${title}"`;
2418
- throw new Error(prefix + "expected boolean, got type=" + typeof value);
2419
- }
2420
- return value;
2421
- }
2422
- function _abytes2(value, length, title = "") {
2423
- const bytes = isBytes(value);
2424
- const len = value?.length;
2425
- const needsLen = length !== void 0;
2426
- if (!bytes || needsLen && len !== length) {
2427
- const prefix = title && `"${title}" `;
2428
- const ofLen = needsLen ? ` of length ${length}` : "";
2429
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
2430
- throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
2431
- }
2432
- return value;
2433
- }
2434
- function hexToNumber(hex) {
2435
- if (typeof hex !== "string")
2436
- throw new Error("hex string expected, got " + typeof hex);
2437
- return hex === "" ? _0n : BigInt("0x" + hex);
2438
- }
2439
- function bytesToNumberBE(bytes) {
2440
- return hexToNumber(bytesToHex(bytes));
2441
- }
2442
- function bytesToNumberLE(bytes) {
2443
- abytes(bytes);
2444
- return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
2445
- }
2446
- function numberToBytesBE(n, len) {
2447
- return hexToBytes(n.toString(16).padStart(len * 2, "0"));
2448
- }
2449
- function numberToBytesLE(n, len) {
2450
- return numberToBytesBE(n, len).reverse();
2451
- }
2452
- function ensureBytes(title, hex, expectedLength) {
2453
- let res;
2454
- if (typeof hex === "string") {
2455
- try {
2456
- res = hexToBytes(hex);
2457
- } catch (e) {
2458
- throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
2459
- }
2460
- } else if (isBytes(hex)) {
2461
- res = Uint8Array.from(hex);
2462
- } else {
2463
- throw new Error(title + " must be hex string or Uint8Array");
2464
- }
2465
- const len = res.length;
2466
- if (typeof expectedLength === "number" && len !== expectedLength)
2467
- throw new Error(title + " of length " + expectedLength + " expected, got " + len);
2468
- return res;
2469
- }
2470
- function equalBytes(a, b) {
2471
- if (a.length !== b.length)
2472
- return false;
2473
- let diff = 0;
2474
- for (let i = 0; i < a.length; i++)
2475
- diff |= a[i] ^ b[i];
2476
- return diff === 0;
2477
- }
2478
- function copyBytes(bytes) {
2479
- return Uint8Array.from(bytes);
2480
- }
2481
- function inRange(n, min, max) {
2482
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
2483
- }
2484
- function aInRange(title, n, min, max) {
2485
- if (!inRange(n, min, max))
2486
- throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
2487
- }
2488
- function bitLen(n) {
2489
- let len;
2490
- for (len = 0; n > _0n; n >>= _1n, len += 1)
2491
- ;
2492
- return len;
2493
- }
2494
- function isHash(val) {
2495
- return typeof val === "function" && Number.isSafeInteger(val.outputLen);
2496
- }
2497
- function _validateObject(object, fields, optFields = {}) {
2498
- if (!object || typeof object !== "object")
2499
- throw new Error("expected valid options object");
2500
- function checkField(fieldName, expectedType, isOpt) {
2501
- const val = object[fieldName];
2502
- if (isOpt && val === void 0)
2503
- return;
2504
- const current = typeof val;
2505
- if (current !== expectedType || val === null)
2506
- throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
2507
- }
2508
- Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
2509
- Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
2510
- }
2511
- function memoized(fn) {
2512
- const map = /* @__PURE__ */ new WeakMap();
2513
- return (arg, ...args) => {
2514
- const val = map.get(arg);
2515
- if (val !== void 0)
2516
- return val;
2517
- const computed = fn(arg, ...args);
2518
- map.set(arg, computed);
2519
- return computed;
2520
- };
2521
- }
2522
- var _0n, _1n, isPosBig, bitMask, notImplemented;
2523
- var init_utils2 = __esm({
2524
- "node_modules/@noble/curves/esm/utils.js"() {
2525
- "use strict";
2526
- init_utils();
2527
- init_utils();
2528
- _0n = /* @__PURE__ */ BigInt(0);
2529
- _1n = /* @__PURE__ */ BigInt(1);
2530
- isPosBig = (n) => typeof n === "bigint" && _0n <= n;
2531
- bitMask = (n) => (_1n << BigInt(n)) - _1n;
2532
- notImplemented = () => {
2533
- throw new Error("not implemented");
2534
- };
2535
- }
2536
- });
2537
-
2538
- // node_modules/@noble/curves/esm/abstract/modular.js
2539
- function mod(a, b) {
2540
- const result = a % b;
2541
- return result >= _0n2 ? result : b + result;
2542
- }
2543
- function pow2(x, power, modulo) {
2544
- let res = x;
2545
- while (power-- > _0n2) {
2546
- res *= res;
2547
- res %= modulo;
2548
- }
2549
- return res;
2550
- }
2551
- function invert(number, modulo) {
2552
- if (number === _0n2)
2553
- throw new Error("invert: expected non-zero number");
2554
- if (modulo <= _0n2)
2555
- throw new Error("invert: expected positive modulus, got " + modulo);
2556
- let a = mod(number, modulo);
2557
- let b = modulo;
2558
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
2559
- while (a !== _0n2) {
2560
- const q = b / a;
2561
- const r = b % a;
2562
- const m = x - u * q;
2563
- const n = y - v * q;
2564
- b = a, a = r, x = u, y = v, u = m, v = n;
2565
- }
2566
- const gcd = b;
2567
- if (gcd !== _1n2)
2568
- throw new Error("invert: does not exist");
2569
- return mod(x, modulo);
2570
- }
2571
- function assertIsSquare(Fp2, root, n) {
2572
- if (!Fp2.eql(Fp2.sqr(root), n))
2573
- throw new Error("Cannot find square root");
2574
- }
2575
- function sqrt3mod4(Fp2, n) {
2576
- const p1div4 = (Fp2.ORDER + _1n2) / _4n;
2577
- const root = Fp2.pow(n, p1div4);
2578
- assertIsSquare(Fp2, root, n);
2579
- return root;
2580
- }
2581
- function sqrt5mod8(Fp2, n) {
2582
- const p5div8 = (Fp2.ORDER - _5n) / _8n;
2583
- const n2 = Fp2.mul(n, _2n);
2584
- const v = Fp2.pow(n2, p5div8);
2585
- const nv = Fp2.mul(n, v);
2586
- const i = Fp2.mul(Fp2.mul(nv, _2n), v);
2587
- const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
2588
- assertIsSquare(Fp2, root, n);
2589
- return root;
2590
- }
2591
- function sqrt9mod16(P) {
2592
- const Fp_ = Field(P);
2593
- const tn = tonelliShanks(P);
2594
- const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
2595
- const c2 = tn(Fp_, c1);
2596
- const c3 = tn(Fp_, Fp_.neg(c1));
2597
- const c4 = (P + _7n) / _16n;
2598
- return (Fp2, n) => {
2599
- let tv1 = Fp2.pow(n, c4);
2600
- let tv2 = Fp2.mul(tv1, c1);
2601
- const tv3 = Fp2.mul(tv1, c2);
2602
- const tv4 = Fp2.mul(tv1, c3);
2603
- const e1 = Fp2.eql(Fp2.sqr(tv2), n);
2604
- const e2 = Fp2.eql(Fp2.sqr(tv3), n);
2605
- tv1 = Fp2.cmov(tv1, tv2, e1);
2606
- tv2 = Fp2.cmov(tv4, tv3, e2);
2607
- const e3 = Fp2.eql(Fp2.sqr(tv2), n);
2608
- const root = Fp2.cmov(tv1, tv2, e3);
2609
- assertIsSquare(Fp2, root, n);
2610
- return root;
2611
- };
2612
- }
2613
- function tonelliShanks(P) {
2614
- if (P < _3n)
2615
- throw new Error("sqrt is not defined for small field");
2616
- let Q = P - _1n2;
2617
- let S = 0;
2618
- while (Q % _2n === _0n2) {
2619
- Q /= _2n;
2620
- S++;
2621
- }
2622
- let Z = _2n;
2623
- const _Fp = Field(P);
2624
- while (FpLegendre(_Fp, Z) === 1) {
2625
- if (Z++ > 1e3)
2626
- throw new Error("Cannot find square root: probably non-prime P");
2627
- }
2628
- if (S === 1)
2629
- return sqrt3mod4;
2630
- let cc = _Fp.pow(Z, Q);
2631
- const Q1div2 = (Q + _1n2) / _2n;
2632
- return function tonelliSlow(Fp2, n) {
2633
- if (Fp2.is0(n))
2634
- return n;
2635
- if (FpLegendre(Fp2, n) !== 1)
2636
- throw new Error("Cannot find square root");
2637
- let M = S;
2638
- let c = Fp2.mul(Fp2.ONE, cc);
2639
- let t = Fp2.pow(n, Q);
2640
- let R = Fp2.pow(n, Q1div2);
2641
- while (!Fp2.eql(t, Fp2.ONE)) {
2642
- if (Fp2.is0(t))
2643
- return Fp2.ZERO;
2644
- let i = 1;
2645
- let t_tmp = Fp2.sqr(t);
2646
- while (!Fp2.eql(t_tmp, Fp2.ONE)) {
2647
- i++;
2648
- t_tmp = Fp2.sqr(t_tmp);
2649
- if (i === M)
2650
- throw new Error("Cannot find square root");
2651
- }
2652
- const exponent = _1n2 << BigInt(M - i - 1);
2653
- const b = Fp2.pow(c, exponent);
2654
- M = i;
2655
- c = Fp2.sqr(b);
2656
- t = Fp2.mul(t, c);
2657
- R = Fp2.mul(R, b);
2658
- }
2659
- return R;
2660
- };
2661
- }
2662
- function FpSqrt(P) {
2663
- if (P % _4n === _3n)
2664
- return sqrt3mod4;
2665
- if (P % _8n === _5n)
2666
- return sqrt5mod8;
2667
- if (P % _16n === _9n)
2668
- return sqrt9mod16(P);
2669
- return tonelliShanks(P);
2670
- }
2671
- function validateField(field) {
2672
- const initial = {
2673
- ORDER: "bigint",
2674
- MASK: "bigint",
2675
- BYTES: "number",
2676
- BITS: "number"
2677
- };
2678
- const opts = FIELD_FIELDS.reduce((map, val) => {
2679
- map[val] = "function";
2680
- return map;
2681
- }, initial);
2682
- _validateObject(field, opts);
2683
- return field;
2684
- }
2685
- function FpPow(Fp2, num, power) {
2686
- if (power < _0n2)
2687
- throw new Error("invalid exponent, negatives unsupported");
2688
- if (power === _0n2)
2689
- return Fp2.ONE;
2690
- if (power === _1n2)
2691
- return num;
2692
- let p = Fp2.ONE;
2693
- let d = num;
2694
- while (power > _0n2) {
2695
- if (power & _1n2)
2696
- p = Fp2.mul(p, d);
2697
- d = Fp2.sqr(d);
2698
- power >>= _1n2;
2699
- }
2700
- return p;
2701
- }
2702
- function FpInvertBatch(Fp2, nums, passZero = false) {
2703
- const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
2704
- const multipliedAcc = nums.reduce((acc, num, i) => {
2705
- if (Fp2.is0(num))
2706
- return acc;
2707
- inverted[i] = acc;
2708
- return Fp2.mul(acc, num);
2709
- }, Fp2.ONE);
2710
- const invertedAcc = Fp2.inv(multipliedAcc);
2711
- nums.reduceRight((acc, num, i) => {
2712
- if (Fp2.is0(num))
2713
- return acc;
2714
- inverted[i] = Fp2.mul(acc, inverted[i]);
2715
- return Fp2.mul(acc, num);
2716
- }, invertedAcc);
2717
- return inverted;
2718
- }
2719
- function FpLegendre(Fp2, n) {
2720
- const p1mod2 = (Fp2.ORDER - _1n2) / _2n;
2721
- const powered = Fp2.pow(n, p1mod2);
2722
- const yes = Fp2.eql(powered, Fp2.ONE);
2723
- const zero = Fp2.eql(powered, Fp2.ZERO);
2724
- const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
2725
- if (!yes && !zero && !no)
2726
- throw new Error("invalid Legendre symbol result");
2727
- return yes ? 1 : zero ? 0 : -1;
2728
- }
2729
- function nLength(n, nBitLength) {
2730
- if (nBitLength !== void 0)
2731
- anumber(nBitLength);
2732
- const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
2733
- const nByteLength = Math.ceil(_nBitLength / 8);
2734
- return { nBitLength: _nBitLength, nByteLength };
2735
- }
2736
- function Field(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
2737
- if (ORDER <= _0n2)
2738
- throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
2739
- let _nbitLength = void 0;
2740
- let _sqrt = void 0;
2741
- let modFromBytes = false;
2742
- let allowedLengths = void 0;
2743
- if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
2744
- if (opts.sqrt || isLE2)
2745
- throw new Error("cannot specify opts in two arguments");
2746
- const _opts = bitLenOrOpts;
2747
- if (_opts.BITS)
2748
- _nbitLength = _opts.BITS;
2749
- if (_opts.sqrt)
2750
- _sqrt = _opts.sqrt;
2751
- if (typeof _opts.isLE === "boolean")
2752
- isLE2 = _opts.isLE;
2753
- if (typeof _opts.modFromBytes === "boolean")
2754
- modFromBytes = _opts.modFromBytes;
2755
- allowedLengths = _opts.allowedLengths;
2756
- } else {
2757
- if (typeof bitLenOrOpts === "number")
2758
- _nbitLength = bitLenOrOpts;
2759
- if (opts.sqrt)
2760
- _sqrt = opts.sqrt;
2761
- }
2762
- const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
2763
- if (BYTES > 2048)
2764
- throw new Error("invalid field: expected ORDER of <= 2048 bytes");
2765
- let sqrtP;
2766
- const f = Object.freeze({
2767
- ORDER,
2768
- isLE: isLE2,
2769
- BITS,
2770
- BYTES,
2771
- MASK: bitMask(BITS),
2772
- ZERO: _0n2,
2773
- ONE: _1n2,
2774
- allowedLengths,
2775
- create: (num) => mod(num, ORDER),
2776
- isValid: (num) => {
2777
- if (typeof num !== "bigint")
2778
- throw new Error("invalid field element: expected bigint, got " + typeof num);
2779
- return _0n2 <= num && num < ORDER;
2780
- },
2781
- is0: (num) => num === _0n2,
2782
- // is valid and invertible
2783
- isValidNot0: (num) => !f.is0(num) && f.isValid(num),
2784
- isOdd: (num) => (num & _1n2) === _1n2,
2785
- neg: (num) => mod(-num, ORDER),
2786
- eql: (lhs, rhs) => lhs === rhs,
2787
- sqr: (num) => mod(num * num, ORDER),
2788
- add: (lhs, rhs) => mod(lhs + rhs, ORDER),
2789
- sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
2790
- mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
2791
- pow: (num, power) => FpPow(f, num, power),
2792
- div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
2793
- // Same as above, but doesn't normalize
2794
- sqrN: (num) => num * num,
2795
- addN: (lhs, rhs) => lhs + rhs,
2796
- subN: (lhs, rhs) => lhs - rhs,
2797
- mulN: (lhs, rhs) => lhs * rhs,
2798
- inv: (num) => invert(num, ORDER),
2799
- sqrt: _sqrt || ((n) => {
2800
- if (!sqrtP)
2801
- sqrtP = FpSqrt(ORDER);
2802
- return sqrtP(f, n);
2803
- }),
2804
- toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
2805
- fromBytes: (bytes, skipValidation = true) => {
2806
- if (allowedLengths) {
2807
- if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
2808
- throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
2809
- }
2810
- const padded = new Uint8Array(BYTES);
2811
- padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
2812
- bytes = padded;
2813
- }
2814
- if (bytes.length !== BYTES)
2815
- throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
2816
- let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
2817
- if (modFromBytes)
2818
- scalar = mod(scalar, ORDER);
2819
- if (!skipValidation) {
2820
- if (!f.isValid(scalar))
2821
- throw new Error("invalid field element: outside of range 0..ORDER");
2822
- }
2823
- return scalar;
2824
- },
2825
- // TODO: we don't need it here, move out to separate fn
2826
- invertBatch: (lst) => FpInvertBatch(f, lst),
2827
- // We can't move this out because Fp6, Fp12 implement it
2828
- // and it's unclear what to return in there.
2829
- cmov: (a, b, c) => c ? b : a
2830
- });
2831
- return Object.freeze(f);
2832
- }
2833
- function FpSqrtEven(Fp2, elm) {
2834
- if (!Fp2.isOdd)
2835
- throw new Error("Field doesn't have isOdd");
2836
- const root = Fp2.sqrt(elm);
2837
- return Fp2.isOdd(root) ? Fp2.neg(root) : root;
2838
- }
2839
- var _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _16n, isNegativeLE, FIELD_FIELDS;
2840
- var init_modular = __esm({
2841
- "node_modules/@noble/curves/esm/abstract/modular.js"() {
2842
- "use strict";
2843
- init_utils2();
2844
- _0n2 = BigInt(0);
2845
- _1n2 = BigInt(1);
2846
- _2n = /* @__PURE__ */ BigInt(2);
2847
- _3n = /* @__PURE__ */ BigInt(3);
2848
- _4n = /* @__PURE__ */ BigInt(4);
2849
- _5n = /* @__PURE__ */ BigInt(5);
2850
- _7n = /* @__PURE__ */ BigInt(7);
2851
- _8n = /* @__PURE__ */ BigInt(8);
2852
- _9n = /* @__PURE__ */ BigInt(9);
2853
- _16n = /* @__PURE__ */ BigInt(16);
2854
- isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
2855
- FIELD_FIELDS = [
2856
- "create",
2857
- "isValid",
2858
- "is0",
2859
- "neg",
2860
- "inv",
2861
- "sqrt",
2862
- "sqr",
2863
- "eql",
2864
- "add",
2865
- "sub",
2866
- "mul",
2867
- "pow",
2868
- "div",
2869
- "addN",
2870
- "subN",
2871
- "mulN",
2872
- "sqrN"
2873
- ];
2874
- }
2875
- });
2876
-
2877
- // node_modules/@noble/curves/esm/abstract/curve.js
2878
- function negateCt(condition, item) {
2879
- const neg = item.negate();
2880
- return condition ? neg : item;
2881
- }
2882
- function normalizeZ(c, points) {
2883
- const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
2884
- return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
2885
- }
2886
- function validateW(W, bits) {
2887
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
2888
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
2889
- }
2890
- function calcWOpts(W, scalarBits) {
2891
- validateW(W, scalarBits);
2892
- const windows = Math.ceil(scalarBits / W) + 1;
2893
- const windowSize = 2 ** (W - 1);
2894
- const maxNumber = 2 ** W;
2895
- const mask = bitMask(W);
2896
- const shiftBy = BigInt(W);
2897
- return { windows, windowSize, mask, maxNumber, shiftBy };
2898
- }
2899
- function calcOffsets(n, window, wOpts) {
2900
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
2901
- let wbits = Number(n & mask);
2902
- let nextN = n >> shiftBy;
2903
- if (wbits > windowSize) {
2904
- wbits -= maxNumber;
2905
- nextN += _1n3;
2906
- }
2907
- const offsetStart = window * windowSize;
2908
- const offset = offsetStart + Math.abs(wbits) - 1;
2909
- const isZero = wbits === 0;
2910
- const isNeg = wbits < 0;
2911
- const isNegF = window % 2 !== 0;
2912
- const offsetF = offsetStart;
2913
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
2914
- }
2915
- function validateMSMPoints(points, c) {
2916
- if (!Array.isArray(points))
2917
- throw new Error("array expected");
2918
- points.forEach((p, i) => {
2919
- if (!(p instanceof c))
2920
- throw new Error("invalid point at index " + i);
2921
- });
2922
- }
2923
- function validateMSMScalars(scalars, field) {
2924
- if (!Array.isArray(scalars))
2925
- throw new Error("array of scalars expected");
2926
- scalars.forEach((s, i) => {
2927
- if (!field.isValid(s))
2928
- throw new Error("invalid scalar at index " + i);
2929
- });
2930
- }
2931
- function getW(P) {
2932
- return pointWindowSizes.get(P) || 1;
2933
- }
2934
- function assert0(n) {
2935
- if (n !== _0n3)
2936
- throw new Error("invalid wNAF");
2937
- }
2938
- function pippenger(c, fieldN, points, scalars) {
2939
- validateMSMPoints(points, c);
2940
- validateMSMScalars(scalars, fieldN);
2941
- const plength = points.length;
2942
- const slength = scalars.length;
2943
- if (plength !== slength)
2944
- throw new Error("arrays of points and scalars must have equal length");
2945
- const zero = c.ZERO;
2946
- const wbits = bitLen(BigInt(plength));
2947
- let windowSize = 1;
2948
- if (wbits > 12)
2949
- windowSize = wbits - 3;
2950
- else if (wbits > 4)
2951
- windowSize = wbits - 2;
2952
- else if (wbits > 0)
2953
- windowSize = 2;
2954
- const MASK = bitMask(windowSize);
2955
- const buckets = new Array(Number(MASK) + 1).fill(zero);
2956
- const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
2957
- let sum = zero;
2958
- for (let i = lastBits; i >= 0; i -= windowSize) {
2959
- buckets.fill(zero);
2960
- for (let j = 0; j < slength; j++) {
2961
- const scalar = scalars[j];
2962
- const wbits2 = Number(scalar >> BigInt(i) & MASK);
2963
- buckets[wbits2] = buckets[wbits2].add(points[j]);
2964
- }
2965
- let resI = zero;
2966
- for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
2967
- sumI = sumI.add(buckets[j]);
2968
- resI = resI.add(sumI);
2969
- }
2970
- sum = sum.add(resI);
2971
- if (i !== 0)
2972
- for (let j = 0; j < windowSize; j++)
2973
- sum = sum.double();
2974
- }
2975
- return sum;
2976
- }
2977
- function createField(order, field, isLE2) {
2978
- if (field) {
2979
- if (field.ORDER !== order)
2980
- throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
2981
- validateField(field);
2982
- return field;
2983
- } else {
2984
- return Field(order, { isLE: isLE2 });
2985
- }
2986
- }
2987
- function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
2988
- if (FpFnLE === void 0)
2989
- FpFnLE = type === "edwards";
2990
- if (!CURVE || typeof CURVE !== "object")
2991
- throw new Error(`expected valid ${type} CURVE object`);
2992
- for (const p of ["p", "n", "h"]) {
2993
- const val = CURVE[p];
2994
- if (!(typeof val === "bigint" && val > _0n3))
2995
- throw new Error(`CURVE.${p} must be positive bigint`);
2996
- }
2997
- const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
2998
- const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
2999
- const _b = type === "weierstrass" ? "b" : "d";
3000
- const params = ["Gx", "Gy", "a", _b];
3001
- for (const p of params) {
3002
- if (!Fp2.isValid(CURVE[p]))
3003
- throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
3004
- }
3005
- CURVE = Object.freeze(Object.assign({}, CURVE));
3006
- return { CURVE, Fp: Fp2, Fn: Fn2 };
3007
- }
3008
- var _0n3, _1n3, pointPrecomputes, pointWindowSizes, wNAF;
3009
- var init_curve = __esm({
3010
- "node_modules/@noble/curves/esm/abstract/curve.js"() {
3011
- "use strict";
3012
- init_utils2();
3013
- init_modular();
3014
- _0n3 = BigInt(0);
3015
- _1n3 = BigInt(1);
3016
- pointPrecomputes = /* @__PURE__ */ new WeakMap();
3017
- pointWindowSizes = /* @__PURE__ */ new WeakMap();
3018
- wNAF = class {
3019
- // Parametrized with a given Point class (not individual point)
3020
- constructor(Point, bits) {
3021
- this.BASE = Point.BASE;
3022
- this.ZERO = Point.ZERO;
3023
- this.Fn = Point.Fn;
3024
- this.bits = bits;
3025
- }
3026
- // non-const time multiplication ladder
3027
- _unsafeLadder(elm, n, p = this.ZERO) {
3028
- let d = elm;
3029
- while (n > _0n3) {
3030
- if (n & _1n3)
3031
- p = p.add(d);
3032
- d = d.double();
3033
- n >>= _1n3;
3034
- }
3035
- return p;
3036
- }
3037
- /**
3038
- * Creates a wNAF precomputation window. Used for caching.
3039
- * Default window size is set by `utils.precompute()` and is equal to 8.
3040
- * Number of precomputed points depends on the curve size:
3041
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
3042
- * - 𝑊 is the window size
3043
- * - 𝑛 is the bitlength of the curve order.
3044
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
3045
- * @param point Point instance
3046
- * @param W window size
3047
- * @returns precomputed point tables flattened to a single array
3048
- */
3049
- precomputeWindow(point, W) {
3050
- const { windows, windowSize } = calcWOpts(W, this.bits);
3051
- const points = [];
3052
- let p = point;
3053
- let base = p;
3054
- for (let window = 0; window < windows; window++) {
3055
- base = p;
3056
- points.push(base);
3057
- for (let i = 1; i < windowSize; i++) {
3058
- base = base.add(p);
3059
- points.push(base);
3060
- }
3061
- p = base.double();
3062
- }
3063
- return points;
3064
- }
3065
- /**
3066
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
3067
- * More compact implementation:
3068
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
3069
- * @returns real and fake (for const-time) points
3070
- */
3071
- wNAF(W, precomputes, n) {
3072
- if (!this.Fn.isValid(n))
3073
- throw new Error("invalid scalar");
3074
- let p = this.ZERO;
3075
- let f = this.BASE;
3076
- const wo = calcWOpts(W, this.bits);
3077
- for (let window = 0; window < wo.windows; window++) {
3078
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
3079
- n = nextN;
3080
- if (isZero) {
3081
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
3082
- } else {
3083
- p = p.add(negateCt(isNeg, precomputes[offset]));
3084
- }
3085
- }
3086
- assert0(n);
3087
- return { p, f };
3088
- }
3089
- /**
3090
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
3091
- * @param acc accumulator point to add result of multiplication
3092
- * @returns point
3093
- */
3094
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
3095
- const wo = calcWOpts(W, this.bits);
3096
- for (let window = 0; window < wo.windows; window++) {
3097
- if (n === _0n3)
3098
- break;
3099
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
3100
- n = nextN;
3101
- if (isZero) {
3102
- continue;
3103
- } else {
3104
- const item = precomputes[offset];
3105
- acc = acc.add(isNeg ? item.negate() : item);
3106
- }
3107
- }
3108
- assert0(n);
3109
- return acc;
3110
- }
3111
- getPrecomputes(W, point, transform) {
3112
- let comp = pointPrecomputes.get(point);
3113
- if (!comp) {
3114
- comp = this.precomputeWindow(point, W);
3115
- if (W !== 1) {
3116
- if (typeof transform === "function")
3117
- comp = transform(comp);
3118
- pointPrecomputes.set(point, comp);
3119
- }
3120
- }
3121
- return comp;
3122
- }
3123
- cached(point, scalar, transform) {
3124
- const W = getW(point);
3125
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
3126
- }
3127
- unsafe(point, scalar, transform, prev) {
3128
- const W = getW(point);
3129
- if (W === 1)
3130
- return this._unsafeLadder(point, scalar, prev);
3131
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
3132
- }
3133
- // We calculate precomputes for elliptic curve point multiplication
3134
- // using windowed method. This specifies window size and
3135
- // stores precomputed values. Usually only base point would be precomputed.
3136
- createCache(P, W) {
3137
- validateW(W, this.bits);
3138
- pointWindowSizes.set(P, W);
3139
- pointPrecomputes.delete(P);
3140
- }
3141
- hasCache(elm) {
3142
- return getW(elm) !== 1;
3143
- }
3144
- };
3145
- }
3146
- });
3147
-
3148
- // node_modules/@noble/curves/esm/abstract/edwards.js
3149
- function isEdValidXY(Fp2, CURVE, x, y) {
3150
- const x2 = Fp2.sqr(x);
3151
- const y2 = Fp2.sqr(y);
3152
- const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
3153
- const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
3154
- return Fp2.eql(left, right);
3155
- }
3156
- function edwards(params, extraOpts = {}) {
3157
- const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
3158
- const { Fp: Fp2, Fn: Fn2 } = validated;
3159
- let CURVE = validated.CURVE;
3160
- const { h: cofactor } = CURVE;
3161
- _validateObject(extraOpts, {}, { uvRatio: "function" });
3162
- const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
3163
- const modP = (n) => Fp2.create(n);
3164
- const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
3165
- try {
3166
- return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
3167
- } catch (e) {
3168
- return { isValid: false, value: _0n4 };
3169
- }
3170
- });
3171
- if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
3172
- throw new Error("bad curve params: generator point");
3173
- function acoord(title, n, banZero = false) {
3174
- const min = banZero ? _1n4 : _0n4;
3175
- aInRange("coordinate " + title, n, min, MASK);
3176
- return n;
3177
- }
3178
- function aextpoint(other) {
3179
- if (!(other instanceof Point))
3180
- throw new Error("ExtendedPoint expected");
3181
- }
3182
- const toAffineMemo = memoized((p, iz) => {
3183
- const { X, Y, Z } = p;
3184
- const is0 = p.is0();
3185
- if (iz == null)
3186
- iz = is0 ? _8n2 : Fp2.inv(Z);
3187
- const x = modP(X * iz);
3188
- const y = modP(Y * iz);
3189
- const zz = Fp2.mul(Z, iz);
3190
- if (is0)
3191
- return { x: _0n4, y: _1n4 };
3192
- if (zz !== _1n4)
3193
- throw new Error("invZ was invalid");
3194
- return { x, y };
3195
- });
3196
- const assertValidMemo = memoized((p) => {
3197
- const { a, d } = CURVE;
3198
- if (p.is0())
3199
- throw new Error("bad point: ZERO");
3200
- const { X, Y, Z, T } = p;
3201
- const X2 = modP(X * X);
3202
- const Y2 = modP(Y * Y);
3203
- const Z2 = modP(Z * Z);
3204
- const Z4 = modP(Z2 * Z2);
3205
- const aX2 = modP(X2 * a);
3206
- const left = modP(Z2 * modP(aX2 + Y2));
3207
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
3208
- if (left !== right)
3209
- throw new Error("bad point: equation left != right (1)");
3210
- const XY = modP(X * Y);
3211
- const ZT = modP(Z * T);
3212
- if (XY !== ZT)
3213
- throw new Error("bad point: equation left != right (2)");
3214
- return true;
3215
- });
3216
- class Point {
3217
- constructor(X, Y, Z, T) {
3218
- this.X = acoord("x", X);
3219
- this.Y = acoord("y", Y);
3220
- this.Z = acoord("z", Z, true);
3221
- this.T = acoord("t", T);
3222
- Object.freeze(this);
3223
- }
3224
- static CURVE() {
3225
- return CURVE;
3226
- }
3227
- static fromAffine(p) {
3228
- if (p instanceof Point)
3229
- throw new Error("extended point not allowed");
3230
- const { x, y } = p || {};
3231
- acoord("x", x);
3232
- acoord("y", y);
3233
- return new Point(x, y, _1n4, modP(x * y));
3234
- }
3235
- // Uses algo from RFC8032 5.1.3.
3236
- static fromBytes(bytes, zip215 = false) {
3237
- const len = Fp2.BYTES;
3238
- const { a, d } = CURVE;
3239
- bytes = copyBytes(_abytes2(bytes, len, "point"));
3240
- _abool2(zip215, "zip215");
3241
- const normed = copyBytes(bytes);
3242
- const lastByte = bytes[len - 1];
3243
- normed[len - 1] = lastByte & ~128;
3244
- const y = bytesToNumberLE(normed);
3245
- const max = zip215 ? MASK : Fp2.ORDER;
3246
- aInRange("point.y", y, _0n4, max);
3247
- const y2 = modP(y * y);
3248
- const u = modP(y2 - _1n4);
3249
- const v = modP(d * y2 - a);
3250
- let { isValid, value: x } = uvRatio2(u, v);
3251
- if (!isValid)
3252
- throw new Error("bad point: invalid y coordinate");
3253
- const isXOdd = (x & _1n4) === _1n4;
3254
- const isLastByteOdd = (lastByte & 128) !== 0;
3255
- if (!zip215 && x === _0n4 && isLastByteOdd)
3256
- throw new Error("bad point: x=0 and x_0=1");
3257
- if (isLastByteOdd !== isXOdd)
3258
- x = modP(-x);
3259
- return Point.fromAffine({ x, y });
3260
- }
3261
- static fromHex(bytes, zip215 = false) {
3262
- return Point.fromBytes(ensureBytes("point", bytes), zip215);
3263
- }
3264
- get x() {
3265
- return this.toAffine().x;
3266
- }
3267
- get y() {
3268
- return this.toAffine().y;
3269
- }
3270
- precompute(windowSize = 8, isLazy = true) {
3271
- wnaf.createCache(this, windowSize);
3272
- if (!isLazy)
3273
- this.multiply(_2n2);
3274
- return this;
3275
- }
3276
- // Useful in fromAffine() - not for fromBytes(), which always created valid points.
3277
- assertValidity() {
3278
- assertValidMemo(this);
3279
- }
3280
- // Compare one point to another.
3281
- equals(other) {
3282
- aextpoint(other);
3283
- const { X: X1, Y: Y1, Z: Z1 } = this;
3284
- const { X: X2, Y: Y2, Z: Z2 } = other;
3285
- const X1Z2 = modP(X1 * Z2);
3286
- const X2Z1 = modP(X2 * Z1);
3287
- const Y1Z2 = modP(Y1 * Z2);
3288
- const Y2Z1 = modP(Y2 * Z1);
3289
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
3290
- }
3291
- is0() {
3292
- return this.equals(Point.ZERO);
3293
- }
3294
- negate() {
3295
- return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
3296
- }
3297
- // Fast algo for doubling Extended Point.
3298
- // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
3299
- // Cost: 4M + 4S + 1*a + 6add + 1*2.
3300
- double() {
3301
- const { a } = CURVE;
3302
- const { X: X1, Y: Y1, Z: Z1 } = this;
3303
- const A = modP(X1 * X1);
3304
- const B = modP(Y1 * Y1);
3305
- const C = modP(_2n2 * modP(Z1 * Z1));
3306
- const D = modP(a * A);
3307
- const x1y1 = X1 + Y1;
3308
- const E = modP(modP(x1y1 * x1y1) - A - B);
3309
- const G = D + B;
3310
- const F = G - C;
3311
- const H = D - B;
3312
- const X3 = modP(E * F);
3313
- const Y3 = modP(G * H);
3314
- const T3 = modP(E * H);
3315
- const Z3 = modP(F * G);
3316
- return new Point(X3, Y3, Z3, T3);
3317
- }
3318
- // Fast algo for adding 2 Extended Points.
3319
- // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
3320
- // Cost: 9M + 1*a + 1*d + 7add.
3321
- add(other) {
3322
- aextpoint(other);
3323
- const { a, d } = CURVE;
3324
- const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
3325
- const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
3326
- const A = modP(X1 * X2);
3327
- const B = modP(Y1 * Y2);
3328
- const C = modP(T1 * d * T2);
3329
- const D = modP(Z1 * Z2);
3330
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
3331
- const F = D - C;
3332
- const G = D + C;
3333
- const H = modP(B - a * A);
3334
- const X3 = modP(E * F);
3335
- const Y3 = modP(G * H);
3336
- const T3 = modP(E * H);
3337
- const Z3 = modP(F * G);
3338
- return new Point(X3, Y3, Z3, T3);
3339
- }
3340
- subtract(other) {
3341
- return this.add(other.negate());
3342
- }
3343
- // Constant-time multiplication.
3344
- multiply(scalar) {
3345
- if (!Fn2.isValidNot0(scalar))
3346
- throw new Error("invalid scalar: expected 1 <= sc < curve.n");
3347
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
3348
- return normalizeZ(Point, [p, f])[0];
3349
- }
3350
- // Non-constant-time multiplication. Uses double-and-add algorithm.
3351
- // It's faster, but should only be used when you don't care about
3352
- // an exposed private key e.g. sig verification.
3353
- // Does NOT allow scalars higher than CURVE.n.
3354
- // Accepts optional accumulator to merge with multiply (important for sparse scalars)
3355
- multiplyUnsafe(scalar, acc = Point.ZERO) {
3356
- if (!Fn2.isValid(scalar))
3357
- throw new Error("invalid scalar: expected 0 <= sc < curve.n");
3358
- if (scalar === _0n4)
3359
- return Point.ZERO;
3360
- if (this.is0() || scalar === _1n4)
3361
- return this;
3362
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
3363
- }
3364
- // Checks if point is of small order.
3365
- // If you add something to small order point, you will have "dirty"
3366
- // point with torsion component.
3367
- // Multiplies point by cofactor and checks if the result is 0.
3368
- isSmallOrder() {
3369
- return this.multiplyUnsafe(cofactor).is0();
3370
- }
3371
- // Multiplies point by curve order and checks if the result is 0.
3372
- // Returns `false` is the point is dirty.
3373
- isTorsionFree() {
3374
- return wnaf.unsafe(this, CURVE.n).is0();
3375
- }
3376
- // Converts Extended point to default (x, y) coordinates.
3377
- // Can accept precomputed Z^-1 - for example, from invertBatch.
3378
- toAffine(invertedZ) {
3379
- return toAffineMemo(this, invertedZ);
3380
- }
3381
- clearCofactor() {
3382
- if (cofactor === _1n4)
3383
- return this;
3384
- return this.multiplyUnsafe(cofactor);
3385
- }
3386
- toBytes() {
3387
- const { x, y } = this.toAffine();
3388
- const bytes = Fp2.toBytes(y);
3389
- bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
3390
- return bytes;
3391
- }
3392
- toHex() {
3393
- return bytesToHex(this.toBytes());
3394
- }
3395
- toString() {
3396
- return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
3397
- }
3398
- // TODO: remove
3399
- get ex() {
3400
- return this.X;
3401
- }
3402
- get ey() {
3403
- return this.Y;
3404
- }
3405
- get ez() {
3406
- return this.Z;
3407
- }
3408
- get et() {
3409
- return this.T;
3410
- }
3411
- static normalizeZ(points) {
3412
- return normalizeZ(Point, points);
3413
- }
3414
- static msm(points, scalars) {
3415
- return pippenger(Point, Fn2, points, scalars);
3416
- }
3417
- _setWindowSize(windowSize) {
3418
- this.precompute(windowSize);
3419
- }
3420
- toRawBytes() {
3421
- return this.toBytes();
3422
- }
3423
- }
3424
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
3425
- Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
3426
- Point.Fp = Fp2;
3427
- Point.Fn = Fn2;
3428
- const wnaf = new wNAF(Point, Fn2.BITS);
3429
- Point.BASE.precompute(8);
3430
- return Point;
3431
- }
3432
- function eddsa(Point, cHash, eddsaOpts = {}) {
3433
- if (typeof cHash !== "function")
3434
- throw new Error('"hash" function param is required');
3435
- _validateObject(eddsaOpts, {}, {
3436
- adjustScalarBytes: "function",
3437
- randomBytes: "function",
3438
- domain: "function",
3439
- prehash: "function",
3440
- mapToCurve: "function"
3441
- });
3442
- const { prehash } = eddsaOpts;
3443
- const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
3444
- const randomBytes4 = eddsaOpts.randomBytes || randomBytes2;
3445
- const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
3446
- const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
3447
- _abool2(phflag, "phflag");
3448
- if (ctx.length || phflag)
3449
- throw new Error("Contexts/pre-hash are not supported");
3450
- return data;
3451
- });
3452
- function modN_LE(hash) {
3453
- return Fn2.create(bytesToNumberLE(hash));
3454
- }
3455
- function getPrivateScalar(key) {
3456
- const len = lengths.secretKey;
3457
- key = ensureBytes("private key", key, len);
3458
- const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
3459
- const head = adjustScalarBytes2(hashed.slice(0, len));
3460
- const prefix = hashed.slice(len, 2 * len);
3461
- const scalar = modN_LE(head);
3462
- return { head, prefix, scalar };
3463
- }
3464
- function getExtendedPublicKey(secretKey) {
3465
- const { head, prefix, scalar } = getPrivateScalar(secretKey);
3466
- const point = BASE.multiply(scalar);
3467
- const pointBytes = point.toBytes();
3468
- return { head, prefix, scalar, point, pointBytes };
3469
- }
3470
- function getPublicKey(secretKey) {
3471
- return getExtendedPublicKey(secretKey).pointBytes;
3472
- }
3473
- function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
3474
- const msg = concatBytes(...msgs);
3475
- return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
3476
- }
3477
- function sign(msg, secretKey, options = {}) {
3478
- msg = ensureBytes("message", msg);
3479
- if (prehash)
3480
- msg = prehash(msg);
3481
- const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
3482
- const r = hashDomainToScalar(options.context, prefix, msg);
3483
- const R = BASE.multiply(r).toBytes();
3484
- const k = hashDomainToScalar(options.context, R, pointBytes, msg);
3485
- const s = Fn2.create(r + k * scalar);
3486
- if (!Fn2.isValid(s))
3487
- throw new Error("sign failed: invalid s");
3488
- const rs = concatBytes(R, Fn2.toBytes(s));
3489
- return _abytes2(rs, lengths.signature, "result");
3490
- }
3491
- const verifyOpts = { zip215: true };
3492
- function verify(sig, msg, publicKey, options = verifyOpts) {
3493
- const { context, zip215 } = options;
3494
- const len = lengths.signature;
3495
- sig = ensureBytes("signature", sig, len);
3496
- msg = ensureBytes("message", msg);
3497
- publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
3498
- if (zip215 !== void 0)
3499
- _abool2(zip215, "zip215");
3500
- if (prehash)
3501
- msg = prehash(msg);
3502
- const mid = len / 2;
3503
- const r = sig.subarray(0, mid);
3504
- const s = bytesToNumberLE(sig.subarray(mid, len));
3505
- let A, R, SB;
3506
- try {
3507
- A = Point.fromBytes(publicKey, zip215);
3508
- R = Point.fromBytes(r, zip215);
3509
- SB = BASE.multiplyUnsafe(s);
3510
- } catch (error) {
3511
- return false;
3512
- }
3513
- if (!zip215 && A.isSmallOrder())
3514
- return false;
3515
- const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
3516
- const RkA = R.add(A.multiplyUnsafe(k));
3517
- return RkA.subtract(SB).clearCofactor().is0();
3518
- }
3519
- const _size = Fp2.BYTES;
3520
- const lengths = {
3521
- secretKey: _size,
3522
- publicKey: _size,
3523
- signature: 2 * _size,
3524
- seed: _size
3525
- };
3526
- function randomSecretKey(seed = randomBytes4(lengths.seed)) {
3527
- return _abytes2(seed, lengths.seed, "seed");
3528
- }
3529
- function keygen(seed) {
3530
- const secretKey = utils.randomSecretKey(seed);
3531
- return { secretKey, publicKey: getPublicKey(secretKey) };
3532
- }
3533
- function isValidSecretKey(key) {
3534
- return isBytes(key) && key.length === Fn2.BYTES;
3535
- }
3536
- function isValidPublicKey(key, zip215) {
3537
- try {
3538
- return !!Point.fromBytes(key, zip215);
3539
- } catch (error) {
3540
- return false;
3541
- }
3542
- }
3543
- const utils = {
3544
- getExtendedPublicKey,
3545
- randomSecretKey,
3546
- isValidSecretKey,
3547
- isValidPublicKey,
3548
- /**
3549
- * Converts ed public key to x public key. Uses formula:
3550
- * - ed25519:
3551
- * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
3552
- * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
3553
- * - ed448:
3554
- * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
3555
- * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
3556
- */
3557
- toMontgomery(publicKey) {
3558
- const { y } = Point.fromBytes(publicKey);
3559
- const size = lengths.publicKey;
3560
- const is25519 = size === 32;
3561
- if (!is25519 && size !== 57)
3562
- throw new Error("only defined for 25519 and 448");
3563
- const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
3564
- return Fp2.toBytes(u);
3565
- },
3566
- toMontgomerySecret(secretKey) {
3567
- const size = lengths.secretKey;
3568
- _abytes2(secretKey, size);
3569
- const hashed = cHash(secretKey.subarray(0, size));
3570
- return adjustScalarBytes2(hashed).subarray(0, size);
3571
- },
3572
- /** @deprecated */
3573
- randomPrivateKey: randomSecretKey,
3574
- /** @deprecated */
3575
- precompute(windowSize = 8, point = Point.BASE) {
3576
- return point.precompute(windowSize, false);
3577
- }
3578
- };
3579
- return Object.freeze({
3580
- keygen,
3581
- getPublicKey,
3582
- sign,
3583
- verify,
3584
- utils,
3585
- Point,
3586
- lengths
3587
- });
3588
- }
3589
- function _eddsa_legacy_opts_to_new(c) {
3590
- const CURVE = {
3591
- a: c.a,
3592
- d: c.d,
3593
- p: c.Fp.ORDER,
3594
- n: c.n,
3595
- h: c.h,
3596
- Gx: c.Gx,
3597
- Gy: c.Gy
3598
- };
3599
- const Fp2 = c.Fp;
3600
- const Fn2 = Field(CURVE.n, c.nBitLength, true);
3601
- const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
3602
- const eddsaOpts = {
3603
- randomBytes: c.randomBytes,
3604
- adjustScalarBytes: c.adjustScalarBytes,
3605
- domain: c.domain,
3606
- prehash: c.prehash,
3607
- mapToCurve: c.mapToCurve
3608
- };
3609
- return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
3610
- }
3611
- function _eddsa_new_output_to_legacy(c, eddsa2) {
3612
- const Point = eddsa2.Point;
3613
- const legacy = Object.assign({}, eddsa2, {
3614
- ExtendedPoint: Point,
3615
- CURVE: c,
3616
- nBitLength: Point.Fn.BITS,
3617
- nByteLength: Point.Fn.BYTES
3618
- });
3619
- return legacy;
3620
- }
3621
- function twistedEdwards(c) {
3622
- const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
3623
- const Point = edwards(CURVE, curveOpts);
3624
- const EDDSA = eddsa(Point, hash, eddsaOpts);
3625
- return _eddsa_new_output_to_legacy(c, EDDSA);
3626
- }
3627
- var _0n4, _1n4, _2n2, _8n2, PrimeEdwardsPoint;
3628
- var init_edwards = __esm({
3629
- "node_modules/@noble/curves/esm/abstract/edwards.js"() {
3630
- "use strict";
3631
- init_utils2();
3632
- init_curve();
3633
- init_modular();
3634
- _0n4 = BigInt(0);
3635
- _1n4 = BigInt(1);
3636
- _2n2 = BigInt(2);
3637
- _8n2 = BigInt(8);
3638
- PrimeEdwardsPoint = class {
3639
- constructor(ep) {
3640
- this.ep = ep;
3641
- }
3642
- // Static methods that must be implemented by subclasses
3643
- static fromBytes(_bytes) {
3644
- notImplemented();
3645
- }
3646
- static fromHex(_hex) {
3647
- notImplemented();
3648
- }
3649
- get x() {
3650
- return this.toAffine().x;
3651
- }
3652
- get y() {
3653
- return this.toAffine().y;
3654
- }
3655
- // Common implementations
3656
- clearCofactor() {
3657
- return this;
3658
- }
3659
- assertValidity() {
3660
- this.ep.assertValidity();
3661
- }
3662
- toAffine(invertedZ) {
3663
- return this.ep.toAffine(invertedZ);
3664
- }
3665
- toHex() {
3666
- return bytesToHex(this.toBytes());
3667
- }
3668
- toString() {
3669
- return this.toHex();
3670
- }
3671
- isTorsionFree() {
3672
- return true;
3673
- }
3674
- isSmallOrder() {
3675
- return false;
3676
- }
3677
- add(other) {
3678
- this.assertSame(other);
3679
- return this.init(this.ep.add(other.ep));
3680
- }
3681
- subtract(other) {
3682
- this.assertSame(other);
3683
- return this.init(this.ep.subtract(other.ep));
3684
- }
3685
- multiply(scalar) {
3686
- return this.init(this.ep.multiply(scalar));
3687
- }
3688
- multiplyUnsafe(scalar) {
3689
- return this.init(this.ep.multiplyUnsafe(scalar));
3690
- }
3691
- double() {
3692
- return this.init(this.ep.double());
3693
- }
3694
- negate() {
3695
- return this.init(this.ep.negate());
3696
- }
3697
- precompute(windowSize, isLazy) {
3698
- return this.init(this.ep.precompute(windowSize, isLazy));
3699
- }
3700
- /** @deprecated use `toBytes` */
3701
- toRawBytes() {
3702
- return this.toBytes();
3703
- }
3704
- };
3705
- }
3706
- });
3707
-
3708
- // node_modules/@noble/curves/esm/abstract/hash-to-curve.js
3709
- function i2osp(value, length) {
3710
- anum(value);
3711
- anum(length);
3712
- if (value < 0 || value >= 1 << 8 * length)
3713
- throw new Error("invalid I2OSP input: " + value);
3714
- const res = Array.from({ length }).fill(0);
3715
- for (let i = length - 1; i >= 0; i--) {
3716
- res[i] = value & 255;
3717
- value >>>= 8;
3718
- }
3719
- return new Uint8Array(res);
3720
- }
3721
- function strxor(a, b) {
3722
- const arr = new Uint8Array(a.length);
3723
- for (let i = 0; i < a.length; i++) {
3724
- arr[i] = a[i] ^ b[i];
3725
- }
3726
- return arr;
3727
- }
3728
- function anum(item) {
3729
- if (!Number.isSafeInteger(item))
3730
- throw new Error("number expected");
3731
- }
3732
- function normDST(DST) {
3733
- if (!isBytes(DST) && typeof DST !== "string")
3734
- throw new Error("DST must be Uint8Array or string");
3735
- return typeof DST === "string" ? utf8ToBytes(DST) : DST;
3736
- }
3737
- function expand_message_xmd(msg, DST, lenInBytes, H) {
3738
- abytes(msg);
3739
- anum(lenInBytes);
3740
- DST = normDST(DST);
3741
- if (DST.length > 255)
3742
- DST = H(concatBytes(utf8ToBytes("H2C-OVERSIZE-DST-"), DST));
3743
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
3744
- const ell = Math.ceil(lenInBytes / b_in_bytes);
3745
- if (lenInBytes > 65535 || ell > 255)
3746
- throw new Error("expand_message_xmd: invalid lenInBytes");
3747
- const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
3748
- const Z_pad = i2osp(0, r_in_bytes);
3749
- const l_i_b_str = i2osp(lenInBytes, 2);
3750
- const b = new Array(ell);
3751
- const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
3752
- b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
3753
- for (let i = 1; i <= ell; i++) {
3754
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
3755
- b[i] = H(concatBytes(...args));
3756
- }
3757
- const pseudo_random_bytes = concatBytes(...b);
3758
- return pseudo_random_bytes.slice(0, lenInBytes);
3759
- }
3760
- function expand_message_xof(msg, DST, lenInBytes, k, H) {
3761
- abytes(msg);
3762
- anum(lenInBytes);
3763
- DST = normDST(DST);
3764
- if (DST.length > 255) {
3765
- const dkLen = Math.ceil(2 * k / 8);
3766
- DST = H.create({ dkLen }).update(utf8ToBytes("H2C-OVERSIZE-DST-")).update(DST).digest();
3767
- }
3768
- if (lenInBytes > 65535 || DST.length > 255)
3769
- throw new Error("expand_message_xof: invalid lenInBytes");
3770
- return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
3771
- }
3772
- function hash_to_field(msg, count, options) {
3773
- _validateObject(options, {
3774
- p: "bigint",
3775
- m: "number",
3776
- k: "number",
3777
- hash: "function"
3778
- });
3779
- const { p, k, m, hash, expand, DST } = options;
3780
- if (!isHash(options.hash))
3781
- throw new Error("expected valid hash");
3782
- abytes(msg);
3783
- anum(count);
3784
- const log2p = p.toString(2).length;
3785
- const L = Math.ceil((log2p + k) / 8);
3786
- const len_in_bytes = count * m * L;
3787
- let prb;
3788
- if (expand === "xmd") {
3789
- prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
3790
- } else if (expand === "xof") {
3791
- prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
3792
- } else if (expand === "_internal_pass") {
3793
- prb = msg;
3794
- } else {
3795
- throw new Error('expand must be "xmd" or "xof"');
3796
- }
3797
- const u = new Array(count);
3798
- for (let i = 0; i < count; i++) {
3799
- const e = new Array(m);
3800
- for (let j = 0; j < m; j++) {
3801
- const elm_offset = L * (j + i * m);
3802
- const tv = prb.subarray(elm_offset, elm_offset + L);
3803
- e[j] = mod(os2ip(tv), p);
3804
- }
3805
- u[i] = e;
3806
- }
3807
- return u;
3808
- }
3809
- function createHasher2(Point, mapToCurve, defaults) {
3810
- if (typeof mapToCurve !== "function")
3811
- throw new Error("mapToCurve() must be defined");
3812
- function map(num) {
3813
- return Point.fromAffine(mapToCurve(num));
3814
- }
3815
- function clear(initial) {
3816
- const P = initial.clearCofactor();
3817
- if (P.equals(Point.ZERO))
3818
- return Point.ZERO;
3819
- P.assertValidity();
3820
- return P;
3821
- }
3822
- return {
3823
- defaults,
3824
- hashToCurve(msg, options) {
3825
- const opts = Object.assign({}, defaults, options);
3826
- const u = hash_to_field(msg, 2, opts);
3827
- const u0 = map(u[0]);
3828
- const u1 = map(u[1]);
3829
- return clear(u0.add(u1));
3830
- },
3831
- encodeToCurve(msg, options) {
3832
- const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
3833
- const opts = Object.assign({}, defaults, optsDst, options);
3834
- const u = hash_to_field(msg, 1, opts);
3835
- const u0 = map(u[0]);
3836
- return clear(u0);
3837
- },
3838
- /** See {@link H2CHasher} */
3839
- mapToCurve(scalars) {
3840
- if (!Array.isArray(scalars))
3841
- throw new Error("expected array of bigints");
3842
- for (const i of scalars)
3843
- if (typeof i !== "bigint")
3844
- throw new Error("expected array of bigints");
3845
- return clear(map(scalars));
3846
- },
3847
- // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
3848
- // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
3849
- hashToScalar(msg, options) {
3850
- const N = Point.Fn.ORDER;
3851
- const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
3852
- return hash_to_field(msg, 1, opts)[0][0];
3853
- }
3854
- };
3855
- }
3856
- var os2ip, _DST_scalar;
3857
- var init_hash_to_curve = __esm({
3858
- "node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() {
3859
- "use strict";
3860
- init_utils2();
3861
- init_modular();
3862
- os2ip = bytesToNumberBE;
3863
- _DST_scalar = utf8ToBytes("HashToScalar-");
3864
- }
3865
- });
3866
-
3867
- // node_modules/@noble/curves/esm/abstract/montgomery.js
3868
- function validateOpts(curve) {
3869
- _validateObject(curve, {
3870
- adjustScalarBytes: "function",
3871
- powPminus2: "function"
3872
- });
3873
- return Object.freeze({ ...curve });
3874
- }
3875
- function montgomery(curveDef) {
3876
- const CURVE = validateOpts(curveDef);
3877
- const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
3878
- const is25519 = type === "x25519";
3879
- if (!is25519 && type !== "x448")
3880
- throw new Error("invalid type");
3881
- const randomBytes_ = rand || randomBytes2;
3882
- const montgomeryBits = is25519 ? 255 : 448;
3883
- const fieldLen = is25519 ? 32 : 56;
3884
- const Gu = is25519 ? BigInt(9) : BigInt(5);
3885
- const a24 = is25519 ? BigInt(121665) : BigInt(39081);
3886
- const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
3887
- const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
3888
- const maxScalar = minScalar + maxAdded + _1n5;
3889
- const modP = (n) => mod(n, P);
3890
- const GuBytes = encodeU(Gu);
3891
- function encodeU(u) {
3892
- return numberToBytesLE(modP(u), fieldLen);
3893
- }
3894
- function decodeU(u) {
3895
- const _u = ensureBytes("u coordinate", u, fieldLen);
3896
- if (is25519)
3897
- _u[31] &= 127;
3898
- return modP(bytesToNumberLE(_u));
3899
- }
3900
- function decodeScalar(scalar) {
3901
- return bytesToNumberLE(adjustScalarBytes2(ensureBytes("scalar", scalar, fieldLen)));
3902
- }
3903
- function scalarMult(scalar, u) {
3904
- const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
3905
- if (pu === _0n5)
3906
- throw new Error("invalid private or public key received");
3907
- return encodeU(pu);
3908
- }
3909
- function scalarMultBase(scalar) {
3910
- return scalarMult(scalar, GuBytes);
3911
- }
3912
- function cswap(swap, x_2, x_3) {
3913
- const dummy = modP(swap * (x_2 - x_3));
3914
- x_2 = modP(x_2 - dummy);
3915
- x_3 = modP(x_3 + dummy);
3916
- return { x_2, x_3 };
3917
- }
3918
- function montgomeryLadder(u, scalar) {
3919
- aInRange("u", u, _0n5, P);
3920
- aInRange("scalar", scalar, minScalar, maxScalar);
3921
- const k = scalar;
3922
- const x_1 = u;
3923
- let x_2 = _1n5;
3924
- let z_2 = _0n5;
3925
- let x_3 = u;
3926
- let z_3 = _1n5;
3927
- let swap = _0n5;
3928
- for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
3929
- const k_t = k >> t & _1n5;
3930
- swap ^= k_t;
3931
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
3932
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
3933
- swap = k_t;
3934
- const A = x_2 + z_2;
3935
- const AA = modP(A * A);
3936
- const B = x_2 - z_2;
3937
- const BB = modP(B * B);
3938
- const E = AA - BB;
3939
- const C = x_3 + z_3;
3940
- const D = x_3 - z_3;
3941
- const DA = modP(D * A);
3942
- const CB = modP(C * B);
3943
- const dacb = DA + CB;
3944
- const da_cb = DA - CB;
3945
- x_3 = modP(dacb * dacb);
3946
- z_3 = modP(x_1 * modP(da_cb * da_cb));
3947
- x_2 = modP(AA * BB);
3948
- z_2 = modP(E * (AA + modP(a24 * E)));
3949
- }
3950
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
3951
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
3952
- const z2 = powPminus2(z_2);
3953
- return modP(x_2 * z2);
3954
- }
3955
- const lengths = {
3956
- secretKey: fieldLen,
3957
- publicKey: fieldLen,
3958
- seed: fieldLen
3959
- };
3960
- const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
3961
- abytes(seed, lengths.seed);
3962
- return seed;
3963
- };
3964
- function keygen(seed) {
3965
- const secretKey = randomSecretKey(seed);
3966
- return { secretKey, publicKey: scalarMultBase(secretKey) };
3967
- }
3968
- const utils = {
3969
- randomSecretKey,
3970
- randomPrivateKey: randomSecretKey
3971
- };
3972
- return {
3973
- keygen,
3974
- getSharedSecret: (secretKey, publicKey) => scalarMult(secretKey, publicKey),
3975
- getPublicKey: (secretKey) => scalarMultBase(secretKey),
3976
- scalarMult,
3977
- scalarMultBase,
3978
- utils,
3979
- GuBytes: GuBytes.slice(),
3980
- lengths
3981
- };
3982
- }
3983
- var _0n5, _1n5, _2n3;
3984
- var init_montgomery = __esm({
3985
- "node_modules/@noble/curves/esm/abstract/montgomery.js"() {
3986
- "use strict";
3987
- init_utils2();
3988
- init_modular();
3989
- _0n5 = BigInt(0);
3990
- _1n5 = BigInt(1);
3991
- _2n3 = BigInt(2);
3992
- }
3993
- });
3994
-
3995
- // node_modules/@noble/curves/esm/ed25519.js
3996
- var ed25519_exports = {};
3997
- __export(ed25519_exports, {
3998
- ED25519_TORSION_SUBGROUP: () => ED25519_TORSION_SUBGROUP,
3999
- RistrettoPoint: () => RistrettoPoint,
4000
- ed25519: () => ed25519,
4001
- ed25519_hasher: () => ed25519_hasher,
4002
- ed25519ctx: () => ed25519ctx,
4003
- ed25519ph: () => ed25519ph,
4004
- edwardsToMontgomery: () => edwardsToMontgomery,
4005
- edwardsToMontgomeryPriv: () => edwardsToMontgomeryPriv,
4006
- edwardsToMontgomeryPub: () => edwardsToMontgomeryPub,
4007
- encodeToCurve: () => encodeToCurve,
4008
- hashToCurve: () => hashToCurve,
4009
- hashToRistretto255: () => hashToRistretto255,
4010
- hash_to_ristretto255: () => hash_to_ristretto255,
4011
- ristretto255: () => ristretto255,
4012
- ristretto255_hasher: () => ristretto255_hasher,
4013
- x25519: () => x25519
4014
- });
4015
- function ed25519_pow_2_252_3(x) {
4016
- const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
4017
- const P = ed25519_CURVE_p;
4018
- const x2 = x * x % P;
4019
- const b2 = x2 * x % P;
4020
- const b4 = pow2(b2, _2n4, P) * b2 % P;
4021
- const b5 = pow2(b4, _1n6, P) * x % P;
4022
- const b10 = pow2(b5, _5n2, P) * b5 % P;
4023
- const b20 = pow2(b10, _10n, P) * b10 % P;
4024
- const b40 = pow2(b20, _20n, P) * b20 % P;
4025
- const b80 = pow2(b40, _40n, P) * b40 % P;
4026
- const b160 = pow2(b80, _80n, P) * b80 % P;
4027
- const b240 = pow2(b160, _80n, P) * b80 % P;
4028
- const b250 = pow2(b240, _10n, P) * b10 % P;
4029
- const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
4030
- return { pow_p_5_8, b2 };
4031
- }
4032
- function adjustScalarBytes(bytes) {
4033
- bytes[0] &= 248;
4034
- bytes[31] &= 127;
4035
- bytes[31] |= 64;
4036
- return bytes;
4037
- }
4038
- function uvRatio(u, v) {
4039
- const P = ed25519_CURVE_p;
4040
- const v3 = mod(v * v * v, P);
4041
- const v7 = mod(v3 * v3 * v, P);
4042
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
4043
- let x = mod(u * v3 * pow, P);
4044
- const vx2 = mod(v * x * x, P);
4045
- const root1 = x;
4046
- const root2 = mod(x * ED25519_SQRT_M1, P);
4047
- const useRoot1 = vx2 === u;
4048
- const useRoot2 = vx2 === mod(-u, P);
4049
- const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
4050
- if (useRoot1)
4051
- x = root1;
4052
- if (useRoot2 || noRoot)
4053
- x = root2;
4054
- if (isNegativeLE(x, P))
4055
- x = mod(-x, P);
4056
- return { isValid: useRoot1 || useRoot2, value: x };
4057
- }
4058
- function ed25519_domain(data, ctx, phflag) {
4059
- if (ctx.length > 255)
4060
- throw new Error("Context is too big");
4061
- return concatBytes(utf8ToBytes("SigEd25519 no Ed25519 collisions"), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
4062
- }
4063
- function map_to_curve_elligator2_curve25519(u) {
4064
- const ELL2_C4 = (ed25519_CURVE_p - _5n2) / _8n3;
4065
- const ELL2_J = BigInt(486662);
4066
- let tv1 = Fp.sqr(u);
4067
- tv1 = Fp.mul(tv1, _2n4);
4068
- let xd = Fp.add(tv1, Fp.ONE);
4069
- let x1n = Fp.neg(ELL2_J);
4070
- let tv2 = Fp.sqr(xd);
4071
- let gxd = Fp.mul(tv2, xd);
4072
- let gx1 = Fp.mul(tv1, ELL2_J);
4073
- gx1 = Fp.mul(gx1, x1n);
4074
- gx1 = Fp.add(gx1, tv2);
4075
- gx1 = Fp.mul(gx1, x1n);
4076
- let tv3 = Fp.sqr(gxd);
4077
- tv2 = Fp.sqr(tv3);
4078
- tv3 = Fp.mul(tv3, gxd);
4079
- tv3 = Fp.mul(tv3, gx1);
4080
- tv2 = Fp.mul(tv2, tv3);
4081
- let y11 = Fp.pow(tv2, ELL2_C4);
4082
- y11 = Fp.mul(y11, tv3);
4083
- let y12 = Fp.mul(y11, ELL2_C3);
4084
- tv2 = Fp.sqr(y11);
4085
- tv2 = Fp.mul(tv2, gxd);
4086
- let e1 = Fp.eql(tv2, gx1);
4087
- let y1 = Fp.cmov(y12, y11, e1);
4088
- let x2n = Fp.mul(x1n, tv1);
4089
- let y21 = Fp.mul(y11, u);
4090
- y21 = Fp.mul(y21, ELL2_C2);
4091
- let y22 = Fp.mul(y21, ELL2_C3);
4092
- let gx2 = Fp.mul(gx1, tv1);
4093
- tv2 = Fp.sqr(y21);
4094
- tv2 = Fp.mul(tv2, gxd);
4095
- let e2 = Fp.eql(tv2, gx2);
4096
- let y2 = Fp.cmov(y22, y21, e2);
4097
- tv2 = Fp.sqr(y1);
4098
- tv2 = Fp.mul(tv2, gxd);
4099
- let e3 = Fp.eql(tv2, gx1);
4100
- let xn = Fp.cmov(x2n, x1n, e3);
4101
- let y = Fp.cmov(y2, y1, e3);
4102
- let e4 = Fp.isOdd(y);
4103
- y = Fp.cmov(y, Fp.neg(y), e3 !== e4);
4104
- return { xMn: xn, xMd: xd, yMn: y, yMd: _1n6 };
4105
- }
4106
- function map_to_curve_elligator2_edwards25519(u) {
4107
- const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u);
4108
- let xn = Fp.mul(xMn, yMd);
4109
- xn = Fp.mul(xn, ELL2_C1_EDWARDS);
4110
- let xd = Fp.mul(xMd, yMn);
4111
- let yn = Fp.sub(xMn, xMd);
4112
- let yd = Fp.add(xMn, xMd);
4113
- let tv1 = Fp.mul(xd, yd);
4114
- let e = Fp.eql(tv1, Fp.ZERO);
4115
- xn = Fp.cmov(xn, Fp.ZERO, e);
4116
- xd = Fp.cmov(xd, Fp.ONE, e);
4117
- yn = Fp.cmov(yn, Fp.ONE, e);
4118
- yd = Fp.cmov(yd, Fp.ONE, e);
4119
- const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true);
4120
- return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) };
4121
- }
4122
- function calcElligatorRistrettoMap(r0) {
4123
- const { d } = ed25519_CURVE;
4124
- const P = ed25519_CURVE_p;
4125
- const mod2 = (n) => Fp.create(n);
4126
- const r = mod2(SQRT_M1 * r0 * r0);
4127
- const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
4128
- let c = BigInt(-1);
4129
- const D = mod2((c - d * r) * mod2(r + d));
4130
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
4131
- let s_ = mod2(s * r0);
4132
- if (!isNegativeLE(s_, P))
4133
- s_ = mod2(-s_);
4134
- if (!Ns_D_is_sq)
4135
- s = s_;
4136
- if (!Ns_D_is_sq)
4137
- c = r;
4138
- const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
4139
- const s2 = s * s;
4140
- const W0 = mod2((s + s) * D);
4141
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
4142
- const W2 = mod2(_1n6 - s2);
4143
- const W3 = mod2(_1n6 + s2);
4144
- return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
4145
- }
4146
- function ristretto255_map(bytes) {
4147
- abytes(bytes, 64);
4148
- const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
4149
- const R1 = calcElligatorRistrettoMap(r1);
4150
- const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
4151
- const R2 = calcElligatorRistrettoMap(r2);
4152
- return new _RistrettoPoint(R1.add(R2));
4153
- }
4154
- function edwardsToMontgomeryPub(edwardsPub) {
4155
- return ed25519.utils.toMontgomery(ensureBytes("pub", edwardsPub));
4156
- }
4157
- function edwardsToMontgomeryPriv(edwardsPriv) {
4158
- return ed25519.utils.toMontgomerySecret(ensureBytes("pub", edwardsPriv));
4159
- }
4160
- 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;
4161
- var init_ed25519 = __esm({
4162
- "node_modules/@noble/curves/esm/ed25519.js"() {
4163
- "use strict";
4164
- init_sha2();
4165
- init_utils();
4166
- init_curve();
4167
- init_edwards();
4168
- init_hash_to_curve();
4169
- init_modular();
4170
- init_montgomery();
4171
- init_utils2();
4172
- _0n6 = /* @__PURE__ */ BigInt(0);
4173
- _1n6 = BigInt(1);
4174
- _2n4 = BigInt(2);
4175
- _3n2 = BigInt(3);
4176
- _5n2 = BigInt(5);
4177
- _8n3 = BigInt(8);
4178
- ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
4179
- ed25519_CURVE = /* @__PURE__ */ (() => ({
4180
- p: ed25519_CURVE_p,
4181
- n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
4182
- h: _8n3,
4183
- a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
4184
- d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
4185
- Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
4186
- Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
4187
- }))();
4188
- ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
4189
- Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
4190
- Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
4191
- ed25519Defaults = /* @__PURE__ */ (() => ({
4192
- ...ed25519_CURVE,
4193
- Fp,
4194
- hash: sha512,
4195
- adjustScalarBytes,
4196
- // dom2
4197
- // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
4198
- // Constant-time, u/√v
4199
- uvRatio
4200
- }))();
4201
- ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
4202
- ed25519ctx = /* @__PURE__ */ (() => twistedEdwards({
4203
- ...ed25519Defaults,
4204
- domain: ed25519_domain
4205
- }))();
4206
- ed25519ph = /* @__PURE__ */ (() => twistedEdwards(Object.assign({}, ed25519Defaults, {
4207
- domain: ed25519_domain,
4208
- prehash: sha512
4209
- })))();
4210
- x25519 = /* @__PURE__ */ (() => {
4211
- const P = Fp.ORDER;
4212
- return montgomery({
4213
- P,
4214
- type: "x25519",
4215
- powPminus2: (x) => {
4216
- const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
4217
- return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
4218
- },
4219
- adjustScalarBytes
4220
- });
4221
- })();
4222
- ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n2) / _8n3)();
4223
- ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n4, ELL2_C1))();
4224
- ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))();
4225
- ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();
4226
- ed25519_hasher = /* @__PURE__ */ (() => createHasher2(ed25519.Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
4227
- DST: "edwards25519_XMD:SHA-512_ELL2_RO_",
4228
- encodeDST: "edwards25519_XMD:SHA-512_ELL2_NU_",
4229
- p: ed25519_CURVE_p,
4230
- m: 1,
4231
- k: 128,
4232
- expand: "xmd",
4233
- hash: sha512
4234
- }))();
4235
- SQRT_M1 = ED25519_SQRT_M1;
4236
- SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
4237
- INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
4238
- ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
4239
- D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
4240
- invertSqrt = (number) => uvRatio(_1n6, number);
4241
- MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
4242
- bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
4243
- _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
4244
- constructor(ep) {
4245
- super(ep);
4246
- }
4247
- static fromAffine(ap) {
4248
- return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
4249
- }
4250
- assertSame(other) {
4251
- if (!(other instanceof __RistrettoPoint))
4252
- throw new Error("RistrettoPoint expected");
4253
- }
4254
- init(ep) {
4255
- return new __RistrettoPoint(ep);
4256
- }
4257
- /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
4258
- static hashToCurve(hex) {
4259
- return ristretto255_map(ensureBytes("ristrettoHash", hex, 64));
4260
- }
4261
- static fromBytes(bytes) {
4262
- abytes(bytes, 32);
4263
- const { a, d } = ed25519_CURVE;
4264
- const P = ed25519_CURVE_p;
4265
- const mod2 = (n) => Fp.create(n);
4266
- const s = bytes255ToNumberLE(bytes);
4267
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
4268
- throw new Error("invalid ristretto255 encoding 1");
4269
- const s2 = mod2(s * s);
4270
- const u1 = mod2(_1n6 + a * s2);
4271
- const u2 = mod2(_1n6 - a * s2);
4272
- const u1_2 = mod2(u1 * u1);
4273
- const u2_2 = mod2(u2 * u2);
4274
- const v = mod2(a * d * u1_2 - u2_2);
4275
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
4276
- const Dx = mod2(I * u2);
4277
- const Dy = mod2(I * Dx * v);
4278
- let x = mod2((s + s) * Dx);
4279
- if (isNegativeLE(x, P))
4280
- x = mod2(-x);
4281
- const y = mod2(u1 * Dy);
4282
- const t = mod2(x * y);
4283
- if (!isValid || isNegativeLE(t, P) || y === _0n6)
4284
- throw new Error("invalid ristretto255 encoding 2");
4285
- return new __RistrettoPoint(new ed25519.Point(x, y, _1n6, t));
4286
- }
4287
- /**
4288
- * Converts ristretto-encoded string to ristretto point.
4289
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
4290
- * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
4291
- */
4292
- static fromHex(hex) {
4293
- return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex, 32));
4294
- }
4295
- static msm(points, scalars) {
4296
- return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
4297
- }
4298
- /**
4299
- * Encodes ristretto point to Uint8Array.
4300
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
4301
- */
4302
- toBytes() {
4303
- let { X, Y, Z, T } = this.ep;
4304
- const P = ed25519_CURVE_p;
4305
- const mod2 = (n) => Fp.create(n);
4306
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
4307
- const u2 = mod2(X * Y);
4308
- const u2sq = mod2(u2 * u2);
4309
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
4310
- const D1 = mod2(invsqrt * u1);
4311
- const D2 = mod2(invsqrt * u2);
4312
- const zInv = mod2(D1 * D2 * T);
4313
- let D;
4314
- if (isNegativeLE(T * zInv, P)) {
4315
- let _x = mod2(Y * SQRT_M1);
4316
- let _y = mod2(X * SQRT_M1);
4317
- X = _x;
4318
- Y = _y;
4319
- D = mod2(D1 * INVSQRT_A_MINUS_D);
4320
- } else {
4321
- D = D2;
4322
- }
4323
- if (isNegativeLE(X * zInv, P))
4324
- Y = mod2(-Y);
4325
- let s = mod2((Z - Y) * D);
4326
- if (isNegativeLE(s, P))
4327
- s = mod2(-s);
4328
- return Fp.toBytes(s);
4329
- }
4330
- /**
4331
- * Compares two Ristretto points.
4332
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
4333
- */
4334
- equals(other) {
4335
- this.assertSame(other);
4336
- const { X: X1, Y: Y1 } = this.ep;
4337
- const { X: X2, Y: Y2 } = other.ep;
4338
- const mod2 = (n) => Fp.create(n);
4339
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
4340
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
4341
- return one || two;
4342
- }
4343
- is0() {
4344
- return this.equals(__RistrettoPoint.ZERO);
4345
- }
4346
- };
4347
- _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
4348
- _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
4349
- _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
4350
- _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
4351
- ristretto255 = { Point: _RistrettoPoint };
4352
- ristretto255_hasher = {
4353
- hashToCurve(msg, options) {
4354
- const DST = options?.DST || "ristretto255_XMD:SHA-512_R255MAP_RO_";
4355
- const xmd = expand_message_xmd(msg, DST, 64, sha512);
4356
- return ristretto255_map(xmd);
4357
- },
4358
- hashToScalar(msg, options = { DST: _DST_scalar }) {
4359
- const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
4360
- return Fn.create(bytesToNumberLE(xmd));
4361
- }
4362
- };
4363
- ED25519_TORSION_SUBGROUP = [
4364
- "0100000000000000000000000000000000000000000000000000000000000000",
4365
- "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
4366
- "0000000000000000000000000000000000000000000000000000000000000080",
4367
- "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
4368
- "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
4369
- "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
4370
- "0000000000000000000000000000000000000000000000000000000000000000",
4371
- "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"
4372
- ];
4373
- edwardsToMontgomery = edwardsToMontgomeryPub;
4374
- RistrettoPoint = _RistrettoPoint;
4375
- hashToCurve = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();
4376
- encodeToCurve = /* @__PURE__ */ (() => ed25519_hasher.encodeToCurve)();
4377
- hashToRistretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();
4378
- hash_to_ristretto255 = /* @__PURE__ */ (() => ristretto255_hasher.hashToCurve)();
4379
- }
4380
- });
4381
-
4382
1830
  // src/bundle.ts
4383
1831
  var bundle_exports = {};
4384
1832
  __export(bundle_exports, {
@@ -4768,6 +2216,160 @@ var init_hook_patterns = __esm({
4768
2216
  }
4769
2217
  });
4770
2218
 
2219
+ // src/scopeblind-bridge.ts
2220
+ function getScopeBlindBridge() {
2221
+ if (!singleton) singleton = new ScopeBlindBridge();
2222
+ return singleton;
2223
+ }
2224
+ var DEFAULT_BASE, FLUSH_INTERVAL_MS, BATCH_MAX, BRASS_REFRESH_MARGIN_MS, ScopeBlindBridge, singleton;
2225
+ var init_scopeblind_bridge = __esm({
2226
+ "src/scopeblind-bridge.ts"() {
2227
+ "use strict";
2228
+ DEFAULT_BASE = "https://scopeblind.com";
2229
+ FLUSH_INTERVAL_MS = 5e3;
2230
+ BATCH_MAX = 128;
2231
+ BRASS_REFRESH_MARGIN_MS = 5 * 60 * 1e3;
2232
+ ScopeBlindBridge = class {
2233
+ token;
2234
+ base;
2235
+ tenantOverride;
2236
+ cachedProof = null;
2237
+ queue = [];
2238
+ flushTimer = null;
2239
+ stats;
2240
+ shuttingDown = false;
2241
+ constructor(env = process.env) {
2242
+ this.token = env.SCOPEBLIND_TOKEN || null;
2243
+ this.base = (env.SCOPEBLIND_BASE || DEFAULT_BASE).replace(/\/$/, "");
2244
+ this.tenantOverride = env.SCOPEBLIND_TENANT || null;
2245
+ this.stats = {
2246
+ enabled: Boolean(this.token),
2247
+ tenant_slug: this.tenantOverride,
2248
+ forwarded_total: 0,
2249
+ rejected_total: 0,
2250
+ last_flush_at: null,
2251
+ last_error: null
2252
+ };
2253
+ if (this.enabled()) {
2254
+ this.flushTimer = setInterval(() => {
2255
+ void this.flush();
2256
+ }, FLUSH_INTERVAL_MS);
2257
+ if (typeof this.flushTimer === "object" && this.flushTimer && "unref" in this.flushTimer) {
2258
+ this.flushTimer.unref?.();
2259
+ }
2260
+ process.on("beforeExit", () => {
2261
+ void this.shutdown();
2262
+ });
2263
+ }
2264
+ }
2265
+ enabled() {
2266
+ return Boolean(this.token);
2267
+ }
2268
+ /** Push a signed receipt into the queue. Non-blocking. */
2269
+ forward(signedReceipt) {
2270
+ if (!this.enabled() || this.shuttingDown) return;
2271
+ this.queue.push(signedReceipt);
2272
+ if (this.queue.length >= BATCH_MAX) void this.flush();
2273
+ }
2274
+ /** Flush the queue. Safe to call concurrently. */
2275
+ async flush() {
2276
+ if (!this.enabled() || this.queue.length === 0) return;
2277
+ const batch = this.queue.splice(0, BATCH_MAX);
2278
+ try {
2279
+ const proof = await this.ensureBrassProof();
2280
+ const slug = this.tenantOverride || proof?.tenant_id;
2281
+ if (!slug) {
2282
+ this.queue.unshift(...batch);
2283
+ return;
2284
+ }
2285
+ this.stats.tenant_slug = slug;
2286
+ const res = await fetch(`${this.base}/fn/console/${slug}/receipts`, {
2287
+ method: "POST",
2288
+ headers: {
2289
+ "content-type": "application/json",
2290
+ authorization: `Bearer ${this.token}`,
2291
+ "user-agent": "protect-mcp/scopeblind-bridge"
2292
+ },
2293
+ body: JSON.stringify({ receipts: batch })
2294
+ });
2295
+ if (!res.ok) {
2296
+ const errBody = await res.text().catch(() => "");
2297
+ this.stats.last_error = `HTTP ${res.status} ${errBody.slice(0, 160)}`;
2298
+ this.stats.rejected_total += batch.length;
2299
+ if (res.status >= 500 && res.status !== 503) {
2300
+ this.queue.unshift(...batch);
2301
+ }
2302
+ return;
2303
+ }
2304
+ const body = await res.json().catch(() => ({}));
2305
+ this.stats.forwarded_total += body?.accepted ?? batch.length;
2306
+ this.stats.rejected_total += body?.rejected ?? 0;
2307
+ this.stats.last_flush_at = (/* @__PURE__ */ new Date()).toISOString();
2308
+ this.stats.last_error = null;
2309
+ } catch (err) {
2310
+ this.stats.last_error = String(err?.message || err);
2311
+ this.queue.unshift(...batch);
2312
+ }
2313
+ }
2314
+ /** Exchange SCOPEBLIND_TOKEN for a BRASS-v2 proof; refresh near expiry. */
2315
+ async ensureBrassProof() {
2316
+ if (!this.token) return null;
2317
+ const now = Date.now();
2318
+ if (this.cachedProof && Date.parse(this.cachedProof.expires_at) - now > BRASS_REFRESH_MARGIN_MS) {
2319
+ return this.cachedProof;
2320
+ }
2321
+ try {
2322
+ const res = await fetch(`${this.base}/fn/brass/issue`, {
2323
+ method: "POST",
2324
+ headers: {
2325
+ "content-type": "application/json",
2326
+ "user-agent": "protect-mcp/scopeblind-bridge"
2327
+ },
2328
+ body: JSON.stringify({
2329
+ token: this.token,
2330
+ scope: "protect-mcp-receipt-emit",
2331
+ ttl_seconds: 3600
2332
+ })
2333
+ });
2334
+ if (!res.ok) {
2335
+ const text = await res.text().catch(() => "");
2336
+ this.stats.last_error = `brass-issue: HTTP ${res.status} ${text.slice(0, 160)}`;
2337
+ return null;
2338
+ }
2339
+ const body = await res.json();
2340
+ if (!body?.auth_proof) {
2341
+ this.stats.last_error = "brass-issue: missing auth_proof in response";
2342
+ return null;
2343
+ }
2344
+ this.cachedProof = body.auth_proof;
2345
+ return this.cachedProof;
2346
+ } catch (err) {
2347
+ this.stats.last_error = `brass-issue: ${err?.message || err}`;
2348
+ return null;
2349
+ }
2350
+ }
2351
+ /**
2352
+ * Return a snapshot of bridge stats. Useful for `protect-mcp scopeblind status`.
2353
+ */
2354
+ getStats() {
2355
+ return {
2356
+ ...this.stats,
2357
+ queued: this.queue.length,
2358
+ brass_proof_expires_at: this.cachedProof?.expires_at || null
2359
+ };
2360
+ }
2361
+ /** Flush remaining receipts and stop the interval. Called on process exit. */
2362
+ async shutdown() {
2363
+ if (this.shuttingDown) return;
2364
+ this.shuttingDown = true;
2365
+ if (this.flushTimer) clearInterval(this.flushTimer);
2366
+ if (this.queue.length > 0) await this.flush();
2367
+ }
2368
+ };
2369
+ singleton = null;
2370
+ }
2371
+ });
2372
+
4771
2373
  // src/hook-server.ts
4772
2374
  var hook_server_exports = {};
4773
2375
  __export(hook_server_exports, {
@@ -4976,7 +2578,7 @@ async function handlePreToolUse(input, state) {
4976
2578
  const hookLatency = Date.now() - hookStart;
4977
2579
  const denyKey = `${toolName}:${input.sessionId || "default"}`;
4978
2580
  state.denyCounter.delete(denyKey);
4979
- emitDecisionLog(state, {
2581
+ const emit = emitDecisionLog(state, {
4980
2582
  tool: toolName,
4981
2583
  decision: "allow",
4982
2584
  reason_code: state.cedarPolicies ? "cedar_allow" : state.jsonPolicy ? "policy_allow" : "observe_mode",
@@ -4988,6 +2590,15 @@ async function handlePreToolUse(input, state) {
4988
2590
  sandbox_state: detectSandboxState(),
4989
2591
  plan_receipt_id: state.activePlanReceiptId || void 0
4990
2592
  });
2593
+ if (state.enforce && emit.signingFailed) {
2594
+ return {
2595
+ hookSpecificOutput: {
2596
+ hookEventName: "PreToolUse",
2597
+ permissionDecision: "deny",
2598
+ permissionDecisionReason: `[ScopeBlind] "${toolName}" was blocked because its receipt could not be signed. Failing closed: a governed action that cannot be proven is not allowed.`
2599
+ }
2600
+ };
2601
+ }
4991
2602
  return {};
4992
2603
  }
4993
2604
  async function handlePostToolUse(input, state) {
@@ -5235,11 +2846,35 @@ function emitDecisionLog(state, entry) {
5235
2846
  } catch {
5236
2847
  }
5237
2848
  state.receiptBuffer.add(log.request_id, signed.signed);
5238
- } else if (signed.warning) {
5239
- process.stderr.write(`[PROTECT_MCP] Warning: ${signed.warning}
2849
+ try {
2850
+ const bridge = getScopeBlindBridge();
2851
+ if (bridge.enabled()) {
2852
+ const parsed = typeof signed.signed === "string" ? JSON.parse(signed.signed) : signed.signed;
2853
+ bridge.forward(parsed);
2854
+ }
2855
+ } catch (err) {
2856
+ process.stderr.write(`[PROTECT_MCP] ScopeBlind forward error: ${err instanceof Error ? err.message : err}
2857
+ `);
2858
+ }
2859
+ } else if (signed.error) {
2860
+ const tombstone = JSON.stringify({
2861
+ type: "scopeblind.signing_failure.v1",
2862
+ request_id: log.request_id,
2863
+ tool: log.tool,
2864
+ decision: log.decision,
2865
+ error: signed.error,
2866
+ at: new Date(log.timestamp).toISOString()
2867
+ });
2868
+ try {
2869
+ (0, import_node_fs8.appendFileSync)(state.receiptFilePath, tombstone + "\n");
2870
+ } catch {
2871
+ }
2872
+ process.stderr.write(`[PROTECT_MCP_SIGNING_FAILURE] ${tombstone}
5240
2873
  `);
2874
+ return { signingFailed: true };
5241
2875
  }
5242
2876
  }
2877
+ return { signingFailed: false };
5243
2878
  }
5244
2879
  async function routeHookEvent(input, state) {
5245
2880
  switch (input.hookEventName) {
@@ -5550,6 +3185,7 @@ var init_hook_server = __esm({
5550
3185
  init_signing();
5551
3186
  init_policy();
5552
3187
  init_http_server();
3188
+ init_scopeblind_bridge();
5553
3189
  DEFAULT_PORT = 9377;
5554
3190
  LOG_FILE3 = ".protect-mcp-log.jsonl";
5555
3191
  RECEIPTS_FILE2 = ".protect-mcp-receipts.jsonl";
@@ -6199,14 +3835,14 @@ async function handleInit(argv) {
6199
3835
  }
6200
3836
  let keypair;
6201
3837
  {
6202
- const { randomBytes: randomBytes4 } = await import("crypto");
6203
- const { ed25519: ed255192 } = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
6204
- const { bytesToHex: bytesToHex2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));
6205
- const privateKey = randomBytes4(32);
6206
- const publicKey = ed255192.getPublicKey(privateKey);
3838
+ const { randomBytes: randomBytes3 } = await import("crypto");
3839
+ const { ed25519 } = await import("@noble/curves/ed25519");
3840
+ const { bytesToHex } = await import("@noble/hashes/utils");
3841
+ const privateKey = randomBytes3(32);
3842
+ const publicKey = ed25519.getPublicKey(privateKey);
6207
3843
  keypair = {
6208
- privateKey: bytesToHex2(privateKey),
6209
- publicKey: bytesToHex2(publicKey),
3844
+ privateKey: bytesToHex(privateKey),
3845
+ publicKey: bytesToHex(publicKey),
6210
3846
  kid: "generated"
6211
3847
  };
6212
3848
  }
@@ -6817,22 +4453,22 @@ ${bold("protect-mcp quickstart")}
6817
4453
  `);
6818
4454
  const keysDir = join6(dir, "keys");
6819
4455
  mkdirSync(keysDir, { recursive: true });
6820
- const { randomBytes: randomBytes4 } = await import("crypto");
4456
+ const { randomBytes: randomBytes3 } = await import("crypto");
6821
4457
  let keypair;
6822
4458
  try {
6823
- const { ed25519: ed255192 } = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
6824
- const { bytesToHex: bytesToHex2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));
6825
- const privateKey = randomBytes4(32);
6826
- const publicKey = ed255192.getPublicKey(privateKey);
4459
+ const { ed25519 } = await import("@noble/curves/ed25519");
4460
+ const { bytesToHex } = await import("@noble/hashes/utils");
4461
+ const privateKey = randomBytes3(32);
4462
+ const publicKey = ed25519.getPublicKey(privateKey);
6827
4463
  keypair = {
6828
- privateKey: bytesToHex2(privateKey),
6829
- publicKey: bytesToHex2(publicKey),
4464
+ privateKey: bytesToHex(privateKey),
4465
+ publicKey: bytesToHex(publicKey),
6830
4466
  kid: `quickstart-${Date.now()}`
6831
4467
  };
6832
4468
  } catch {
6833
4469
  keypair = {
6834
- privateKey: randomBytes4(32).toString("hex"),
6835
- publicKey: randomBytes4(32).toString("hex"),
4470
+ privateKey: randomBytes3(32).toString("hex"),
4471
+ publicKey: randomBytes3(32).toString("hex"),
6836
4472
  kid: `quickstart-${Date.now()}`
6837
4473
  };
6838
4474
  }
@@ -7166,13 +4802,13 @@ ${bold("protect-mcp init-hooks")}
7166
4802
  if (!existsSync7(keysDir)) mkdirSync(keysDir, { recursive: true });
7167
4803
  const { randomBytes: rb } = await import("crypto");
7168
4804
  try {
7169
- const { ed25519: ed255192 } = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
7170
- const { bytesToHex: bytesToHex2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));
4805
+ const { ed25519 } = await import("@noble/curves/ed25519");
4806
+ const { bytesToHex } = await import("@noble/hashes/utils");
7171
4807
  const privateKey = rb(32);
7172
- const publicKey = ed255192.getPublicKey(privateKey);
4808
+ const publicKey = ed25519.getPublicKey(privateKey);
7173
4809
  writeFileSync2(keyPath, JSON.stringify({
7174
- privateKey: bytesToHex2(privateKey),
7175
- publicKey: bytesToHex2(publicKey),
4810
+ privateKey: bytesToHex(privateKey),
4811
+ publicKey: bytesToHex(publicKey),
7176
4812
  kid: `hook-${Date.now()}`,
7177
4813
  generated_at: (/* @__PURE__ */ new Date()).toISOString(),
7178
4814
  warning: "KEEP THIS FILE SECRET. Never commit to version control."
@@ -7712,16 +5348,33 @@ main().catch((err) => {
7712
5348
  `);
7713
5349
  process.exit(1);
7714
5350
  });
7715
- /*! Bundled license information:
7716
-
7717
- @noble/hashes/esm/utils.js:
7718
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7719
-
7720
- @noble/curves/esm/utils.js:
7721
- @noble/curves/esm/abstract/modular.js:
7722
- @noble/curves/esm/abstract/curve.js:
7723
- @noble/curves/esm/abstract/edwards.js:
7724
- @noble/curves/esm/abstract/montgomery.js:
7725
- @noble/curves/esm/ed25519.js:
7726
- (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7727
- */
5351
+ /**
5352
+ * scopeblind-bridge.ts
5353
+ *
5354
+ * Optional bridge between protect-mcp (local, MIT) and a paid ScopeBlind
5355
+ * tenant. When SCOPEBLIND_TOKEN is set in the environment, every signed
5356
+ * receipt that protect-mcp emits also gets forwarded to the tenant's
5357
+ * dashboard at https://scopeblind.com/console/<slug>.
5358
+ *
5359
+ * Lifecycle:
5360
+ * 1. On first use, exchange SCOPEBLIND_TOKEN for a short-lived BRASS-v2
5361
+ * auth proof from /fn/brass/issue. Cache the proof in memory until
5362
+ * ~5 minutes before expiry, then refresh.
5363
+ * 2. As receipts are emitted by hook-server.ts, push them into an
5364
+ * in-memory batch queue.
5365
+ * 3. Flush the queue every 5s (or when it reaches 128 receipts) by POSTing
5366
+ * to /fn/console/<slug>/receipts with Bearer SCOPEBLIND_TOKEN.
5367
+ *
5368
+ * Failure mode: forward errors NEVER throw upstream. protect-mcp continues
5369
+ * to mint and persist receipts locally regardless of dashboard availability.
5370
+ * The bridge logs failures to stderr (best-effort) and retries on the next
5371
+ * flush.
5372
+ *
5373
+ * Configuration:
5374
+ * SCOPEBLIND_TOKEN Tenant bearer token (from welcome email).
5375
+ * SCOPEBLIND_TENANT Optional slug override. By default we discover
5376
+ * the slug from the BRASS proof's tenant_id.
5377
+ * SCOPEBLIND_BASE Defaults to https://scopeblind.com.
5378
+ *
5379
+ * @license MIT
5380
+ */