save-forever-mcp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { secp256k1, sha256 } from './chunk-4UXTALEH.js';
3
- import { toHex, getAddress, keccak256, checksumAddress, isAddress, InvalidAddressError, isHex, hexToBytes, numberToHex, concat, concatHex, hexToBigInt, InvalidSerializableTransactionError, bytesToHex, InvalidLegacyVError, trim, stringToHex, size, createCursor, BaseError, stringify, integerRegex, bytesRegex, BytesSizeMismatchError, encodeAbiParameters, InvalidChainIdError, maxUint256, FeeCapTooHighError, TipAboveFeeCapError, InvalidStorageKeySizeError, hexToNumber, slice, toBytes } from './chunk-ZGDY5OSW.js';
4
- import './chunk-5DKVHEO2.js';
2
+ import { secp256k1, sha256, Field, wNAF, sha512, hmac, validateBasic, FpInvertBatch, pippenger, mod, isNegativeLE, pow2 } from './chunk-JKB3QFBD.js';
3
+ import { toHex, getAddress, keccak256, checksumAddress, isAddress, InvalidAddressError, isHex, hexToBytes, numberToHex, concat, concatHex, hexToBigInt, InvalidSerializableTransactionError, bytesToHex, InvalidLegacyVError, trim, stringToHex, size, createCursor, BaseError, stringify, integerRegex, bytesRegex, BytesSizeMismatchError, encodeAbiParameters, InvalidChainIdError, maxUint256, FeeCapTooHighError, TipAboveFeeCapError, InvalidStorageKeySizeError, hexToNumber, slice, toBytes as toBytes$1 } from './chunk-TGY4KIJJ.js';
4
+ import { randomBytes, concatBytes, utf8ToBytes, abool, memoized, numberToBytesLE, ahash, anumber, clean, toBytes, validateObject, aInRange, ensureBytes, bytesToNumberLE, bytesToHex as bytesToHex$1, concatBytes2 } from './chunk-JACDA5LQ.js';
5
5
  import { __commonJS, __export, __toESM } from './chunk-77HVPD4G.js';
6
6
  import process3 from 'process';
7
7
  import { readFile, writeFile } from 'fs/promises';
8
8
  import { resolve } from 'path';
9
- import { randomInt, randomBytes, createDecipheriv, scryptSync, createCipheriv } from 'crypto';
9
+ import { randomInt, randomBytes as randomBytes$1, createDecipheriv, scryptSync, createCipheriv } from 'crypto';
10
10
 
11
11
  // node_modules/ajv/dist/compile/codegen/code.js
