@oneaddress/partner-sdk 2.4.1 → 2.6.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/edge.js CHANGED
@@ -42,41 +42,41 @@ function isBytes(a) {
42
42
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
43
43
  }
44
44
  function anumber(n, title = "") {
45
- if (typeof n !== "number") {
46
- const prefix = title && `"${title}" `;
47
- throw new TypeError(`${prefix}expected number, got ${typeof n}`);
48
- }
49
- if (!Number.isSafeInteger(n) || n < 0) {
50
- const prefix = title && `"${title}" `;
51
- throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
52
- }
45
+ if (typeof n !== "number")
46
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
47
+ if (!Number.isSafeInteger(n) || n < 0)
48
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
49
+ return n;
50
+ }
51
+ function abool(value, title = "") {
52
+ if (typeof value !== "boolean")
53
+ throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
54
+ return value;
53
55
  }
54
56
  function abytes(value, length, title = "") {
57
+ if (isBytes(value) && (length === void 0 || value.length === length))
58
+ return value;
59
+ if (length !== void 0)
60
+ anumber(length, "length");
55
61
  const bytes = isBytes(value);
56
- const len = value?.length;
57
- const needsLen = length !== void 0;
58
- if (!bytes || needsLen && len !== length) {
59
- const prefix = title && `"${title}" `;
60
- const ofLen = needsLen ? ` of length ${length}` : "";
61
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
62
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
63
- if (!bytes)
64
- throw new TypeError(message);
65
- throw new RangeError(message);
66
- }
67
- return value;
62
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
63
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
64
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
65
+ if (!bytes)
66
+ throw new TypeError(message);
67
+ throw new RangeError(message);
68
68
  }
69
69
  function aexists(instance, checkFinished = true) {
70
70
  if (instance.destroyed)
71
- throw new Error("Hash instance has been destroyed");
71
+ throw new Error("hash was destroyed");
72
72
  if (checkFinished && instance.finished)
73
- throw new Error("Hash#digest() has already been called");
73
+ throw new Error("digest() was already called");
74
74
  }
75
75
  function aoutput(out, instance) {
76
- abytes(out, void 0, "digestInto() output");
76
+ abytes(out, void 0, "output");
77
77
  const min = instance.outputLen;
78
- if (out.length < min) {
79
- throw new RangeError('"digestInto() output" expected to be of length >=' + min);
78
+ if (!(out.length >= min)) {
79
+ throw new RangeError('"output" expected length >= ' + min);
80
80
  }
81
81
  }
82
82
  function u32(arr) {
@@ -87,9 +87,6 @@ function clean(...arrays) {
87
87
  arrays[i].fill(0);
88
88
  }
89
89
  }
90
- function createView(arr) {
91
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
92
- }
93
90
  function byteSwap(word) {
94
91
  return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
95
92
  }
@@ -110,13 +107,7 @@ function bytesToHex(bytes) {
110
107
  return hex;
111
108
  }
112
109
  function asciiToBase16(ch) {
113
- if (ch >= asciis._0 && ch <= asciis._9)
114
- return ch - asciis._0;
115
- if (ch >= asciis.A && ch <= asciis.F)
116
- return ch - (asciis.A - 10);
117
- if (ch >= asciis.a && ch <= asciis.f)
118
- return ch - (asciis.a - 10);
119
- return;
110
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
120
111
  }
121
112
  function hexToBytes(hex) {
122
113
  if (typeof hex !== "string")
@@ -161,7 +152,17 @@ function concatBytes(...arrays) {
161
152
  }
162
153
  return res;
163
154
  }
155
+ function checkOpts(defaults, opts2, title = "opts") {
156
+ aopts(defaults, "defaults");
157
+ if (opts2 !== void 0)
158
+ aopts(opts2, title);
159
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts2);
160
+ return merged;
161
+ }
164
162
  function createHasher(hashCons, info = {}) {
163
+ if (typeof hashCons !== "function")
164
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
165
+ info = checkOpts({}, info, "info");
165
166
  const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest();
166
167
  const tmp = hashCons(void 0);
167
168
  hashC.outputLen = tmp.outputLen;
@@ -180,10 +181,23 @@ function randomBytes(bytesLength = 32) {
180
181
  throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
181
182
  return cr.getRandomValues(new Uint8Array(bytesLength));
182
183
  }
183
- var isLE, swap32IfBE, hasHexBuiltin, hexes, asciis, oidNist;
184
+ var atitle, aobject, aopts, isLE, swap32IfBE, hasHexBuiltin, hexes, oidNist;
184
185
  var init_utils = __esm({
185
186
  "../../node_modules/@noble/hashes/utils.js"() {
186
187
  "use strict";
188
+ atitle = (title) => title ? `"${title}" ` : "";
189
+ aobject = (value, label) => {
190
+ if (value === null || typeof value !== "object" || Array.isArray(value))
191
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
192
+ };
193
+ aopts = (value, label) => {
194
+ aobject(value, label);
195
+ const proto = Object.getPrototypeOf(value);
196
+ if (proto !== Object.prototype && proto !== null)
197
+ throw new TypeError(`"${label}" expected plain object`);
198
+ if (Object.hasOwn(value, "__proto__"))
199
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
200
+ };
187
201
  isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
188
202
  swap32IfBE = isLE ? (u) => u : byteSwap32;
189
203
  hasHexBuiltin = /* @__PURE__ */ (() => (
@@ -191,7 +205,6 @@ var init_utils = __esm({
191
205
  typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
192
206
  ))();
193
207
  hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
194
- asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
195
208
  oidNist = (suffix) => ({
196
209
  // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
197
210
  // Larger suffix values would need base-128 OID encoding and a different length byte.
@@ -201,11 +214,27 @@ var init_utils = __esm({
201
214
  });
202
215
 
203
216
  // ../../node_modules/@noble/curves/utils.js
204
- function abool(value, title = "") {
205
- if (typeof value !== "boolean") {
206
- const prefix = title && `"${title}" `;
207
- throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
208
- }
217
+ function aarray(item, title, inner = () => {
218
+ }) {
219
+ if (!Array.isArray(item))
220
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
221
+ for (let i = 0; i < item.length; i++)
222
+ inner(item[i], `${title}[${i}]`);
223
+ return item;
224
+ }
225
+ function aobject2(value, title = "object") {
226
+ if (value === null || typeof value !== "object" || Array.isArray(value))
227
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
228
+ return value;
229
+ }
230
+ function afunction(value, title) {
231
+ if (typeof value !== "function")
232
+ throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
233
+ return value;
234
+ }
235
+ function abool2(value, title = "") {
236
+ if (typeof value !== "boolean")
237
+ throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
209
238
  return value;
210
239
  }
211
240
  function abignumber(n) {
@@ -240,26 +269,17 @@ function bytesToNumberLE(bytes) {
240
269
  function numberToBytesBE(n, len) {
241
270
  anumber(len);
242
271
  if (len === 0)
243
- throw new RangeError("zero length");
272
+ throw new Error("zero output length is invalid");
244
273
  n = abignumber(n);
274
+ const expectedLen = len * 2;
245
275
  const hex = n.toString(16);
246
- if (hex.length > len * 2)
247
- throw new RangeError("number too large");
248
- return hexToBytes(hex.padStart(len * 2, "0"));
276
+ if (hex.length > expectedLen)
277
+ throw new RangeError("number is too large");
278
+ return hexToBytes(hex.padStart(expectedLen, "0"));
249
279
  }
250
280
  function numberToBytesLE(n, len) {
251
281
  return numberToBytesBE(n, len).reverse();
252
282
  }
253
- function equalBytes(a, b) {
254
- a = abytes2(a);
255
- b = abytes2(b);
256
- if (a.length !== b.length)
257
- return false;
258
- let diff = 0;
259
- for (let i = 0; i < a.length; i++)
260
- diff |= a[i] ^ b[i];
261
- return diff === 0;
262
- }
263
283
  function copyBytes(bytes) {
264
284
  return Uint8Array.from(abytes2(bytes));
265
285
  }
@@ -274,6 +294,9 @@ function asciiToBytes(ascii) {
274
294
  return charCode;
275
295
  });
276
296
  }
297
+ function isPosBig(n) {
298
+ return typeof n === "bigint" && _0n <= n;
299
+ }
277
300
  function inRange(n, min, max) {
278
301
  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
279
302
  }
@@ -284,29 +307,29 @@ function aInRange(title, n, min, max) {
284
307
  function bitLen(n) {
285
308
  if (n < _0n)
286
309
  throw new Error("expected non-negative bigint, got " + n);
287
- let len;
288
- for (len = 0; n > _0n; n >>= _1n, len += 1)
289
- ;
290
- return len;
291
- }
292
- function validateObject(object, fields = {}, optFields = {}) {
293
- if (Object.prototype.toString.call(object) !== "[object Object]")
294
- throw new TypeError("expected valid options object");
310
+ return n === _0n ? 0 : n.toString(2).length;
311
+ }
312
+ function validateObject(object, fields = {}, optFields = {}, title = "object") {
313
+ aobject2(object, title);
314
+ aobject2(fields, "fields");
315
+ aobject2(optFields, "optFields");
295
316
  function checkField(fieldName, expectedType, isOpt) {
296
- if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
297
- throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
317
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
298
318
  const val = object[fieldName];
319
+ if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
320
+ throw new TypeError(`${label} is invalid: expected own property`);
321
+ }
299
322
  if (isOpt && val === void 0)
300
323
  return;
301
324
  const current = typeof val;
302
325
  if (current !== expectedType || val === null)
303
- throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
326
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
304
327
  }
305
328
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
306
329
  iter(fields, false);
307
330
  iter(optFields, true);
308
331
  }
309
- var abytes2, anumber2, bytesToHex2, concatBytes2, hexToBytes2, isBytes2, randomBytes2, _0n, _1n, isPosBig, bitMask, notImplemented;
332
+ var abytes2, anumber2, bytesToHex2, concatBytes2, hexToBytes2, isBytes2, randomBytes2, _0n, _1n, atitle2, bitMask;
310
333
  var init_utils2 = __esm({
311
334
  "../../node_modules/@noble/curves/utils.js"() {
312
335
  "use strict";
@@ -320,10 +343,10 @@ var init_utils2 = __esm({
320
343
  randomBytes2 = (bytesLength) => randomBytes(bytesLength);
321
344
  _0n = /* @__PURE__ */ BigInt(0);
322
345
  _1n = /* @__PURE__ */ BigInt(1);
323
- isPosBig = (n) => typeof n === "bigint" && _0n <= n;
324
- bitMask = (n) => (_1n << BigInt(n)) - _1n;
325
- notImplemented = () => {
326
- throw new Error("not implemented");
346
+ atitle2 = (title) => title ? `"${title}" ` : "";
347
+ bitMask = (n) => {
348
+ asafenumber(n, "n");
349
+ return (_1n << BigInt(n)) - _1n;
327
350
  };
328
351
  }
329
352
  });
@@ -335,7 +358,55 @@ function mod(a, b) {
335
358
  const result = a % b;
336
359
  return result >= _0n2 ? result : b + result;
337
360
  }
361
+ function pow(num, power, modulo) {
362
+ if (modulo <= _1n2)
363
+ throw new Error("pow: expected modulus > 1, got " + modulo);
364
+ if (typeof power !== "bigint")
365
+ throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
366
+ if (power < _0n2)
367
+ throw new Error("invalid exponent, negatives unsupported");
368
+ if (power === _0n2)
369
+ return _1n2;
370
+ if (power === _1n2)
371
+ return num;
372
+ let d = num % modulo;
373
+ if (d < _0n2)
374
+ d += modulo;
375
+ if (power < POW_WINDOWED_MIN) {
376
+ let p2 = _1n2;
377
+ while (power > _0n2) {
378
+ if (power & _1n2)
379
+ p2 = p2 * d % modulo;
380
+ d = d * d % modulo;
381
+ power >>= _1n2;
382
+ }
383
+ return p2;
384
+ }
385
+ const digits = [];
386
+ while (power > _0n2) {
387
+ digits.push(Number(power & _15n));
388
+ power >>= _4n;
389
+ }
390
+ const table = new Array(16);
391
+ table[0] = _1n2;
392
+ table[1] = d;
393
+ for (let i = 2; i < 16; i++)
394
+ table[i] = table[i - 1] * d % modulo;
395
+ let p = table[digits[digits.length - 1]];
396
+ for (let w = digits.length - 2; w >= 0; w--) {
397
+ p = p * p % modulo;
398
+ p = p * p % modulo;
399
+ p = p * p % modulo;
400
+ p = p * p % modulo;
401
+ const digit = digits[w];
402
+ if (digit !== 0)
403
+ p = p * table[digit] % modulo;
404
+ }
405
+ return p;
406
+ }
338
407
  function pow2(x, power, modulo) {
408
+ if (modulo <= _1n2)
409
+ throw new Error("pow2: expected modulus > 1, got " + modulo);
339
410
  if (power < _0n2)
340
411
  throw new Error("pow2: expected non-negative exponent, got " + power);
341
412
  let res = x;
@@ -348,37 +419,40 @@ function pow2(x, power, modulo) {
348
419
  function invert(number, modulo) {
349
420
  if (number === _0n2)
350
421
  throw new Error("invert: expected non-zero number");
351
- if (modulo <= _0n2)
352
- throw new Error("invert: expected positive modulus, got " + modulo);
422
+ if (modulo <= _1n2)
423
+ throw new Error("invert: expected modulus > 1, got " + modulo);
353
424
  let a = mod(number, modulo);
354
425
  let b = modulo;
355
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
426
+ let x = _0n2, u = _1n2;
356
427
  while (a !== _0n2) {
357
428
  const q = b / a;
358
429
  const r = b - a * q;
359
430
  const m = x - u * q;
360
- const n = y - v * q;
361
- b = a, a = r, x = u, y = v, u = m, v = n;
431
+ b = a, a = r, x = u, u = m;
362
432
  }
363
433
  const gcd = b;
364
434
  if (gcd !== _1n2)
365
435
  throw new Error("invert: does not exist");
366
436
  return mod(x, modulo);
367
437
  }
368
- function assertIsSquare(Fp2, root, n) {
369
- const F2 = Fp2;
438
+ function assertIsSquare(Fp, root, n) {
439
+ const F2 = Fp;
370
440
  if (!F2.eql(F2.sqr(root), n))
371
441
  throw new Error("Cannot find square root");
372
442
  }
373
- function sqrt3mod4(Fp2, n) {
374
- const F2 = Fp2;
443
+ function aoddModulus(order, fnName) {
444
+ if ((order & _1n2) === _0n2)
445
+ throw new Error(fnName + ": expected odd modulus, got " + order);
446
+ }
447
+ function sqrt3mod4(Fp, n) {
448
+ const F2 = Fp;
375
449
  const p1div4 = (F2.ORDER + _1n2) / _4n;
376
450
  const root = F2.pow(n, p1div4);
377
451
  assertIsSquare(F2, root, n);
378
452
  return root;
379
453
  }
380
- function sqrt5mod8(Fp2, n) {
381
- const F2 = Fp2;
454
+ function sqrt5mod8(Fp, n) {
455
+ const F2 = Fp;
382
456
  const p5div8 = (F2.ORDER - _5n) / _8n;
383
457
  const n2 = F2.mul(n, _2n);
384
458
  const v = F2.pow(n2, p5div8);
@@ -395,8 +469,8 @@ function sqrt9mod16(P) {
395
469
  const c2 = tn(Fp_, c1);
396
470
  const c3 = tn(Fp_, Fp_.neg(c1));
397
471
  const c4 = (P + _7n) / _16n;
398
- return ((Fp2, n) => {
399
- const F2 = Fp2;
472
+ return ((Fp, n) => {
473
+ const F2 = Fp;
400
474
  let tv1 = F2.pow(n, c4);
401
475
  let tv2 = F2.mul(tv1, c1);
402
476
  const tv3 = F2.mul(tv1, c2);
@@ -414,6 +488,7 @@ function sqrt9mod16(P) {
414
488
  function tonelliShanks(P) {
415
489
  if (P < _3n)
416
490
  throw new Error("sqrt is not defined for small field");
491
+ aoddModulus(P, "tonelliShanks");
417
492
  let Q2 = P - _1n2;
418
493
  let S = 0;
419
494
  while (Q2 % _2n === _0n2) {
@@ -430,8 +505,8 @@ function tonelliShanks(P) {
430
505
  return sqrt3mod4;
431
506
  let cc = _Fp.pow(Z, Q2);
432
507
  const Q1div2 = (Q2 + _1n2) / _2n;
433
- return function tonelliSlow(Fp2, n) {
434
- const F2 = Fp2;
508
+ return function tonelliSlow(Fp, n) {
509
+ const F2 = Fp;
435
510
  if (F2.is0(n))
436
511
  return n;
437
512
  if (FpLegendre(F2, n) !== 1)
@@ -442,7 +517,7 @@ function tonelliShanks(P) {
442
517
  let R = F2.pow(n, Q1div2);
443
518
  while (!F2.eql(t, F2.ONE)) {
444
519
  if (F2.is0(t))
445
- return F2.ZERO;
520
+ throw new Error("Cannot find square root: probably non-prime P");
446
521
  let i = 1;
447
522
  let t_tmp = F2.sqr(t);
448
523
  while (!F2.eql(t_tmp, F2.ONE)) {
@@ -462,6 +537,7 @@ function tonelliShanks(P) {
462
537
  };
463
538
  }
464
539
  function FpSqrt(P) {
540
+ aoddModulus(P, "Fp.sqrt");
465
541
  if (P % _4n === _3n)
466
542
  return sqrt3mod4;
467
543
  if (P % _8n === _5n)
@@ -471,44 +547,24 @@ function FpSqrt(P) {
471
547
  return tonelliShanks(P);
472
548
  }
473
549
  function validateField(field) {
474
- const initial = {
475
- ORDER: "bigint",
476
- BYTES: "number",
477
- BITS: "number"
478
- };
479
- const opts2 = FIELD_FIELDS.reduce((map, val) => {
480
- map[val] = "function";
481
- return map;
482
- }, initial);
483
- validateObject(field, opts2);
550
+ aobject2(field, "field");
551
+ if (typeof field.ORDER !== "bigint")
552
+ throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
484
553
  asafenumber(field.BYTES, "BYTES");
485
554
  asafenumber(field.BITS, "BITS");
555
+ for (const name of FIELD_FIELDS)
556
+ afunction(field[name], "field." + name);
486
557
  if (field.BYTES < 1 || field.BITS < 1)
487
558
  throw new Error("invalid field: expected BYTES/BITS > 0");
488
559
  if (field.ORDER <= _1n2)
489
560
  throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
490
561
  return field;
491
562
  }
492
- function FpPow(Fp2, num, power) {
493
- const F2 = Fp2;
494
- if (power < _0n2)
495
- throw new Error("invalid exponent, negatives unsupported");
496
- if (power === _0n2)
497
- return F2.ONE;
498
- if (power === _1n2)
499
- return num;
500
- let p = F2.ONE;
501
- let d = num;
502
- while (power > _0n2) {
503
- if (power & _1n2)
504
- p = F2.mul(p, d);
505
- d = F2.sqr(d);
506
- power >>= _1n2;
507
- }
508
- return p;
509
- }
510
- function FpInvertBatch(Fp2, nums, passZero = false) {
511
- const F2 = Fp2;
563
+ function FpInvertBatch(Fp, nums, passZero = false) {
564
+ validateField(Fp);
565
+ aarray(nums, "nums");
566
+ abool2(passZero, "passZero");
567
+ const F2 = Fp;
512
568
  const inverted = new Array(nums.length).fill(passZero ? F2.ZERO : void 0);
513
569
  const multipliedAcc = nums.reduce((acc, num, i) => {
514
570
  if (F2.is0(num))
@@ -525,8 +581,10 @@ function FpInvertBatch(Fp2, nums, passZero = false) {
525
581
  }, invertedAcc);
526
582
  return inverted;
527
583
  }
528
- function FpLegendre(Fp2, n) {
529
- const F2 = Fp2;
584
+ function FpLegendre(Fp, n) {
585
+ validateField(Fp);
586
+ const F2 = Fp;
587
+ aoddModulus(F2.ORDER, "FpLegendre");
530
588
  const p1mod2 = (F2.ORDER - _1n2) / _2n;
531
589
  const powered = F2.pow(n, p1mod2);
532
590
  const yes = F2.eql(powered, F2.ONE);
@@ -545,15 +603,16 @@ function nLength(n, nBitLength) {
545
603
  throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
546
604
  const bits = bitLen(n);
547
605
  if (nBitLength !== void 0 && nBitLength < bits)
548
- throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
606
+ throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
549
607
  const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
550
608
  const nByteLength = Math.ceil(_nBitLength / 8);
551
609
  return { nBitLength: _nBitLength, nByteLength };
552
610
  }
553
611
  function Field(ORDER, opts2 = {}) {
612
+ Object.freeze(_Field.prototype);
554
613
  return new _Field(ORDER, opts2);
555
614
  }
556
- var _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _16n, isNegativeLE, FIELD_FIELDS, FIELD_SQRT, _Field;
615
+ var _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _15n, _16n, POW_WINDOWED_MIN, isNegativeLE, FIELD_FIELDS, FIELD_SQRT, _Field;
557
616
  var init_modular = __esm({
558
617
  "../../node_modules/@noble/curves/abstract/modular.js"() {
559
618
  "use strict";
@@ -567,7 +626,9 @@ var init_modular = __esm({
567
626
  _7n = /* @__PURE__ */ BigInt(7);
568
627
  _8n = /* @__PURE__ */ BigInt(8);
569
628
  _9n = /* @__PURE__ */ BigInt(9);
629
+ _15n = /* @__PURE__ */ BigInt(15);
570
630
  _16n = /* @__PURE__ */ BigInt(16);
631
+ POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
571
632
  isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
572
633
  FIELD_FIELDS = [
573
634
  "create",
@@ -660,7 +721,7 @@ var init_modular = __esm({
660
721
  return mod(lhs * rhs, this.ORDER);
661
722
  }
662
723
  pow(num, power) {
663
- return FpPow(this, num, power);
724
+ return pow(num, power, this.ORDER);
664
725
  }
665
726
  div(lhs, rhs) {
666
727
  return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
@@ -714,63 +775,150 @@ var init_modular = __esm({
714
775
  }
715
776
  // TODO: we don't need it here, move out to separate fn
716
777
  invertBatch(lst) {
717
- return FpInvertBatch(this, lst);
778
+ return FpInvertBatch(this, lst, true);
718
779
  }
719
780
  // We can't move this out because Fp6, Fp12 implement it
720
781
  // and it's unclear what to return in there.
721
782
  cmov(a, b, condition) {
722
- abool(condition, "condition");
783
+ abool2(condition, "condition");
723
784
  return condition ? b : a;
724
785
  }
725
786
  };
726
- Object.freeze(_Field.prototype);
727
787
  }
728
788
  });
729
789
 
730
790
  // ../../node_modules/@noble/curves/abstract/curve.js
731
- function negateCt(condition, item) {
732
- const neg = item.negate();
733
- return condition ? neg : item;
791
+ function validatePointCons(Point) {
792
+ const pc = Point;
793
+ if (typeof pc !== "function")
794
+ throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
795
+ afunction(pc.fromAffine, "Point.fromAffine");
796
+ afunction(pc.fromBytes, "Point.fromBytes");
797
+ afunction(pc.fromHex, "Point.fromHex");
798
+ aobject2(pc.BASE, "Point.BASE");
799
+ aobject2(pc.ZERO, "Point.ZERO");
800
+ validateField(pc.Fp);
801
+ validateField(pc.Fn);
734
802
  }
735
803
  function normalizeZ(c, points) {
804
+ validatePointCons(c);
805
+ validateMSMPoints(points, c);
736
806
  const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
737
807
  return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
738
808
  }
739
- function validateW(W, bits) {
740
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
741
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
809
+ function validateW(W, bits, min = 1) {
810
+ if (!Number.isSafeInteger(W) || W < min || W > bits)
811
+ throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
742
812
  }
743
- function calcWOpts(W, scalarBits) {
744
- validateW(W, scalarBits);
745
- const windows = Math.ceil(scalarBits / W) + 1;
746
- const windowSize = 2 ** (W - 1);
747
- const maxNumber = 2 ** W;
748
- const mask = bitMask(W);
749
- const shiftBy = BigInt(W);
750
- return { windows, windowSize, mask, maxNumber, shiftBy };
751
- }
752
- function calcOffsets(n, window, wOpts) {
753
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
754
- let wbits = Number(n & mask);
755
- let nextN = n >> shiftBy;
756
- if (wbits > windowSize) {
757
- wbits -= maxNumber;
758
- nextN += _1n3;
759
- }
760
- const offsetStart = window * windowSize;
761
- const offset = offsetStart + Math.abs(wbits) - 1;
762
- const isZero = wbits === 0;
763
- const isNeg = wbits < 0;
764
- const isNegF = window % 2 !== 0;
765
- const offsetF = offsetStart;
766
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
767
- }
768
- function getW(P) {
813
+ function validateTableBytes(numPoints, fpBytes) {
814
+ const bytes = numPoints * (4 * fpBytes + 128);
815
+ if (bytes > TABLE_BYTES_MAX)
816
+ throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
817
+ }
818
+ function probeRandomBytes(randomBytes5, length) {
819
+ if (randomBytes5 === void 0)
820
+ return void 0;
821
+ afunction(randomBytes5, "randomBytes");
822
+ try {
823
+ const probe = randomBytes5(length);
824
+ if (!isBytes2(probe) || probe.length !== length)
825
+ return void 0;
826
+ } catch {
827
+ return void 0;
828
+ }
829
+ return randomBytes5;
830
+ }
831
+ function validateMSMPoints(points, c) {
832
+ aarray(points, "points");
833
+ points.forEach((p, i) => {
834
+ if (!(p instanceof c))
835
+ throw new Error("invalid point at index " + i);
836
+ });
837
+ }
838
+ function validateMSMScalars(scalars, field, maxScalar) {
839
+ if (!Array.isArray(scalars))
840
+ throw new Error("array of scalars expected");
841
+ scalars.forEach((s, i) => {
842
+ const ok = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
843
+ if (!ok)
844
+ throw new Error("invalid scalar at index " + i);
845
+ });
846
+ }
847
+ function getWindowSize(P) {
769
848
  return pointWindowSizes.get(P) || 1;
770
849
  }
771
- function assert0(n) {
850
+ function oddMultiples(p, size) {
851
+ const dbl = p.double();
852
+ const t = [p];
853
+ for (let j = 1; j < size; j++)
854
+ t.push(t[j - 1].add(dbl));
855
+ return t;
856
+ }
857
+ function wnafDigits(n, W) {
858
+ const size = 2 ** W;
859
+ const half = size / 2;
860
+ const mask = BigInt(size - 1);
861
+ const d = [];
862
+ while (n > _0n3) {
863
+ let w = 0;
864
+ if (n & _1n3) {
865
+ w = Number(n & mask);
866
+ if (w >= half)
867
+ w -= size;
868
+ n -= BigInt(w);
869
+ }
870
+ d.push(w);
871
+ n >>= _1n3;
872
+ }
873
+ return d;
874
+ }
875
+ function signedWindowDigits(n, W, windows) {
876
+ const size = 2 ** W;
877
+ const half = size / 2;
878
+ const mask = BigInt(size - 1);
879
+ const shiftBy = BigInt(W);
880
+ const d = [];
881
+ for (let w = 0; w < windows; w++) {
882
+ let v = Number(n & mask);
883
+ n >>= shiftBy;
884
+ if (v > half) {
885
+ v -= size;
886
+ n += _1n3;
887
+ }
888
+ d.push(v);
889
+ }
772
890
  if (n !== _0n3)
773
- throw new Error("invalid wNAF");
891
+ throw new Error("invalid wnaf");
892
+ return d;
893
+ }
894
+ function wnafWalk(zero, tables, digits) {
895
+ let max = 0;
896
+ for (const d of digits)
897
+ max = Math.max(max, d.length);
898
+ let acc = zero;
899
+ for (let bit = max - 1; bit >= 0; bit--) {
900
+ if (bit !== max - 1)
901
+ acc = acc.double();
902
+ for (let i = 0; i < digits.length; i++) {
903
+ const w = digits[i][bit];
904
+ if (w) {
905
+ const item = tables[i][Math.abs(w) - 1 >> 1];
906
+ acc = acc.add(w < 0 ? item.negate() : item);
907
+ }
908
+ }
909
+ }
910
+ return acc;
911
+ }
912
+ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
913
+ validatePointCons(c);
914
+ validateMSMPoints(points, c);
915
+ abool2(allowOversized, "allowOversized");
916
+ validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
917
+ if (points.length !== scalars.length)
918
+ throw new Error("arrays of points and scalars must have equal length");
919
+ const tables = points.map((p) => oddMultiples(p, 4));
920
+ const digits = scalars.map((n) => wnafDigits(n, 4));
921
+ return wnafWalk(c.ZERO, tables, digits);
774
922
  }
775
923
  function createField(order, field, isLE2) {
776
924
  if (field) {
@@ -783,25 +931,28 @@ function createField(order, field, isLE2) {
783
931
  }
784
932
  }
785
933
  function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
934
+ if (type !== "weierstrass" && type !== "edwards")
935
+ throw new Error('expected curve type "weierstrass" or "edwards"');
786
936
  if (FpFnLE === void 0)
787
937
  FpFnLE = type === "edwards";
788
938
  if (!CURVE || typeof CURVE !== "object")
789
939
  throw new Error(`expected valid ${type} CURVE object`);
940
+ validateObject(curveOpts);
790
941
  for (const p of ["p", "n", "h"]) {
791
942
  const val = CURVE[p];
792
- if (!(typeof val === "bigint" && val > _0n3))
943
+ if (!(isPosBig(val) && val !== _0n3))
793
944
  throw new Error(`CURVE.${p} must be positive bigint`);
794
945
  }
795
- const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
796
- const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
946
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
947
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
797
948
  const _b = type === "weierstrass" ? "b" : "d";
798
949
  const params = ["Gx", "Gy", "a", _b];
799
950
  for (const p of params) {
800
- if (!Fp2.isValid(CURVE[p]))
951
+ if (!Fp.isValid(CURVE[p]))
801
952
  throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
802
953
  }
803
954
  CURVE = Object.freeze(Object.assign({}, CURVE));
804
- return { CURVE, Fp: Fp2, Fn: Fn2 };
955
+ return { CURVE, Fp, Fn };
805
956
  }
806
957
  function createKeygen(randomSecretKey, getPublicKey) {
807
958
  return function keygen(seed) {
@@ -809,7 +960,7 @@ function createKeygen(randomSecretKey, getPublicKey) {
809
960
  return { secretKey, publicKey: getPublicKey(secretKey) };
810
961
  };
811
962
  }
812
- var _0n3, _1n3, pointPrecomputes, pointWindowSizes, wNAF;
963
+ var _0n3, _1n3, _4n2, BLIND_BYTES, BLIND_BITS, FW_WINDOW, TABLE_BYTES_MAX, pointWindowSizes, ScalarMultiplier;
813
964
  var init_curve = __esm({
814
965
  "../../node_modules/@noble/curves/abstract/curve.js"() {
815
966
  "use strict";
@@ -817,169 +968,257 @@ var init_curve = __esm({
817
968
  init_modular();
818
969
  _0n3 = /* @__PURE__ */ BigInt(0);
819
970
  _1n3 = /* @__PURE__ */ BigInt(1);
820
- pointPrecomputes = /* @__PURE__ */ new WeakMap();
971
+ _4n2 = /* @__PURE__ */ BigInt(4);
972
+ BLIND_BYTES = 16;
973
+ BLIND_BITS = 128;
974
+ FW_WINDOW = 5;
975
+ TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
821
976
  pointWindowSizes = /* @__PURE__ */ new WeakMap();
822
- wNAF = class {
977
+ ScalarMultiplier = class {
823
978
  // Parametrized with a given Point class (not individual point)
824
- constructor(Point, bits) {
979
+ constructor(Point, randomBytes5) {
980
+ __publicField(this, "Point");
825
981
  __publicField(this, "BASE");
826
982
  __publicField(this, "ZERO");
827
- __publicField(this, "Fn");
983
+ __publicField(this, "randomBytes");
984
+ __publicField(this, "wnafPrecomputes", /* @__PURE__ */ new WeakMap());
985
+ __publicField(this, "baseCanBeBlinded");
828
986
  __publicField(this, "bits");
987
+ validatePointCons(Point);
988
+ this.randomBytes = probeRandomBytes(randomBytes5, BLIND_BYTES);
989
+ this.Point = Point;
829
990
  this.BASE = Point.BASE;
830
991
  this.ZERO = Point.ZERO;
831
- this.Fn = Point.Fn;
832
- this.bits = bits;
833
- }
834
- // non-const time multiplication ladder
835
- _unsafeLadder(elm, n, p = this.ZERO) {
836
- let d = elm;
837
- while (n > _0n3) {
838
- if (n & _1n3)
839
- p = p.add(d);
840
- d = d.double();
841
- n >>= _1n3;
842
- }
843
- return p;
992
+ this.bits = Point.Fn.BITS;
844
993
  }
845
994
  /**
846
- * Creates a wNAF precomputation window. Used for caching.
847
- * Default window size is set by `utils.precompute()` and is equal to 8.
848
- * Number of precomputed points depends on the curve size:
849
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
850
- * - 𝑊 is the window size
851
- * - 𝑛 is the bitlength of the curve order.
852
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
995
+ * Creates a signed fixed-window wNAF precomputation table: for every window w, the
996
+ * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
997
+ * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
998
+ * window absorbs the final carry of signed-digit recoding.
999
+ * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
853
1000
  * @param point - Point instance
854
1001
  * @param W - window size
855
- * @returns precomputed point tables flattened to a single array
1002
+ * @param bits - scalar bitlength the table must cover
856
1003
  */
857
- precomputeWindow(point, W) {
858
- const { windows, windowSize } = calcWOpts(W, this.bits);
859
- const points = [];
860
- let p = point;
861
- let base = p;
862
- for (let window = 0; window < windows; window++) {
863
- base = p;
864
- points.push(base);
865
- for (let i = 1; i < windowSize; i++) {
866
- base = base.add(p);
867
- points.push(base);
1004
+ buildWnafTable(point, W, bits) {
1005
+ const windows = Math.ceil(bits / W) + 1;
1006
+ const half = 2 ** (W - 1);
1007
+ const comp = [];
1008
+ let base = point;
1009
+ for (let w = 0; w < windows; w++) {
1010
+ let acc = base;
1011
+ for (let i = 0; i < half; i++) {
1012
+ comp.push(acc);
1013
+ acc = acc.add(base);
868
1014
  }
869
- p = base.double();
1015
+ base = comp[comp.length - 1].double();
870
1016
  }
871
- return points;
1017
+ return { W, bits, windows, comp };
872
1018
  }
873
1019
  /**
874
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
875
- * More compact implementation:
876
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1020
+ * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
1021
+ * Constant-time: fixed window count with one table addition per window — zero digits feed
1022
+ * the fake accumulator — and no doublings; the lookup scans the whole window slice.
1023
+ * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
1024
+ * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
1025
+ * signedWindowDigits throws if `n` exceeds the table.
877
1026
  * @returns real and fake (for const-time) points
878
1027
  */
879
- wNAF(W, precomputes, n) {
880
- if (!this.Fn.isValid(n))
881
- throw new Error("invalid scalar");
1028
+ wnafCachedCT(precomputes, n) {
1029
+ const { W, windows, comp } = precomputes;
1030
+ const half = 2 ** (W - 1);
1031
+ const digits = signedWindowDigits(n, W, windows);
882
1032
  let p = this.ZERO;
883
1033
  let f = this.BASE;
884
- const wo = calcWOpts(W, this.bits);
885
- for (let window = 0; window < wo.windows; window++) {
886
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
887
- n = nextN;
888
- if (isZero) {
889
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
890
- } else {
891
- p = p.add(negateCt(isNeg, precomputes[offset]));
892
- }
1034
+ for (let w = 0; w < windows; w++) {
1035
+ const digit = digits[w];
1036
+ const start = w * half;
1037
+ const idx = Math.abs(digit) - 1;
1038
+ let sel = comp[start];
1039
+ for (let i = 1; i < half; i++)
1040
+ sel = i === idx ? comp[start + i] : sel;
1041
+ const neg = sel.negate();
1042
+ if (digit === 0)
1043
+ f = f.add(comp[start]);
1044
+ else
1045
+ p = p.add(digit < 0 ? neg : sel);
893
1046
  }
894
- assert0(n);
895
1047
  return { p, f };
896
1048
  }
897
- /**
898
- * Implements unsafe EC multiplication using precomputed tables
899
- * and w-ary non-adjacent form.
900
- * @param acc - accumulator point to add result of multiplication
901
- * @returns point
902
- */
903
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
904
- const wo = calcWOpts(W, this.bits);
905
- for (let window = 0; window < wo.windows; window++) {
906
- if (n === _0n3)
907
- break;
908
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
909
- n = nextN;
910
- if (isZero) {
911
- continue;
912
- } else {
913
- const item = precomputes[offset];
914
- acc = acc.add(isNeg ? item.negate() : item);
915
- }
916
- }
917
- assert0(n);
918
- return acc;
919
- }
920
- getPrecomputes(W, point, transform) {
921
- let comp = pointPrecomputes.get(point);
1049
+ // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
1050
+ // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
1051
+ // incompatible `transform(...)` layouts and expect a separate cache entry.
1052
+ getWnafPrecomputes(W, point, bits, transform) {
1053
+ let entries = this.wnafPrecomputes.get(point);
1054
+ let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
922
1055
  if (!comp) {
923
- comp = this.precomputeWindow(point, W);
924
- if (W !== 1) {
925
- if (typeof transform === "function")
926
- comp = transform(comp);
927
- pointPrecomputes.set(point, comp);
1056
+ comp = this.buildWnafTable(point, W, bits);
1057
+ if (typeof transform === "function")
1058
+ comp = { ...comp, comp: transform(comp.comp) };
1059
+ if (!entries) {
1060
+ entries = [];
1061
+ this.wnafPrecomputes.set(point, entries);
928
1062
  }
1063
+ entries.push(comp);
929
1064
  }
930
1065
  return comp;
931
1066
  }
932
- cached(point, scalar, transform) {
933
- const W = getW(point);
934
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1067
+ assertPoint(point) {
1068
+ if (!(point instanceof this.Point))
1069
+ throw new TypeError('"point" expected Point instance, got type=' + typeof point);
1070
+ }
1071
+ // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
1072
+ // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
1073
+ // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
1074
+ validateMulInput(point, scalar) {
1075
+ this.assertPoint(point);
1076
+ if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
1077
+ throw new Error("invalid scalar");
935
1078
  }
936
- unsafe(point, scalar, transform, prev) {
937
- const W = getW(point);
1079
+ // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
1080
+ // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
1081
+ // multiply. `n` must be < 2^bits.
1082
+ runCT(point, n, bits, transform) {
1083
+ const W = getWindowSize(point);
938
1084
  if (W === 1)
939
- return this._unsafeLadder(point, scalar, prev);
940
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1085
+ return this.fixedWindowCT(point, n, bits);
1086
+ return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
941
1087
  }
942
- // We calculate precomputes for elliptic curve point multiplication
943
- // using windowed method. This specifies window size and
944
- // stores precomputed values. Usually only base point would be precomputed.
945
- createCache(P, W) {
1088
+ mulCT(point, scalar, transform) {
1089
+ this.validateMulInput(point, scalar);
1090
+ return this.runCT(point, scalar, this.bits, transform);
1091
+ }
1092
+ mulCTBlinded(point, scalar, transform) {
1093
+ this.validateMulInput(point, scalar);
1094
+ if (this.randomBytes === void 0)
1095
+ throw new Error("randomBytes is required for scalar blinding");
1096
+ const bits = this.Point.Fn.BITS + BLIND_BITS;
1097
+ const blind = this.randomBytes(BLIND_BYTES);
1098
+ if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
1099
+ throw new Error("randomBytes returned invalid byte array");
1100
+ blind[0] = blind[0] & 63 | 128;
1101
+ const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
1102
+ return this.runCT(point, n, bits, transform);
1103
+ }
1104
+ /**
1105
+ * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
1106
+ * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
1107
+ * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
1108
+ * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
1109
+ * every table entry, and one addition (adds the identity when the window digit is 0 — never
1110
+ * skipped).
1111
+ *
1112
+ * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
1113
+ * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
1114
+ * projective form (no normalizeZ): normalizing this small a table costs more than the
1115
+ * mixed-add savings it would buy for a single multiply.
1116
+ * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
1117
+ * (this path needs no fake accumulator — its op-count is already scalar-independent).
1118
+ */
1119
+ fixedWindowCT(point, n, bits) {
1120
+ const W = FW_WINDOW;
1121
+ const size = 1 << W;
1122
+ const mask = bitMask(W);
1123
+ const table = new Array(size);
1124
+ table[0] = this.ZERO;
1125
+ for (let i = 1; i < size; i++)
1126
+ table[i] = table[i - 1].add(point);
1127
+ const windows = Math.ceil(bits / W);
1128
+ let acc = this.ZERO;
1129
+ for (let window = windows - 1; window >= 0; window--) {
1130
+ if (window !== windows - 1)
1131
+ for (let d = 0; d < W; d++)
1132
+ acc = acc.double();
1133
+ const digit = Number(n >> BigInt(window * W) & mask);
1134
+ let sel = table[0];
1135
+ for (let i = 1; i < size; i++)
1136
+ sel = i === digit ? table[i] : sel;
1137
+ acc = acc.add(sel);
1138
+ }
1139
+ return { p: acc, f: acc };
1140
+ }
1141
+ shouldBlind(point, cofactor) {
1142
+ if (this.randomBytes === void 0)
1143
+ return false;
1144
+ if (cofactor === _1n3)
1145
+ return true;
1146
+ if (point !== this.BASE)
1147
+ return false;
1148
+ if (this.baseCanBeBlinded === void 0)
1149
+ this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
1150
+ return this.baseCanBeBlinded;
1151
+ }
1152
+ mulSecret(point, scalar, cofactor, transform) {
1153
+ return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
1154
+ }
1155
+ mulUnsafe(point, scalar, transform) {
1156
+ this.assertPoint(point);
1157
+ if (!isPosBig(scalar))
1158
+ throw new Error("invalid scalar");
1159
+ const W = getWindowSize(point);
1160
+ if (W === 1 || scalar >= this.Point.Fn.ORDER)
1161
+ return mulAddUnsafe(this.Point, [point], [scalar], true);
1162
+ const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
1163
+ return this.wnafCachedCT(precomputes, scalar).p;
1164
+ }
1165
+ // Remembers the window size used for precomputed wNAF multiplication of the given point
1166
+ // and drops any previously built tables. Usually only the base point is precomputed.
1167
+ // W=1 resets the point to the un-precomputed (table-less) paths.
1168
+ // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
1169
+ setWindowSize(point, W) {
1170
+ this.assertPoint(point);
946
1171
  validateW(W, this.bits);
947
- pointWindowSizes.set(P, W);
948
- pointPrecomputes.delete(P);
1172
+ const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
1173
+ validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
1174
+ pointWindowSizes.set(point, W);
1175
+ this.wnafPrecomputes.delete(point);
949
1176
  }
950
- hasCache(elm) {
951
- return getW(elm) !== 1;
1177
+ // True when a window size is set: tables themselves are built lazily on first multiply.
1178
+ hasWindowSize(point) {
1179
+ return getWindowSize(point) !== 1;
952
1180
  }
953
1181
  };
954
1182
  }
955
1183
  });
956
1184
 
957
1185
  // ../../node_modules/@noble/curves/abstract/edwards.js
958
- function isEdValidXY(Fp2, CURVE, x, y) {
959
- const x2 = Fp2.sqr(x);
960
- const y2 = Fp2.sqr(y);
961
- const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
962
- const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
963
- return Fp2.eql(left, right);
1186
+ function isEdValidXY(Fp, CURVE, x, y) {
1187
+ const x2 = Fp.sqr(x);
1188
+ const y2 = Fp.sqr(y);
1189
+ const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
1190
+ const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
1191
+ return Fp.eql(left, right);
964
1192
  }
965
1193
  function edwards(params, extraOpts = {}) {
1194
+ validateObject(extraOpts, {}, {}, "extraOpts");
966
1195
  const opts2 = extraOpts;
967
1196
  const validated = createCurveFields("edwards", params, opts2, opts2.FpFnLE);
968
- const { Fp: Fp2, Fn: Fn2 } = validated;
1197
+ const { Fp, Fn } = validated;
969
1198
  let CURVE = validated.CURVE;
970
1199
  const { h: cofactor } = CURVE;
971
- validateObject(opts2, {}, { uvRatio: "function" });
972
- const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
973
- const modP = (n) => Fp2.create(n);
1200
+ if (FpLegendre(Fp, CURVE.a) !== 1)
1201
+ throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
1202
+ if (FpLegendre(Fp, CURVE.d) !== -1)
1203
+ throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
1204
+ validateObject(opts2, {}, { uvRatio: "function", randomBytes: "function" });
1205
+ const randomBytes5 = opts2.randomBytes === void 0 ? randomBytes2 : opts2.randomBytes;
1206
+ const MASK = _2n2 << BigInt(Fp.BYTES * 8) - _1n4;
1207
+ function isOdd(n) {
1208
+ if (!Fp.isOdd)
1209
+ throw new Error("Field does not have .isOdd()");
1210
+ return Fp.isOdd(n);
1211
+ }
974
1212
  const uvRatio2 = opts2.uvRatio === void 0 ? (u, v) => {
975
1213
  try {
976
- return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
1214
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
977
1215
  } catch (e) {
978
1216
  return { isValid: false, value: _0n4 };
979
1217
  }
980
1218
  } : opts2.uvRatio;
981
- if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1219
+ if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
982
1220
  throw new Error("bad curve params: generator point");
1221
+ const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x) : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x : (x) => Fp.mul(CURVE.a, x);
983
1222
  function acoord(title, n, banZero = false) {
984
1223
  const min = banZero ? _1n4 : _0n4;
985
1224
  aInRange("coordinate " + title, n, min, MASK);
@@ -1015,32 +1254,32 @@ function edwards(params, extraOpts = {}) {
1015
1254
  const { x, y } = p || {};
1016
1255
  acoord("x", x);
1017
1256
  acoord("y", y);
1018
- return new _Point(x, y, _1n4, modP(x * y));
1257
+ return new _Point(x, y, Fp.ONE, Fp.mul(x, y));
1019
1258
  }
1020
1259
  // Uses algo from RFC8032 5.1.3.
1021
1260
  static fromBytes(bytes, zip215 = false) {
1022
- const len = Fp2.BYTES;
1261
+ const len = Fp.BYTES;
1023
1262
  const { a, d } = CURVE;
1024
1263
  bytes = copyBytes(abytes2(bytes, len, "point"));
1025
- abool(zip215, "zip215");
1264
+ abool2(zip215, "zip215");
1026
1265
  const normed = copyBytes(bytes);
1027
1266
  const lastByte = bytes[len - 1];
1028
1267
  normed[len - 1] = lastByte & ~128;
1029
1268
  const y = bytesToNumberLE(normed);
1030
- const max = zip215 ? MASK : Fp2.ORDER;
1269
+ const max = zip215 ? MASK : Fp.ORDER;
1031
1270
  aInRange("point.y", y, _0n4, max);
1032
- const y2 = modP(y * y);
1033
- const u = modP(y2 - _1n4);
1034
- const v = modP(d * y2 - a);
1271
+ const y2 = Fp.sqr(y);
1272
+ const u = Fp.sub(y2, Fp.ONE);
1273
+ const v = Fp.sub(Fp.mulN(d, y2), a);
1035
1274
  let { isValid, value: x } = uvRatio2(u, v);
1036
1275
  if (!isValid)
1037
1276
  throw new Error("bad point: invalid y coordinate");
1038
- const isXOdd = (x & _1n4) === _1n4;
1277
+ const isXOdd = isOdd(x);
1039
1278
  const isLastByteOdd = (lastByte & 128) !== 0;
1040
- if (!zip215 && x === _0n4 && isLastByteOdd)
1279
+ if (!zip215 && Fp.is0(x) && isLastByteOdd)
1041
1280
  throw new Error("bad point: x=0 and x_0=1");
1042
1281
  if (isLastByteOdd !== isXOdd)
1043
- x = modP(-x);
1282
+ x = Fp.neg(x);
1044
1283
  return _Point.fromAffine({ x, y });
1045
1284
  }
1046
1285
  static fromHex(hex, zip215 = false) {
@@ -1052,8 +1291,8 @@ function edwards(params, extraOpts = {}) {
1052
1291
  get y() {
1053
1292
  return this.toAffine().y;
1054
1293
  }
1055
- precompute(windowSize = 8, isLazy = true) {
1056
- wnaf.createCache(this, windowSize);
1294
+ precompute(windowSize = 6, isLazy = true) {
1295
+ wnaf.setWindowSize(this, windowSize);
1057
1296
  if (!isLazy)
1058
1297
  this.multiply(_2n2);
1059
1298
  return this;
@@ -1065,18 +1304,18 @@ function edwards(params, extraOpts = {}) {
1065
1304
  if (p.is0())
1066
1305
  throw new Error("bad point: ZERO");
1067
1306
  const { X, Y, Z, T } = p;
1068
- const X2 = modP(X * X);
1069
- const Y2 = modP(Y * Y);
1070
- const Z2 = modP(Z * Z);
1071
- const Z4 = modP(Z2 * Z2);
1072
- const aX2 = modP(X2 * a);
1073
- const left = modP(Z2 * modP(aX2 + Y2));
1074
- const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1075
- if (left !== right)
1307
+ const X2 = Fp.sqr(X);
1308
+ const Y2 = Fp.sqr(Y);
1309
+ const Z2 = Fp.sqr(Z);
1310
+ const Z4 = Fp.sqr(Z2);
1311
+ const aX2 = Fp.mul(X2, a);
1312
+ const left = Fp.mul(Fp.add(aX2, Y2), Z2);
1313
+ const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2)));
1314
+ if (!Fp.eql(left, right))
1076
1315
  throw new Error("bad point: equation left != right (1)");
1077
- const XY = modP(X * Y);
1078
- const ZT = modP(Z * T);
1079
- if (XY !== ZT)
1316
+ const XY = Fp.mul(X, Y);
1317
+ const ZT = Fp.mul(Z, T);
1318
+ if (!Fp.eql(XY, ZT))
1080
1319
  throw new Error("bad point: equation left != right (2)");
1081
1320
  }
1082
1321
  // Compare one point to another.
@@ -1084,37 +1323,36 @@ function edwards(params, extraOpts = {}) {
1084
1323
  aedpoint(other);
1085
1324
  const { X: X1, Y: Y1, Z: Z1 } = this;
1086
1325
  const { X: X2, Y: Y2, Z: Z2 } = other;
1087
- const X1Z2 = modP(X1 * Z2);
1088
- const X2Z1 = modP(X2 * Z1);
1089
- const Y1Z2 = modP(Y1 * Z2);
1090
- const Y2Z1 = modP(Y2 * Z1);
1091
- return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1326
+ const X1Z2 = Fp.mul(X1, Z2);
1327
+ const X2Z1 = Fp.mul(X2, Z1);
1328
+ const Y1Z2 = Fp.mul(Y1, Z2);
1329
+ const Y2Z1 = Fp.mul(Y2, Z1);
1330
+ return Fp.eql(X1Z2, X2Z1) && Fp.eql(Y1Z2, Y2Z1);
1092
1331
  }
1093
1332
  is0() {
1094
1333
  return this.equals(_Point.ZERO);
1095
1334
  }
1096
1335
  negate() {
1097
- return new _Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1336
+ return new _Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));
1098
1337
  }
1099
1338
  // Fast algo for doubling Extended Point.
1100
1339
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1101
1340
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
1102
1341
  double() {
1103
- const { a } = CURVE;
1104
1342
  const { X: X1, Y: Y1, Z: Z1 } = this;
1105
- const A = modP(X1 * X1);
1106
- const B = modP(Y1 * Y1);
1107
- const C = modP(_2n2 * modP(Z1 * Z1));
1108
- const D = modP(a * A);
1109
- const x1y1 = X1 + Y1;
1110
- const E = modP(modP(x1y1 * x1y1) - A - B);
1111
- const G = D + B;
1112
- const F2 = G - C;
1113
- const H = D - B;
1114
- const X3 = modP(E * F2);
1115
- const Y3 = modP(G * H);
1116
- const T3 = modP(E * H);
1117
- const Z3 = modP(F2 * G);
1343
+ const A = Fp.sqr(X1);
1344
+ const B2 = Fp.sqr(Y1);
1345
+ const C = Fp.mul(Fp.sqr(Z1), _2n2);
1346
+ const D = mulA(A);
1347
+ const x1y1 = Fp.addN(X1, Y1);
1348
+ const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B2);
1349
+ const G = Fp.addN(D, B2);
1350
+ const F2 = Fp.subN(G, C);
1351
+ const H = Fp.subN(D, B2);
1352
+ const X3 = Fp.mul(E, F2);
1353
+ const Y3 = Fp.mul(G, H);
1354
+ const T3 = Fp.mul(E, H);
1355
+ const Z3 = Fp.mul(F2, G);
1118
1356
  return new _Point(X3, Y3, Z3, T3);
1119
1357
  }
1120
1358
  // Fast algo for adding 2 Extended Points.
@@ -1122,21 +1360,21 @@ function edwards(params, extraOpts = {}) {
1122
1360
  // Cost: 9M + 1*a + 1*d + 7add.
1123
1361
  add(other) {
1124
1362
  aedpoint(other);
1125
- const { a, d } = CURVE;
1363
+ const { d } = CURVE;
1126
1364
  const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1127
1365
  const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1128
- const A = modP(X1 * X2);
1129
- const B = modP(Y1 * Y2);
1130
- const C = modP(T1 * d * T2);
1131
- const D = modP(Z1 * Z2);
1132
- const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1133
- const F2 = D - C;
1134
- const G = D + C;
1135
- const H = modP(B - a * A);
1136
- const X3 = modP(E * F2);
1137
- const Y3 = modP(G * H);
1138
- const T3 = modP(E * H);
1139
- const Z3 = modP(F2 * G);
1366
+ const A = Fp.mul(X1, X2);
1367
+ const B2 = Fp.mul(Y1, Y2);
1368
+ const C = Fp.mul(Fp.mulN(T1, d), T2);
1369
+ const D = Fp.mul(Z1, Z2);
1370
+ const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B2);
1371
+ const F2 = Fp.subN(D, C);
1372
+ const G = Fp.addN(D, C);
1373
+ const H = Fp.sub(B2, mulA(A));
1374
+ const X3 = Fp.mul(E, F2);
1375
+ const Y3 = Fp.mul(G, H);
1376
+ const T3 = Fp.mul(E, H);
1377
+ const Z3 = Fp.mul(F2, G);
1140
1378
  return new _Point(X3, Y3, Z3, T3);
1141
1379
  }
1142
1380
  subtract(other) {
@@ -1145,10 +1383,10 @@ function edwards(params, extraOpts = {}) {
1145
1383
  }
1146
1384
  // Constant-time multiplication.
1147
1385
  multiply(scalar) {
1148
- if (!Fn2.isValidNot0(scalar))
1386
+ if (!Fn.isValidNot0(scalar))
1149
1387
  throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1150
- const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(_Point, p2));
1151
- return normalizeZ(_Point, [p, f])[0];
1388
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
1389
+ return normalize([p, f])[0];
1152
1390
  }
1153
1391
  // Non-constant-time multiplication. Uses double-and-add algorithm.
1154
1392
  // It's faster, but should only be used when you don't care about
@@ -1156,13 +1394,13 @@ function edwards(params, extraOpts = {}) {
1156
1394
  // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1157
1395
  // n and larger values are rejected instead of being reduced mod n to the identity point.
1158
1396
  multiplyUnsafe(scalar) {
1159
- if (!Fn2.isValid(scalar))
1397
+ if (!Fn.isValid(scalar))
1160
1398
  throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1161
1399
  if (scalar === _0n4)
1162
1400
  return _Point.ZERO;
1163
1401
  if (this.is0() || scalar === _1n4)
1164
1402
  return this;
1165
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(_Point, p));
1403
+ return wnaf.mulUnsafe(this, scalar, normalize);
1166
1404
  }
1167
1405
  // Checks if point is of small order.
1168
1406
  // If you add something to small order point, you will have "dirty"
@@ -1174,35 +1412,43 @@ function edwards(params, extraOpts = {}) {
1174
1412
  // Multiplies point by curve order and checks if the result is 0.
1175
1413
  // Returns `false` is the point is dirty.
1176
1414
  isTorsionFree() {
1177
- return wnaf.unsafe(this, CURVE.n).is0();
1415
+ return wnaf.mulUnsafe(this, CURVE.n).is0();
1178
1416
  }
1179
1417
  // Converts Extended point to default (x, y) coordinates.
1180
1418
  // Can accept precomputed Z^-1 - for example, from invertBatch.
1181
1419
  toAffine(invertedZ) {
1182
1420
  const p = this;
1183
1421
  let iz = invertedZ;
1422
+ if (iz != null && typeof iz !== "bigint")
1423
+ throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
1184
1424
  const { X, Y, Z } = p;
1185
1425
  const is0 = p.is0();
1186
1426
  if (iz == null)
1187
- iz = is0 ? _8n2 : Fp2.inv(Z);
1188
- const x = modP(X * iz);
1189
- const y = modP(Y * iz);
1190
- const zz = Fp2.mul(Z, iz);
1427
+ iz = is0 ? Fp.create(_8n2) : Fp.inv(Z);
1428
+ const x = Fp.mul(X, iz);
1429
+ const y = Fp.mul(Y, iz);
1430
+ const zz = Fp.mul(Z, iz);
1191
1431
  if (is0)
1192
- return { x: _0n4, y: _1n4 };
1193
- if (zz !== _1n4)
1432
+ return { x: Fp.ZERO, y: Fp.ONE };
1433
+ if (!Fp.eql(zz, Fp.ONE))
1194
1434
  throw new Error("invZ was invalid");
1195
1435
  return { x, y };
1196
1436
  }
1197
1437
  clearCofactor() {
1198
1438
  if (cofactor === _1n4)
1199
1439
  return this;
1440
+ if (cofactor === _2n2)
1441
+ return this.double();
1442
+ if (cofactor === _4n3)
1443
+ return this.double().double();
1444
+ if (cofactor === _8n2)
1445
+ return this.double().double().double();
1200
1446
  return this.multiplyUnsafe(cofactor);
1201
1447
  }
1202
1448
  toBytes() {
1203
1449
  const { x, y } = this.toAffine();
1204
- const bytes = Fp2.toBytes(y);
1205
- bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1450
+ const bytes = Fp.toBytes(y);
1451
+ bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
1206
1452
  return bytes;
1207
1453
  }
1208
1454
  toHex() {
@@ -1212,117 +1458,47 @@ function edwards(params, extraOpts = {}) {
1212
1458
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1213
1459
  }
1214
1460
  };
1215
- // base / generator point
1216
- __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy)));
1217
- // zero / infinity / identity point
1218
- __publicField(_Point, "ZERO", new _Point(_0n4, _1n4, _1n4, _0n4));
1219
- // 0, 1, 1, 0
1220
- // math field
1221
- __publicField(_Point, "Fp", Fp2);
1222
- // scalar field
1223
- __publicField(_Point, "Fn", Fn2);
1461
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy)));
1462
+ __publicField(_Point, "ZERO", new _Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO));
1463
+ __publicField(_Point, "Fp", Fp);
1464
+ __publicField(_Point, "Fn", Fn);
1224
1465
  let Point = _Point;
1225
- const wnaf = new wNAF(Point, Fn2.BITS);
1226
- if (Fn2.BITS >= 8)
1227
- Point.BASE.precompute(8);
1466
+ const normalize = (points) => normalizeZ(Point, points);
1467
+ const wnaf = new ScalarMultiplier(Point, randomBytes5);
1468
+ if (wnaf.bits >= 6)
1469
+ Point.BASE.precompute(6);
1228
1470
  Object.freeze(Point.prototype);
1229
1471
  Object.freeze(Point);
1230
1472
  return Point;
1231
1473
  }
1232
- var _0n4, _1n4, _2n2, _8n2, PrimeEdwardsPoint;
1474
+ var _0n4, _1n4, _2n2, _4n3, _8n2;
1233
1475
  var init_edwards = __esm({
1234
1476
  "../../node_modules/@noble/curves/abstract/edwards.js"() {
1235
1477
  "use strict";
1236
1478
  init_utils2();
1237
1479
  init_curve();
1480
+ init_modular();
1238
1481
  _0n4 = /* @__PURE__ */ BigInt(0);
1239
1482
  _1n4 = /* @__PURE__ */ BigInt(1);
1240
1483
  _2n2 = /* @__PURE__ */ BigInt(2);
1484
+ _4n3 = /* @__PURE__ */ BigInt(4);
1241
1485
  _8n2 = /* @__PURE__ */ BigInt(8);
1242
- PrimeEdwardsPoint = class {
1243
- /**
1244
- * Wrap one internal Edwards representative directly.
1245
- * This is not a canonical encoding boundary: alternate Edwards
1246
- * representatives may still describe the same abstract wrapper element.
1247
- */
1248
- constructor(ep) {
1249
- __publicField(this, "ep");
1250
- this.ep = ep;
1251
- }
1252
- // Static methods that must be implemented by subclasses
1253
- static fromBytes(_bytes) {
1254
- notImplemented();
1255
- }
1256
- static fromHex(_hex) {
1257
- notImplemented();
1258
- }
1259
- get x() {
1260
- return this.toAffine().x;
1261
- }
1262
- get y() {
1263
- return this.toAffine().y;
1264
- }
1265
- // Common implementations
1266
- clearCofactor() {
1267
- return this;
1268
- }
1269
- assertValidity() {
1270
- this.ep.assertValidity();
1271
- }
1272
- /**
1273
- * Return affine coordinates of the current internal Edwards representative.
1274
- * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1275
- * Equal abstract elements may expose different `x` / `y`; use
1276
- * `toBytes()` / `fromBytes()` for canonical roundtrips.
1277
- */
1278
- toAffine(invertedZ) {
1279
- return this.ep.toAffine(invertedZ);
1280
- }
1281
- toHex() {
1282
- return bytesToHex2(this.toBytes());
1283
- }
1284
- toString() {
1285
- return this.toHex();
1286
- }
1287
- isTorsionFree() {
1288
- return true;
1289
- }
1290
- isSmallOrder() {
1291
- return false;
1292
- }
1293
- add(other) {
1294
- this.assertSame(other);
1295
- return this.init(this.ep.add(other.ep));
1296
- }
1297
- subtract(other) {
1298
- this.assertSame(other);
1299
- return this.init(this.ep.subtract(other.ep));
1300
- }
1301
- multiply(scalar) {
1302
- return this.init(this.ep.multiply(scalar));
1303
- }
1304
- multiplyUnsafe(scalar) {
1305
- return this.init(this.ep.multiplyUnsafe(scalar));
1306
- }
1307
- double() {
1308
- return this.init(this.ep.double());
1309
- }
1310
- negate() {
1311
- return this.init(this.ep.negate());
1312
- }
1313
- precompute(windowSize, isLazy) {
1314
- this.ep.precompute(windowSize, isLazy);
1315
- return this;
1316
- }
1317
- };
1318
- __publicField(PrimeEdwardsPoint, "BASE");
1319
- __publicField(PrimeEdwardsPoint, "ZERO");
1320
- __publicField(PrimeEdwardsPoint, "Fp");
1321
- __publicField(PrimeEdwardsPoint, "Fn");
1322
1486
  }
1323
1487
  });
1324
1488
 
1325
1489
  // ../../node_modules/@noble/curves/abstract/montgomery.js
1490
+ function cmask(P, swap) {
1491
+ return P + swap - (swap >> _1n5 << _1n5);
1492
+ }
1493
+ function cswap(P) {
1494
+ const offset = BigInt(6) * P;
1495
+ return (mask, x_2, x_3) => {
1496
+ const sum = x_2 + x_3;
1497
+ const d = offset + x_3 - x_2;
1498
+ const a = (d * mask + x_2) % P;
1499
+ return { x_2: a, x_3: sum - a };
1500
+ };
1501
+ }
1326
1502
  function validateOpts(curve) {
1327
1503
  validateObject(curve, {
1328
1504
  P: "bigint",
@@ -1330,23 +1506,26 @@ function validateOpts(curve) {
1330
1506
  adjustScalarBytes: "function",
1331
1507
  powPminus2: "function"
1332
1508
  }, {
1333
- randomBytes: "function"
1509
+ randomBytes: "function",
1510
+ scalarMultBase: "function"
1334
1511
  });
1335
1512
  return Object.freeze({ ...curve });
1336
1513
  }
1337
1514
  function montgomery(curveDef) {
1338
1515
  const CURVE = validateOpts(curveDef);
1339
1516
  const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
1517
+ const mulBaseHook = CURVE.scalarMultBase;
1340
1518
  const is25519 = type === "x25519";
1341
1519
  if (!is25519 && type !== "x448")
1342
1520
  throw new Error("invalid type");
1343
1521
  const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1344
1522
  const montgomeryBits = is25519 ? 255 : 448;
1523
+ const swap = cswap(P);
1345
1524
  const fieldLen = is25519 ? 32 : 56;
1346
1525
  const Gu = is25519 ? BigInt(9) : BigInt(5);
1347
1526
  const a24 = is25519 ? BigInt(121665) : BigInt(39081);
1348
1527
  const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
1349
- const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
1528
+ const maxAdded = is25519 ? BigInt(8) * (_2n3 ** BigInt(251) - _1n5) : BigInt(4) * (_2n3 ** BigInt(445) - _1n5);
1350
1529
  const maxScalar = minScalar + maxAdded + _1n5;
1351
1530
  const modP = (n) => mod(n, P);
1352
1531
  const GuBytes = encodeU(Gu);
@@ -1362,23 +1541,34 @@ function montgomery(curveDef) {
1362
1541
  function decodeScalar(scalar) {
1363
1542
  return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
1364
1543
  }
1544
+ const lowOrderU = new Set(is25519 ? [
1545
+ _0n5,
1546
+ _1n5,
1547
+ P - _1n5,
1548
+ BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),
1549
+ BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")
1550
+ ] : [_0n5, _1n5, P - _1n5]);
1365
1551
  function scalarMult(scalar, u) {
1366
- const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
1552
+ const pointU = decodeU(u);
1553
+ if (lowOrderU.has(pointU))
1554
+ throw new Error("invalid private or public key received");
1555
+ const pu = montgomeryLadder(pointU, decodeScalar(scalar));
1367
1556
  if (pu === _0n5)
1368
1557
  throw new Error("invalid private or public key received");
1369
1558
  return encodeU(pu);
1370
1559
  }
1371
1560
  function scalarMultBase(scalar) {
1372
- return scalarMult(scalar, GuBytes);
1561
+ if (mulBaseHook === void 0)
1562
+ return scalarMult(scalar, GuBytes);
1563
+ const k = decodeScalar(scalar);
1564
+ aInRange("scalar", k, minScalar, maxScalar);
1565
+ const pu = modP(mulBaseHook(k));
1566
+ if (pu === _0n5)
1567
+ throw new Error("invalid private or public key received");
1568
+ return encodeU(pu);
1373
1569
  }
1374
1570
  const getPublicKey = scalarMultBase;
1375
1571
  const getSharedSecret = scalarMult;
1376
- function cswap(swap, x_2, x_3) {
1377
- const dummy = modP(swap * (x_2 - x_3));
1378
- x_2 = modP(x_2 - dummy);
1379
- x_3 = modP(x_3 + dummy);
1380
- return { x_2, x_3 };
1381
- }
1382
1572
  function montgomeryLadder(u, scalar) {
1383
1573
  aInRange("u", u, _0n5, P);
1384
1574
  aInRange("scalar", scalar, minScalar, maxScalar);
@@ -1388,22 +1578,20 @@ function montgomery(curveDef) {
1388
1578
  let z_2 = _0n5;
1389
1579
  let x_3 = u;
1390
1580
  let z_3 = _1n5;
1391
- let swap = _0n5;
1581
+ const kx = k ^ k >> _1n5;
1392
1582
  for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
1393
- const k_t = k >> t & _1n5;
1394
- swap ^= k_t;
1395
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1396
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1397
- swap = k_t;
1583
+ const mask2 = cmask(P, kx >> t);
1584
+ ({ x_2, x_3 } = swap(mask2, x_2, x_3));
1585
+ ({ x_2: z_2, x_3: z_3 } = swap(mask2, z_2, z_3));
1398
1586
  const A = x_2 + z_2;
1399
1587
  const AA = modP(A * A);
1400
- const B = x_2 - z_2;
1401
- const BB = modP(B * B);
1588
+ const B2 = x_2 - z_2;
1589
+ const BB = modP(B2 * B2);
1402
1590
  const E = AA - BB;
1403
1591
  const C = x_3 + z_3;
1404
1592
  const D = x_3 - z_3;
1405
1593
  const DA = modP(D * A);
1406
- const CB = modP(C * B);
1594
+ const CB = modP(C * B2);
1407
1595
  const dacb = DA + CB;
1408
1596
  const da_cb = DA - CB;
1409
1597
  x_3 = modP(dacb * dacb);
@@ -1411,8 +1599,9 @@ function montgomery(curveDef) {
1411
1599
  x_2 = modP(AA * BB);
1412
1600
  z_2 = modP(E * (AA + modP(a24 * E)));
1413
1601
  }
1414
- ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1415
- ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1602
+ const mask = cmask(P, k);
1603
+ ({ x_2, x_3 } = swap(mask, x_2, x_3));
1604
+ ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));
1416
1605
  const z2 = powPminus2(z_2);
1417
1606
  return modP(x_2 * z2);
1418
1607
  }
@@ -1447,132 +1636,9 @@ var init_montgomery = __esm({
1447
1636
  init_utils2();
1448
1637
  init_curve();
1449
1638
  init_modular();
1450
- _0n5 = BigInt(0);
1451
- _1n5 = BigInt(1);
1452
- _2n3 = BigInt(2);
1453
- }
1454
- });
1455
-
1456
- // ../../node_modules/@noble/hashes/_md.js
1457
- var HashMD, SHA512_IV;
1458
- var init_md = __esm({
1459
- "../../node_modules/@noble/hashes/_md.js"() {
1460
- "use strict";
1461
- init_utils();
1462
- HashMD = class {
1463
- constructor(blockLen, outputLen, padOffset, isLE2) {
1464
- __publicField(this, "blockLen");
1465
- __publicField(this, "outputLen");
1466
- __publicField(this, "canXOF", false);
1467
- __publicField(this, "padOffset");
1468
- __publicField(this, "isLE");
1469
- // For partial updates less than block size
1470
- __publicField(this, "buffer");
1471
- __publicField(this, "view");
1472
- __publicField(this, "finished", false);
1473
- __publicField(this, "length", 0);
1474
- __publicField(this, "pos", 0);
1475
- __publicField(this, "destroyed", false);
1476
- this.blockLen = blockLen;
1477
- this.outputLen = outputLen;
1478
- this.padOffset = padOffset;
1479
- this.isLE = isLE2;
1480
- this.buffer = new Uint8Array(blockLen);
1481
- this.view = createView(this.buffer);
1482
- }
1483
- update(data) {
1484
- aexists(this);
1485
- abytes(data);
1486
- const { view, buffer, blockLen } = this;
1487
- const len = data.length;
1488
- for (let pos = 0; pos < len; ) {
1489
- const take = Math.min(blockLen - this.pos, len - pos);
1490
- if (take === blockLen) {
1491
- const dataView = createView(data);
1492
- for (; blockLen <= len - pos; pos += blockLen)
1493
- this.process(dataView, pos);
1494
- continue;
1495
- }
1496
- buffer.set(data.subarray(pos, pos + take), this.pos);
1497
- this.pos += take;
1498
- pos += take;
1499
- if (this.pos === blockLen) {
1500
- this.process(view, 0);
1501
- this.pos = 0;
1502
- }
1503
- }
1504
- this.length += data.length;
1505
- this.roundClean();
1506
- return this;
1507
- }
1508
- digestInto(out) {
1509
- aexists(this);
1510
- aoutput(out, this);
1511
- this.finished = true;
1512
- const { buffer, view, blockLen, isLE: isLE2 } = this;
1513
- let { pos } = this;
1514
- buffer[pos++] = 128;
1515
- clean(this.buffer.subarray(pos));
1516
- if (this.padOffset > blockLen - pos) {
1517
- this.process(view, 0);
1518
- pos = 0;
1519
- }
1520
- for (let i = pos; i < blockLen; i++)
1521
- buffer[i] = 0;
1522
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
1523
- this.process(view, 0);
1524
- const oview = createView(out);
1525
- const len = this.outputLen;
1526
- if (len % 4)
1527
- throw new Error("_sha2: outputLen must be aligned to 32bit");
1528
- const outLen = len / 4;
1529
- const state = this.get();
1530
- if (outLen > state.length)
1531
- throw new Error("_sha2: outputLen bigger than state");
1532
- for (let i = 0; i < outLen; i++)
1533
- oview.setUint32(4 * i, state[i], isLE2);
1534
- }
1535
- digest() {
1536
- const { buffer, outputLen } = this;
1537
- this.digestInto(buffer);
1538
- const res = buffer.slice(0, outputLen);
1539
- this.destroy();
1540
- return res;
1541
- }
1542
- _cloneInto(to) {
1543
- to ||= new this.constructor();
1544
- to.set(...this.get());
1545
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
1546
- to.destroyed = destroyed;
1547
- to.finished = finished;
1548
- to.length = length;
1549
- to.pos = pos;
1550
- if (length % blockLen)
1551
- to.buffer.set(buffer);
1552
- return to;
1553
- }
1554
- clone() {
1555
- return this._cloneInto();
1556
- }
1557
- };
1558
- SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1559
- 1779033703,
1560
- 4089235720,
1561
- 3144134277,
1562
- 2227873595,
1563
- 1013904242,
1564
- 4271175723,
1565
- 2773480762,
1566
- 1595750129,
1567
- 1359893119,
1568
- 2917565137,
1569
- 2600822924,
1570
- 725511199,
1571
- 528734635,
1572
- 4215389547,
1573
- 1541459225,
1574
- 327033209
1575
- ]);
1639
+ _0n5 = /* @__PURE__ */ BigInt(0);
1640
+ _1n5 = /* @__PURE__ */ BigInt(1);
1641
+ _2n3 = /* @__PURE__ */ BigInt(2);
1576
1642
  }
1577
1643
  });
1578
1644
 
@@ -1592,265 +1658,31 @@ function split(lst, le = false) {
1592
1658
  }
1593
1659
  return [Ah, Al];
1594
1660
  }
1595
- function add(Ah, Al, Bh, Bl) {
1596
- const l = (Al >>> 0) + (Bl >>> 0);
1597
- return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1598
- }
1599
- var U32_MASK64, _32n, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotlSH, rotlSL, rotlBH, rotlBL, add3L, add3H, add4L, add4H, add5L, add5H;
1661
+ var U32_MASK64, _32n;
1600
1662
  var init_u64 = __esm({
1601
1663
  "../../node_modules/@noble/hashes/_u64.js"() {
1602
1664
  "use strict";
1603
- U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1665
+ U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
1604
1666
  _32n = /* @__PURE__ */ BigInt(32);
1605
- shrSH = (h, _l, s) => h >>> s;
1606
- shrSL = (h, l, s) => h << 32 - s | l >>> s;
1607
- rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1608
- rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1609
- rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1610
- rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1611
- rotlSH = (h, l, s) => h << s | l >>> 32 - s;
1612
- rotlSL = (h, l, s) => l << s | h >>> 32 - s;
1613
- rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
1614
- rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
1615
- add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1616
- add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1617
- add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1618
- add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1619
- add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1620
- add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1621
- }
1622
- });
1623
-
1624
- // ../../node_modules/@noble/hashes/sha2.js
1625
- var K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA2_64B, _SHA512, sha512;
1626
- var init_sha2 = __esm({
1627
- "../../node_modules/@noble/hashes/sha2.js"() {
1628
- "use strict";
1629
- init_md();
1630
- init_u64();
1631
- init_utils();
1632
- K512 = /* @__PURE__ */ (() => split([
1633
- "0x428a2f98d728ae22",
1634
- "0x7137449123ef65cd",
1635
- "0xb5c0fbcfec4d3b2f",
1636
- "0xe9b5dba58189dbbc",
1637
- "0x3956c25bf348b538",
1638
- "0x59f111f1b605d019",
1639
- "0x923f82a4af194f9b",
1640
- "0xab1c5ed5da6d8118",
1641
- "0xd807aa98a3030242",
1642
- "0x12835b0145706fbe",
1643
- "0x243185be4ee4b28c",
1644
- "0x550c7dc3d5ffb4e2",
1645
- "0x72be5d74f27b896f",
1646
- "0x80deb1fe3b1696b1",
1647
- "0x9bdc06a725c71235",
1648
- "0xc19bf174cf692694",
1649
- "0xe49b69c19ef14ad2",
1650
- "0xefbe4786384f25e3",
1651
- "0x0fc19dc68b8cd5b5",
1652
- "0x240ca1cc77ac9c65",
1653
- "0x2de92c6f592b0275",
1654
- "0x4a7484aa6ea6e483",
1655
- "0x5cb0a9dcbd41fbd4",
1656
- "0x76f988da831153b5",
1657
- "0x983e5152ee66dfab",
1658
- "0xa831c66d2db43210",
1659
- "0xb00327c898fb213f",
1660
- "0xbf597fc7beef0ee4",
1661
- "0xc6e00bf33da88fc2",
1662
- "0xd5a79147930aa725",
1663
- "0x06ca6351e003826f",
1664
- "0x142929670a0e6e70",
1665
- "0x27b70a8546d22ffc",
1666
- "0x2e1b21385c26c926",
1667
- "0x4d2c6dfc5ac42aed",
1668
- "0x53380d139d95b3df",
1669
- "0x650a73548baf63de",
1670
- "0x766a0abb3c77b2a8",
1671
- "0x81c2c92e47edaee6",
1672
- "0x92722c851482353b",
1673
- "0xa2bfe8a14cf10364",
1674
- "0xa81a664bbc423001",
1675
- "0xc24b8b70d0f89791",
1676
- "0xc76c51a30654be30",
1677
- "0xd192e819d6ef5218",
1678
- "0xd69906245565a910",
1679
- "0xf40e35855771202a",
1680
- "0x106aa07032bbd1b8",
1681
- "0x19a4c116b8d2d0c8",
1682
- "0x1e376c085141ab53",
1683
- "0x2748774cdf8eeb99",
1684
- "0x34b0bcb5e19b48a8",
1685
- "0x391c0cb3c5c95a63",
1686
- "0x4ed8aa4ae3418acb",
1687
- "0x5b9cca4f7763e373",
1688
- "0x682e6ff3d6b2b8a3",
1689
- "0x748f82ee5defb2fc",
1690
- "0x78a5636f43172f60",
1691
- "0x84c87814a1f0ab72",
1692
- "0x8cc702081a6439ec",
1693
- "0x90befffa23631e28",
1694
- "0xa4506cebde82bde9",
1695
- "0xbef9a3f7b2c67915",
1696
- "0xc67178f2e372532b",
1697
- "0xca273eceea26619c",
1698
- "0xd186b8c721c0c207",
1699
- "0xeada7dd6cde0eb1e",
1700
- "0xf57d4f7fee6ed178",
1701
- "0x06f067aa72176fba",
1702
- "0x0a637dc5a2c898a6",
1703
- "0x113f9804bef90dae",
1704
- "0x1b710b35131c471b",
1705
- "0x28db77f523047d84",
1706
- "0x32caab7b40c72493",
1707
- "0x3c9ebe0a15c9bebc",
1708
- "0x431d67c49c100d4c",
1709
- "0x4cc5d4becb3e42b6",
1710
- "0x597f299cfc657e2a",
1711
- "0x5fcb6fab3ad6faec",
1712
- "0x6c44198c4a475817"
1713
- ].map((n) => BigInt(n))))();
1714
- SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1715
- SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1716
- SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1717
- SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1718
- SHA2_64B = class extends HashMD {
1719
- constructor(outputLen) {
1720
- super(128, outputLen, 16, false);
1721
- }
1722
- // prettier-ignore
1723
- get() {
1724
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1725
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1726
- }
1727
- // prettier-ignore
1728
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1729
- this.Ah = Ah | 0;
1730
- this.Al = Al | 0;
1731
- this.Bh = Bh | 0;
1732
- this.Bl = Bl | 0;
1733
- this.Ch = Ch | 0;
1734
- this.Cl = Cl | 0;
1735
- this.Dh = Dh | 0;
1736
- this.Dl = Dl | 0;
1737
- this.Eh = Eh | 0;
1738
- this.El = El | 0;
1739
- this.Fh = Fh | 0;
1740
- this.Fl = Fl | 0;
1741
- this.Gh = Gh | 0;
1742
- this.Gl = Gl | 0;
1743
- this.Hh = Hh | 0;
1744
- this.Hl = Hl | 0;
1745
- }
1746
- process(view, offset) {
1747
- for (let i = 0; i < 16; i++, offset += 4) {
1748
- SHA512_W_H[i] = view.getUint32(offset);
1749
- SHA512_W_L[i] = view.getUint32(offset += 4);
1750
- }
1751
- for (let i = 16; i < 80; i++) {
1752
- const W15h = SHA512_W_H[i - 15] | 0;
1753
- const W15l = SHA512_W_L[i - 15] | 0;
1754
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1755
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1756
- const W2h = SHA512_W_H[i - 2] | 0;
1757
- const W2l = SHA512_W_L[i - 2] | 0;
1758
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1759
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1760
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1761
- const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1762
- SHA512_W_H[i] = SUMh | 0;
1763
- SHA512_W_L[i] = SUMl | 0;
1764
- }
1765
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1766
- for (let i = 0; i < 80; i++) {
1767
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1768
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1769
- const CHIh = Eh & Fh ^ ~Eh & Gh;
1770
- const CHIl = El & Fl ^ ~El & Gl;
1771
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1772
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1773
- const T1l = T1ll | 0;
1774
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1775
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1776
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1777
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1778
- Hh = Gh | 0;
1779
- Hl = Gl | 0;
1780
- Gh = Fh | 0;
1781
- Gl = Fl | 0;
1782
- Fh = Eh | 0;
1783
- Fl = El | 0;
1784
- ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1785
- Dh = Ch | 0;
1786
- Dl = Cl | 0;
1787
- Ch = Bh | 0;
1788
- Cl = Bl | 0;
1789
- Bh = Ah | 0;
1790
- Bl = Al | 0;
1791
- const All = add3L(T1l, sigma0l, MAJl);
1792
- Ah = add3H(All, T1h, sigma0h, MAJh);
1793
- Al = All | 0;
1794
- }
1795
- ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1796
- ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1797
- ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1798
- ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1799
- ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1800
- ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1801
- ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1802
- ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1803
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1804
- }
1805
- roundClean() {
1806
- clean(SHA512_W_H, SHA512_W_L);
1807
- }
1808
- destroy() {
1809
- this.destroyed = true;
1810
- clean(this.buffer);
1811
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1812
- }
1813
- };
1814
- _SHA512 = class extends SHA2_64B {
1815
- constructor() {
1816
- super(64);
1817
- __publicField(this, "Ah", SHA512_IV[0] | 0);
1818
- __publicField(this, "Al", SHA512_IV[1] | 0);
1819
- __publicField(this, "Bh", SHA512_IV[2] | 0);
1820
- __publicField(this, "Bl", SHA512_IV[3] | 0);
1821
- __publicField(this, "Ch", SHA512_IV[4] | 0);
1822
- __publicField(this, "Cl", SHA512_IV[5] | 0);
1823
- __publicField(this, "Dh", SHA512_IV[6] | 0);
1824
- __publicField(this, "Dl", SHA512_IV[7] | 0);
1825
- __publicField(this, "Eh", SHA512_IV[8] | 0);
1826
- __publicField(this, "El", SHA512_IV[9] | 0);
1827
- __publicField(this, "Fh", SHA512_IV[10] | 0);
1828
- __publicField(this, "Fl", SHA512_IV[11] | 0);
1829
- __publicField(this, "Gh", SHA512_IV[12] | 0);
1830
- __publicField(this, "Gl", SHA512_IV[13] | 0);
1831
- __publicField(this, "Hh", SHA512_IV[14] | 0);
1832
- __publicField(this, "Hl", SHA512_IV[15] | 0);
1833
- }
1834
- };
1835
- sha512 = /* @__PURE__ */ createHasher(
1836
- () => new _SHA512(),
1837
- /* @__PURE__ */ oidNist(3)
1838
- );
1839
1667
  }
1840
1668
  });
1841
1669
 
1842
1670
  // ../../node_modules/@noble/curves/abstract/fft.js
1843
- function checkU32(n) {
1671
+ function checkU32(n, title = "n") {
1672
+ if (typeof n !== "number")
1673
+ throw new TypeError(`wrong u32 integer "${title}": expected number, got type=${typeof n}`);
1844
1674
  if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
1845
- throw new Error("wrong u32 integer:" + n);
1675
+ throw new RangeError(`wrong u32 integer "${title}": expected 0..4294967295, got ${n}`);
1846
1676
  return n;
1847
1677
  }
1848
1678
  function isPowerOfTwo(x) {
1849
- checkU32(x);
1679
+ checkU32(x, "x");
1850
1680
  return (x & x - 1) === 0 && x !== 0;
1851
1681
  }
1852
1682
  function reverseBits(n, bits) {
1853
1683
  checkU32(n);
1684
+ if (typeof bits !== "number")
1685
+ throw new TypeError('"bits" expected number, got type=' + typeof bits);
1854
1686
  if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
1855
1687
  throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
1856
1688
  let reversed = 0;
@@ -1863,6 +1695,8 @@ function log2(n) {
1863
1695
  return 31 - Math.clz32(n);
1864
1696
  }
1865
1697
  function bitReversalInplace(values) {
1698
+ if (!values || typeof values !== "object" || typeof values.length !== "number")
1699
+ throw new TypeError('"values" expected array-like, got type=' + typeof values);
1866
1700
  const n = values.length;
1867
1701
  if (!isPowerOfTwo(n))
1868
1702
  throw new Error("expected positive power-of-two length, got " + n);
@@ -1881,15 +1715,21 @@ var FFTCore;
1881
1715
  var init_fft = __esm({
1882
1716
  "../../node_modules/@noble/curves/abstract/fft.js"() {
1883
1717
  "use strict";
1718
+ init_utils2();
1884
1719
  FFTCore = (F2, coreOpts) => {
1720
+ validateObject(coreOpts, { N: "number", roots: "object", dit: "boolean" }, { invertButterflies: "boolean", skipStages: "number", brp: "boolean" }, "coreOpts");
1885
1721
  const { N: N2, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
1722
+ checkU32(N2, "coreOpts.N");
1886
1723
  const bits = log2(N2);
1887
1724
  if (!isPowerOfTwo(N2))
1888
1725
  throw new Error("FFT: Polynomial size should be power of two");
1726
+ checkU32(skipStages, "coreOpts.skipStages");
1727
+ const maxSkipStages = bits === 0 ? 0 : bits - 1;
1728
+ if (skipStages > maxSkipStages)
1729
+ throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);
1889
1730
  if (roots.length !== N2)
1890
1731
  throw new Error(`FFT: wrong roots length: expected ${N2}, got ${roots.length}`);
1891
1732
  const isDit = dit !== invertButterflies;
1892
- isDit;
1893
1733
  return (values) => {
1894
1734
  if (values.length !== N2)
1895
1735
  throw new Error("FFT: wrong Polynomial length");
@@ -1930,68 +1770,6 @@ var init_fft = __esm({
1930
1770
  }
1931
1771
  });
1932
1772
 
1933
- // ../../node_modules/@noble/curves/abstract/hash-to-curve.js
1934
- function i2osp(value, length) {
1935
- asafenumber(value);
1936
- asafenumber(length);
1937
- if (length < 0 || length > 4)
1938
- throw new Error("invalid I2OSP length: " + length);
1939
- if (value < 0 || value > 2 ** (8 * length) - 1)
1940
- throw new Error("invalid I2OSP input: " + value);
1941
- const res = Array.from({ length }).fill(0);
1942
- for (let i = length - 1; i >= 0; i--) {
1943
- res[i] = value & 255;
1944
- value >>>= 8;
1945
- }
1946
- return new Uint8Array(res);
1947
- }
1948
- function strxor(a, b) {
1949
- const arr = new Uint8Array(a.length);
1950
- for (let i = 0; i < a.length; i++) {
1951
- arr[i] = a[i] ^ b[i];
1952
- }
1953
- return arr;
1954
- }
1955
- function normDST(DST) {
1956
- if (!isBytes2(DST) && typeof DST !== "string")
1957
- throw new Error("DST must be Uint8Array or ascii string");
1958
- const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
1959
- if (dst.length === 0)
1960
- throw new Error("DST must be non-empty");
1961
- return dst;
1962
- }
1963
- function expand_message_xmd(msg, DST, lenInBytes, H) {
1964
- abytes2(msg);
1965
- asafenumber(lenInBytes);
1966
- DST = normDST(DST);
1967
- if (DST.length > 255)
1968
- DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1969
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1970
- const ell = Math.ceil(lenInBytes / b_in_bytes);
1971
- if (lenInBytes > 65535 || ell > 255)
1972
- throw new Error("expand_message_xmd: invalid lenInBytes");
1973
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1974
- const Z_pad = new Uint8Array(r_in_bytes);
1975
- const l_i_b_str = i2osp(lenInBytes, 2);
1976
- const b = new Array(ell);
1977
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1978
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1979
- for (let i = 1; i < ell; i++) {
1980
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1981
- b[i] = H(concatBytes2(...args));
1982
- }
1983
- const pseudo_random_bytes = concatBytes2(...b);
1984
- return pseudo_random_bytes.slice(0, lenInBytes);
1985
- }
1986
- var _DST_scalar;
1987
- var init_hash_to_curve = __esm({
1988
- "../../node_modules/@noble/curves/abstract/hash-to-curve.js"() {
1989
- "use strict";
1990
- init_utils2();
1991
- _DST_scalar = "HashToScalar-";
1992
- }
1993
- });
1994
-
1995
1773
  // ../../node_modules/@noble/curves/ed25519.js
1996
1774
  function ed25519_pow_2_252_3(x) {
1997
1775
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
@@ -2020,8 +1798,8 @@ function uvRatio(u, v) {
2020
1798
  const P = ed25519_CURVE_p;
2021
1799
  const v3 = mod(v * v * v, P);
2022
1800
  const v7 = mod(v3 * v3 * v, P);
2023
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2024
- let x = mod(u * v3 * pow, P);
1801
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1802
+ let x = mod(u * v3 * pow3, P);
2025
1803
  const vx2 = mod(v * x * x, P);
2026
1804
  const root1 = x;
2027
1805
  const root2 = mod(x * ED25519_SQRT_M1, P);
@@ -2036,41 +1814,13 @@ function uvRatio(u, v) {
2036
1814
  x = mod(-x, P);
2037
1815
  return { isValid: useRoot1 || useRoot2, value: x };
2038
1816
  }
2039
- function calcElligatorRistrettoMap(r0) {
2040
- const { d } = ed25519_CURVE;
2041
- const P = ed25519_CURVE_p;
2042
- const mod2 = (n) => Fp.create(n);
2043
- const r = mod2(SQRT_M1 * r0 * r0);
2044
- const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2045
- let c = BigInt(-1);
2046
- const D = mod2((c - d * r) * mod2(r + d));
2047
- let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2048
- let s_ = mod2(s * r0);
2049
- if (!isNegativeLE(s_, P))
2050
- s_ = mod2(-s_);
2051
- if (!Ns_D_is_sq)
2052
- s = s_;
2053
- if (!Ns_D_is_sq)
2054
- c = r;
2055
- const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2056
- const s2 = s * s;
2057
- const W0 = mod2((s + s) * D);
2058
- const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2059
- const W2 = mod2(_1n6 - s2);
2060
- const W3 = mod2(_1n6 + s2);
2061
- return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2062
- }
2063
- var _0n6, _1n6, _2n4, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, ed25519_Point, Fp, Fn, x25519, SQRT_M1, SQRT_AD_MINUS_ONE, INVSQRT_A_MINUS_D, ONE_MINUS_D_SQ, D_MINUS_ONE_SQ, invertSqrt, MAX_255B, bytes255ToNumberLE, __RistrettoPoint, _RistrettoPoint, ristretto255_hasher;
1817
+ var _0n6, _1n6, _2n4, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, ed25519_Point, x25519;
2064
1818
  var init_ed25519 = __esm({
2065
1819
  "../../node_modules/@noble/curves/ed25519.js"() {
2066
1820
  "use strict";
2067
- init_sha2();
2068
- init_utils();
2069
1821
  init_edwards();
2070
- init_hash_to_curve();
2071
1822
  init_modular();
2072
1823
  init_montgomery();
2073
- init_utils2();
2074
1824
  _0n6 = /* @__PURE__ */ BigInt(0);
2075
1825
  _1n6 = /* @__PURE__ */ BigInt(1);
2076
1826
  _2n4 = /* @__PURE__ */ BigInt(2);
@@ -2089,198 +1839,41 @@ var init_ed25519 = __esm({
2089
1839
  }))();
2090
1840
  ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2091
1841
  ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2092
- Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2093
- Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
2094
1842
  x25519 = /* @__PURE__ */ (() => {
2095
1843
  const P = ed25519_CURVE_p;
1844
+ const powPminus2 = (x) => {
1845
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
1846
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
1847
+ };
2096
1848
  return montgomery({
2097
1849
  P,
2098
1850
  type: "x25519",
2099
- powPminus2: (x) => {
2100
- const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2101
- return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2102
- },
2103
- adjustScalarBytes
1851
+ powPminus2,
1852
+ adjustScalarBytes,
1853
+ // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached
1854
+ // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.
1855
+ // Same construction as libsodium's crypto_scalarmult_curve25519_base.
1856
+ scalarMultBase: (k) => {
1857
+ const kn = mod(k, ed25519_Point.Fn.ORDER);
1858
+ if (kn === _0n6)
1859
+ return _0n6;
1860
+ const p = ed25519_Point.BASE.multiply(kn);
1861
+ return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);
1862
+ }
2104
1863
  });
2105
1864
  })();
2106
- SQRT_M1 = ED25519_SQRT_M1;
2107
- SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2108
- INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2109
- ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2110
- D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2111
- invertSqrt = (number) => uvRatio(_1n6, number);
2112
- MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2113
- bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
2114
- __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2115
- constructor(ep) {
2116
- super(ep);
2117
- }
2118
- /**
2119
- * Create one Ristretto255 point from affine Edwards coordinates.
2120
- * This wraps the internal Edwards representative directly and is not a
2121
- * canonical ristretto255 decoding path.
2122
- * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
2123
- */
2124
- static fromAffine(ap) {
2125
- return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2126
- }
2127
- assertSame(other) {
2128
- if (!(other instanceof __RistrettoPoint))
2129
- throw new Error("RistrettoPoint expected");
2130
- }
2131
- init(ep) {
2132
- return new __RistrettoPoint(ep);
2133
- }
2134
- static fromBytes(bytes) {
2135
- abytes(bytes, 32);
2136
- const { a, d } = ed25519_CURVE;
2137
- const P = ed25519_CURVE_p;
2138
- const mod2 = (n) => Fp.create(n);
2139
- const s = bytes255ToNumberLE(bytes);
2140
- if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2141
- throw new Error("invalid ristretto255 encoding 1");
2142
- const s2 = mod2(s * s);
2143
- const u1 = mod2(_1n6 + a * s2);
2144
- const u2 = mod2(_1n6 - a * s2);
2145
- const u1_2 = mod2(u1 * u1);
2146
- const u2_2 = mod2(u2 * u2);
2147
- const v = mod2(a * d * u1_2 - u2_2);
2148
- const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2149
- const Dx = mod2(I * u2);
2150
- const Dy = mod2(I * Dx * v);
2151
- let x = mod2((s + s) * Dx);
2152
- if (isNegativeLE(x, P))
2153
- x = mod2(-x);
2154
- const y = mod2(u1 * Dy);
2155
- const t = mod2(x * y);
2156
- if (!isValid || isNegativeLE(t, P) || y === _0n6)
2157
- throw new Error("invalid ristretto255 encoding 2");
2158
- return new __RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2159
- }
2160
- /**
2161
- * Converts ristretto-encoded string to ristretto point.
2162
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2163
- * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2164
- */
2165
- static fromHex(hex) {
2166
- return __RistrettoPoint.fromBytes(hexToBytes(hex));
2167
- }
2168
- /**
2169
- * Encodes ristretto point to Uint8Array.
2170
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2171
- */
2172
- toBytes() {
2173
- let { X, Y, Z, T } = this.ep;
2174
- const P = ed25519_CURVE_p;
2175
- const mod2 = (n) => Fp.create(n);
2176
- const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2177
- const u2 = mod2(X * Y);
2178
- const u2sq = mod2(u2 * u2);
2179
- const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2180
- const D1 = mod2(invsqrt * u1);
2181
- const D2 = mod2(invsqrt * u2);
2182
- const zInv = mod2(D1 * D2 * T);
2183
- let D;
2184
- if (isNegativeLE(T * zInv, P)) {
2185
- let _x = mod2(Y * SQRT_M1);
2186
- let _y = mod2(X * SQRT_M1);
2187
- X = _x;
2188
- Y = _y;
2189
- D = mod2(D1 * INVSQRT_A_MINUS_D);
2190
- } else {
2191
- D = D2;
2192
- }
2193
- if (isNegativeLE(X * zInv, P))
2194
- Y = mod2(-Y);
2195
- let s = mod2((Z - Y) * D);
2196
- if (isNegativeLE(s, P))
2197
- s = mod2(-s);
2198
- return Fp.toBytes(s);
2199
- }
2200
- /**
2201
- * Compares two Ristretto points.
2202
- * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2203
- */
2204
- equals(other) {
2205
- this.assertSame(other);
2206
- const { X: X1, Y: Y1 } = this.ep;
2207
- const { X: X2, Y: Y2 } = other.ep;
2208
- const mod2 = (n) => Fp.create(n);
2209
- const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2210
- const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2211
- return one || two;
2212
- }
2213
- is0() {
2214
- return this.equals(__RistrettoPoint.ZERO);
2215
- }
2216
- };
2217
- // Do NOT change syntax: the following gymnastics is done,
2218
- // because typescript strips comments, which makes bundlers disable tree-shaking.
2219
- // prettier-ignore
2220
- __publicField(__RistrettoPoint, "BASE", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.BASE))());
2221
- // prettier-ignore
2222
- __publicField(__RistrettoPoint, "ZERO", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.ZERO))());
2223
- // prettier-ignore
2224
- __publicField(__RistrettoPoint, "Fp", /* @__PURE__ */ (() => Fp)());
2225
- // prettier-ignore
2226
- __publicField(__RistrettoPoint, "Fn", /* @__PURE__ */ (() => Fn)());
2227
- _RistrettoPoint = __RistrettoPoint;
2228
- Object.freeze(_RistrettoPoint.BASE);
2229
- Object.freeze(_RistrettoPoint.ZERO);
2230
- Object.freeze(_RistrettoPoint.prototype);
2231
- Object.freeze(_RistrettoPoint);
2232
- ristretto255_hasher = Object.freeze({
2233
- Point: _RistrettoPoint,
2234
- /**
2235
- * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
2236
- * * There are no test vectors
2237
- * * encodeToCurve / mapToCurve is undefined
2238
- * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
2239
- * * hashToScalar is undefined too, so we just use OPRF implementation
2240
- * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2241
- (os2ip -> bytes255ToNumberLE)
2242
- * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2243
- * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
2244
- version here. Using `bytes255ToNumblerLE` will create a different result
2245
- if we use `bytes255ToNumberLE` as os2ip
2246
- * * current version is closest to spec.
2247
- */
2248
- hashToCurve(msg, options) {
2249
- const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2250
- const xmd = expand_message_xmd(msg, DST, 64, sha512);
2251
- return ristretto255_hasher.deriveToCurve(xmd);
2252
- },
2253
- hashToScalar(msg, options = { DST: _DST_scalar }) {
2254
- const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2255
- return Fn.create(bytesToNumberLE(xmd));
2256
- },
2257
- /**
2258
- * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2259
- * Converts 64 uniform random bytes into a curve point.
2260
- *
2261
- * WARNING: This represents an older hash-to-curve construction from before
2262
- * RFC 9380 was finalized.
2263
- * It was later reused as a component in the newer
2264
- * `hash_to_ristretto255` function defined in RFC 9380.
2265
- */
2266
- deriveToCurve(bytes) {
2267
- abytes(bytes, 64);
2268
- const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2269
- const R1 = calcElligatorRistrettoMap(r1);
2270
- const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2271
- const R2 = calcElligatorRistrettoMap(r2);
2272
- return new _RistrettoPoint(R1.add(R2));
2273
- }
2274
- });
2275
1865
  }
2276
1866
  });
2277
1867
 
2278
1868
  // ../../node_modules/@noble/hashes/sha3.js
2279
1869
  function keccakP(s, rounds = 24) {
1870
+ if (!(s instanceof Uint32Array))
1871
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
1872
+ if (s.length !== 50)
1873
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
2280
1874
  anumber(rounds, "rounds");
2281
1875
  if (rounds < 1 || rounds > 24)
2282
1876
  throw new Error('"rounds" expected integer 1..24');
2283
- const B = new Uint32Array(5 * 2);
2284
1877
  for (let round = 24 - rounds; round < 24; round++) {
2285
1878
  for (let x = 0; x < 10; x++)
2286
1879
  B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
@@ -2326,7 +1919,7 @@ function keccakP(s, rounds = 24) {
2326
1919
  }
2327
1920
  clean(B);
2328
1921
  }
2329
- var _0n7, _1n7, _2n5, _7n2, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, genKeccak, sha3_256, sha3_512, genShake, shake128, shake256;
1922
+ var _0n7, _1n7, _2n5, _7n2, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, rotlSH, rotlSL, rotlBH, rotlBL, rotlH, rotlL, B, Keccak, genKeccak, sha3_256, sha3_512, genShake, shake128, shake256;
2330
1923
  var init_sha3 = __esm({
2331
1924
  "../../node_modules/@noble/hashes/sha3.js"() {
2332
1925
  "use strict";
@@ -2356,8 +1949,13 @@ var init_sha3 = __esm({
2356
1949
  IOTAS = split(_SHA3_IOTA, true);
2357
1950
  SHA3_IOTA_H = IOTAS[0];
2358
1951
  SHA3_IOTA_L = IOTAS[1];
1952
+ rotlSH = (h, l, s) => h << s | l >>> 32 - s;
1953
+ rotlSL = (h, l, s) => l << s | h >>> 32 - s;
1954
+ rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
1955
+ rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
2359
1956
  rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
2360
1957
  rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
1958
+ B = new Uint32Array(5 * 2);
2361
1959
  Keccak = class _Keccak {
2362
1960
  // NOTE: we accept arguments in bytes instead of bits here.
2363
1961
  constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
@@ -2373,6 +1971,10 @@ var init_sha3 = __esm({
2373
1971
  __publicField(this, "canXOF");
2374
1972
  __publicField(this, "enableXOF", false);
2375
1973
  __publicField(this, "rounds");
1974
+ anumber(blockLen, "blockLen");
1975
+ anumber(suffix, "suffix");
1976
+ anumber(rounds, "rounds");
1977
+ abool(enableXOF, "enableXOF");
2376
1978
  this.blockLen = blockLen;
2377
1979
  this.suffix = suffix;
2378
1980
  this.outputLen = outputLen;
@@ -2381,7 +1983,7 @@ var init_sha3 = __esm({
2381
1983
  this.rounds = rounds;
2382
1984
  anumber(outputLen, "outputLen");
2383
1985
  if (!(0 < blockLen && blockLen < 200))
2384
- throw new Error("only keccak-f1600 function is supported");
1986
+ throw new Error('"blockLen" must be 1..199');
2385
1987
  this.state = new Uint8Array(200);
2386
1988
  this.state32 = u32(this.state);
2387
1989
  }
@@ -2398,9 +2000,20 @@ var init_sha3 = __esm({
2398
2000
  update(data) {
2399
2001
  aexists(this);
2400
2002
  abytes(data);
2401
- const { blockLen, state } = this;
2003
+ const { blockLen, state, state32 } = this;
2402
2004
  const len = data.length;
2005
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
2006
+ const blockLen32 = blockLen / 4;
2007
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : void 0;
2403
2008
  for (let pos = 0; pos < len; ) {
2009
+ if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
2010
+ for (let i = 0, o = pos / 4; i < blockLen32; i++)
2011
+ state32[i] ^= data32[o + i];
2012
+ pos += blockLen;
2013
+ this.pos = blockLen;
2014
+ this.keccak();
2015
+ continue;
2016
+ }
2404
2017
  const take = Math.min(blockLen - this.pos, len - pos);
2405
2018
  for (let i = 0; i < take; i++)
2406
2019
  state[this.pos++] ^= data[pos++];
@@ -2438,7 +2051,7 @@ var init_sha3 = __esm({
2438
2051
  }
2439
2052
  xofInto(out) {
2440
2053
  if (!this.enableXOF)
2441
- throw new Error("XOF is not possible for this instance");
2054
+ throw new Error("XOF is not enabled");
2442
2055
  return this.writeInto(out);
2443
2056
  }
2444
2057
  xof(bytes) {
@@ -2449,7 +2062,7 @@ var init_sha3 = __esm({
2449
2062
  aoutput(out, this);
2450
2063
  if (this.finished)
2451
2064
  throw new Error("digest() was already called");
2452
- this.writeInto(out.subarray(0, this.outputLen));
2065
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
2453
2066
  this.destroy();
2454
2067
  }
2455
2068
  digest() {
@@ -2491,14 +2104,32 @@ var init_sha3 = __esm({
2491
2104
  64,
2492
2105
  /* @__PURE__ */ oidNist(10)
2493
2106
  );
2494
- genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info);
2107
+ genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => {
2108
+ opts2 = checkOpts({}, opts2);
2109
+ return new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true);
2110
+ }, info);
2495
2111
  shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2496
2112
  shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2497
2113
  }
2498
2114
  });
2499
2115
 
2500
2116
  // ../../node_modules/@noble/post-quantum/utils.js
2501
- function equalBytes2(a, b) {
2117
+ function aarray2(item, title, inner = () => {
2118
+ }) {
2119
+ if (!Array.isArray(item))
2120
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
2121
+ for (let i = 0; i < item.length; i++)
2122
+ inner(item[i], `${title}[${i}]`);
2123
+ return item;
2124
+ }
2125
+ function aobject3(value, title = "object") {
2126
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2127
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
2128
+ return value;
2129
+ }
2130
+ function equalBytes(a, b) {
2131
+ a = abytes(a);
2132
+ b = abytes(b);
2502
2133
  if (a.length !== b.length)
2503
2134
  return false;
2504
2135
  let diff = 0;
@@ -2507,7 +2138,7 @@ function equalBytes2(a, b) {
2507
2138
  return diff === 0;
2508
2139
  }
2509
2140
  function copyBytes2(bytes) {
2510
- return Uint8Array.from(abytes(bytes));
2141
+ return new Uint8Array(abytes(bytes));
2511
2142
  }
2512
2143
  function splitCoder(label, ...lengths) {
2513
2144
  const getLength = (c) => typeof c === "number" ? c : c.bytesLen;
@@ -2547,11 +2178,12 @@ function vecCoder(c, vecLen) {
2547
2178
  return {
2548
2179
  bytesLen,
2549
2180
  encode: (u) => {
2550
- if (u.length !== vecLen)
2551
- throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
2181
+ const uArr = aarray2(u, "u");
2182
+ if (uArr.length !== vecLen)
2183
+ throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
2552
2184
  const res = new Uint8Array(bytesLen);
2553
- for (let i = 0, pos = 0; i < u.length; i++) {
2554
- const b = coder.encode(u[i]);
2185
+ for (let i = 0, pos = 0; i < uArr.length; i++) {
2186
+ const b = coder.encode(uArr[i]);
2555
2187
  res.set(b, pos);
2556
2188
  b.fill(0);
2557
2189
  pos += b.length;
@@ -2577,8 +2209,9 @@ function cleanBytes(...list) {
2577
2209
  }
2578
2210
  }
2579
2211
  function getMask(bits) {
2580
- if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
2581
- throw new RangeError(`expected bits in [0..32], got ${bits}`);
2212
+ anumber(bits, "bits");
2213
+ if (bits > 32)
2214
+ throw new RangeError('"bits" expected <= 32, got ' + bits);
2582
2215
  return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
2583
2216
  }
2584
2217
  var abytesDoc, randomBytes3;
@@ -2619,13 +2252,25 @@ var init_crystals = __esm({
2619
2252
  return out;
2620
2253
  }
2621
2254
  const nttZetas = getZettas();
2622
- const field = {
2255
+ const inv = (_a) => {
2256
+ throw new Error("not implemented");
2257
+ };
2258
+ const field = isKyber ? {
2259
+ add: (a, b) => {
2260
+ const r = a + b | 0;
2261
+ return r >= Q2 ? r - Q2 | 0 : r;
2262
+ },
2263
+ sub: (a, b) => {
2264
+ const r = a - b | 0;
2265
+ return r < 0 ? r + Q2 | 0 : r;
2266
+ },
2267
+ mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2268
+ inv
2269
+ } : {
2623
2270
  add: (a, b) => mod2((a | 0) + (b | 0)) | 0,
2624
2271
  sub: (a, b) => mod2((a | 0) - (b | 0)) | 0,
2625
2272
  mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2626
- inv: (_a) => {
2627
- throw new Error("not implemented");
2628
- }
2273
+ inv
2629
2274
  };
2630
2275
  const nttOpts = {
2631
2276
  N: N2,
@@ -2648,6 +2293,12 @@ var init_crystals = __esm({
2648
2293
  }
2649
2294
  };
2650
2295
  const bitsCoder = (d, c) => {
2296
+ for (let i = 0, bufLen = 0; i < N2; i++) {
2297
+ bufLen += d;
2298
+ if (bufLen > 32)
2299
+ getMask(bufLen);
2300
+ bufLen %= 8;
2301
+ }
2651
2302
  const mask = getMask(d);
2652
2303
  const bytesLen = d * (N2 / 8);
2653
2304
  return {
@@ -2659,7 +2310,7 @@ var init_crystals = __esm({
2659
2310
  buf |= (c.encode(poly[i]) & mask) << bufLen;
2660
2311
  bufLen += d;
2661
2312
  for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
2662
- r[pos++] = buf & getMask(bufLen);
2313
+ r[pos++] = buf & 255;
2663
2314
  }
2664
2315
  return r;
2665
2316
  },
@@ -2723,17 +2374,21 @@ var init_crystals = __esm({
2723
2374
  function polyAdd(a_, b_) {
2724
2375
  const a = a_;
2725
2376
  const b = b_;
2726
- for (let i = 0; i < N; i++)
2727
- a[i] = crystals.mod(a[i] + b[i]);
2377
+ for (let i = 0; i < N; i++) {
2378
+ const r = a[i] + b[i];
2379
+ a[i] = r >= Q ? r - Q : r;
2380
+ }
2728
2381
  }
2729
2382
  function polySub(a_, b_) {
2730
2383
  const a = a_;
2731
2384
  const b = b_;
2732
- for (let i = 0; i < N; i++)
2733
- a[i] = crystals.mod(a[i] - b[i]);
2385
+ for (let i = 0; i < N; i++) {
2386
+ const r = a[i] - b[i];
2387
+ a[i] = r < 0 ? r + Q : r;
2388
+ }
2734
2389
  }
2735
2390
  function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
2736
- const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);
2391
+ const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);
2737
2392
  const c1 = crystals.mod(a0 * b1 + a1 * b0);
2738
2393
  return { c0, c1 };
2739
2394
  }
@@ -2780,6 +2435,14 @@ function createKyber(opts2) {
2780
2435
  const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
2781
2436
  const msgLen = 32;
2782
2437
  const seedLen = 64;
2438
+ const validateModulus = (publicKey, fn) => {
2439
+ const eke = publicKey.subarray(0, 384 * rawOpts.K);
2440
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2441
+ const ok = equalBytes(ek, eke);
2442
+ cleanBytes(ek);
2443
+ if (!ok)
2444
+ throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
2445
+ };
2783
2446
  const kemLengths = Object.freeze({
2784
2447
  ...lengths,
2785
2448
  seed: 64,
@@ -2790,38 +2453,55 @@ function createKyber(opts2) {
2790
2453
  return Object.freeze({
2791
2454
  info: Object.freeze({ type: "ml-kem" }),
2792
2455
  lengths: kemLengths,
2793
- keygen: (seed = randomBytes3(seedLen)) => {
2794
- abytesDoc(seed, seedLen, "seed");
2795
- const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
2796
- const publicKeyHash = HASH256(publicKey);
2797
- const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
2798
- cleanBytes(sk, publicKeyHash);
2799
- return {
2800
- publicKey,
2801
- secretKey
2802
- };
2456
+ keygen: (seed) => {
2457
+ const ownSeed = seed === void 0;
2458
+ const s = ownSeed ? randomBytes3(seedLen) : seed;
2459
+ let sk;
2460
+ let publicKeyHash;
2461
+ try {
2462
+ abytesDoc(s, seedLen, "seed");
2463
+ const keys = KPKE.keygen(s.subarray(0, 32));
2464
+ const publicKey = keys.publicKey;
2465
+ sk = keys.secretKey;
2466
+ publicKeyHash = HASH256(publicKey);
2467
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s.subarray(32)]);
2468
+ return {
2469
+ publicKey,
2470
+ secretKey
2471
+ };
2472
+ } finally {
2473
+ if (sk !== void 0)
2474
+ cleanBytes(sk);
2475
+ if (publicKeyHash !== void 0)
2476
+ cleanBytes(publicKeyHash);
2477
+ if (ownSeed)
2478
+ cleanBytes(s);
2479
+ }
2803
2480
  },
2804
2481
  getPublicKey: (secretKey) => {
2805
2482
  const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
2806
2483
  return Uint8Array.from(publicKey);
2807
2484
  },
2808
- encapsulate: (publicKey, msg = randomBytes3(msgLen)) => {
2809
- abytesDoc(publicKey, lengths.publicKey, "publicKey");
2810
- abytesDoc(msg, msgLen, "message");
2811
- const eke = publicKey.subarray(0, 384 * opts2.K);
2812
- const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2813
- if (!equalBytes2(ek, eke)) {
2814
- cleanBytes(ek);
2815
- throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
2485
+ encapsulate: (publicKey, msg) => {
2486
+ const ownMsg = msg === void 0;
2487
+ const m = ownMsg ? randomBytes3(msgLen) : msg;
2488
+ let kr;
2489
+ try {
2490
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2491
+ abytesDoc(m, msgLen, "message");
2492
+ validateModulus(publicKey, "encapsulate");
2493
+ kr = HASH512.create().update(m).update(HASH256(publicKey)).digest();
2494
+ const cipherText = KPKE.encrypt(publicKey, m, kr.subarray(32, 64));
2495
+ return {
2496
+ cipherText,
2497
+ sharedSecret: kr.subarray(0, 32)
2498
+ };
2499
+ } finally {
2500
+ if (kr !== void 0)
2501
+ cleanBytes(kr.subarray(32));
2502
+ if (ownMsg)
2503
+ cleanBytes(m);
2816
2504
  }
2817
- cleanBytes(ek);
2818
- const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
2819
- const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2820
- cleanBytes(kr.subarray(32));
2821
- return {
2822
- cipherText,
2823
- sharedSecret: kr.subarray(0, 32)
2824
- };
2825
2505
  },
2826
2506
  decapsulate: (cipherText, secretKey) => {
2827
2507
  abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
@@ -2829,17 +2509,67 @@ function createKyber(opts2) {
2829
2509
  const k768 = secretCoder.bytesLen - 96;
2830
2510
  const start = k768 + 32;
2831
2511
  const test = HASH256(secretKey.subarray(k768 / 2, start));
2832
- if (!equalBytes2(test, secretKey.subarray(start, start + 32)))
2512
+ if (!equalBytes(test, secretKey.subarray(start, start + 32)))
2833
2513
  throw new Error("invalid secretKey: hash check failed");
2834
2514
  const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
2835
2515
  const msg = KPKE.decrypt(cipherText, sk);
2836
2516
  const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2837
2517
  const Khat = kr.subarray(0, 32);
2838
2518
  const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2839
- const isValid = equalBytes2(cipherText, cipherText2);
2519
+ const isValid = equalBytes(cipherText, cipherText2);
2840
2520
  const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2841
- cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
2521
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2842
2522
  return isValid ? Khat : Kbar;
2523
+ },
2524
+ /**
2525
+ * Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate
2526
+ * against the same key skip re-validation, H(ek), t̂ decoding and the K² SampleNTT
2527
+ * XOF expansions of Â. Only public data is cached; see {@link KEMPrepared}.
2528
+ */
2529
+ prepare: (publicKey) => {
2530
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2531
+ validateModulus(publicKey, "prepare");
2532
+ const ek = copyBytes2(publicKey);
2533
+ const publicKeyHash = HASH256(ek);
2534
+ const cached = KPKE.prepare(ek);
2535
+ return Object.freeze({
2536
+ publicKey: ek,
2537
+ encapsulate: (msg) => {
2538
+ const ownMsg = msg === void 0;
2539
+ const m = ownMsg ? randomBytes3(msgLen) : msg;
2540
+ let kr;
2541
+ try {
2542
+ abytesDoc(m, msgLen, "message");
2543
+ kr = HASH512.create().update(m).update(publicKeyHash).digest();
2544
+ const cipherText = cached.encrypt(m, kr.subarray(32, 64));
2545
+ return {
2546
+ cipherText,
2547
+ sharedSecret: kr.subarray(0, 32)
2548
+ };
2549
+ } finally {
2550
+ if (kr !== void 0)
2551
+ cleanBytes(kr.subarray(32));
2552
+ if (ownMsg)
2553
+ cleanBytes(m);
2554
+ }
2555
+ },
2556
+ decapsulate: (cipherText, secretKey) => {
2557
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2558
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2559
+ const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);
2560
+ if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))
2561
+ throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
2562
+ const msg = KPKE.decrypt(cipherText, sk);
2563
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2564
+ const Khat = kr.subarray(0, 32);
2565
+ const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));
2566
+ const isValid = equalBytes(cipherText, cipherText2);
2567
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2568
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2569
+ return isValid ? Khat : Kbar;
2570
+ },
2571
+ clean: cached.clean
2572
+ });
2843
2573
  }
2844
2574
  });
2845
2575
  }
@@ -2921,6 +2651,31 @@ var init_ml_kem = __esm({
2921
2651
  const secretCoder = vecCoder(polyCoder(12), K);
2922
2652
  const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
2923
2653
  const seedCoder = splitCoder("seed", 32, 32);
2654
+ const encryptCore = (tHat, getA, msg, seed) => {
2655
+ const rHat = [];
2656
+ for (let i = 0; i < K; i++)
2657
+ rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2658
+ const tmp2 = new Uint16Array(N);
2659
+ const u = [];
2660
+ for (let i = 0; i < K; i++) {
2661
+ const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2662
+ const tmp = new Uint16Array(N);
2663
+ for (let j = 0; j < K; j++) {
2664
+ const aij = getA(i, j);
2665
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2666
+ }
2667
+ polyAdd(e1, crystals.NTT.decode(tmp));
2668
+ u.push(e1);
2669
+ polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2670
+ cleanBytes(tmp);
2671
+ }
2672
+ const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2673
+ polyAdd(e2, crystals.NTT.decode(tmp2));
2674
+ const v = poly1.decode(msg);
2675
+ polyAdd(v, e2);
2676
+ cleanBytes(tHat, rHat, tmp2, e2);
2677
+ return cipherCoder.encode([u, v]);
2678
+ };
2924
2679
  return {
2925
2680
  secretCoder,
2926
2681
  lengths: {
@@ -2958,31 +2713,26 @@ var init_ml_kem = __esm({
2958
2713
  },
2959
2714
  encrypt: (publicKey, msg, seed) => {
2960
2715
  const [tHat, rho] = publicCoder.decode(publicKey);
2961
- const rHat = [];
2962
- for (let i = 0; i < K; i++)
2963
- rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2964
2716
  const x = XOF(rho);
2965
- const tmp2 = new Uint16Array(N);
2966
- const u = [];
2967
- for (let i = 0; i < K; i++) {
2968
- const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2969
- const tmp = new Uint16Array(N);
2970
- for (let j = 0; j < K; j++) {
2971
- const aij = SampleNTT(x.get(i, j));
2972
- polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2973
- }
2974
- polyAdd(e1, crystals.NTT.decode(tmp));
2975
- u.push(e1);
2976
- polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2977
- cleanBytes(tmp);
2978
- }
2717
+ const res = encryptCore(tHat, (i, j) => SampleNTT(x.get(i, j)), msg, seed);
2718
+ x.clean();
2719
+ return res;
2720
+ },
2721
+ // Expands the full  matrix (public data derived from rho) once, so repeated encryptions
2722
+ // against the same ek skip the K² SampleNTT XOF expansions. Cached polys are copied per
2723
+ // call because encryptCore mutates its inputs in place.
2724
+ prepare: (publicKey) => {
2725
+ const [tHat, rho] = publicCoder.decode(publicKey);
2726
+ const x = XOF(rho);
2727
+ const A = [];
2728
+ for (let i = 0; i < K; i++)
2729
+ for (let j = 0; j < K; j++)
2730
+ A.push(SampleNTT(x.get(i, j)));
2979
2731
  x.clean();
2980
- const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2981
- polyAdd(e2, crystals.NTT.decode(tmp2));
2982
- const v = poly1.decode(msg);
2983
- polyAdd(v, e2);
2984
- cleanBytes(tHat, rHat, tmp2, e2);
2985
- return cipherCoder.encode([u, v]);
2732
+ return {
2733
+ encrypt: (msg, seed) => encryptCore(tHat.map((p) => p.slice()), (i, j) => A[i * K + j].slice(), msg, seed),
2734
+ clean: () => cleanBytes(tHat, A)
2735
+ };
2986
2736
  },
2987
2737
  decrypt: (cipherText, privateKey) => {
2988
2738
  const [u, v] = cipherCoder.decode(cipherText);
@@ -2991,8 +2741,9 @@ var init_ml_kem = __esm({
2991
2741
  for (let i = 0; i < K; i++)
2992
2742
  polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
2993
2743
  polySub(v, crystals.NTT.decode(tmp));
2994
- cleanBytes(tmp, sk, u);
2995
- return poly1.encode(v);
2744
+ const res = poly1.encode(v);
2745
+ cleanBytes(tmp, sk, u, v);
2746
+ return res;
2996
2747
  }
2997
2748
  };
2998
2749
  };
@@ -3013,17 +2764,22 @@ var init_ml_kem = __esm({
3013
2764
 
3014
2765
  // ../../node_modules/@noble/post-quantum/hybrid.js
3015
2766
  function ecKeygen(curve, allowZeroKey = false) {
2767
+ const c = aobject3(curve, "curve");
2768
+ aobject3(c.lengths, "curve.lengths");
2769
+ afunction(c.keygen, "curve.keygen");
2770
+ afunction(c.getPublicKey, "curve.getPublicKey");
2771
+ abool2(allowZeroKey, "allowZeroKey");
3016
2772
  const lengths = curve.lengths;
3017
2773
  let keygen = curve.keygen;
3018
2774
  if (allowZeroKey) {
3019
2775
  if (!("getSharedSecret" in curve && "sign" in curve && "verify" in curve))
3020
2776
  throw new Error("allowZeroKey requires a Weierstrass curve");
3021
2777
  const wCurve = curve;
3022
- const Fn2 = wCurve.Point.Fn;
2778
+ const Fn = wCurve.Point.Fn;
3023
2779
  keygen = (seed = randomBytes3(lengths.seed)) => {
3024
2780
  abytes(seed, lengths.seed, "seed");
3025
- const seedScalar = Fn2.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
3026
- const secretKey = Fn2.toBytes(Fn2.create(seedScalar));
2781
+ const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
2782
+ const secretKey = Fn.toBytes(Fn.create(seedScalar));
3027
2783
  return {
3028
2784
  secretKey,
3029
2785
  publicKey: curve.getPublicKey(secretKey)
@@ -3036,10 +2792,14 @@ function ecKeygen(curve, allowZeroKey = false) {
3036
2792
  getPublicKey: (secretKey) => curve.getPublicKey(secretKey)
3037
2793
  };
3038
2794
  }
3039
- function ecdhKem(curve, allowZeroKey = false) {
2795
+ function _ecdhKem(curve, allowZeroKey = false) {
3040
2796
  const kg = ecKeygen(curve, allowZeroKey);
3041
2797
  if (!curve.getSharedSecret)
3042
2798
  throw new Error("wrong curve");
2799
+ const decapsulate = (cipherText, secretKey) => {
2800
+ const res = curve.getSharedSecret(secretKey, cipherText);
2801
+ return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
2802
+ };
3043
2803
  return {
3044
2804
  lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },
3045
2805
  keygen: kg.keygen,
@@ -3048,8 +2808,8 @@ function ecdhKem(curve, allowZeroKey = false) {
3048
2808
  const seed = copyBytes2(rand);
3049
2809
  let ek = void 0;
3050
2810
  try {
3051
- ek = this.keygen(seed).secretKey;
3052
- const sharedSecret = this.decapsulate(publicKey, ek);
2811
+ ek = kg.keygen(seed).secretKey;
2812
+ const sharedSecret = decapsulate(publicKey, ek);
3053
2813
  const cipherText = curve.getPublicKey(ek);
3054
2814
  return { sharedSecret, cipherText };
3055
2815
  } finally {
@@ -3058,18 +2818,23 @@ function ecdhKem(curve, allowZeroKey = false) {
3058
2818
  cleanBytes(ek);
3059
2819
  }
3060
2820
  },
3061
- decapsulate(cipherText, secretKey) {
3062
- const res = curve.getSharedSecret(secretKey, cipherText);
3063
- return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
3064
- }
2821
+ decapsulate
3065
2822
  };
3066
2823
  }
2824
+ function positiveLength(value, title) {
2825
+ const length = anumber(value, title);
2826
+ if (length === 0)
2827
+ throw new RangeError(`"${title}" expected integer greater than 0, got 0`);
2828
+ return length;
2829
+ }
3067
2830
  function splitLengths(lst, name) {
3068
- return splitCoder(name, ...lst.map((i) => {
2831
+ const coder = splitCoder(name, ...lst.map((i) => {
3069
2832
  if (typeof i.lengths[name] !== "number")
3070
2833
  throw new Error("wrong length: " + name);
3071
- return i.lengths[name];
2834
+ return positiveLength(i.lengths[name], name);
3072
2835
  }));
2836
+ positiveLength(coder.bytesLen, name);
2837
+ return coder;
3073
2838
  }
3074
2839
  function expandSeedXof(xof) {
3075
2840
  return ((seed, seedLen) => xof(seed, { dkLen: seedLen }));
@@ -3079,11 +2844,9 @@ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
3079
2844
  const ck = ck_;
3080
2845
  const seedCoder = splitLengths(ck, "seed");
3081
2846
  const pkCoder = splitLengths(ck, "publicKey");
3082
- if (realSeedLen === void 0)
3083
- realSeedLen = seedCoder.bytesLen;
3084
- anumber(realSeedLen);
2847
+ const rootSeedLen = positiveLength(realSeedLen === void 0 ? seedCoder.bytesLen : realSeedLen, "realSeedLen");
3085
2848
  function expandDecapsulationKey(seed) {
3086
- abytes(seed, realSeedLen);
2849
+ abytes(seed, rootSeedLen);
3087
2850
  const expandedRaw = expandSeed(seed, seedCoder.bytesLen);
3088
2851
  const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes2(expandedRaw) : expandedRaw;
3089
2852
  const expanded = [];
@@ -3108,41 +2871,79 @@ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
3108
2871
  cleanBytes(secretKey);
3109
2872
  }
3110
2873
  }
3111
- return {
3112
- info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },
3113
- getPublicKey(secretKey) {
3114
- return this.keygen(secretKey).publicKey;
3115
- },
3116
- keygen(seed = randomBytes3(realSeedLen)) {
3117
- const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);
2874
+ const keygen = (seed) => {
2875
+ const root = seed === void 0 ? randomBytes3(rootSeedLen) : copyBytes2(seed);
2876
+ let res;
2877
+ try {
2878
+ const { publicKey: pk, secretKey } = expandDecapsulationKey(root);
3118
2879
  try {
3119
- const publicKey = pkCoder.encode(pk);
3120
- return { secretKey: seed, publicKey };
2880
+ res = {
2881
+ secretKey: root,
2882
+ publicKey: pkCoder.encode(pk)
2883
+ };
3121
2884
  } finally {
3122
- cleanBytes(pk);
3123
- cleanBytes(secretKey);
2885
+ cleanBytes(pk, secretKey);
3124
2886
  }
2887
+ return res;
2888
+ } finally {
2889
+ if (!res)
2890
+ cleanBytes(root);
2891
+ }
2892
+ };
2893
+ return {
2894
+ info: { lengths: { seed: rootSeedLen, publicKey: pkCoder.bytesLen, secretKey: rootSeedLen } },
2895
+ // Composite secret keys are root seeds, so public-key derivation reruns key expansion from
2896
+ // that seed instead of decoding a packed child-secret-key structure.
2897
+ getPublicKey: (secretKey) => {
2898
+ const keys = keygen(secretKey);
2899
+ cleanBytes(keys.secretKey);
2900
+ return keys.publicKey;
3125
2901
  },
2902
+ keygen,
3126
2903
  expandDecapsulationKey,
3127
- realSeedLen
2904
+ realSeedLen: rootSeedLen
3128
2905
  };
3129
2906
  }
3130
2907
  function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
2908
+ if (realSeedLen !== void 0)
2909
+ positiveLength(realSeedLen, "realSeedLen");
2910
+ if (realMsgLen !== void 0)
2911
+ positiveLength(realMsgLen, "realMsgLen");
2912
+ if (typeof expandSeed !== "function")
2913
+ throw new TypeError('"expandSeed" expected function, got type=' + typeof expandSeed);
2914
+ if (typeof combiner !== "function")
2915
+ throw new TypeError('"combiner" expected function, got type=' + typeof combiner);
3131
2916
  const rawCombiner = combiner;
3132
2917
  const rawKems = kems;
2918
+ if (rawKems.length === 0)
2919
+ throw new RangeError("combineKEMS requires at least one KEM");
2920
+ for (let i = 0; i < rawKems.length; i++)
2921
+ validateKEM(rawKems[i], `kems[${i}]`);
3133
2922
  const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);
3134
2923
  const ctCoder = splitLengths(rawKems, "cipherText");
3135
2924
  const pkCoder = splitLengths(rawKems, "publicKey");
3136
2925
  const msgCoder = splitLengths(rawKems, "msg");
3137
- if (realMsgLen === void 0)
3138
- realMsgLen = msgCoder.bytesLen;
3139
- anumber(realMsgLen);
2926
+ const sharedSecretLen = positiveLength(realMsgLen === void 0 ? msgCoder.bytesLen : realMsgLen, "realMsgLen");
3140
2927
  const lengths = Object.freeze({
3141
2928
  ...keys.info.lengths,
3142
- msg: realMsgLen,
2929
+ msg: sharedSecretLen,
3143
2930
  msgRand: msgCoder.bytesLen,
3144
2931
  cipherText: ctCoder.bytesLen
3145
2932
  });
2933
+ const combine = (publicKeys, cipherTexts, sharedSecrets) => {
2934
+ const combined = rawCombiner(publicKeys, cipherTexts, sharedSecrets);
2935
+ try {
2936
+ return copyBytes2(abytes(combined, sharedSecretLen, "sharedSecret"));
2937
+ } catch (error) {
2938
+ if (isBytes(combined)) {
2939
+ const overlaps = (value) => combined.buffer === value.buffer && combined.byteOffset < value.byteOffset + value.byteLength && value.byteOffset < combined.byteOffset + combined.byteLength;
2940
+ const aliasesPublicInput = publicKeys.some(overlaps) || cipherTexts.some(overlaps);
2941
+ if (!aliasesPublicInput)
2942
+ cleanBytes(combined);
2943
+ }
2944
+ throw error;
2945
+ }
2946
+ };
3146
2947
  return Object.freeze({
3147
2948
  lengths,
3148
2949
  getPublicKey: keys.getPublicKey,
@@ -3158,11 +2959,12 @@ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3158
2959
  sharedSecret.push(enc.sharedSecret);
3159
2960
  cipherText.push(enc.cipherText);
3160
2961
  }
2962
+ const encodedCipherText = ctCoder.encode(cipherText);
3161
2963
  return {
3162
2964
  // Detach the combiner result before cleanup: a caller-provided combiner may alias one of
3163
2965
  // the child sharedSecret buffers, and those child buffers are zeroized immediately below.
3164
- sharedSecret: copyBytes2(rawCombiner(pks, cipherText, sharedSecret)),
3165
- cipherText: ctCoder.encode(cipherText)
2966
+ sharedSecret: combine(pks, cipherText, sharedSecret),
2967
+ cipherText: encodedCipherText
3166
2968
  };
3167
2969
  } finally {
3168
2970
  cleanBytes(sharedSecret, cipherText);
@@ -3171,16 +2973,18 @@ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3171
2973
  decapsulate(ct, seed) {
3172
2974
  const cts = ctCoder.decode(ct);
3173
2975
  const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);
3174
- const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
2976
+ const sharedSecret = [];
3175
2977
  try {
3176
- return copyBytes2(rawCombiner(publicKey, cts, sharedSecret));
2978
+ for (let i = 0; i < rawKems.length; i++)
2979
+ sharedSecret.push(rawKems[i].decapsulate(cts[i], secretKey[i]));
2980
+ return combine(publicKey, cts, sharedSecret);
3177
2981
  } finally {
3178
2982
  cleanBytes(secretKey, sharedSecret);
3179
2983
  }
3180
2984
  }
3181
2985
  });
3182
2986
  }
3183
- var x25519kem, ml_kem768_x25519, XWing;
2987
+ var validateKEM, x25519kem, ml_kem768_x25519;
3184
2988
  var init_hybrid = __esm({
3185
2989
  "../../node_modules/@noble/post-quantum/hybrid.js"() {
3186
2990
  "use strict";
@@ -3190,7 +2994,16 @@ var init_hybrid = __esm({
3190
2994
  init_utils();
3191
2995
  init_ml_kem();
3192
2996
  init_utils3();
3193
- x25519kem = /* @__PURE__ */ ecdhKem(x25519);
2997
+ validateKEM = (kem, title) => {
2998
+ const k = aobject3(kem, title);
2999
+ aobject3(k.lengths, `${title}.lengths`);
3000
+ afunction(k.keygen, `${title}.keygen`);
3001
+ afunction(k.getPublicKey, `${title}.getPublicKey`);
3002
+ afunction(k.encapsulate, `${title}.encapsulate`);
3003
+ afunction(k.decapsulate, `${title}.decapsulate`);
3004
+ return k;
3005
+ };
3006
+ x25519kem = /* @__PURE__ */ _ecdhKem(x25519);
3194
3007
  ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(
3195
3008
  32,
3196
3009
  32,
@@ -3200,7 +3013,6 @@ var init_hybrid = __esm({
3200
3013
  ml_kem768,
3201
3014
  x25519kem
3202
3015
  ))();
3203
- XWing = /* @__PURE__ */ (() => ml_kem768_x25519)();
3204
3016
  }
3205
3017
  });
3206
3018
 
@@ -3438,12 +3250,15 @@ function classifyEndpointProbe(input) {
3438
3250
  function countsAsFailure(verdict) {
3439
3251
  return !verdict.dispatchable;
3440
3252
  }
3441
- var ENDPOINT_FAILURE_THRESHOLD, MISSING_STATUSES;
3253
+ var ENDPOINT_FAILURE_THRESHOLD, MISSING_STATUSES, ENDPOINT_PROBE_INTERVAL_MINUTES, ENDPOINT_STALE_AFTER_MINUTES, ENDPOINT_UNUSABLE_AFTER_MINUTES;
3442
3254
  var init_endpoint_health = __esm({
3443
3255
  "../crypto/src/endpoint-health.ts"() {
3444
3256
  "use strict";
3445
3257
  ENDPOINT_FAILURE_THRESHOLD = 3;
3446
3258
  MISSING_STATUSES = /* @__PURE__ */ new Set([404, 405, 410]);
3259
+ ENDPOINT_PROBE_INTERVAL_MINUTES = 15;
3260
+ ENDPOINT_STALE_AFTER_MINUTES = ENDPOINT_PROBE_INTERVAL_MINUTES * 4;
3261
+ ENDPOINT_UNUSABLE_AFTER_MINUTES = ENDPOINT_PROBE_INTERVAL_MINUTES * 24;
3447
3262
  }
3448
3263
  });
3449
3264
 
@@ -3532,6 +3347,56 @@ var init_partner_key_attestation = __esm({
3532
3347
  }
3533
3348
  });
3534
3349
 
3350
+ // ../crypto/src/registry-root-pin.ts
3351
+ function __setPinnedRegistryRootsForTests(pins) {
3352
+ overrideForTests = pins;
3353
+ }
3354
+ function pinnedRegistryRoots() {
3355
+ return overrideForTests ?? PINNED_REGISTRY_ROOTS;
3356
+ }
3357
+ function b64ToBytes2(b64) {
3358
+ const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3359
+ const binary = atob(normalised);
3360
+ const out = new Uint8Array(binary.length);
3361
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
3362
+ return out;
3363
+ }
3364
+ async function spkiSha256HexFromB64(spkiB64) {
3365
+ const digest = await crypto.subtle.digest("SHA-256", b64ToBytes2(spkiB64));
3366
+ return bytesToHex3(new Uint8Array(digest));
3367
+ }
3368
+ async function rootIsPinned(root) {
3369
+ try {
3370
+ const digest = await spkiSha256HexFromB64(root.public_key_b64);
3371
+ return pinnedRegistryRoots().some(
3372
+ (p) => p.root_key_id === root.root_key_id && p.spki_sha256 === digest
3373
+ );
3374
+ } catch {
3375
+ return false;
3376
+ }
3377
+ }
3378
+ async function unpinnedRootIds(roots) {
3379
+ const out = [];
3380
+ for (const root of roots) {
3381
+ if (!await rootIsPinned(root)) out.push(String(root?.root_key_id ?? "(no id)"));
3382
+ }
3383
+ return out;
3384
+ }
3385
+ var PINNED_REGISTRY_ROOTS, overrideForTests;
3386
+ var init_registry_root_pin = __esm({
3387
+ "../crypto/src/registry-root-pin.ts"() {
3388
+ "use strict";
3389
+ init_partner_key_attestation();
3390
+ PINNED_REGISTRY_ROOTS = Object.freeze([
3391
+ Object.freeze({
3392
+ root_key_id: "rk1_251368ec9b0a84ae",
3393
+ spki_sha256: "251368ec9b0a84ae9881533bd1687efb7d439edd927aef47c1bb3bb069b3dc1d"
3394
+ })
3395
+ ]);
3396
+ overrideForTests = null;
3397
+ }
3398
+ });
3399
+
3535
3400
  // ../crypto/src/registry-head.ts
3536
3401
  function assertNoLineBreak(field, value) {
3537
3402
  if (typeof value !== "string" || value.length === 0) {
@@ -3604,7 +3469,7 @@ function buildRegistryHeadStatement(payload) {
3604
3469
  }
3605
3470
  return lines.join("\n");
3606
3471
  }
3607
- function b64ToBytes2(b64) {
3472
+ function b64ToBytes3(b64) {
3608
3473
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3609
3474
  const binary = atob(normalised);
3610
3475
  const out = new Uint8Array(binary.length);
@@ -3649,7 +3514,7 @@ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date())
3649
3514
  });
3650
3515
  const rootKey = await crypto.subtle.importKey(
3651
3516
  "spki",
3652
- b64ToBytes2(root.public_key_b64),
3517
+ b64ToBytes3(root.public_key_b64),
3653
3518
  { name: "ECDSA", namedCurve: "P-256" },
3654
3519
  false,
3655
3520
  ["verify"]
@@ -3677,7 +3542,7 @@ function headNamesPartner(doc, partnerId) {
3677
3542
  async function partnerKeyFingerprint(publicKeyB64) {
3678
3543
  const digest = await crypto.subtle.digest(
3679
3544
  "SHA-256",
3680
- b64ToBytes2(publicKeyB64)
3545
+ b64ToBytes3(publicKeyB64)
3681
3546
  );
3682
3547
  return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
3683
3548
  }
@@ -3714,6 +3579,7 @@ async function saysRootNotConfigured(res) {
3714
3579
  }
3715
3580
  }
3716
3581
  async function outcomeFor(partnerId, key, reg, bound) {
3582
+ if (reg.unpinnedRoots.length > 0) return "root-unpinned";
3717
3583
  if (!reg.head) return "head-unusable";
3718
3584
  if (!key.key_signature || !key.root_key_id) {
3719
3585
  if (!key.countersignature_exempt) return "unsigned";
@@ -3772,6 +3638,10 @@ function createPartnerKeyVerifier(env = {}) {
3772
3638
  if (roots.length === 0) {
3773
3639
  return { ok: false, failure: { reason: "roots-empty", status: rootsRes.status } };
3774
3640
  }
3641
+ const unpinnedRoots = await unpinnedRootIds(roots);
3642
+ if (unpinnedRoots.length > 0) {
3643
+ return { ok: true, registry: { roots: [], head: null, headVerdict: "root-unpinned", unpinnedRoots } };
3644
+ }
3775
3645
  let head = null;
3776
3646
  let headVerdict = "absent";
3777
3647
  if (headRes.ok) {
@@ -3779,7 +3649,7 @@ function createPartnerKeyVerifier(env = {}) {
3779
3649
  headVerdict = await verifyRegistryHead(head, roots);
3780
3650
  if (headVerdict !== "ok" && headVerdict !== "expired") head = null;
3781
3651
  }
3782
- return { ok: true, registry: { roots, head, headVerdict } };
3652
+ return { ok: true, registry: { roots, head, headVerdict, unpinnedRoots: [] } };
3783
3653
  } catch {
3784
3654
  return { ok: false, failure: { reason: "fetch-failed" } };
3785
3655
  }
@@ -3811,6 +3681,7 @@ function createPartnerKeyVerifier(env = {}) {
3811
3681
  "bad-attestation": [],
3812
3682
  "not-in-head": [],
3813
3683
  "head-unusable": [],
3684
+ "root-unpinned": [],
3814
3685
  "error": []
3815
3686
  };
3816
3687
  const blocked = {};
@@ -3854,6 +3725,9 @@ function createPartnerKeyVerifier(env = {}) {
3854
3725
  // Counted, not listed: an operator reading a real finding needs to know
3855
3726
  // how many keys were skipped as exempt, without the ids adding noise.
3856
3727
  exempt: tally.exempt.length,
3728
+ // The served root ids the bundle refused, so a report of a rotation
3729
+ // that outran its client build names the root to add.
3730
+ ...reg.unpinnedRoots.length > 0 ? { unpinnedRoots: reg.unpinnedRoots } : {},
3857
3731
  ...Object.fromEntries(failed.map((o) => [o, tally[o]]))
3858
3732
  });
3859
3733
  }
@@ -3873,6 +3747,7 @@ var init_verify_partner_keys = __esm({
3873
3747
  "../crypto/src/verify-partner-keys.ts"() {
3874
3748
  "use strict";
3875
3749
  init_partner_key_attestation();
3750
+ init_registry_root_pin();
3876
3751
  init_registry_head();
3877
3752
  ACCEPTABLE = /* @__PURE__ */ new Set(["ok", "exempt"]);
3878
3753
  EMPTY_BOUND = /* @__PURE__ */ new Set();
@@ -4003,13 +3878,18 @@ var src_exports = {};
4003
3878
  __export(src_exports, {
4004
3879
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
4005
3880
  ENDPOINT_FAILURE_THRESHOLD: () => ENDPOINT_FAILURE_THRESHOLD,
3881
+ ENDPOINT_PROBE_INTERVAL_MINUTES: () => ENDPOINT_PROBE_INTERVAL_MINUTES,
3882
+ ENDPOINT_STALE_AFTER_MINUTES: () => ENDPOINT_STALE_AFTER_MINUTES,
3883
+ ENDPOINT_UNUSABLE_AFTER_MINUTES: () => ENDPOINT_UNUSABLE_AFTER_MINUTES,
4006
3884
  PARTNER_KEY_ATTESTATION_ALG: () => PARTNER_KEY_ATTESTATION_ALG,
4007
3885
  PARTNER_KEY_ATTESTATION_V1: () => PARTNER_KEY_ATTESTATION_V1,
4008
3886
  PARTNER_KEY_REFUSED_MESSAGE: () => PARTNER_KEY_REFUSED_MESSAGE,
3887
+ PINNED_REGISTRY_ROOTS: () => PINNED_REGISTRY_ROOTS,
4009
3888
  REGISTRY_HEAD_ALG: () => REGISTRY_HEAD_ALG,
4010
3889
  REGISTRY_HEAD_V1: () => REGISTRY_HEAD_V1,
4011
3890
  REGISTRY_HEAD_V2: () => REGISTRY_HEAD_V2,
4012
3891
  SENDER_HELD_KEY_ALGORITHM: () => SENDER_HELD_KEY_ALGORITHM,
3892
+ __setPinnedRegistryRootsForTests: () => __setPinnedRegistryRootsForTests,
4013
3893
  blockedPublicKeyReason: () => blockedPublicKeyReason,
4014
3894
  buildPartnerKeyAttestation: () => buildPartnerKeyAttestation,
4015
3895
  buildRegistryHeadStatement: () => buildRegistryHeadStatement,
@@ -4043,15 +3923,19 @@ __export(src_exports, {
4043
3923
  normalizeForBlindIndex: () => normalizeForBlindIndex,
4044
3924
  openSealedWithSenderHeldKey: () => openSealedWithSenderHeldKey,
4045
3925
  partnerKeyFingerprint: () => partnerKeyFingerprint,
3926
+ pinnedRegistryRoots: () => pinnedRegistryRoots,
3927
+ rootIsPinned: () => rootIsPinned,
4046
3928
  rootKeyIdFromSpki: () => rootKeyIdFromSpki,
4047
3929
  rootKeyIdFromSpkiB64: () => rootKeyIdFromSpkiB64,
4048
3930
  signWebhookPayload: () => signWebhookPayload,
3931
+ spkiSha256HexFromB64: () => spkiSha256HexFromB64,
3932
+ unpinnedRootIds: () => unpinnedRootIds,
4049
3933
  verifyPartnerKeyAttestation: () => verifyPartnerKeyAttestation,
4050
3934
  verifyPartnerKeyAttestationWithRoots: () => verifyPartnerKeyAttestationWithRoots,
4051
3935
  verifyRegistryHead: () => verifyRegistryHead,
4052
3936
  verifyWebhookSignature: () => verifyWebhookSignature
4053
3937
  });
4054
- function b64ToBytes3(b64) {
3938
+ function b64ToBytes4(b64) {
4055
3939
  const binary = atob(b64);
4056
3940
  const bytes = new Uint8Array(binary.length);
4057
3941
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.codePointAt(i) ?? 0;
@@ -4059,13 +3943,13 @@ function b64ToBytes3(b64) {
4059
3943
  }
4060
3944
  function keyB64ToBytes(key) {
4061
3945
  const begin = key.indexOf("-----BEGIN");
4062
- if (begin === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3946
+ if (begin === -1) return b64ToBytes4(key.replace(/\s+/g, ""));
4063
3947
  const armourEnd = key.indexOf("-----", begin + "-----BEGIN".length);
4064
- if (armourEnd === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3948
+ if (armourEnd === -1) return b64ToBytes4(key.replace(/\s+/g, ""));
4065
3949
  const bodyStart = armourEnd + "-----".length;
4066
3950
  const end = key.indexOf("-----END", bodyStart);
4067
3951
  const body = end === -1 ? key.slice(bodyStart) : key.slice(bodyStart, end);
4068
- return b64ToBytes3(body.replace(/\s+/g, ""));
3952
+ return b64ToBytes4(body.replace(/\s+/g, ""));
4069
3953
  }
4070
3954
  function bytesToB64(bytes) {
4071
3955
  return btoa(String.fromCodePoint(...bytes));
@@ -4141,7 +4025,7 @@ async function generatePartnerKeyPair() {
4141
4025
  };
4142
4026
  }
4143
4027
  function generateHybridPartnerKeyPair() {
4144
- const { secretKey, publicKey } = XWing.keygen();
4028
+ const { secretKey, publicKey } = ml_kem768_x25519.keygen();
4145
4029
  return {
4146
4030
  publicKeyB64: bytesToB64(publicKey),
4147
4031
  privateKeyB64: bytesToB64(secretKey)
@@ -4149,7 +4033,7 @@ function generateHybridPartnerKeyPair() {
4149
4033
  }
4150
4034
  async function encryptAddressForPartner(address, partner) {
4151
4035
  const address_ = normaliseAddress(address);
4152
- const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
4036
+ const partnerPubKey = await importP256PublicKey(b64ToBytes4(partner.publicKeyB64));
4153
4037
  const ephemeral = await subtle().generateKey(
4154
4038
  { name: "ECDH", namedCurve: "P-256" },
4155
4039
  true,
@@ -4197,7 +4081,7 @@ async function encryptAddressForPartner(address, partner) {
4197
4081
  };
4198
4082
  }
4199
4083
  async function encryptPayloadForPartner(payload, partner) {
4200
- const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
4084
+ const partnerPubKey = await importP256PublicKey(b64ToBytes4(partner.publicKeyB64));
4201
4085
  const ephemeral = await subtle().generateKey(
4202
4086
  { name: "ECDH", namedCurve: "P-256" },
4203
4087
  true,
@@ -4250,7 +4134,7 @@ async function decryptAddress(encrypted, privateKeyB64) {
4250
4134
  );
4251
4135
  const ephemeralPub = await subtle().importKey(
4252
4136
  "raw",
4253
- b64ToBytes3(encrypted.ephemeralPublicKey),
4137
+ b64ToBytes4(encrypted.ephemeralPublicKey),
4254
4138
  { name: "ECDH", namedCurve: "P-256" },
4255
4139
  false,
4256
4140
  []
@@ -4260,7 +4144,7 @@ async function decryptAddress(encrypted, privateKeyB64) {
4260
4144
  privateKey,
4261
4145
  256
4262
4146
  );
4263
- const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes3(encrypted.hkdfSalt) : new Uint8Array(32);
4147
+ const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes4(encrypted.hkdfSalt) : new Uint8Array(32);
4264
4148
  const aesKey = await subtle().importKey(
4265
4149
  "raw",
4266
4150
  await subtle().deriveBits(
@@ -4278,9 +4162,9 @@ async function decryptAddress(encrypted, privateKeyB64) {
4278
4162
  ["decrypt"]
4279
4163
  );
4280
4164
  const plainBuf = await subtle().decrypt(
4281
- { name: "AES-GCM", iv: b64ToBytes3(encrypted.iv) },
4165
+ { name: "AES-GCM", iv: b64ToBytes4(encrypted.iv) },
4282
4166
  aesKey,
4283
- b64ToBytes3(encrypted.ciphertext)
4167
+ b64ToBytes4(encrypted.ciphertext)
4284
4168
  );
4285
4169
  return JSON.parse(new TextDecoder().decode(plainBuf));
4286
4170
  }
@@ -4305,7 +4189,7 @@ function bytesToB64Url(bytes) {
4305
4189
  }
4306
4190
  function b64UrlToBytes(b64url) {
4307
4191
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
4308
- return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
4192
+ return b64ToBytes4(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
4309
4193
  }
4310
4194
  function toArrayBuffer(bytes) {
4311
4195
  return bytes.slice().buffer;
@@ -4327,7 +4211,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
4327
4211
  const session_envelope = bytesToB64Url(concat(sessionIv, sessionCt));
4328
4212
  const skRawForWrap = new Uint8Array(await subtle().exportKey("raw", sk));
4329
4213
  if (isHybridScheme(partner.algorithm)) {
4330
- const { cipherText: kemCt, sharedSecret: sharedSecret2 } = XWing.encapsulate(b64ToBytes3(partner.public_key_b64));
4214
+ const { cipherText: kemCt, sharedSecret: sharedSecret2 } = ml_kem768_x25519.encapsulate(b64ToBytes4(partner.public_key_b64));
4331
4215
  const wrapSalt2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_SALT_LENGTH));
4332
4216
  const wrapKeyRaw2 = await subtle().deriveBits(
4333
4217
  { name: "HKDF", hash: "SHA-256", salt: wrapSalt2, info: sessionWrapInfoPq(partner.partner_id) },
@@ -4354,7 +4238,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
4354
4238
  };
4355
4239
  }
4356
4240
  if (isRsaScheme(partner.algorithm)) {
4357
- const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes3(partner.public_key_b64));
4241
+ const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes4(partner.public_key_b64));
4358
4242
  const rsaWrapped = new Uint8Array(
4359
4243
  await subtle().encrypt({ name: "RSA-OAEP" }, partnerRsaPub, skRawForWrap)
4360
4244
  );
@@ -4371,7 +4255,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
4371
4255
  }
4372
4256
  };
4373
4257
  }
4374
- const partnerPub = await importP256PublicKey(b64ToBytes3(partner.public_key_b64));
4258
+ const partnerPub = await importP256PublicKey(b64ToBytes4(partner.public_key_b64));
4375
4259
  const ephemeral = await subtle().generateKey(
4376
4260
  { name: "ECDH", namedCurve: "P-256" },
4377
4261
  true,
@@ -4453,7 +4337,7 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expe
4453
4337
  throw new Error("decryptSession: hybrid share missing epk (KEM ciphertext)");
4454
4338
  }
4455
4339
  const kemCiphertext = b64UrlToBytes(share.epk);
4456
- const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(XWing.decapsulate(kemCiphertext, b64ToBytes3(privateKeyB64)));
4340
+ const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(ml_kem768_x25519.decapsulate(kemCiphertext, b64ToBytes4(privateKeyB64)));
4457
4341
  if (ops && sharedSecret.byteLength !== 32) {
4458
4342
  throw new Error(
4459
4343
  `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; X-Wing decapsulation is 32 bytes with no KDF applied.`
@@ -4676,6 +4560,7 @@ var init_src = __esm({
4676
4560
  init_blocked_public_keys();
4677
4561
  init_endpoint_health();
4678
4562
  init_partner_key_attestation();
4563
+ init_registry_root_pin();
4679
4564
  init_registry_head();
4680
4565
  init_verify_partner_keys();
4681
4566
  init_sender_held_keys();
@@ -4746,7 +4631,7 @@ __export(edge_exports, {
4746
4631
  module.exports = __toCommonJS(edge_exports);
4747
4632
 
4748
4633
  // src/index.ts
4749
- var import_crypto = __toESM(require("crypto"));
4634
+ var import_crypto2 = __toESM(require("crypto"));
4750
4635
  init_src();
4751
4636
 
4752
4637
  // ../protocol/src/types.ts
@@ -4795,6 +4680,36 @@ var D5_BODY_ALL_ALLOWED = [
4795
4680
  // ../protocol/src/retention.ts
4796
4681
  var DAY_MS = 24 * 60 * 60 * 1e3;
4797
4682
 
4683
+ // src/app-hosts.ts
4684
+ function allowedAppHosts() {
4685
+ const hosts = ["oneaddress.io", "app.oneaddress.io"];
4686
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
4687
+ hosts.push("localhost", "127.0.0.1");
4688
+ }
4689
+ return new Set(hosts);
4690
+ }
4691
+ function resolveAppOrigin(baseUrl, label) {
4692
+ let parsed;
4693
+ try {
4694
+ parsed = new URL(baseUrl);
4695
+ } catch {
4696
+ throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
4697
+ }
4698
+ const allowed = allowedAppHosts();
4699
+ if (!allowed.has(parsed.hostname)) {
4700
+ throw new Error(
4701
+ `[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
4702
+ );
4703
+ }
4704
+ const loopback = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
4705
+ if (parsed.protocol !== "https:" && !loopback) {
4706
+ throw new Error(
4707
+ `[OneAddress SDK] ${label}: appBaseUrl must use https (plain http is accepted for localhost only)`
4708
+ );
4709
+ }
4710
+ return parsed.origin;
4711
+ }
4712
+
4798
4713
  // src/index.ts
4799
4714
  init_src();
4800
4715
  init_src();
@@ -4844,15 +4759,18 @@ function findMatchingStoredName(providedNames, storedCandidates) {
4844
4759
  // src/outbox.ts
4845
4760
  var import_node_crypto = require("crypto");
4846
4761
 
4762
+ // src/registry-head-check.ts
4763
+ init_src();
4764
+
4847
4765
  // src/index.ts
4848
4766
  function verifySignature(rawBody, signature, timestamp, secret) {
4849
4767
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
4850
4768
  const sigPayload = `${timestamp}.${rawBody}`;
4851
- const expected = import_crypto.default.createHmac("sha256", secret).update(sigPayload).digest("hex");
4769
+ const expected = import_crypto2.default.createHmac("sha256", secret).update(sigPayload).digest("hex");
4852
4770
  const sigBuffer = Buffer.from(signature, "hex");
4853
4771
  const expBuffer = Buffer.from(expected, "hex");
4854
4772
  if (sigBuffer.length !== expBuffer.length) return false;
4855
- return import_crypto.default.timingSafeEqual(sigBuffer, expBuffer);
4773
+ return import_crypto2.default.timingSafeEqual(sigBuffer, expBuffer);
4856
4774
  }
4857
4775
  function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
4858
4776
  if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
@@ -4882,26 +4800,26 @@ function pemToBuffer(pem) {
4882
4800
  }
4883
4801
  async function decryptAddress2(payload, privateKeyPem, partnerId) {
4884
4802
  const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
4885
- const privateKey = await import_crypto.default.subtle.importKey(
4803
+ const privateKey = await import_crypto2.default.subtle.importKey(
4886
4804
  "pkcs8",
4887
4805
  pemToBuffer(privateKeyPem),
4888
4806
  { name: "ECDH", namedCurve: "P-256" },
4889
4807
  false,
4890
4808
  ["deriveBits"]
4891
4809
  );
4892
- const ephemeralKey = await import_crypto.default.subtle.importKey(
4810
+ const ephemeralKey = await import_crypto2.default.subtle.importKey(
4893
4811
  "raw",
4894
4812
  base64urlToBuffer(ephemeralPublicKey),
4895
4813
  { name: "ECDH", namedCurve: "P-256" },
4896
4814
  false,
4897
4815
  []
4898
4816
  );
4899
- const sharedBits = await import_crypto.default.subtle.deriveBits(
4817
+ const sharedBits = await import_crypto2.default.subtle.deriveBits(
4900
4818
  { name: "ECDH", public: ephemeralKey },
4901
4819
  privateKey,
4902
4820
  256
4903
4821
  );
4904
- const hkdfKey = await import_crypto.default.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
4822
+ const hkdfKey = await import_crypto2.default.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
4905
4823
  let salt;
4906
4824
  if (hkdfSalt) {
4907
4825
  const saltBytes = base64urlToBuffer(hkdfSalt);
@@ -4915,13 +4833,13 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
4915
4833
  salt = new Uint8Array(32);
4916
4834
  }
4917
4835
  const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
4918
- const aesKeyBits = await import_crypto.default.subtle.deriveBits(
4836
+ const aesKeyBits = await import_crypto2.default.subtle.deriveBits(
4919
4837
  { name: "HKDF", hash: "SHA-256", salt, info },
4920
4838
  hkdfKey,
4921
4839
  256
4922
4840
  );
4923
- const aesKey = await import_crypto.default.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["decrypt"]);
4924
- const plaintext = await import_crypto.default.subtle.decrypt(
4841
+ const aesKey = await import_crypto2.default.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["decrypt"]);
4842
+ const plaintext = await import_crypto2.default.subtle.decrypt(
4925
4843
  { name: "AES-GCM", iv: base64urlToBuffer(iv), tagLength: 128 },
4926
4844
  aesKey,
4927
4845
  base64urlToBuffer(ciphertext)
@@ -4948,38 +4866,38 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
4948
4866
  );
4949
4867
  }
4950
4868
  async function reEncryptForRecipient(plaintextBytes, recipientSpkiPem, info) {
4951
- const recipientKey = await import_crypto.default.subtle.importKey(
4869
+ const recipientKey = await import_crypto2.default.subtle.importKey(
4952
4870
  "spki",
4953
4871
  pemToBuffer(recipientSpkiPem),
4954
4872
  { name: "ECDH", namedCurve: "P-256" },
4955
4873
  false,
4956
4874
  []
4957
4875
  );
4958
- const ephemeralPair = await import_crypto.default.subtle.generateKey(
4876
+ const ephemeralPair = await import_crypto2.default.subtle.generateKey(
4959
4877
  { name: "ECDH", namedCurve: "P-256" },
4960
4878
  true,
4961
4879
  ["deriveBits"]
4962
4880
  );
4963
- const sharedBits = await import_crypto.default.subtle.deriveBits(
4881
+ const sharedBits = await import_crypto2.default.subtle.deriveBits(
4964
4882
  { name: "ECDH", public: recipientKey },
4965
4883
  ephemeralPair.privateKey,
4966
4884
  256
4967
4885
  );
4968
- const hkdfSaltBytes = import_crypto.default.getRandomValues(new Uint8Array(32));
4969
- const hkdfKey = await import_crypto.default.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
4970
- const aesKeyBits = await import_crypto.default.subtle.deriveBits(
4886
+ const hkdfSaltBytes = import_crypto2.default.getRandomValues(new Uint8Array(32));
4887
+ const hkdfKey = await import_crypto2.default.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
4888
+ const aesKeyBits = await import_crypto2.default.subtle.deriveBits(
4971
4889
  { name: "HKDF", hash: "SHA-256", salt: hkdfSaltBytes, info },
4972
4890
  hkdfKey,
4973
4891
  256
4974
4892
  );
4975
- const aesKey = await import_crypto.default.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["encrypt"]);
4976
- const ivBytes = import_crypto.default.getRandomValues(new Uint8Array(12));
4977
- const ciphertextBuf = await import_crypto.default.subtle.encrypt(
4893
+ const aesKey = await import_crypto2.default.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["encrypt"]);
4894
+ const ivBytes = import_crypto2.default.getRandomValues(new Uint8Array(12));
4895
+ const ciphertextBuf = await import_crypto2.default.subtle.encrypt(
4978
4896
  { name: "AES-GCM", iv: ivBytes, tagLength: 128 },
4979
4897
  aesKey,
4980
4898
  plaintextBytes
4981
4899
  );
4982
- const ephemeralPublicKeyRaw = await import_crypto.default.subtle.exportKey("raw", ephemeralPair.publicKey);
4900
+ const ephemeralPublicKeyRaw = await import_crypto2.default.subtle.exportKey("raw", ephemeralPair.publicKey);
4983
4901
  return {
4984
4902
  ephemeralPublicKey: Buffer.from(ephemeralPublicKeyRaw).toString("base64"),
4985
4903
  iv: Buffer.from(ivBytes).toString("base64"),
@@ -5028,7 +4946,7 @@ async function confirmUpdate(opts2) {
5028
4946
  ...memberName !== void 0 ? { member_name: memberName } : {}
5029
4947
  });
5030
4948
  const timestamp = String(Math.floor(Date.now() / 1e3));
5031
- const signature = import_crypto.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
4949
+ const signature = import_crypto2.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
5032
4950
  let base = appBaseUrl;
5033
4951
  while (base.endsWith("/")) base = base.slice(0, -1);
5034
4952
  let res;
@@ -5056,31 +4974,9 @@ async function confirmUpdate(opts2) {
5056
4974
  }
5057
4975
  return { ok: false, status: res.status, error };
5058
4976
  }
5059
- function allowedLoaHosts() {
5060
- const hosts = ["oneaddress.io", "app.oneaddress.io"];
5061
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5062
- hosts.push("localhost", "127.0.0.1");
5063
- }
5064
- return new Set(hosts);
5065
- }
5066
4977
  async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
5067
- let parsedBase;
5068
- try {
5069
- parsedBase = new URL(appBaseUrl);
5070
- } catch {
5071
- throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
5072
- }
5073
- const allowedHosts = allowedLoaHosts();
5074
- if (!allowedHosts.has(parsedBase.hostname)) {
5075
- throw new Error(
5076
- `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
5077
- );
5078
- }
5079
- const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
5080
- if (parsedBase.protocol !== "https:" && !loopback) {
5081
- throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
5082
- }
5083
- const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
4978
+ const origin = resolveAppOrigin(appBaseUrl, "fetchLoaPublicKey");
4979
+ const url = `${origin}/.well-known/oneaddress-loa-key.pem`;
5084
4980
  const res = await fetch(url);
5085
4981
  if (!res.ok) {
5086
4982
  throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
@@ -5096,7 +4992,7 @@ async function verifyLOA(loa, publicKeyPem) {
5096
4992
  return false;
5097
4993
  }
5098
4994
  try {
5099
- const key = await import_crypto.default.subtle.importKey(
4995
+ const key = await import_crypto2.default.subtle.importKey(
5100
4996
  "spki",
5101
4997
  pemToBuffer(publicKeyPem),
5102
4998
  { name: "ECDSA", namedCurve: "P-256" },
@@ -5105,7 +5001,7 @@ async function verifyLOA(loa, publicKeyPem) {
5105
5001
  );
5106
5002
  const sigBytes = Buffer.from(loa.signature, "hex");
5107
5003
  const textBytes = new TextEncoder().encode(loa.text);
5108
- return await import_crypto.default.subtle.verify(
5004
+ return await import_crypto2.default.subtle.verify(
5109
5005
  { name: "ECDSA", hash: "SHA-256" },
5110
5006
  key,
5111
5007
  sigBytes,
@@ -5128,7 +5024,7 @@ function toB64Url(buf) {
5128
5024
  return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
5129
5025
  }
5130
5026
  function d5LoaRef(loa) {
5131
- return toB64Url(import_crypto.default.createHash("sha256").update(canonicalD5LoaForm(loa), "utf8").digest());
5027
+ return toB64Url(import_crypto2.default.createHash("sha256").update(canonicalD5LoaForm(loa), "utf8").digest());
5132
5028
  }
5133
5029
  async function verifyD5LOA(loa, publicKeyPem) {
5134
5030
  if (loa.signature_algorithm !== "ECDSA-P256") {
@@ -5139,14 +5035,14 @@ async function verifyD5LOA(loa, publicKeyPem) {
5139
5035
  return false;
5140
5036
  }
5141
5037
  try {
5142
- const key = await import_crypto.default.subtle.importKey(
5038
+ const key = await import_crypto2.default.subtle.importKey(
5143
5039
  "spki",
5144
5040
  pemToBuffer(publicKeyPem),
5145
5041
  { name: "ECDSA", namedCurve: "P-256" },
5146
5042
  false,
5147
5043
  ["verify"]
5148
5044
  );
5149
- return await import_crypto.default.subtle.verify(
5045
+ return await import_crypto2.default.subtle.verify(
5150
5046
  { name: "ECDSA", hash: "SHA-256" },
5151
5047
  key,
5152
5048
  Buffer.from(loa.oneaddress_signature, "hex"),
@@ -5309,6 +5205,21 @@ var InvalidUpdateTypesError = class extends Error {
5309
5205
  this.name = "InvalidUpdateTypesError";
5310
5206
  }
5311
5207
  };
5208
+ var MissingKeyError = class extends Error {
5209
+ constructor(keyId) {
5210
+ super(`[OneAddress SDK] no private key for key_id ${keyId}`);
5211
+ this.keyId = keyId;
5212
+ this.name = "MissingKeyError";
5213
+ }
5214
+ };
5215
+ var SessionDecryptError = class extends Error {
5216
+ constructor(keyId, detail) {
5217
+ super(`[OneAddress SDK] session decrypt failed${keyId ? ` for key_id ${keyId}` : ""}`);
5218
+ this.keyId = keyId;
5219
+ this.detail = detail;
5220
+ this.name = "SessionDecryptError";
5221
+ }
5222
+ };
5312
5223
  function requireContactValue(kind, value) {
5313
5224
  if (typeof value !== "string" || value === "") {
5314
5225
  throw new Error(
@@ -5336,7 +5247,7 @@ function assertUsablePrivateKey(privateKeyPem) {
5336
5247
  const der = pemToBuffer(privateKeyPem);
5337
5248
  if (der.length === XWING_SEED_BYTES) return;
5338
5249
  try {
5339
- import_crypto.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5250
+ import_crypto2.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5340
5251
  } catch (err) {
5341
5252
  const refused = new Error(
5342
5253
  `[OneAddress SDK] privateKeyPem does not import as a PKCS#8 private key (${err instanceof Error ? err.message : String(err)}). Paste the whole key including the BEGIN/END lines; a key stored as one line with literal \\n sequences is accepted, a truncated one is not.`
@@ -5422,7 +5333,14 @@ function createOneAddressHandler(options) {
5422
5333
  }
5423
5334
  async function buildD5Pieces(body, partnerId) {
5424
5335
  const share = body.session_key_share;
5425
- const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
5336
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
5337
+ if (keyId && shareKeyId && shareKeyId !== keyId) throw new MissingKeyError(shareKeyId);
5338
+ let data;
5339
+ try {
5340
+ data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
5341
+ } catch (err) {
5342
+ throw new SessionDecryptError(shareKeyId, err instanceof Error ? err.message : String(err));
5343
+ }
5426
5344
  const updateTypes = readUpdateTypes(data.update_types);
5427
5345
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
5428
5346
  const address = updateTypes.includes("address") ? validateAddress({
@@ -5555,6 +5473,22 @@ function createOneAddressHandler(options) {
5555
5473
  detail: "update_types must be an array of " + UPDATE_TYPE_ORDER.join("|") + ". A name this build does not know was refused rather than dropped. Update @oneaddress/partner-sdk."
5556
5474
  });
5557
5475
  }
5476
+ if (err instanceof MissingKeyError) {
5477
+ console.error("[OneAddress SDK] Handler error:", err.message);
5478
+ return declared(503, {
5479
+ error: "missing_key",
5480
+ key_id: err.keyId,
5481
+ detail: "This receiver is configured for a different key_id and holds no private key for the one this dispatch names. Retry once the key is installed. If the key was retired and destroyed before its destroy_after date, it cannot be recovered from either side."
5482
+ });
5483
+ }
5484
+ if (err instanceof SessionDecryptError) {
5485
+ console.error("[OneAddress SDK] Handler error:", err.detail);
5486
+ return declared(422, {
5487
+ error: "decrypt_failed",
5488
+ ...err.keyId ? { key_id: err.keyId } : {},
5489
+ detail: err.detail
5490
+ });
5491
+ }
5558
5492
  throw err;
5559
5493
  }
5560
5494
  const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));