12
12
  var require_code = __commonJS({
@@ -31100,7 +31100,7 @@ var sha2562 = sha256;
31100
31100
 
31101
31101
  // node_modules/viem/_esm/utils/hash/sha256.js
31102
31102
  function sha2563(value, to_) {
31103
- const bytes = sha2562(isHex(value, { strict: false }) ? toBytes(value) : value);
31103
+ const bytes = sha2562(isHex(value, { strict: false }) ? toBytes$1(value) : value);
31104
31104
  return bytes;
31105
31105
  }
31106
31106
 
@@ -31888,6 +31888,262 @@ function toClientEvmSigner(signer) {
31888
31888
  return signer;
31889
31889
  }
31890
31890
 
31891
+ // node_modules/@scure/base/lib/esm/index.js
31892
+ function isBytes(a) {
31893
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
31894
+ }
31895
+ function isArrayOf(isString, arr) {
31896
+ if (!Array.isArray(arr))
31897
+ return false;
31898
+ if (arr.length === 0)
31899
+ return true;
31900
+ if (isString) {
31901
+ return arr.every((item) => typeof item === "string");
31902
+ } else {
31903
+ return arr.every((item) => Number.isSafeInteger(item));
31904
+ }
31905
+ }
31906
+ function afn(input) {
31907
+ if (typeof input !== "function")
31908
+ throw new Error("function expected");
31909
+ return true;
31910
+ }
31911
+ function astr(label, input) {
31912
+ if (typeof input !== "string")
31913
+ throw new Error(`${label}: string expected`);
31914
+ return true;
31915
+ }
31916
+ function anumber2(n) {
31917
+ if (!Number.isSafeInteger(n))
31918
+ throw new Error(`invalid integer: ${n}`);
31919
+ }
31920
+ function aArr(input) {
31921
+ if (!Array.isArray(input))
31922
+ throw new Error("array expected");
31923
+ }
31924
+ function astrArr(label, input) {
31925
+ if (!isArrayOf(true, input))
31926
+ throw new Error(`${label}: array of strings expected`);
31927
+ }
31928
+ function anumArr(label, input) {
31929
+ if (!isArrayOf(false, input))
31930
+ throw new Error(`${label}: array of numbers expected`);
31931
+ }
31932
+ // @__NO_SIDE_EFFECTS__
31933
+ function chain(...args) {
31934
+ const id = (a) => a;
31935
+ const wrap2 = (a, b) => (c) => a(b(c));
31936
+ const encode3 = args.map((x) => x.encode).reduceRight(wrap2, id);
31937
+ const decode3 = args.map((x) => x.decode).reduce(wrap2, id);
31938
+ return { encode: encode3, decode: decode3 };
31939
+ }
31940
+ // @__NO_SIDE_EFFECTS__
31941
+ function alphabet(letters) {
31942
+ const lettersA = letters.split("") ;
31943
+ const len = lettersA.length;
31944
+ astrArr("alphabet", lettersA);
31945
+ const indexes = new Map(lettersA.map((l, i) => [l, i]));
31946
+ return {
31947
+ encode: (digits) => {
31948
+ aArr(digits);
31949
+ return digits.map((i) => {
31950
+ if (!Number.isSafeInteger(i) || i < 0 || i >= len)
31951
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
31952
+ return lettersA[i];
31953
+ });
31954
+ },
31955
+ decode: (input) => {
31956
+ aArr(input);
31957
+ return input.map((letter) => {
31958
+ astr("alphabet.decode", letter);
31959
+ const i = indexes.get(letter);
31960
+ if (i === void 0)
31961
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
31962
+ return i;
31963
+ });
31964
+ }
31965
+ };
31966
+ }
31967
+ // @__NO_SIDE_EFFECTS__
31968
+ function join(separator = "") {
31969
+ astr("join", separator);
31970
+ return {
31971
+ encode: (from) => {
31972
+ astrArr("join.decode", from);
31973
+ return from.join(separator);
31974
+ },
31975
+ decode: (to) => {
31976
+ astr("join.decode", to);
31977
+ return to.split(separator);
31978
+ }
31979
+ };
31980
+ }
31981
+ var gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
31982
+ var radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
31983
+ var powers = /* @__PURE__ */ (() => {
31984
+ let res = [];
31985
+ for (let i = 0; i < 40; i++)
31986
+ res.push(2 ** i);
31987
+ return res;
31988
+ })();
31989
+ function convertRadix2(data, from, to, padding) {
31990
+ aArr(data);
31991
+ if (from <= 0 || from > 32)
31992
+ throw new Error(`convertRadix2: wrong from=${from}`);
31993
+ if (to <= 0 || to > 32)
31994
+ throw new Error(`convertRadix2: wrong to=${to}`);
31995
+ if (/* @__PURE__ */ radix2carry(from, to) > 32) {
31996
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from, to)}`);
31997
+ }
31998
+ let carry = 0;
31999
+ let pos = 0;
32000
+ const max = powers[from];
32001
+ const mask = powers[to] - 1;
32002
+ const res = [];
32003
+ for (const n of data) {
32004
+ anumber2(n);
32005
+ if (n >= max)
32006
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
32007
+ carry = carry << from | n;
32008
+ if (pos + from > 32)
32009
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
32010
+ pos += from;
32011
+ for (; pos >= to; pos -= to)
32012
+ res.push((carry >> pos - to & mask) >>> 0);
32013
+ const pow = powers[pos];
32014
+ if (pow === void 0)
32015
+ throw new Error("invalid carry");
32016
+ carry &= pow - 1;
32017
+ }
32018
+ carry = carry << to - pos & mask;
32019
+ if (!padding && pos >= from)
32020
+ throw new Error("Excess padding");
32021
+ if (!padding && carry > 0)
32022
+ throw new Error(`Non-zero padding: ${carry}`);
32023
+ if (padding && pos > 0)
32024
+ res.push(carry >>> 0);
32025
+ return res;
32026
+ }
32027
+ // @__NO_SIDE_EFFECTS__
32028
+ function radix2(bits, revPadding = false) {
32029
+ anumber2(bits);
32030
+ if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32)
32031
+ throw new Error("radix2: carry overflow");
32032
+ return {
32033
+ encode: (bytes) => {
32034
+ if (!isBytes(bytes))
32035
+ throw new Error("radix2.encode input should be Uint8Array");
32036
+ return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
32037
+ },
32038
+ decode: (digits) => {
32039
+ anumArr("radix2.decode", digits);
32040
+ return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
32041
+ }
32042
+ };
32043
+ }
32044
+ function unsafeWrapper(fn) {
32045
+ afn(fn);
32046
+ return function(...args) {
32047
+ try {
32048
+ return fn.apply(null, args);
32049
+ } catch (e) {
32050
+ }
32051
+ };
32052
+ }
32053
+ var BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */ join(""));
32054
+ var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
32055
+ function bech32Polymod(pre) {
32056
+ const b = pre >> 25;
32057
+ let chk = (pre & 33554431) << 5;
32058
+ for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
32059
+ if ((b >> i & 1) === 1)
32060
+ chk ^= POLYMOD_GENERATORS[i];
32061
+ }
32062
+ return chk;
32063
+ }
32064
+ function bechChecksum(prefix, words, encodingConst = 1) {
32065
+ const len = prefix.length;
32066
+ let chk = 1;
32067
+ for (let i = 0; i < len; i++) {
32068
+ const c = prefix.charCodeAt(i);
32069
+ if (c < 33 || c > 126)
32070
+ throw new Error(`Invalid prefix (${prefix})`);
32071
+ chk = bech32Polymod(chk) ^ c >> 5;
32072
+ }
32073
+ chk = bech32Polymod(chk);
32074
+ for (let i = 0; i < len; i++)
32075
+ chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
32076
+ for (let v of words)
32077
+ chk = bech32Polymod(chk) ^ v;
32078
+ for (let i = 0; i < 6; i++)
32079
+ chk = bech32Polymod(chk);
32080
+ chk ^= encodingConst;
32081
+ return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
32082
+ }
32083
+ // @__NO_SIDE_EFFECTS__
32084
+ function genBech32(encoding) {
32085
+ const ENCODING_CONST = 1 ;
32086
+ const _words = /* @__PURE__ */ radix2(5);
32087
+ const fromWords = _words.decode;
32088
+ const toWords = _words.encode;
32089
+ const fromWordsUnsafe = unsafeWrapper(fromWords);
32090
+ function encode3(prefix, words, limit = 90) {
32091
+ astr("bech32.encode prefix", prefix);
32092
+ if (isBytes(words))
32093
+ words = Array.from(words);
32094
+ anumArr("bech32.encode", words);
32095
+ const plen = prefix.length;
32096
+ if (plen === 0)
32097
+ throw new TypeError(`Invalid prefix length ${plen}`);
32098
+ const actualLength = plen + 7 + words.length;
32099
+ if (limit !== false && actualLength > limit)
32100
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
32101
+ const lowered = prefix.toLowerCase();
32102
+ const sum = bechChecksum(lowered, words, ENCODING_CONST);
32103
+ return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
32104
+ }
32105
+ function decode3(str, limit = 90) {
32106
+ astr("bech32.decode input", str);
32107
+ const slen = str.length;
32108
+ if (slen < 8 || limit !== false && slen > limit)
32109
+ throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
32110
+ const lowered = str.toLowerCase();
32111
+ if (str !== lowered && str !== str.toUpperCase())
32112
+ throw new Error(`String must be lowercase or uppercase`);
32113
+ const sepIndex = lowered.lastIndexOf("1");
32114
+ if (sepIndex === 0 || sepIndex === -1)
32115
+ throw new Error(`Letter "1" must be present between prefix and data only`);
32116
+ const prefix = lowered.slice(0, sepIndex);
32117
+ const data = lowered.slice(sepIndex + 1);
32118
+ if (data.length < 6)
32119
+ throw new Error("Data must be at least 6 characters long");
32120
+ const words = BECH_ALPHABET.decode(data).slice(0, -6);
32121
+ const sum = bechChecksum(prefix, words, ENCODING_CONST);
32122
+ if (!data.endsWith(sum))
32123
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
32124
+ return { prefix, words };
32125
+ }
32126
+ const decodeUnsafe = unsafeWrapper(decode3);
32127
+ function decodeToBytes(str) {
32128
+ const { prefix, words } = decode3(str, false);
32129
+ return { prefix, words, bytes: fromWords(words) };
32130
+ }
32131
+ function encodeFromBytes(prefix, bytes) {
32132
+ return encode3(prefix, toWords(bytes));
32133
+ }
32134
+ return {
32135
+ encode: encode3,
32136
+ decode: decode3,
32137
+ encodeFromBytes,
32138
+ decodeToBytes,
32139
+ decodeUnsafe,
32140
+ fromWords,
32141
+ fromWordsUnsafe,
32142
+ toWords
32143
+ };
32144
+ }
32145
+ var bech32 = /* @__PURE__ */ genBech32();
32146
+
31891
32147
  // node_modules/viem/_esm/accounts/toAccount.js
31892
32148
  function toAccount(source) {
31893
32149
  if (typeof source === "string") {
@@ -32022,6 +32278,8 @@ var SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
32022
32278
 
32023
32279
  // src/crypto/messages.ts
32024
32280
  var SAVE_FOREVER_UNLOCK_MSG = "Save Forever \u2014 derive my private-archive unlock key.\nThis signature only controls access to files you save at saveforever.xyz. (v1)";
32281
+ var SAVE_FOREVER_MANAGE_MSG = "Save Forever \u2014 list and organize the archives owned by my wallet.\nThis signature only proves wallet ownership to view and manage my own files (names, folders, hidden); it grants no access to file contents. (v1)";
32282
+ var SAVE_FOREVER_SHARE_LIST_MSG = "Save Forever \u2014 list the files shared with my share identity.";
32025
32283
 
32026
32284
  // src/crypto/walletKey.ts
32027
32285
  function walletKeyFromSignature(signature, salt) {
@@ -32058,7 +32316,7 @@ function codeKeyFrom(recoveryCode, salt) {
32058
32316
  return scryptSync(normalized, salt, KEY_BYTES, SCRYPT);
32059
32317
  }
32060
32318
  function wrap(key, salt, dek, aad) {
32061
- const nonce = randomBytes(NONCE_BYTES);
32319
+ const nonce = randomBytes$1(NONCE_BYTES);
32062
32320
  return Buffer.concat([Buffer.from([ENVELOPE_VERSION]), salt, nonce, gcmEncrypt(key, nonce, dek, aad)]);
32063
32321
  }
32064
32322
  function unwrap(wrapped, deriveKey, aad) {
@@ -32075,22 +32333,27 @@ function encryptPrivate(plaintext, ownerSignature, recoveryCode, archiveId, mani
32075
32333
  throw new Error("Invalid recovery code.");
32076
32334
  }
32077
32335
  if (!archiveId) throw new Error("Missing archive id for AAD binding.");
32078
- const dek = randomBytes(KEY_BYTES);
32079
- const fileNonce = randomBytes(NONCE_BYTES);
32336
+ const dek = randomBytes$1(KEY_BYTES);
32337
+ const fileNonce = randomBytes$1(NONCE_BYTES);
32080
32338
  const ciphertext = gcmEncrypt(dek, fileNonce, plaintext, aadFor(DOMAIN_FILE, archiveId, ENVELOPE_VERSION));
32081
- const walletSalt = randomBytes(SALT_BYTES);
32339
+ const walletSalt = randomBytes$1(SALT_BYTES);
32082
32340
  const wrapAad = aadFor(DOMAIN_WRAP, archiveId, ENVELOPE_VERSION);
32083
32341
  const walletWrap = wrap(walletKeyFromSignature(ownerSignature, walletSalt), walletSalt, dek, wrapAad);
32084
- const codeSalt = randomBytes(SALT_BYTES);
32342
+ const codeSalt = randomBytes$1(SALT_BYTES);
32085
32343
  const codeWrap = wrap(codeKeyFrom(recoveryCode, codeSalt), codeSalt, dek, wrapAad);
32086
32344
  const manifest = manifestBytes ? encryptManifestWithDek(manifestBytes, dek, archiveId) : void 0;
32087
32345
  return { ciphertext, fileNonce, walletWrap, codeWrap, manifest };
32088
32346
  }
32089
32347
  function encryptManifestWithDek(manifestBytes, dek, archiveId) {
32090
- const nonce = randomBytes(NONCE_BYTES);
32348
+ const nonce = randomBytes$1(NONCE_BYTES);
32091
32349
  const body = gcmEncrypt(Buffer.from(dek), nonce, manifestBytes, aadFor(DOMAIN_MANIFEST, archiveId, ENVELOPE_VERSION));
32092
32350
  return Buffer.concat([Buffer.from([ENVELOPE_VERSION]), nonce, body]);
32093
32351
  }
32352
+ function decryptFileWithDek(ciphertext, fileNonce, dek, archiveId) {
32353
+ return new Uint8Array(
32354
+ gcmDecrypt(Buffer.from(dek), Buffer.from(fileNonce), ciphertext, aadFor(DOMAIN_FILE, archiveId, ENVELOPE_VERSION))
32355
+ );
32356
+ }
32094
32357
  function decryptManifestWithDek(blob, dek, archiveId) {
32095
32358
  const buf = Buffer.from(blob);
32096
32359
  if (buf[0] !== ENVELOPE_VERSION) throw new Error(`unsupported manifest version ${buf[0]}`);
@@ -32121,6 +32384,1233 @@ function decryptWithCode(args) {
32121
32384
  );
32122
32385
  }
32123
32386
 
32387
+ // node_modules/@noble/curves/esm/abstract/edwards.js
32388
+ var _0n = BigInt(0);
32389
+ var _1n = BigInt(1);
32390
+ var _2n = BigInt(2);
32391
+ var _8n = BigInt(8);
32392
+ var VERIFY_DEFAULT = { zip215: true };
32393
+ function validateOpts(curve) {
32394
+ const opts = validateBasic(curve);
32395
+ validateObject(curve, {
32396
+ hash: "function",
32397
+ a: "bigint",
32398
+ d: "bigint",
32399
+ randomBytes: "function"
32400
+ }, {
32401
+ adjustScalarBytes: "function",
32402
+ domain: "function",
32403
+ uvRatio: "function",
32404
+ mapToCurve: "function"
32405
+ });
32406
+ return Object.freeze({ ...opts });
32407
+ }
32408
+ function twistedEdwards(curveDef) {
32409
+ const CURVE = validateOpts(curveDef);
32410
+ const { Fp: Fp2, n: CURVE_ORDER, prehash, hash: cHash, randomBytes: randomBytes4, nByteLength, h: cofactor } = CURVE;
32411
+ const MASK = _2n << BigInt(nByteLength * 8) - _1n;
32412
+ const modP = Fp2.create;
32413
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
32414
+ function isEdValidXY(x, y) {
32415
+ const x2 = Fp2.sqr(x);
32416
+ const y2 = Fp2.sqr(y);
32417
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
32418
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
32419
+ return Fp2.eql(left, right);
32420
+ }
32421
+ if (!isEdValidXY(CURVE.Gx, CURVE.Gy))
32422
+ throw new Error("bad curve params: generator point");
32423
+ const uvRatio2 = CURVE.uvRatio || ((u, v) => {
32424
+ try {
32425
+ return { isValid: true, value: Fp2.sqrt(u * Fp2.inv(v)) };
32426
+ } catch (e) {
32427
+ return { isValid: false, value: _0n };
32428
+ }
32429
+ });
32430
+ const adjustScalarBytes2 = CURVE.adjustScalarBytes || ((bytes) => bytes);
32431
+ const domain2 = CURVE.domain || ((data, ctx, phflag) => {
32432
+ abool("phflag", phflag);
32433
+ if (ctx.length || phflag)
32434
+ throw new Error("Contexts/pre-hash are not supported");
32435
+ return data;
32436
+ });
32437
+ function aCoordinate(title, n, banZero = false) {
32438
+ const min = banZero ? _1n : _0n;
32439
+ aInRange("coordinate " + title, n, min, MASK);
32440
+ }
32441
+ function aextpoint(other) {
32442
+ if (!(other instanceof Point))
32443
+ throw new Error("ExtendedPoint expected");
32444
+ }
32445
+ const toAffineMemo = memoized((p, iz) => {
32446
+ const { ex: x, ey: y, ez: z2 } = p;
32447
+ const is0 = p.is0();
32448
+ if (iz == null)
32449
+ iz = is0 ? _8n : Fp2.inv(z2);
32450
+ const ax = modP(x * iz);
32451
+ const ay = modP(y * iz);
32452
+ const zz = modP(z2 * iz);
32453
+ if (is0)
32454
+ return { x: _0n, y: _1n };
32455
+ if (zz !== _1n)
32456
+ throw new Error("invZ was invalid");
32457
+ return { x: ax, y: ay };
32458
+ });
32459
+ const assertValidMemo = memoized((p) => {
32460
+ const { a, d } = CURVE;
32461
+ if (p.is0())
32462
+ throw new Error("bad point: ZERO");
32463
+ const { ex: X, ey: Y, ez: Z, et: T } = p;
32464
+ const X2 = modP(X * X);
32465
+ const Y2 = modP(Y * Y);
32466
+ const Z2 = modP(Z * Z);
32467
+ const Z4 = modP(Z2 * Z2);
32468
+ const aX2 = modP(X2 * a);
32469
+ const left = modP(Z2 * modP(aX2 + Y2));
32470
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
32471
+ if (left !== right)
32472
+ throw new Error("bad point: equation left != right (1)");
32473
+ const XY = modP(X * Y);
32474
+ const ZT = modP(Z * T);
32475
+ if (XY !== ZT)
32476
+ throw new Error("bad point: equation left != right (2)");
32477
+ return true;
32478
+ });
32479
+ class Point {
32480
+ constructor(ex, ey, ez, et) {
32481
+ aCoordinate("x", ex);
32482
+ aCoordinate("y", ey);
32483
+ aCoordinate("z", ez, true);
32484
+ aCoordinate("t", et);
32485
+ this.ex = ex;
32486
+ this.ey = ey;
32487
+ this.ez = ez;
32488
+ this.et = et;
32489
+ Object.freeze(this);
32490
+ }
32491
+ get x() {
32492
+ return this.toAffine().x;
32493
+ }
32494
+ get y() {
32495
+ return this.toAffine().y;
32496
+ }
32497
+ static fromAffine(p) {
32498
+ if (p instanceof Point)
32499
+ throw new Error("extended point not allowed");
32500
+ const { x, y } = p || {};
32501
+ aCoordinate("x", x);
32502
+ aCoordinate("y", y);
32503
+ return new Point(x, y, _1n, modP(x * y));
32504
+ }
32505
+ static normalizeZ(points) {
32506
+ const toInv = FpInvertBatch(Fp2, points.map((p) => p.ez));
32507
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
32508
+ }
32509
+ // Multiscalar Multiplication
32510
+ static msm(points, scalars) {
32511
+ return pippenger(Point, Fn, points, scalars);
32512
+ }
32513
+ // "Private method", don't use it directly
32514
+ _setWindowSize(windowSize) {
32515
+ wnaf.setWindowSize(this, windowSize);
32516
+ }
32517
+ // Not required for fromHex(), which always creates valid points.
32518
+ // Could be useful for fromAffine().
32519
+ assertValidity() {
32520
+ assertValidMemo(this);
32521
+ }
32522
+ // Compare one point to another.
32523
+ equals(other) {
32524
+ aextpoint(other);
32525
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
32526
+ const { ex: X2, ey: Y2, ez: Z2 } = other;
32527
+ const X1Z2 = modP(X1 * Z2);
32528
+ const X2Z1 = modP(X2 * Z1);
32529
+ const Y1Z2 = modP(Y1 * Z2);
32530
+ const Y2Z1 = modP(Y2 * Z1);
32531
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
32532
+ }
32533
+ is0() {
32534
+ return this.equals(Point.ZERO);
32535
+ }
32536
+ negate() {
32537
+ return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
32538
+ }
32539
+ // Fast algo for doubling Extended Point.
32540
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
32541
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
32542
+ double() {
32543
+ const { a } = CURVE;
32544
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
32545
+ const A = modP(X1 * X1);
32546
+ const B = modP(Y1 * Y1);
32547
+ const C = modP(_2n * modP(Z1 * Z1));
32548
+ const D = modP(a * A);
32549
+ const x1y1 = X1 + Y1;
32550
+ const E = modP(modP(x1y1 * x1y1) - A - B);
32551
+ const G2 = D + B;
32552
+ const F = G2 - C;
32553
+ const H = D - B;
32554
+ const X3 = modP(E * F);
32555
+ const Y3 = modP(G2 * H);
32556
+ const T3 = modP(E * H);
32557
+ const Z3 = modP(F * G2);
32558
+ return new Point(X3, Y3, Z3, T3);
32559
+ }
32560
+ // Fast algo for adding 2 Extended Points.
32561
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
32562
+ // Cost: 9M + 1*a + 1*d + 7add.
32563
+ add(other) {
32564
+ aextpoint(other);
32565
+ const { a, d } = CURVE;
32566
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
32567
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
32568
+ const A = modP(X1 * X2);
32569
+ const B = modP(Y1 * Y2);
32570
+ const C = modP(T1 * d * T2);
32571
+ const D = modP(Z1 * Z2);
32572
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
32573
+ const F = D - C;
32574
+ const G2 = D + C;
32575
+ const H = modP(B - a * A);
32576
+ const X3 = modP(E * F);
32577
+ const Y3 = modP(G2 * H);
32578
+ const T3 = modP(E * H);
32579
+ const Z3 = modP(F * G2);
32580
+ return new Point(X3, Y3, Z3, T3);
32581
+ }
32582
+ subtract(other) {
32583
+ return this.add(other.negate());
32584
+ }
32585
+ wNAF(n) {
32586
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
32587
+ }
32588
+ // Constant-time multiplication.
32589
+ multiply(scalar) {
32590
+ const n = scalar;
32591
+ aInRange("scalar", n, _1n, CURVE_ORDER);
32592
+ const { p, f } = this.wNAF(n);
32593
+ return Point.normalizeZ([p, f])[0];
32594
+ }
32595
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
32596
+ // It's faster, but should only be used when you don't care about
32597
+ // an exposed private key e.g. sig verification.
32598
+ // Does NOT allow scalars higher than CURVE.n.
32599
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
32600
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
32601
+ const n = scalar;
32602
+ aInRange("scalar", n, _0n, CURVE_ORDER);
32603
+ if (n === _0n)
32604
+ return I;
32605
+ if (this.is0() || n === _1n)
32606
+ return this;
32607
+ return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
32608
+ }
32609
+ // Checks if point is of small order.
32610
+ // If you add something to small order point, you will have "dirty"
32611
+ // point with torsion component.
32612
+ // Multiplies point by cofactor and checks if the result is 0.
32613
+ isSmallOrder() {
32614
+ return this.multiplyUnsafe(cofactor).is0();
32615
+ }
32616
+ // Multiplies point by curve order and checks if the result is 0.
32617
+ // Returns `false` is the point is dirty.
32618
+ isTorsionFree() {
32619
+ return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
32620
+ }
32621
+ // Converts Extended point to default (x, y) coordinates.
32622
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
32623
+ toAffine(iz) {
32624
+ return toAffineMemo(this, iz);
32625
+ }
32626
+ clearCofactor() {
32627
+ const { h: cofactor2 } = CURVE;
32628
+ if (cofactor2 === _1n)
32629
+ return this;
32630
+ return this.multiplyUnsafe(cofactor2);
32631
+ }
32632
+ // Converts hash string or Uint8Array to Point.
32633
+ // Uses algo from RFC8032 5.1.3.
32634
+ static fromHex(hex3, zip215 = false) {
32635
+ const { d, a } = CURVE;
32636
+ const len = Fp2.BYTES;
32637
+ hex3 = ensureBytes("pointHex", hex3, len);
32638
+ abool("zip215", zip215);
32639
+ const normed = hex3.slice();
32640
+ const lastByte = hex3[len - 1];
32641
+ normed[len - 1] = lastByte & -129;
32642
+ const y = bytesToNumberLE(normed);
32643
+ const max = zip215 ? MASK : Fp2.ORDER;
32644
+ aInRange("pointHex.y", y, _0n, max);
32645
+ const y2 = modP(y * y);
32646
+ const u = modP(y2 - _1n);
32647
+ const v = modP(d * y2 - a);
32648
+ let { isValid: isValid2, value: x } = uvRatio2(u, v);
32649
+ if (!isValid2)
32650
+ throw new Error("Point.fromHex: invalid y coordinate");
32651
+ const isXOdd = (x & _1n) === _1n;
32652
+ const isLastByteOdd = (lastByte & 128) !== 0;
32653
+ if (!zip215 && x === _0n && isLastByteOdd)
32654
+ throw new Error("Point.fromHex: x=0 and x_0=1");
32655
+ if (isLastByteOdd !== isXOdd)
32656
+ x = modP(-x);
32657
+ return Point.fromAffine({ x, y });
32658
+ }
32659
+ static fromPrivateKey(privKey) {
32660
+ const { scalar } = getPrivateScalar(privKey);
32661
+ return G.multiply(scalar);
32662
+ }
32663
+ toRawBytes() {
32664
+ const { x, y } = this.toAffine();
32665
+ const bytes = numberToBytesLE(y, Fp2.BYTES);
32666
+ bytes[bytes.length - 1] |= x & _1n ? 128 : 0;
32667
+ return bytes;
32668
+ }
32669
+ toHex() {
32670
+ return bytesToHex$1(this.toRawBytes());
32671
+ }
32672
+ }
32673
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
32674
+ Point.ZERO = new Point(_0n, _1n, _1n, _0n);
32675
+ const { BASE: G, ZERO: I } = Point;
32676
+ const wnaf = wNAF(Point, nByteLength * 8);
32677
+ function modN(a) {
32678
+ return mod(a, CURVE_ORDER);
32679
+ }
32680
+ function modN_LE(hash2) {
32681
+ return modN(bytesToNumberLE(hash2));
32682
+ }
32683
+ function getPrivateScalar(key) {
32684
+ const len = Fp2.BYTES;
32685
+ key = ensureBytes("private key", key, len);
32686
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
32687
+ const head = adjustScalarBytes2(hashed.slice(0, len));
32688
+ const prefix = hashed.slice(len, 2 * len);
32689
+ const scalar = modN_LE(head);
32690
+ return { head, prefix, scalar };
32691
+ }
32692
+ function getExtendedPublicKey(key) {
32693
+ const { head, prefix, scalar } = getPrivateScalar(key);
32694
+ const point = G.multiply(scalar);
32695
+ const pointBytes = point.toRawBytes();
32696
+ return { head, prefix, scalar, point, pointBytes };
32697
+ }
32698
+ function getPublicKey(privKey) {
32699
+ return getExtendedPublicKey(privKey).pointBytes;
32700
+ }
32701
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
32702
+ const msg = concatBytes2(...msgs);
32703
+ return modN_LE(cHash(domain2(msg, ensureBytes("context", context), !!prehash)));
32704
+ }
32705
+ function sign2(msg, privKey, options = {}) {
32706
+ msg = ensureBytes("message", msg);
32707
+ if (prehash)
32708
+ msg = prehash(msg);
32709
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
32710
+ const r = hashDomainToScalar(options.context, prefix, msg);
32711
+ const R = G.multiply(r).toRawBytes();
32712
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
32713
+ const s = modN(r + k * scalar);
32714
+ aInRange("signature.s", s, _0n, CURVE_ORDER);
32715
+ const res = concatBytes2(R, numberToBytesLE(s, Fp2.BYTES));
32716
+ return ensureBytes("result", res, Fp2.BYTES * 2);
32717
+ }
32718
+ const verifyOpts = VERIFY_DEFAULT;
32719
+ function verify(sig, msg, publicKey, options = verifyOpts) {
32720
+ const { context, zip215 } = options;
32721
+ const len = Fp2.BYTES;
32722
+ sig = ensureBytes("signature", sig, 2 * len);
32723
+ msg = ensureBytes("message", msg);
32724
+ publicKey = ensureBytes("publicKey", publicKey, len);
32725
+ if (zip215 !== void 0)
32726
+ abool("zip215", zip215);
32727
+ if (prehash)
32728
+ msg = prehash(msg);
32729
+ const s = bytesToNumberLE(sig.slice(len, 2 * len));
32730
+ let A, R, SB;
32731
+ try {
32732
+ A = Point.fromHex(publicKey, zip215);
32733
+ R = Point.fromHex(sig.slice(0, len), zip215);
32734
+ SB = G.multiplyUnsafe(s);
32735
+ } catch (error51) {
32736
+ return false;
32737
+ }
32738
+ if (!zip215 && A.isSmallOrder())
32739
+ return false;
32740
+ const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
32741
+ const RkA = R.add(A.multiplyUnsafe(k));
32742
+ return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
32743
+ }
32744
+ G._setWindowSize(8);
32745
+ const utils = {
32746
+ getExtendedPublicKey,
32747
+ /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */
32748
+ randomPrivateKey: () => randomBytes4(Fp2.BYTES),
32749
+ /**
32750
+ * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
32751
+ * values. This slows down first getPublicKey() by milliseconds (see Speed section),
32752
+ * but allows to speed-up subsequent getPublicKey() calls up to 20x.
32753
+ * @param windowSize 2, 4, 8, 16
32754
+ */
32755
+ precompute(windowSize = 8, point = Point.BASE) {
32756
+ point._setWindowSize(windowSize);
32757
+ point.multiply(BigInt(3));
32758
+ return point;
32759
+ }
32760
+ };
32761
+ return {
32762
+ CURVE,
32763
+ getPublicKey,
32764
+ sign: sign2,
32765
+ verify,
32766
+ ExtendedPoint: Point,
32767
+ utils
32768
+ };
32769
+ }
32770
+
32771
+ // node_modules/@noble/curves/esm/abstract/montgomery.js
32772
+ var _0n2 = BigInt(0);
32773
+ var _1n2 = BigInt(1);
32774
+ var _2n2 = BigInt(2);
32775
+ function validateOpts2(curve) {
32776
+ validateObject(curve, {
32777
+ adjustScalarBytes: "function",
32778
+ powPminus2: "function"
32779
+ });
32780
+ return Object.freeze({ ...curve });
32781
+ }
32782
+ function montgomery(curveDef) {
32783
+ const CURVE = validateOpts2(curveDef);
32784
+ const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2 } = CURVE;
32785
+ const is25519 = type === "x25519";
32786
+ if (!is25519 && type !== "x448")
32787
+ throw new Error("invalid type");
32788
+ const montgomeryBits = is25519 ? 255 : 448;
32789
+ const fieldLen = is25519 ? 32 : 56;
32790
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
32791
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
32792
+ const minScalar = is25519 ? _2n2 ** BigInt(254) : _2n2 ** BigInt(447);
32793
+ const maxAdded = is25519 ? BigInt(8) * _2n2 ** BigInt(251) - _1n2 : BigInt(4) * _2n2 ** BigInt(445) - _1n2;
32794
+ const maxScalar = minScalar + maxAdded + _1n2;
32795
+ const modP = (n) => mod(n, P);
32796
+ const GuBytes = encodeU(Gu);
32797
+ function encodeU(u) {
32798
+ return numberToBytesLE(modP(u), fieldLen);
32799
+ }
32800
+ function decodeU(u) {
32801
+ const _u = ensureBytes("u coordinate", u, fieldLen);
32802
+ if (is25519)
32803
+ _u[31] &= 127;
32804
+ return modP(bytesToNumberLE(_u));
32805
+ }
32806
+ function decodeScalar(scalar) {
32807
+ return bytesToNumberLE(adjustScalarBytes2(ensureBytes("scalar", scalar, fieldLen)));
32808
+ }
32809
+ function scalarMult(scalar, u) {
32810
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
32811
+ if (pu === _0n2)
32812
+ throw new Error("invalid private or public key received");
32813
+ return encodeU(pu);
32814
+ }
32815
+ function scalarMultBase(scalar) {
32816
+ return scalarMult(scalar, GuBytes);
32817
+ }
32818
+ function cswap(swap, x_2, x_3) {
32819
+ const dummy = modP(swap * (x_2 - x_3));
32820
+ x_2 = modP(x_2 - dummy);
32821
+ x_3 = modP(x_3 + dummy);
32822
+ return { x_2, x_3 };
32823
+ }
32824
+ function montgomeryLadder(u, scalar) {
32825
+ aInRange("u", u, _0n2, P);
32826
+ aInRange("scalar", scalar, minScalar, maxScalar);
32827
+ const k = scalar;
32828
+ const x_1 = u;
32829
+ let x_2 = _1n2;
32830
+ let z_2 = _0n2;
32831
+ let x_3 = u;
32832
+ let z_3 = _1n2;
32833
+ let swap = _0n2;
32834
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n2; t--) {
32835
+ const k_t = k >> t & _1n2;
32836
+ swap ^= k_t;
32837
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
32838
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
32839
+ swap = k_t;
32840
+ const A = x_2 + z_2;
32841
+ const AA = modP(A * A);
32842
+ const B = x_2 - z_2;
32843
+ const BB = modP(B * B);
32844
+ const E = AA - BB;
32845
+ const C = x_3 + z_3;
32846
+ const D = x_3 - z_3;
32847
+ const DA = modP(D * A);
32848
+ const CB = modP(C * B);
32849
+ const dacb = DA + CB;
32850
+ const da_cb = DA - CB;
32851
+ x_3 = modP(dacb * dacb);
32852
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
32853
+ x_2 = modP(AA * BB);
32854
+ z_2 = modP(E * (AA + modP(a24 * E)));
32855
+ }
32856
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
32857
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
32858
+ const z2 = powPminus2(z_2);
32859
+ return modP(x_2 * z2);
32860
+ }
32861
+ return {
32862
+ scalarMult,
32863
+ scalarMultBase,
32864
+ getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),
32865
+ getPublicKey: (privateKey) => scalarMultBase(privateKey),
32866
+ utils: { randomPrivateKey: () => CURVE.randomBytes(fieldLen) },
32867
+ GuBytes: GuBytes.slice()
32868
+ };
32869
+ }
32870
+
32871
+ // node_modules/@noble/curves/esm/ed25519.js
32872
+ var ED25519_P = BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");
32873
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
32874
+ BigInt(0);
32875
+ var _1n3 = BigInt(1);
32876
+ var _2n3 = BigInt(2);
32877
+ var _3n = BigInt(3);
32878
+ var _5n = BigInt(5);
32879
+ var _8n2 = BigInt(8);
32880
+ function ed25519_pow_2_252_3(x) {
32881
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
32882
+ const P = ED25519_P;
32883
+ const x2 = x * x % P;
32884
+ const b2 = x2 * x % P;
32885
+ const b4 = pow2(b2, _2n3, P) * b2 % P;
32886
+ const b5 = pow2(b4, _1n3, P) * x % P;
32887
+ const b10 = pow2(b5, _5n, P) * b5 % P;
32888
+ const b20 = pow2(b10, _10n, P) * b10 % P;
32889
+ const b40 = pow2(b20, _20n, P) * b20 % P;
32890
+ const b80 = pow2(b40, _40n, P) * b40 % P;
32891
+ const b160 = pow2(b80, _80n, P) * b80 % P;
32892
+ const b240 = pow2(b160, _80n, P) * b80 % P;
32893
+ const b250 = pow2(b240, _10n, P) * b10 % P;
32894
+ const pow_p_5_8 = pow2(b250, _2n3, P) * x % P;
32895
+ return { pow_p_5_8, b2 };
32896
+ }
32897
+ function adjustScalarBytes(bytes) {
32898
+ bytes[0] &= 248;
32899
+ bytes[31] &= 127;
32900
+ bytes[31] |= 64;
32901
+ return bytes;
32902
+ }
32903
+ function uvRatio(u, v) {
32904
+ const P = ED25519_P;
32905
+ const v3 = mod(v * v * v, P);
32906
+ const v7 = mod(v3 * v3 * v, P);
32907
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
32908
+ let x = mod(u * v3 * pow, P);
32909
+ const vx2 = mod(v * x * x, P);
32910
+ const root1 = x;
32911
+ const root2 = mod(x * ED25519_SQRT_M1, P);
32912
+ const useRoot1 = vx2 === u;
32913
+ const useRoot2 = vx2 === mod(-u, P);
32914
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
32915
+ if (useRoot1)
32916
+ x = root1;
32917
+ if (useRoot2 || noRoot)
32918
+ x = root2;
32919
+ if (isNegativeLE(x, P))
32920
+ x = mod(-x, P);
32921
+ return { isValid: useRoot1 || useRoot2, value: x };
32922
+ }
32923
+ var Fp = /* @__PURE__ */ (() => Field(ED25519_P, void 0, true))();
32924
+ var ed25519Defaults = /* @__PURE__ */ (() => ({
32925
+ // Removing Fp.create() will still work, and is 10% faster on sign
32926
+ a: Fp.create(BigInt(-1)),
32927
+ // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))
32928
+ d: BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),
32929
+ // Finite field 2n**255n - 19n
32930
+ Fp,
32931
+ // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;
32932
+ n: BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),
32933
+ h: _8n2,
32934
+ Gx: BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),
32935
+ Gy: BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),
32936
+ hash: sha512,
32937
+ randomBytes,
32938
+ adjustScalarBytes,
32939
+ // dom2
32940
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
32941
+ // Constant-time, u/√v
32942
+ uvRatio
32943
+ }))();
32944
+ var ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
32945
+ var x25519 = /* @__PURE__ */ (() => montgomery({
32946
+ P: ED25519_P,
32947
+ type: "x25519",
32948
+ powPminus2: (x) => {
32949
+ const P = ED25519_P;
32950
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
32951
+ return mod(pow2(pow_p_5_8, _3n, P) * b2, P);
32952
+ },
32953
+ adjustScalarBytes,
32954
+ randomBytes
32955
+ }))();
32956
+ function edwardsToMontgomeryPub(edwardsPub) {
32957
+ const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);
32958
+ const _1n4 = BigInt(1);
32959
+ return Fp.toBytes(Fp.create((_1n4 + y) * Fp.inv(_1n4 - y)));
32960
+ }
32961
+ function edwardsToMontgomeryPriv(edwardsPriv) {
32962
+ const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));
32963
+ return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);
32964
+ }
32965
+
32966
+ // node_modules/@noble/ciphers/esm/utils.js
32967
+ function isBytes2(a) {
32968
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
32969
+ }
32970
+ function abytes(b, ...lengths) {
32971
+ if (!isBytes2(b))
32972
+ throw new Error("Uint8Array expected");
32973
+ if (lengths.length > 0 && !lengths.includes(b.length))
32974
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
32975
+ }
32976
+ function aexists(instance, checkFinished = true) {
32977
+ if (instance.destroyed)
32978
+ throw new Error("Hash instance has been destroyed");
32979
+ if (checkFinished && instance.finished)
32980
+ throw new Error("Hash#digest() has already been called");
32981
+ }
32982
+ function aoutput(out, instance) {
32983
+ abytes(out);
32984
+ const min = instance.outputLen;
32985
+ if (out.length < min) {
32986
+ throw new Error("digestInto() expects output buffer of length at least " + min);
32987
+ }
32988
+ }
32989
+ function u8(arr) {
32990
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
32991
+ }
32992
+ function u32(arr) {
32993
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
32994
+ }
32995
+ function clean2(...arrays) {
32996
+ for (let i = 0; i < arrays.length; i++) {
32997
+ arrays[i].fill(0);
32998
+ }
32999
+ }
33000
+ function createView(arr) {
33001
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
33002
+ }
33003
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
33004
+ function utf8ToBytes2(str) {
33005
+ if (typeof str !== "string")
33006
+ throw new Error("string expected");
33007
+ return new Uint8Array(new TextEncoder().encode(str));
33008
+ }
33009
+ function toBytes3(data) {
33010
+ if (typeof data === "string")
33011
+ data = utf8ToBytes2(data);
33012
+ else if (isBytes2(data))
33013
+ data = copyBytes(data);
33014
+ else
33015
+ throw new Error("Uint8Array expected, got " + typeof data);
33016
+ return data;
33017
+ }
33018
+ function equalBytes(a, b) {
33019
+ if (a.length !== b.length)
33020
+ return false;
33021
+ let diff = 0;
33022
+ for (let i = 0; i < a.length; i++)
33023
+ diff |= a[i] ^ b[i];
33024
+ return diff === 0;
33025
+ }
33026
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
33027
+ function wrappedCipher(key, ...args) {
33028
+ abytes(key);
33029
+ if (!isLE)
33030
+ throw new Error("Non little-endian hardware is not yet supported");
33031
+ if (params.nonceLength !== void 0) {
33032
+ const nonce = args[0];
33033
+ if (!nonce)
33034
+ throw new Error("nonce / iv required");
33035
+ if (params.varSizeNonce)
33036
+ abytes(nonce);
33037
+ else
33038
+ abytes(nonce, params.nonceLength);
33039
+ }
33040
+ const tagl = params.tagLength;
33041
+ if (tagl && args[1] !== void 0) {
33042
+ abytes(args[1]);
33043
+ }
33044
+ const cipher = constructor(key, ...args);
33045
+ const checkOutput = (fnLength, output) => {
33046
+ if (output !== void 0) {
33047
+ if (fnLength !== 2)
33048
+ throw new Error("cipher output not supported");
33049
+ abytes(output);
33050
+ }
33051
+ };
33052
+ let called = false;
33053
+ const wrCipher = {
33054
+ encrypt(data, output) {
33055
+ if (called)
33056
+ throw new Error("cannot encrypt() twice with same key + nonce");
33057
+ called = true;
33058
+ abytes(data);
33059
+ checkOutput(cipher.encrypt.length, output);
33060
+ return cipher.encrypt(data, output);
33061
+ },
33062
+ decrypt(data, output) {
33063
+ abytes(data);
33064
+ if (tagl && data.length < tagl)
33065
+ throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
33066
+ checkOutput(cipher.decrypt.length, output);
33067
+ return cipher.decrypt(data, output);
33068
+ }
33069
+ };
33070
+ return wrCipher;
33071
+ }
33072
+ Object.assign(wrappedCipher, params);
33073
+ return wrappedCipher;
33074
+ };
33075
+ function getOutput(expectedLength, out, onlyAligned = true) {
33076
+ if (out === void 0)
33077
+ return new Uint8Array(expectedLength);
33078
+ if (out.length !== expectedLength)
33079
+ throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
33080
+ if (onlyAligned && !isAligned32(out))
33081
+ throw new Error("invalid output, must be aligned");
33082
+ return out;
33083
+ }
33084
+ function setBigUint64(view, byteOffset, value, isLE2) {
33085
+ if (typeof view.setBigUint64 === "function")
33086
+ return view.setBigUint64(byteOffset, value, isLE2);
33087
+ const _32n = BigInt(32);
33088
+ const _u32_max = BigInt(4294967295);
33089
+ const wh = Number(value >> _32n & _u32_max);
33090
+ const wl = Number(value & _u32_max);
33091
+ const h = 0;
33092
+ const l = 4;
33093
+ view.setUint32(byteOffset + h, wh, isLE2);
33094
+ view.setUint32(byteOffset + l, wl, isLE2);
33095
+ }
33096
+ function u64Lengths(dataLength, aadLength, isLE2) {
33097
+ const num = new Uint8Array(16);
33098
+ const view = createView(num);
33099
+ setBigUint64(view, 0, BigInt(aadLength), isLE2);
33100
+ setBigUint64(view, 8, BigInt(dataLength), isLE2);
33101
+ return num;
33102
+ }
33103
+ function isAligned32(bytes) {
33104
+ return bytes.byteOffset % 4 === 0;
33105
+ }
33106
+ function copyBytes(bytes) {
33107
+ return Uint8Array.from(bytes);
33108
+ }
33109
+
33110
+ // node_modules/@noble/ciphers/esm/_polyval.js
33111
+ var BLOCK_SIZE = 16;
33112
+ var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
33113
+ var ZEROS32 = u32(ZEROS16);
33114
+ var POLY = 225;
33115
+ var mul2 = (s0, s1, s2, s3) => {
33116
+ const hiBit = s3 & 1;
33117
+ return {
33118
+ s3: s2 << 31 | s3 >>> 1,
33119
+ s2: s1 << 31 | s2 >>> 1,
33120
+ s1: s0 << 31 | s1 >>> 1,
33121
+ s0: s0 >>> 1 ^ POLY << 24 & -(hiBit & 1)
33122
+ // reduce % poly
33123
+ };
33124
+ };
33125
+ var swapLE = (n) => (n >>> 0 & 255) << 24 | (n >>> 8 & 255) << 16 | (n >>> 16 & 255) << 8 | n >>> 24 & 255 | 0;
33126
+ function _toGHASHKey(k) {
33127
+ k.reverse();
33128
+ const hiBit = k[15] & 1;
33129
+ let carry = 0;
33130
+ for (let i = 0; i < k.length; i++) {
33131
+ const t = k[i];
33132
+ k[i] = t >>> 1 | carry;
33133
+ carry = (t & 1) << 7;
33134
+ }
33135
+ k[0] ^= -hiBit & 225;
33136
+ return k;
33137
+ }
33138
+ var estimateWindow = (bytes) => {
33139
+ if (bytes > 64 * 1024)
33140
+ return 8;
33141
+ if (bytes > 1024)
33142
+ return 4;
33143
+ return 2;
33144
+ };
33145
+ var GHASH = class {
33146
+ // We select bits per window adaptively based on expectedLength
33147
+ constructor(key, expectedLength) {
33148
+ this.blockLen = BLOCK_SIZE;
33149
+ this.outputLen = BLOCK_SIZE;
33150
+ this.s0 = 0;
33151
+ this.s1 = 0;
33152
+ this.s2 = 0;
33153
+ this.s3 = 0;
33154
+ this.finished = false;
33155
+ key = toBytes3(key);
33156
+ abytes(key, 16);
33157
+ const kView = createView(key);
33158
+ let k0 = kView.getUint32(0, false);
33159
+ let k1 = kView.getUint32(4, false);
33160
+ let k2 = kView.getUint32(8, false);
33161
+ let k3 = kView.getUint32(12, false);
33162
+ const doubles = [];
33163
+ for (let i = 0; i < 128; i++) {
33164
+ doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
33165
+ ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
33166
+ }
33167
+ const W = estimateWindow(expectedLength || 1024);
33168
+ if (![1, 2, 4, 8].includes(W))
33169
+ throw new Error("ghash: invalid window size, expected 2, 4 or 8");
33170
+ this.W = W;
33171
+ const bits = 128;
33172
+ const windows = bits / W;
33173
+ const windowSize = this.windowSize = 2 ** W;
33174
+ const items = [];
33175
+ for (let w = 0; w < windows; w++) {
33176
+ for (let byte = 0; byte < windowSize; byte++) {
33177
+ let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
33178
+ for (let j = 0; j < W; j++) {
33179
+ const bit = byte >>> W - j - 1 & 1;
33180
+ if (!bit)
33181
+ continue;
33182
+ const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
33183
+ s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3;
33184
+ }
33185
+ items.push({ s0, s1, s2, s3 });
33186
+ }
33187
+ }
33188
+ this.t = items;
33189
+ }
33190
+ _updateBlock(s0, s1, s2, s3) {
33191
+ s0 ^= this.s0, s1 ^= this.s1, s2 ^= this.s2, s3 ^= this.s3;
33192
+ const { W, t, windowSize } = this;
33193
+ let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
33194
+ const mask = (1 << W) - 1;
33195
+ let w = 0;
33196
+ for (const num of [s0, s1, s2, s3]) {
33197
+ for (let bytePos = 0; bytePos < 4; bytePos++) {
33198
+ const byte = num >>> 8 * bytePos & 255;
33199
+ for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
33200
+ const bit = byte >>> W * bitPos & mask;
33201
+ const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
33202
+ o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3;
33203
+ w += 1;
33204
+ }
33205
+ }
33206
+ }
33207
+ this.s0 = o0;
33208
+ this.s1 = o1;
33209
+ this.s2 = o2;
33210
+ this.s3 = o3;
33211
+ }
33212
+ update(data) {
33213
+ aexists(this);
33214
+ data = toBytes3(data);
33215
+ abytes(data);
33216
+ const b32 = u32(data);
33217
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
33218
+ const left = data.length % BLOCK_SIZE;
33219
+ for (let i = 0; i < blocks; i++) {
33220
+ this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);
33221
+ }
33222
+ if (left) {
33223
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
33224
+ this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);
33225
+ clean2(ZEROS32);
33226
+ }
33227
+ return this;
33228
+ }
33229
+ destroy() {
33230
+ const { t } = this;
33231
+ for (const elm of t) {
33232
+ elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0;
33233
+ }
33234
+ }
33235
+ digestInto(out) {
33236
+ aexists(this);
33237
+ aoutput(out, this);
33238
+ this.finished = true;
33239
+ const { s0, s1, s2, s3 } = this;
33240
+ const o32 = u32(out);
33241
+ o32[0] = s0;
33242
+ o32[1] = s1;
33243
+ o32[2] = s2;
33244
+ o32[3] = s3;
33245
+ return out;
33246
+ }
33247
+ digest() {
33248
+ const res = new Uint8Array(BLOCK_SIZE);
33249
+ this.digestInto(res);
33250
+ this.destroy();
33251
+ return res;
33252
+ }
33253
+ };
33254
+ var Polyval = class extends GHASH {
33255
+ constructor(key, expectedLength) {
33256
+ key = toBytes3(key);
33257
+ abytes(key);
33258
+ const ghKey = _toGHASHKey(copyBytes(key));
33259
+ super(ghKey, expectedLength);
33260
+ clean2(ghKey);
33261
+ }
33262
+ update(data) {
33263
+ data = toBytes3(data);
33264
+ aexists(this);
33265
+ const b32 = u32(data);
33266
+ const left = data.length % BLOCK_SIZE;
33267
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
33268
+ for (let i = 0; i < blocks; i++) {
33269
+ this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));
33270
+ }
33271
+ if (left) {
33272
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
33273
+ this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));
33274
+ clean2(ZEROS32);
33275
+ }
33276
+ return this;
33277
+ }
33278
+ digestInto(out) {
33279
+ aexists(this);
33280
+ aoutput(out, this);
33281
+ this.finished = true;
33282
+ const { s0, s1, s2, s3 } = this;
33283
+ const o32 = u32(out);
33284
+ o32[0] = s0;
33285
+ o32[1] = s1;
33286
+ o32[2] = s2;
33287
+ o32[3] = s3;
33288
+ return out.reverse();
33289
+ }
33290
+ };
33291
+ function wrapConstructorWithKey(hashCons) {
33292
+ const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes3(msg)).digest();
33293
+ const tmp = hashCons(new Uint8Array(16), 0);
33294
+ hashC.outputLen = tmp.outputLen;
33295
+ hashC.blockLen = tmp.blockLen;
33296
+ hashC.create = (key, expectedLength) => hashCons(key, expectedLength);
33297
+ return hashC;
33298
+ }
33299
+ var ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));
33300
+ wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));
33301
+
33302
+ // node_modules/@noble/ciphers/esm/aes.js
33303
+ var BLOCK_SIZE2 = 16;
33304
+ var BLOCK_SIZE32 = 4;
33305
+ var EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE2);
33306
+ var POLY2 = 283;
33307
+ function mul22(n) {
33308
+ return n << 1 ^ POLY2 & -(n >> 7);
33309
+ }
33310
+ function mul(a, b) {
33311
+ let res = 0;
33312
+ for (; b > 0; b >>= 1) {
33313
+ res ^= a & -(b & 1);
33314
+ a = mul22(a);
33315
+ }
33316
+ return res;
33317
+ }
33318
+ var sbox = /* @__PURE__ */ (() => {
33319
+ const t = new Uint8Array(256);
33320
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul22(x))
33321
+ t[i] = x;
33322
+ const box = new Uint8Array(256);
33323
+ box[0] = 99;
33324
+ for (let i = 0; i < 255; i++) {
33325
+ let x = t[255 - i];
33326
+ x |= x << 8;
33327
+ box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
33328
+ }
33329
+ clean2(t);
33330
+ return box;
33331
+ })();
33332
+ var rotr32_8 = (n) => n << 24 | n >>> 8;
33333
+ var rotl32_8 = (n) => n << 8 | n >>> 24;
33334
+ function genTtable(sbox2, fn) {
33335
+ if (sbox2.length !== 256)
33336
+ throw new Error("Wrong sbox length");
33337
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
33338
+ const T1 = T0.map(rotl32_8);
33339
+ const T2 = T1.map(rotl32_8);
33340
+ const T3 = T2.map(rotl32_8);
33341
+ const T01 = new Uint32Array(256 * 256);
33342
+ const T23 = new Uint32Array(256 * 256);
33343
+ const sbox22 = new Uint16Array(256 * 256);
33344
+ for (let i = 0; i < 256; i++) {
33345
+ for (let j = 0; j < 256; j++) {
33346
+ const idx = i * 256 + j;
33347
+ T01[idx] = T0[i] ^ T1[j];
33348
+ T23[idx] = T2[i] ^ T3[j];
33349
+ sbox22[idx] = sbox2[i] << 8 | sbox2[j];
33350
+ }
33351
+ }
33352
+ return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
33353
+ }
33354
+ var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
33355
+ var xPowers = /* @__PURE__ */ (() => {
33356
+ const p = new Uint8Array(16);
33357
+ for (let i = 0, x = 1; i < 16; i++, x = mul22(x))
33358
+ p[i] = x;
33359
+ return p;
33360
+ })();
33361
+ function expandKeyLE(key) {
33362
+ abytes(key);
33363
+ const len = key.length;
33364
+ if (![16, 24, 32].includes(len))
33365
+ throw new Error("aes: invalid key size, should be 16, 24 or 32, got " + len);
33366
+ const { sbox2 } = tableEncoding;
33367
+ const toClean = [];
33368
+ if (!isAligned32(key))
33369
+ toClean.push(key = copyBytes(key));
33370
+ const k32 = u32(key);
33371
+ const Nk = k32.length;
33372
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
33373
+ const xk = new Uint32Array(len + 28);
33374
+ xk.set(k32);
33375
+ for (let i = Nk; i < xk.length; i++) {
33376
+ let t = xk[i - 1];
33377
+ if (i % Nk === 0)
33378
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
33379
+ else if (Nk > 6 && i % Nk === 4)
33380
+ t = subByte(t);
33381
+ xk[i] = xk[i - Nk] ^ t;
33382
+ }
33383
+ clean2(...toClean);
33384
+ return xk;
33385
+ }
33386
+ function apply0123(T01, T23, s0, s1, s2, s3) {
33387
+ return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
33388
+ }
33389
+ function applySbox(sbox2, s0, s1, s2, s3) {
33390
+ return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
33391
+ }
33392
+ function encrypt(xk, s0, s1, s2, s3) {
33393
+ const { sbox2, T01, T23 } = tableEncoding;
33394
+ let k = 0;
33395
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
33396
+ const rounds = xk.length / 4 - 2;
33397
+ for (let i = 0; i < rounds; i++) {
33398
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
33399
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
33400
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
33401
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
33402
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
33403
+ }
33404
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
33405
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
33406
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
33407
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
33408
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
33409
+ }
33410
+ function ctr32(xk, isLE2, nonce, src, dst) {
33411
+ abytes(nonce, BLOCK_SIZE2);
33412
+ abytes(src);
33413
+ dst = getOutput(src.length, dst);
33414
+ const ctr = nonce;
33415
+ const c32 = u32(ctr);
33416
+ const view = createView(ctr);
33417
+ const src32 = u32(src);
33418
+ const dst32 = u32(dst);
33419
+ const ctrPos = 12;
33420
+ const srcLen = src.length;
33421
+ let ctrNum = view.getUint32(ctrPos, isLE2);
33422
+ let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
33423
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
33424
+ dst32[i + 0] = src32[i + 0] ^ s0;
33425
+ dst32[i + 1] = src32[i + 1] ^ s1;
33426
+ dst32[i + 2] = src32[i + 2] ^ s2;
33427
+ dst32[i + 3] = src32[i + 3] ^ s3;
33428
+ ctrNum = ctrNum + 1 >>> 0;
33429
+ view.setUint32(ctrPos, ctrNum, isLE2);
33430
+ ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
33431
+ }
33432
+ const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32);
33433
+ if (start < srcLen) {
33434
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
33435
+ const buf = u8(b32);
33436
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
33437
+ dst[i] = src[i] ^ buf[pos];
33438
+ clean2(b32);
33439
+ }
33440
+ return dst;
33441
+ }
33442
+ function computeTag(fn, isLE2, key, data, AAD) {
33443
+ const aadLength = AAD ? AAD.length : 0;
33444
+ const h = fn.create(key, data.length + aadLength);
33445
+ if (AAD)
33446
+ h.update(AAD);
33447
+ const num = u64Lengths(8 * data.length, 8 * aadLength, isLE2);
33448
+ h.update(data);
33449
+ h.update(num);
33450
+ const res = h.digest();
33451
+ clean2(num);
33452
+ return res;
33453
+ }
33454
+ var gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {
33455
+ if (nonce.length < 8)
33456
+ throw new Error("aes/gcm: invalid nonce length");
33457
+ const tagLength = 16;
33458
+ function _computeTag(authKey, tagMask, data) {
33459
+ const tag = computeTag(ghash, false, authKey, data, AAD);
33460
+ for (let i = 0; i < tagMask.length; i++)
33461
+ tag[i] ^= tagMask[i];
33462
+ return tag;
33463
+ }
33464
+ function deriveKeys() {
33465
+ const xk = expandKeyLE(key);
33466
+ const authKey = EMPTY_BLOCK.slice();
33467
+ const counter = EMPTY_BLOCK.slice();
33468
+ ctr32(xk, false, counter, counter, authKey);
33469
+ if (nonce.length === 12) {
33470
+ counter.set(nonce);
33471
+ } else {
33472
+ const nonceLen = EMPTY_BLOCK.slice();
33473
+ const view = createView(nonceLen);
33474
+ setBigUint64(view, 8, BigInt(nonce.length * 8), false);
33475
+ const g = ghash.create(authKey).update(nonce).update(nonceLen);
33476
+ g.digestInto(counter);
33477
+ g.destroy();
33478
+ }
33479
+ const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
33480
+ return { xk, authKey, counter, tagMask };
33481
+ }
33482
+ return {
33483
+ encrypt(plaintext) {
33484
+ const { xk, authKey, counter, tagMask } = deriveKeys();
33485
+ const out = new Uint8Array(plaintext.length + tagLength);
33486
+ const toClean = [xk, authKey, counter, tagMask];
33487
+ if (!isAligned32(plaintext))
33488
+ toClean.push(plaintext = copyBytes(plaintext));
33489
+ ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
33490
+ const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
33491
+ toClean.push(tag);
33492
+ out.set(tag, plaintext.length);
33493
+ clean2(...toClean);
33494
+ return out;
33495
+ },
33496
+ decrypt(ciphertext) {
33497
+ const { xk, authKey, counter, tagMask } = deriveKeys();
33498
+ const toClean = [xk, authKey, tagMask, counter];
33499
+ if (!isAligned32(ciphertext))
33500
+ toClean.push(ciphertext = copyBytes(ciphertext));
33501
+ const data = ciphertext.subarray(0, -tagLength);
33502
+ const passedTag = ciphertext.subarray(-tagLength);
33503
+ const tag = _computeTag(authKey, tagMask, data);
33504
+ toClean.push(tag);
33505
+ if (!equalBytes(tag, passedTag))
33506
+ throw new Error("aes/gcm: invalid ghash tag");
33507
+ const out = ctr32(xk, false, counter, data);
33508
+ clean2(...toClean);
33509
+ return out;
33510
+ }
33511
+ };
33512
+ });
33513
+
33514
+ // node_modules/@noble/hashes/esm/hkdf.js
33515
+ function extract(hash2, ikm, salt) {
33516
+ ahash(hash2);
33517
+ if (salt === void 0)
33518
+ salt = new Uint8Array(hash2.outputLen);
33519
+ return hmac(hash2, toBytes(salt), toBytes(ikm));
33520
+ }
33521
+ var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
33522
+ var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
33523
+ function expand(hash2, prk, info, length = 32) {
33524
+ ahash(hash2);
33525
+ anumber(length);
33526
+ const olen = hash2.outputLen;
33527
+ if (length > 255 * olen)
33528
+ throw new Error("Length should be <= 255*HashLen");
33529
+ const blocks = Math.ceil(length / olen);
33530
+ if (info === void 0)
33531
+ info = EMPTY_BUFFER;
33532
+ const okm = new Uint8Array(blocks * olen);
33533
+ const HMAC = hmac.create(hash2, prk);
33534
+ const HMACTmp = HMAC._cloneInto();
33535
+ const T = new Uint8Array(HMAC.outputLen);
33536
+ for (let counter = 0; counter < blocks; counter++) {
33537
+ HKDF_COUNTER[0] = counter + 1;
33538
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
33539
+ okm.set(T, olen * counter);
33540
+ HMAC._cloneInto(HMACTmp);
33541
+ }
33542
+ HMAC.destroy();
33543
+ HMACTmp.destroy();
33544
+ clean(T, HKDF_COUNTER);
33545
+ return okm.slice(0, length);
33546
+ }
33547
+ var hkdf = (hash2, ikm, salt, info, length) => expand(hash2, extract(hash2, ikm, salt), info, length);
33548
+
33549
+ // src/crypto/share.ts
33550
+ var VERSION = 1;
33551
+ var DOMAIN_SHARE = 4;
33552
+ var NONCE_BYTES2 = 12;
33553
+ var KEY_BYTES2 = 32;
33554
+ var TAG_BYTES2 = 16;
33555
+ var HRP = "sfshare";
33556
+ var BECH32_LIMIT = 200;
33557
+ var HKDF_LABEL = "sf-share-v1";
33558
+ var SHARE_WRAP_BYTES = 1 + 32 + NONCE_BYTES2 + KEY_BYTES2 + TAG_BYTES2;
33559
+ var SHARE_SEED_DOMAIN = "Save Forever share identity v1\n";
33560
+ function shareSeedFromSignature(signature) {
33561
+ if (signature.trim().length < 132) throw new Error("Invalid signature for the share identity.");
33562
+ return sha2562(utf8ToBytes(SHARE_SEED_DOMAIN + signature.trim().toLowerCase()));
33563
+ }
33564
+ function sharePublicKey(seed) {
33565
+ return ed25519.getPublicKey(seed);
33566
+ }
33567
+ function shareCodeFromSeed(seed) {
33568
+ return encodeShareCode(sharePublicKey(seed));
33569
+ }
33570
+ function encodeShareCode(edPub) {
33571
+ if (edPub.length !== 32) throw new Error("share pubkey must be 32 bytes");
33572
+ return bech32.encode(HRP, bech32.toWords(edPub), BECH32_LIMIT);
33573
+ }
33574
+ function decodeShareCode(code) {
33575
+ const trimmed = typeof code === "string" ? code.trim() : "";
33576
+ const decoded = bech32.decode(trimmed, BECH32_LIMIT);
33577
+ if (decoded.prefix !== HRP) throw new Error(`not a Save Forever share code (expected ${HRP}\u2026)`);
33578
+ const bytes = bech32.fromWords(decoded.words);
33579
+ if (bytes.length !== 32) throw new Error("share code is not a 32-byte key");
33580
+ ed25519.ExtendedPoint.fromHex(bytes);
33581
+ return Uint8Array.from(bytes);
33582
+ }
33583
+ var aadFor2 = (archiveId, recipientEdPub) => concatBytes(Uint8Array.of(DOMAIN_SHARE), utf8ToBytes(archiveId), Uint8Array.of(VERSION), recipientEdPub);
33584
+ var infoFor = (ePub, recipXPub, archiveId) => concatBytes(utf8ToBytes(HKDF_LABEL), ePub, recipXPub, utf8ToBytes(archiveId));
33585
+ function shareWrapDek(dek, recipientEdPub, archiveId) {
33586
+ if (dek.length !== KEY_BYTES2) throw new Error("DEK must be 32 bytes");
33587
+ if (!archiveId) throw new Error("Missing archive id for AAD binding.");
33588
+ const recipXPub = edwardsToMontgomeryPub(recipientEdPub);
33589
+ const eSec = x25519.utils.randomPrivateKey();
33590
+ const ePub = x25519.getPublicKey(eSec);
33591
+ const shared = x25519.getSharedSecret(eSec, recipXPub);
33592
+ const key = hkdf(sha2562, shared, new Uint8Array(0), infoFor(ePub, recipXPub, archiveId), KEY_BYTES2);
33593
+ const nonce = randomBytes(NONCE_BYTES2);
33594
+ const body = gcm(key, nonce, aadFor2(archiveId, recipientEdPub)).encrypt(dek);
33595
+ return concatBytes(Uint8Array.of(VERSION), ePub, nonce, body);
33596
+ }
33597
+ function unwrapDekFromShare(wrap2, seed, archiveId) {
33598
+ if (wrap2.length < SHARE_WRAP_BYTES) throw new Error("share wrap too short");
33599
+ if (wrap2[0] !== VERSION) throw new Error(`unsupported share version ${wrap2[0]}`);
33600
+ const ePub = wrap2.subarray(1, 33);
33601
+ const nonce = wrap2.subarray(33, 33 + NONCE_BYTES2);
33602
+ const body = wrap2.subarray(33 + NONCE_BYTES2);
33603
+ const edPub = ed25519.getPublicKey(seed);
33604
+ const recipXPub = edwardsToMontgomeryPub(edPub);
33605
+ const xPriv = edwardsToMontgomeryPriv(seed);
33606
+ const shared = x25519.getSharedSecret(xPriv, ePub);
33607
+ const key = hkdf(sha2562, shared, new Uint8Array(0), infoFor(ePub, recipXPub, archiveId), KEY_BYTES2);
33608
+ return gcm(key, nonce, aadFor2(archiveId, edPub)).decrypt(body);
33609
+ }
33610
+ function signShareList(seed, message) {
33611
+ return ed25519.sign(utf8ToBytes(message), seed);
33612
+ }
33613
+
32124
33614
  // src/crypto/wordlist.ts
32125
33615
  var WORDLIST = [
32126
33616
  "maple",
@@ -32391,7 +33881,7 @@ function generateRecoveryCode() {
32391
33881
  return words.join("-");
32392
33882
  }
32393
33883
  function newArchiveId() {
32394
- return `sf_${randomBytes(16).toString("hex")}`;
33884
+ return `sf_${randomBytes$1(16).toString("hex")}`;
32395
33885
  }
32396
33886
 
32397
33887
  // src/client/archiveClient.ts
@@ -32500,7 +33990,102 @@ function createArchiveClient(opts) {
32500
33990
  }
32501
33991
  return { plaintext, contentType, archiveId, arweaveTx: meta3.arweave_tx };
32502
33992
  }
32503
- return { account, network, archive, retrieve };
33993
+ async function shareSeed() {
33994
+ return shareSeedFromSignature(await account.signMessage({ message: SAVE_FOREVER_UNLOCK_MSG }));
33995
+ }
33996
+ async function myShareCode() {
33997
+ return shareCodeFromSeed(await shareSeed());
33998
+ }
33999
+ async function manageSigned() {
34000
+ const message = `${SAVE_FOREVER_MANAGE_MSG}
34001
+ ts:${Date.now()}`;
34002
+ return { address: account.address, message, signature: await account.signMessage({ message }) };
34003
+ }
34004
+ async function share(archiveId, recipientCode) {
34005
+ const recipient = decodeShareCode(recipientCode);
34006
+ const listRes = await fetch(`${serverUrl}/archives/list`, {
34007
+ method: "POST",
34008
+ headers: { "Content-Type": "application/json" },
34009
+ body: JSON.stringify(await manageSigned())
34010
+ });
34011
+ const listJson = await listRes.json();
34012
+ if (!listRes.ok) throw new Error(`List failed (${listRes.status}): ${JSON.stringify(listJson)}`);
34013
+ const row = listJson.archives?.find((a) => a.archive_id === archiveId);
34014
+ if (!row?.walletWrap) throw new Error(`You don't own ${archiveId} (or it has no keys).`);
34015
+ const dek = unwrapDekWithWallet(unb64(row.walletWrap), await account.signMessage({ message: SAVE_FOREVER_UNLOCK_MSG }), archiveId);
34016
+ const wrap2 = shareWrapDek(dek, recipient, archiveId);
34017
+ const res = await fetch(`${serverUrl}/archives/share`, {
34018
+ method: "POST",
34019
+ headers: { "Content-Type": "application/json" },
34020
+ body: JSON.stringify({ ...await manageSigned(), archive_id: archiveId, recipient_code: recipientCode, wrap: b64(wrap2) })
34021
+ });
34022
+ if (!res.ok) throw new Error(`Share failed (${res.status}): ${JSON.stringify(await res.json().catch(() => ({})))}`);
34023
+ }
34024
+ async function fetchShared() {
34025
+ const seed = await shareSeed();
34026
+ const message = `${SAVE_FOREVER_SHARE_LIST_MSG}
34027
+ ts:${Date.now()}`;
34028
+ const res = await fetch(`${serverUrl}/shares/list`, {
34029
+ method: "POST",
34030
+ headers: { "Content-Type": "application/json" },
34031
+ body: JSON.stringify({ recipient_code: shareCodeFromSeed(seed), message, signature: b64(signShareList(seed, message)) })
34032
+ });
34033
+ const json2 = await res.json();
34034
+ if (!res.ok) throw new Error(`shares/list failed (${res.status}): ${JSON.stringify(json2)}`);
34035
+ return { seed, items: json2.shared ?? [] };
34036
+ }
34037
+ async function listSharedWithMe() {
34038
+ const { seed, items } = await fetchShared();
34039
+ return items.map((s) => {
34040
+ const archiveId = String(s.archive_id);
34041
+ let contentType;
34042
+ let name;
34043
+ try {
34044
+ const dek = unwrapDekFromShare(unb64(String(s.recipientWrap)), seed, archiveId);
34045
+ if (s.manifest) {
34046
+ const m = JSON.parse(new TextDecoder().decode(decryptManifestWithDek(unb64(String(s.manifest)), dek, archiveId)));
34047
+ contentType = typeof m.contentType === "string" ? m.contentType : void 0;
34048
+ name = typeof m.name === "string" ? m.name : void 0;
34049
+ }
34050
+ } catch {
34051
+ }
34052
+ return { archiveId, contentType, name };
34053
+ });
34054
+ }
34055
+ async function retrieveShared(archiveId) {
34056
+ const { seed, items } = await fetchShared();
34057
+ const item = items.find((s) => String(s.archive_id) === archiveId);
34058
+ if (!item) throw new Error(`${archiveId} is not shared with you.`);
34059
+ const dek = unwrapDekFromShare(unb64(String(item.recipientWrap)), seed, archiveId);
34060
+ const urls = (item.ciphertext_urls ?? []).filter(Boolean);
34061
+ const attempts = opts.retrieveAttempts ?? 12;
34062
+ let ciphertext;
34063
+ for (let t = 0; t < attempts && !ciphertext; t++) {
34064
+ for (const u of urls) {
34065
+ try {
34066
+ const r = await fetch(u);
34067
+ if (r.ok) {
34068
+ ciphertext = new Uint8Array(await r.arrayBuffer());
34069
+ break;
34070
+ }
34071
+ } catch {
34072
+ }
34073
+ }
34074
+ if (!ciphertext) await new Promise((r) => setTimeout(r, 8e3));
34075
+ }
34076
+ if (!ciphertext) throw new Error("Ciphertext not available from any gateway yet \u2014 retry shortly.");
34077
+ const plaintext = decryptFileWithDek(ciphertext, unb64(String(item.fileNonce)), dek, archiveId);
34078
+ let contentType;
34079
+ try {
34080
+ if (item.manifest) {
34081
+ const m = JSON.parse(new TextDecoder().decode(decryptManifestWithDek(unb64(String(item.manifest)), dek, archiveId)));
34082
+ contentType = typeof m.contentType === "string" ? m.contentType : void 0;
34083
+ }
34084
+ } catch {
34085
+ }
34086
+ return { plaintext, contentType, archiveId, arweaveTx: String(item.arweave_tx) };
34087
+ }
34088
+ return { account, network, archive, retrieve, myShareCode, share, listSharedWithMe, retrieveShared };
32504
34089
  }
32505
34090
 
32506
34091
  // mcp/server.ts
@@ -32530,7 +34115,7 @@ function guardOps() {
32530
34115
  }
32531
34116
  ops++;
32532
34117
  }
32533
- var server = new McpServer({ name: "save-forever", version: "0.1.0" });
34118
+ var server = new McpServer({ name: "save-forever", version: "0.3.0" });
32534
34119
  server.registerTool(
32535
34120
  "archive_file",
32536
34121
  {
@@ -32619,6 +34204,106 @@ written to: ${out}`
32619
34204
  }
32620
34205
  }
32621
34206
  );
34207
+ server.registerTool(
34208
+ "my_share_code",
34209
+ {
34210
+ title: "Get my share code",
34211
+ description: "Returns YOUR share code (sfshare\u2026). Give it to someone so they can share files with you (free).",
34212
+ inputSchema: {}
34213
+ },
34214
+ async () => {
34215
+ try {
34216
+ return { content: [{ type: "text", text: `Your share code (give it out so others can share files with you):
34217
+
34218
+ ${await af.myShareCode()}` }] };
34219
+ } catch (e) {
34220
+ return { isError: true, content: [{ type: "text", text: `Failed: ${e.message}` }] };
34221
+ }
34222
+ }
34223
+ );
34224
+ server.registerTool(
34225
+ "share_archive",
34226
+ {
34227
+ title: "Share a file with a share code",
34228
+ description: "Grant a recipient PERMANENT decrypt access to one of YOUR archives, by their share code (sfshare\u2026). Free + end-to-end encrypted. Permanent: revoking later stops future retrieval but can't claw back a key already fetched.",
34229
+ inputSchema: {
34230
+ archive_id: external_exports.string().describe("The archive_id to share (must be owned by the configured wallet)"),
34231
+ recipient_code: external_exports.string().describe("The recipient's share code, e.g. sfshare1\u2026")
34232
+ }
34233
+ },
34234
+ async ({ archive_id, recipient_code }) => {
34235
+ try {
34236
+ await af.share(archive_id, recipient_code);
34237
+ return { content: [{ type: "text", text: `\u2705 Shared ${archive_id} with ${recipient_code}. They can decrypt it forever.` }] };
34238
+ } catch (e) {
34239
+ return { isError: true, content: [{ type: "text", text: `Share failed: ${e.message}` }] };
34240
+ }
34241
+ }
34242
+ );
34243
+ server.registerTool(
34244
+ "list_shared_with_me",
34245
+ {
34246
+ title: "List files shared with me",
34247
+ description: "List files other wallets have shared WITH you (decrypted names/types). Free. Use retrieve_shared to download one.",
34248
+ inputSchema: {}
34249
+ },
34250
+ async () => {
34251
+ try {
34252
+ const files = await af.listSharedWithMe();
34253
+ if (files.length === 0) return { content: [{ type: "text", text: "Nothing is shared with you yet." }] };
34254
+ const lines = files.map((f) => `- ${f.archiveId} ${f.name ?? "(no name)"} (${f.contentType ?? "?"})`).join("\n");
34255
+ return { content: [{ type: "text", text: `Shared with you (${files.length}):
34256
+ ${lines}` }] };
34257
+ } catch (e) {
34258
+ return { isError: true, content: [{ type: "text", text: `Failed: ${e.message}` }] };
34259
+ }
34260
+ }
34261
+ );
34262
+ server.registerTool(
34263
+ "retrieve_shared",
34264
+ {
34265
+ title: "Retrieve a file shared with me",
34266
+ description: "Download + decrypt a file someone shared WITH you, by archive_id. Free (no payment). Writes to output_path.",
34267
+ inputSchema: {
34268
+ archive_id: external_exports.string().describe("The archive_id from list_shared_with_me"),
34269
+ output_path: external_exports.string().optional().describe("Where to write the decrypted file (default ./<archive_id>.bin)")
34270
+ }
34271
+ },
34272
+ async ({ archive_id, output_path }) => {
34273
+ try {
34274
+ const r = await af.retrieveShared(archive_id);
34275
+ const out = resolve(output_path ?? resolve(RECOVERY_DIR, `${archive_id}.bin`));
34276
+ await writeFile(out, Buffer.from(r.plaintext));
34277
+ return {
34278
+ content: [
34279
+ {
34280
+ type: "text",
34281
+ text: `\u2705 Retrieved a shared file.
34282
+ archive_id: ${archive_id}
34283
+ content_type: ${r.contentType ?? "application/octet-stream"}
34284
+ bytes: ${r.plaintext.byteLength}
34285
+ written to: ${out}`
34286
+ }
34287
+ ]
34288
+ };
34289
+ } catch (e) {
34290
+ return { isError: true, content: [{ type: "text", text: `Retrieve failed: ${e.message}` }] };
34291
+ }
34292
+ }
34293
+ );
32622
34294
  var transport = new StdioServerTransport();
32623
34295
  await server.connect(transport);
32624
34296
  console.error(`save-forever-mcp running (api=${API_URL}, network=${NETWORK}, per-call cap=$${MAX_USD})`);
34297
+ /*! Bundled license information:
34298
+
34299
+ @scure/base/lib/esm/index.js:
34300
+ (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
34301
+
34302
+ @noble/curves/esm/abstract/edwards.js:
34303
+ @noble/curves/esm/abstract/montgomery.js:
34304
+ @noble/curves/esm/ed25519.js:
34305
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
34306
+
34307
+ @noble/ciphers/esm/utils.js:
34308
+ (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
34309
+ */