@oneaddress/partner-sdk 2.6.0 → 2.8.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/index.js CHANGED
@@ -87,6 +87,9 @@ 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
+ }
90
93
  function byteSwap(word) {
91
94
  return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
92
95
  }
@@ -280,6 +283,16 @@ function numberToBytesBE(n, len) {
280
283
  function numberToBytesLE(n, len) {
281
284
  return numberToBytesBE(n, len).reverse();
282
285
  }
286
+ function equalBytes(a, b) {
287
+ a = abytes2(a);
288
+ b = abytes2(b);
289
+ if (a.length !== b.length)
290
+ return false;
291
+ let diff = 0;
292
+ for (let i = 0; i < a.length; i++)
293
+ diff |= a[i] ^ b[i];
294
+ return diff === 0;
295
+ }
283
296
  function copyBytes(bytes) {
284
297
  return Uint8Array.from(abytes2(bytes));
285
298
  }
@@ -329,7 +342,7 @@ function validateObject(object, fields = {}, optFields = {}, title = "object") {
329
342
  iter(fields, false);
330
343
  iter(optFields, true);
331
344
  }
332
- var abytes2, anumber2, bytesToHex2, concatBytes2, hexToBytes2, isBytes2, randomBytes2, _0n, _1n, atitle2, bitMask;
345
+ var abytes2, anumber2, bytesToHex2, concatBytes2, hexToBytes2, isBytes2, randomBytes2, _0n, _1n, atitle2, bitMask, notImplemented;
333
346
  var init_utils2 = __esm({
334
347
  "../../node_modules/@noble/curves/utils.js"() {
335
348
  "use strict";
@@ -348,6 +361,9 @@ var init_utils2 = __esm({
348
361
  asafenumber(n, "n");
349
362
  return (_1n << BigInt(n)) - _1n;
350
363
  };
364
+ notImplemented = () => {
365
+ throw new Error("not implemented");
366
+ };
351
367
  }
352
368
  });
353
369
 
@@ -435,8 +451,19 @@ function invert(number, modulo) {
435
451
  throw new Error("invert: does not exist");
436
452
  return mod(x, modulo);
437
453
  }
438
- function assertIsSquare(Fp, root, n) {
439
- const F2 = Fp;
454
+ function invertCt(a, prime) {
455
+ if (prime <= _1n2)
456
+ throw new Error("invertCt: expected prime modulus > 1, got " + prime);
457
+ const an = mod(a, prime);
458
+ if (an === _0n2)
459
+ throw new Error("invertCt: expected non-zero number");
460
+ const inverse = pow(an, prime - _2n, prime);
461
+ if (mod(an * inverse, prime) !== _1n2)
462
+ throw new Error("invertCt: does not exist");
463
+ return inverse;
464
+ }
465
+ function assertIsSquare(Fp2, root, n) {
466
+ const F2 = Fp2;
440
467
  if (!F2.eql(F2.sqr(root), n))
441
468
  throw new Error("Cannot find square root");
442
469
  }
@@ -444,15 +471,15 @@ function aoddModulus(order, fnName) {
444
471
  if ((order & _1n2) === _0n2)
445
472
  throw new Error(fnName + ": expected odd modulus, got " + order);
446
473
  }
447
- function sqrt3mod4(Fp, n) {
448
- const F2 = Fp;
474
+ function sqrt3mod4(Fp2, n) {
475
+ const F2 = Fp2;
449
476
  const p1div4 = (F2.ORDER + _1n2) / _4n;
450
477
  const root = F2.pow(n, p1div4);
451
478
  assertIsSquare(F2, root, n);
452
479
  return root;
453
480
  }
454
- function sqrt5mod8(Fp, n) {
455
- const F2 = Fp;
481
+ function sqrt5mod8(Fp2, n) {
482
+ const F2 = Fp2;
456
483
  const p5div8 = (F2.ORDER - _5n) / _8n;
457
484
  const n2 = F2.mul(n, _2n);
458
485
  const v = F2.pow(n2, p5div8);
@@ -469,8 +496,8 @@ function sqrt9mod16(P) {
469
496
  const c2 = tn(Fp_, c1);
470
497
  const c3 = tn(Fp_, Fp_.neg(c1));
471
498
  const c4 = (P + _7n) / _16n;
472
- return ((Fp, n) => {
473
- const F2 = Fp;
499
+ return ((Fp2, n) => {
500
+ const F2 = Fp2;
474
501
  let tv1 = F2.pow(n, c4);
475
502
  let tv2 = F2.mul(tv1, c1);
476
503
  const tv3 = F2.mul(tv1, c2);
@@ -505,8 +532,8 @@ function tonelliShanks(P) {
505
532
  return sqrt3mod4;
506
533
  let cc = _Fp.pow(Z, Q2);
507
534
  const Q1div2 = (Q2 + _1n2) / _2n;
508
- return function tonelliSlow(Fp, n) {
509
- const F2 = Fp;
535
+ return function tonelliSlow(Fp2, n) {
536
+ const F2 = Fp2;
510
537
  if (F2.is0(n))
511
538
  return n;
512
539
  if (FpLegendre(F2, n) !== 1)
@@ -560,11 +587,11 @@ function validateField(field) {
560
587
  throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
561
588
  return field;
562
589
  }
563
- function FpInvertBatch(Fp, nums, passZero = false) {
564
- validateField(Fp);
590
+ function FpInvertBatch(Fp2, nums, passZero = false) {
591
+ validateField(Fp2);
565
592
  aarray(nums, "nums");
566
593
  abool2(passZero, "passZero");
567
- const F2 = Fp;
594
+ const F2 = Fp2;
568
595
  const inverted = new Array(nums.length).fill(passZero ? F2.ZERO : void 0);
569
596
  const multipliedAcc = nums.reduce((acc, num, i) => {
570
597
  if (F2.is0(num))
@@ -581,9 +608,9 @@ function FpInvertBatch(Fp, nums, passZero = false) {
581
608
  }, invertedAcc);
582
609
  return inverted;
583
610
  }
584
- function FpLegendre(Fp, n) {
585
- validateField(Fp);
586
- const F2 = Fp;
611
+ function FpLegendre(Fp2, n) {
612
+ validateField(Fp2);
613
+ const F2 = Fp2;
587
614
  aoddModulus(F2.ORDER, "FpLegendre");
588
615
  const p1mod2 = (F2.ORDER - _1n2) / _2n;
589
616
  const powered = F2.pow(n, p1mod2);
@@ -612,6 +639,29 @@ function Field(ORDER, opts2 = {}) {
612
639
  Object.freeze(_Field.prototype);
613
640
  return new _Field(ORDER, opts2);
614
641
  }
642
+ function getFieldBytesLength(fieldOrder) {
643
+ if (typeof fieldOrder !== "bigint")
644
+ throw new Error("field order must be bigint");
645
+ if (fieldOrder <= _1n2)
646
+ throw new Error("field order must be greater than 1");
647
+ const bitLength = bitLen(fieldOrder - _1n2);
648
+ return Math.ceil(bitLength / 8);
649
+ }
650
+ function getMinHashLength(fieldOrder) {
651
+ const length = getFieldBytesLength(fieldOrder);
652
+ return length + Math.ceil(length / 2);
653
+ }
654
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
655
+ abytes2(key);
656
+ const len = key.length;
657
+ const fieldLen = getFieldBytesLength(fieldOrder);
658
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
659
+ if (len < minLen || len > 1024)
660
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
661
+ const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
662
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
663
+ return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
664
+ }
615
665
  var _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _15n, _16n, POW_WINDOWED_MIN, isNegativeLE, FIELD_FIELDS, FIELD_SQRT, _Field;
616
666
  var init_modular = __esm({
617
667
  "../../node_modules/@noble/curves/abstract/modular.js"() {
@@ -943,16 +993,16 @@ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
943
993
  if (!(isPosBig(val) && val !== _0n3))
944
994
  throw new Error(`CURVE.${p} must be positive bigint`);
945
995
  }
946
- const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
947
- const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
996
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
997
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
948
998
  const _b = type === "weierstrass" ? "b" : "d";
949
999
  const params = ["Gx", "Gy", "a", _b];
950
1000
  for (const p of params) {
951
- if (!Fp.isValid(CURVE[p]))
1001
+ if (!Fp2.isValid(CURVE[p]))
952
1002
  throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
953
1003
  }
954
1004
  CURVE = Object.freeze(Object.assign({}, CURVE));
955
- return { CURVE, Fp, Fn };
1005
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
956
1006
  }
957
1007
  function createKeygen(randomSecretKey, getPublicKey) {
958
1008
  return function keygen(seed) {
@@ -1183,42 +1233,42 @@ var init_curve = __esm({
1183
1233
  });
1184
1234
 
1185
1235
  // ../../node_modules/@noble/curves/abstract/edwards.js
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);
1236
+ function isEdValidXY(Fp2, CURVE, x, y) {
1237
+ const x2 = Fp2.sqr(x);
1238
+ const y2 = Fp2.sqr(y);
1239
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
1240
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
1241
+ return Fp2.eql(left, right);
1192
1242
  }
1193
1243
  function edwards(params, extraOpts = {}) {
1194
1244
  validateObject(extraOpts, {}, {}, "extraOpts");
1195
1245
  const opts2 = extraOpts;
1196
1246
  const validated = createCurveFields("edwards", params, opts2, opts2.FpFnLE);
1197
- const { Fp, Fn } = validated;
1247
+ const { Fp: Fp2, Fn: Fn2 } = validated;
1198
1248
  let CURVE = validated.CURVE;
1199
1249
  const { h: cofactor } = CURVE;
1200
- if (FpLegendre(Fp, CURVE.a) !== 1)
1250
+ if (FpLegendre(Fp2, CURVE.a) !== 1)
1201
1251
  throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
1202
- if (FpLegendre(Fp, CURVE.d) !== -1)
1252
+ if (FpLegendre(Fp2, CURVE.d) !== -1)
1203
1253
  throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
1204
1254
  validateObject(opts2, {}, { uvRatio: "function", randomBytes: "function" });
1205
1255
  const randomBytes5 = opts2.randomBytes === void 0 ? randomBytes2 : opts2.randomBytes;
1206
- const MASK = _2n2 << BigInt(Fp.BYTES * 8) - _1n4;
1256
+ const MASK = _2n2 << BigInt(Fp2.BYTES * 8) - _1n4;
1207
1257
  function isOdd(n) {
1208
- if (!Fp.isOdd)
1258
+ if (!Fp2.isOdd)
1209
1259
  throw new Error("Field does not have .isOdd()");
1210
- return Fp.isOdd(n);
1260
+ return Fp2.isOdd(n);
1211
1261
  }
1212
1262
  const uvRatio2 = opts2.uvRatio === void 0 ? (u, v) => {
1213
1263
  try {
1214
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
1264
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
1215
1265
  } catch (e) {
1216
1266
  return { isValid: false, value: _0n4 };
1217
1267
  }
1218
1268
  } : opts2.uvRatio;
1219
- if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
1269
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1220
1270
  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);
1271
+ const mulA = Fp2.eql(CURVE.a, Fp2.neg(Fp2.ONE)) ? (x) => Fp2.neg(x) : Fp2.eql(CURVE.a, Fp2.ONE) ? (x) => x : (x) => Fp2.mul(CURVE.a, x);
1222
1272
  function acoord(title, n, banZero = false) {
1223
1273
  const min = banZero ? _1n4 : _0n4;
1224
1274
  aInRange("coordinate " + title, n, min, MASK);
@@ -1254,11 +1304,11 @@ function edwards(params, extraOpts = {}) {
1254
1304
  const { x, y } = p || {};
1255
1305
  acoord("x", x);
1256
1306
  acoord("y", y);
1257
- return new _Point(x, y, Fp.ONE, Fp.mul(x, y));
1307
+ return new _Point(x, y, Fp2.ONE, Fp2.mul(x, y));
1258
1308
  }
1259
1309
  // Uses algo from RFC8032 5.1.3.
1260
1310
  static fromBytes(bytes, zip215 = false) {
1261
- const len = Fp.BYTES;
1311
+ const len = Fp2.BYTES;
1262
1312
  const { a, d } = CURVE;
1263
1313
  bytes = copyBytes(abytes2(bytes, len, "point"));
1264
1314
  abool2(zip215, "zip215");
@@ -1266,20 +1316,20 @@ function edwards(params, extraOpts = {}) {
1266
1316
  const lastByte = bytes[len - 1];
1267
1317
  normed[len - 1] = lastByte & ~128;
1268
1318
  const y = bytesToNumberLE(normed);
1269
- const max = zip215 ? MASK : Fp.ORDER;
1319
+ const max = zip215 ? MASK : Fp2.ORDER;
1270
1320
  aInRange("point.y", y, _0n4, max);
1271
- const y2 = Fp.sqr(y);
1272
- const u = Fp.sub(y2, Fp.ONE);
1273
- const v = Fp.sub(Fp.mulN(d, y2), a);
1321
+ const y2 = Fp2.sqr(y);
1322
+ const u = Fp2.sub(y2, Fp2.ONE);
1323
+ const v = Fp2.sub(Fp2.mulN(d, y2), a);
1274
1324
  let { isValid, value: x } = uvRatio2(u, v);
1275
1325
  if (!isValid)
1276
1326
  throw new Error("bad point: invalid y coordinate");
1277
1327
  const isXOdd = isOdd(x);
1278
1328
  const isLastByteOdd = (lastByte & 128) !== 0;
1279
- if (!zip215 && Fp.is0(x) && isLastByteOdd)
1329
+ if (!zip215 && Fp2.is0(x) && isLastByteOdd)
1280
1330
  throw new Error("bad point: x=0 and x_0=1");
1281
1331
  if (isLastByteOdd !== isXOdd)
1282
- x = Fp.neg(x);
1332
+ x = Fp2.neg(x);
1283
1333
  return _Point.fromAffine({ x, y });
1284
1334
  }
1285
1335
  static fromHex(hex, zip215 = false) {
@@ -1304,18 +1354,18 @@ function edwards(params, extraOpts = {}) {
1304
1354
  if (p.is0())
1305
1355
  throw new Error("bad point: ZERO");
1306
1356
  const { X, Y, Z, T } = p;
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))
1357
+ const X2 = Fp2.sqr(X);
1358
+ const Y2 = Fp2.sqr(Y);
1359
+ const Z2 = Fp2.sqr(Z);
1360
+ const Z4 = Fp2.sqr(Z2);
1361
+ const aX2 = Fp2.mul(X2, a);
1362
+ const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
1363
+ const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
1364
+ if (!Fp2.eql(left, right))
1315
1365
  throw new Error("bad point: equation left != right (1)");
1316
- const XY = Fp.mul(X, Y);
1317
- const ZT = Fp.mul(Z, T);
1318
- if (!Fp.eql(XY, ZT))
1366
+ const XY = Fp2.mul(X, Y);
1367
+ const ZT = Fp2.mul(Z, T);
1368
+ if (!Fp2.eql(XY, ZT))
1319
1369
  throw new Error("bad point: equation left != right (2)");
1320
1370
  }
1321
1371
  // Compare one point to another.
@@ -1323,36 +1373,36 @@ function edwards(params, extraOpts = {}) {
1323
1373
  aedpoint(other);
1324
1374
  const { X: X1, Y: Y1, Z: Z1 } = this;
1325
1375
  const { X: X2, Y: Y2, Z: Z2 } = other;
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);
1376
+ const X1Z2 = Fp2.mul(X1, Z2);
1377
+ const X2Z1 = Fp2.mul(X2, Z1);
1378
+ const Y1Z2 = Fp2.mul(Y1, Z2);
1379
+ const Y2Z1 = Fp2.mul(Y2, Z1);
1380
+ return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
1331
1381
  }
1332
1382
  is0() {
1333
1383
  return this.equals(_Point.ZERO);
1334
1384
  }
1335
1385
  negate() {
1336
- return new _Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));
1386
+ return new _Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
1337
1387
  }
1338
1388
  // Fast algo for doubling Extended Point.
1339
1389
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1340
1390
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
1341
1391
  double() {
1342
1392
  const { X: X1, Y: Y1, Z: Z1 } = this;
1343
- const A = Fp.sqr(X1);
1344
- const B2 = Fp.sqr(Y1);
1345
- const C = Fp.mul(Fp.sqr(Z1), _2n2);
1393
+ const A = Fp2.sqr(X1);
1394
+ const B2 = Fp2.sqr(Y1);
1395
+ const C = Fp2.mul(Fp2.sqr(Z1), _2n2);
1346
1396
  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);
1397
+ const x1y1 = Fp2.addN(X1, Y1);
1398
+ const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B2);
1399
+ const G = Fp2.addN(D, B2);
1400
+ const F2 = Fp2.subN(G, C);
1401
+ const H = Fp2.subN(D, B2);
1402
+ const X3 = Fp2.mul(E, F2);
1403
+ const Y3 = Fp2.mul(G, H);
1404
+ const T3 = Fp2.mul(E, H);
1405
+ const Z3 = Fp2.mul(F2, G);
1356
1406
  return new _Point(X3, Y3, Z3, T3);
1357
1407
  }
1358
1408
  // Fast algo for adding 2 Extended Points.
@@ -1363,18 +1413,18 @@ function edwards(params, extraOpts = {}) {
1363
1413
  const { d } = CURVE;
1364
1414
  const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1365
1415
  const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
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);
1416
+ const A = Fp2.mul(X1, X2);
1417
+ const B2 = Fp2.mul(Y1, Y2);
1418
+ const C = Fp2.mul(Fp2.mulN(T1, d), T2);
1419
+ const D = Fp2.mul(Z1, Z2);
1420
+ const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B2);
1421
+ const F2 = Fp2.subN(D, C);
1422
+ const G = Fp2.addN(D, C);
1423
+ const H = Fp2.sub(B2, mulA(A));
1424
+ const X3 = Fp2.mul(E, F2);
1425
+ const Y3 = Fp2.mul(G, H);
1426
+ const T3 = Fp2.mul(E, H);
1427
+ const Z3 = Fp2.mul(F2, G);
1378
1428
  return new _Point(X3, Y3, Z3, T3);
1379
1429
  }
1380
1430
  subtract(other) {
@@ -1383,7 +1433,7 @@ function edwards(params, extraOpts = {}) {
1383
1433
  }
1384
1434
  // Constant-time multiplication.
1385
1435
  multiply(scalar) {
1386
- if (!Fn.isValidNot0(scalar))
1436
+ if (!Fn2.isValidNot0(scalar))
1387
1437
  throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1388
1438
  const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
1389
1439
  return normalize([p, f])[0];
@@ -1394,7 +1444,7 @@ function edwards(params, extraOpts = {}) {
1394
1444
  // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1395
1445
  // n and larger values are rejected instead of being reduced mod n to the identity point.
1396
1446
  multiplyUnsafe(scalar) {
1397
- if (!Fn.isValid(scalar))
1447
+ if (!Fn2.isValid(scalar))
1398
1448
  throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1399
1449
  if (scalar === _0n4)
1400
1450
  return _Point.ZERO;
@@ -1424,13 +1474,13 @@ function edwards(params, extraOpts = {}) {
1424
1474
  const { X, Y, Z } = p;
1425
1475
  const is0 = p.is0();
1426
1476
  if (iz == null)
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);
1477
+ iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
1478
+ const x = Fp2.mul(X, iz);
1479
+ const y = Fp2.mul(Y, iz);
1480
+ const zz = Fp2.mul(Z, iz);
1431
1481
  if (is0)
1432
- return { x: Fp.ZERO, y: Fp.ONE };
1433
- if (!Fp.eql(zz, Fp.ONE))
1482
+ return { x: Fp2.ZERO, y: Fp2.ONE };
1483
+ if (!Fp2.eql(zz, Fp2.ONE))
1434
1484
  throw new Error("invZ was invalid");
1435
1485
  return { x, y };
1436
1486
  }
@@ -1447,7 +1497,7 @@ function edwards(params, extraOpts = {}) {
1447
1497
  }
1448
1498
  toBytes() {
1449
1499
  const { x, y } = this.toAffine();
1450
- const bytes = Fp.toBytes(y);
1500
+ const bytes = Fp2.toBytes(y);
1451
1501
  bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
1452
1502
  return bytes;
1453
1503
  }
@@ -1458,10 +1508,10 @@ function edwards(params, extraOpts = {}) {
1458
1508
  return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1459
1509
  }
1460
1510
  };
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);
1511
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy)));
1512
+ __publicField(_Point, "ZERO", new _Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO));
1513
+ __publicField(_Point, "Fp", Fp2);
1514
+ __publicField(_Point, "Fn", Fn2);
1465
1515
  let Point = _Point;
1466
1516
  const normalize = (points) => normalizeZ(Point, points);
1467
1517
  const wnaf = new ScalarMultiplier(Point, randomBytes5);
@@ -1471,7 +1521,7 @@ function edwards(params, extraOpts = {}) {
1471
1521
  Object.freeze(Point);
1472
1522
  return Point;
1473
1523
  }
1474
- var _0n4, _1n4, _2n2, _4n3, _8n2;
1524
+ var _0n4, _1n4, _2n2, _4n3, _8n2, PrimeEdwardsPoint;
1475
1525
  var init_edwards = __esm({
1476
1526
  "../../node_modules/@noble/curves/abstract/edwards.js"() {
1477
1527
  "use strict";
@@ -1483,6 +1533,86 @@ var init_edwards = __esm({
1483
1533
  _2n2 = /* @__PURE__ */ BigInt(2);
1484
1534
  _4n3 = /* @__PURE__ */ BigInt(4);
1485
1535
  _8n2 = /* @__PURE__ */ BigInt(8);
1536
+ PrimeEdwardsPoint = class {
1537
+ /**
1538
+ * Wrap one internal Edwards representative directly.
1539
+ * This is not a canonical encoding boundary: alternate Edwards
1540
+ * representatives may still describe the same abstract wrapper element.
1541
+ */
1542
+ constructor(ep) {
1543
+ __publicField(this, "ep");
1544
+ this.ep = ep;
1545
+ }
1546
+ // Static methods that must be implemented by subclasses
1547
+ static fromBytes(_bytes) {
1548
+ notImplemented();
1549
+ }
1550
+ static fromHex(_hex) {
1551
+ notImplemented();
1552
+ }
1553
+ get x() {
1554
+ return this.toAffine().x;
1555
+ }
1556
+ get y() {
1557
+ return this.toAffine().y;
1558
+ }
1559
+ // Common implementations
1560
+ clearCofactor() {
1561
+ return this;
1562
+ }
1563
+ assertValidity() {
1564
+ this.ep.assertValidity();
1565
+ }
1566
+ /**
1567
+ * Return affine coordinates of the current internal Edwards representative.
1568
+ * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1569
+ * Equal abstract elements may expose different `x` / `y`; use
1570
+ * `toBytes()` / `fromBytes()` for canonical roundtrips.
1571
+ */
1572
+ toAffine(invertedZ) {
1573
+ return this.ep.toAffine(invertedZ);
1574
+ }
1575
+ toHex() {
1576
+ return bytesToHex2(this.toBytes());
1577
+ }
1578
+ toString() {
1579
+ return this.toHex();
1580
+ }
1581
+ isTorsionFree() {
1582
+ return true;
1583
+ }
1584
+ isSmallOrder() {
1585
+ return false;
1586
+ }
1587
+ add(other) {
1588
+ this.assertSame(other);
1589
+ return this.init(this.ep.add(other.ep));
1590
+ }
1591
+ subtract(other) {
1592
+ this.assertSame(other);
1593
+ return this.init(this.ep.subtract(other.ep));
1594
+ }
1595
+ multiply(scalar) {
1596
+ return this.init(this.ep.multiply(scalar));
1597
+ }
1598
+ multiplyUnsafe(scalar) {
1599
+ return this.init(this.ep.multiplyUnsafe(scalar));
1600
+ }
1601
+ double() {
1602
+ return this.init(this.ep.double());
1603
+ }
1604
+ negate() {
1605
+ return this.init(this.ep.negate());
1606
+ }
1607
+ precompute(windowSize, isLazy) {
1608
+ this.ep.precompute(windowSize, isLazy);
1609
+ return this;
1610
+ }
1611
+ };
1612
+ __publicField(PrimeEdwardsPoint, "BASE");
1613
+ __publicField(PrimeEdwardsPoint, "ZERO");
1614
+ __publicField(PrimeEdwardsPoint, "Fp");
1615
+ __publicField(PrimeEdwardsPoint, "Fn");
1486
1616
  }
1487
1617
  });
1488
1618
 
@@ -1658,12 +1788,402 @@ function split(lst, le = false) {
1658
1788
  }
1659
1789
  return [Ah, Al];
1660
1790
  }
1661
- var U32_MASK64, _32n;
1791
+ function setU64FromNum(view, byteOffset, n, isLE2) {
1792
+ const h = fromNumH(n);
1793
+ const l = fromNumL(n);
1794
+ view.setUint32(byteOffset, isLE2 ? l : h, isLE2);
1795
+ view.setUint32(byteOffset + 4, isLE2 ? h : l, isLE2);
1796
+ }
1797
+ function add(Ah, Al, Bh, Bl) {
1798
+ const l = (Al >>> 0) + (Bl >>> 0);
1799
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1800
+ }
1801
+ var U32_MASK64, _32n, fromNumH, fromNumL, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, add3L, add3H, add4L, add4H, add5L, add5H;
1662
1802
  var init_u64 = __esm({
1663
1803
  "../../node_modules/@noble/hashes/_u64.js"() {
1664
1804
  "use strict";
1665
1805
  U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
1666
1806
  _32n = /* @__PURE__ */ BigInt(32);
1807
+ fromNumH = (n) => n / 2 ** 32 | 0;
1808
+ fromNumL = (n) => n >>> 0;
1809
+ shrSH = (h, _l, s) => h >>> s;
1810
+ shrSL = (h, l, s) => h << 32 - s | l >>> s;
1811
+ rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1812
+ rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1813
+ rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1814
+ rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1815
+ add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1816
+ add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1817
+ add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1818
+ add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1819
+ add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1820
+ add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1821
+ }
1822
+ });
1823
+
1824
+ // ../../node_modules/@noble/hashes/_md.js
1825
+ var HashMD, SHA512_IV;
1826
+ var init_md = __esm({
1827
+ "../../node_modules/@noble/hashes/_md.js"() {
1828
+ "use strict";
1829
+ init_u64();
1830
+ init_utils();
1831
+ HashMD = class {
1832
+ constructor(blockLen, outputLen, padOffset, isLE2) {
1833
+ __publicField(this, "blockLen");
1834
+ __publicField(this, "outputLen");
1835
+ __publicField(this, "canXOF", false);
1836
+ __publicField(this, "padOffset");
1837
+ __publicField(this, "isLE");
1838
+ // For partial updates less than block size
1839
+ __publicField(this, "buffer");
1840
+ __publicField(this, "view");
1841
+ __publicField(this, "finished", false);
1842
+ __publicField(this, "length", 0);
1843
+ __publicField(this, "pos", 0);
1844
+ __publicField(this, "destroyed", false);
1845
+ this.blockLen = blockLen;
1846
+ this.outputLen = outputLen;
1847
+ this.padOffset = padOffset;
1848
+ this.isLE = isLE2;
1849
+ this.buffer = new Uint8Array(blockLen);
1850
+ this.view = createView(this.buffer);
1851
+ }
1852
+ update(data) {
1853
+ aexists(this);
1854
+ abytes(data);
1855
+ const { view, buffer, blockLen } = this;
1856
+ const len = data.length;
1857
+ let processed = false;
1858
+ for (let pos = 0; pos < len; ) {
1859
+ const take = Math.min(blockLen - this.pos, len - pos);
1860
+ if (take === blockLen) {
1861
+ const dataView = createView(data);
1862
+ for (; blockLen <= len - pos; pos += blockLen)
1863
+ this.process(dataView, pos);
1864
+ processed = true;
1865
+ continue;
1866
+ }
1867
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
1868
+ this.pos += take;
1869
+ pos += take;
1870
+ if (this.pos === blockLen) {
1871
+ this.process(view, 0);
1872
+ this.pos = 0;
1873
+ processed = true;
1874
+ }
1875
+ }
1876
+ this.length += data.length;
1877
+ if (processed)
1878
+ this.roundClean();
1879
+ return this;
1880
+ }
1881
+ digestInto(out) {
1882
+ aexists(this);
1883
+ aoutput(out, this);
1884
+ this.finished = true;
1885
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
1886
+ let { pos } = this;
1887
+ buffer[pos++] = 128;
1888
+ buffer.fill(0, pos);
1889
+ if (this.padOffset > blockLen - pos) {
1890
+ this.process(view, 0);
1891
+ buffer.fill(0);
1892
+ }
1893
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE2);
1894
+ this.process(view, 0);
1895
+ this.roundClean();
1896
+ const oview = out === buffer ? view : createView(out);
1897
+ const len = this.outputLen;
1898
+ const outLen = len / 4;
1899
+ const state = this.get();
1900
+ if (len % 4 || outLen > state.length)
1901
+ throw new Error("invalid outputLen");
1902
+ for (let i = 0; i < outLen; i++)
1903
+ oview.setUint32(4 * i, state[i], isLE2);
1904
+ }
1905
+ digest() {
1906
+ const { buffer, outputLen } = this;
1907
+ this.digestInto(buffer);
1908
+ const res = buffer.slice(0, outputLen);
1909
+ this.destroy();
1910
+ return res;
1911
+ }
1912
+ _cloneIntoMeta(to) {
1913
+ const { buffer, length, finished, destroyed, pos } = this;
1914
+ to.destroyed = destroyed;
1915
+ to.finished = finished;
1916
+ to.length = length;
1917
+ to.pos = pos;
1918
+ if (pos)
1919
+ to.buffer.set(buffer);
1920
+ return to;
1921
+ }
1922
+ clone() {
1923
+ return this._cloneInto();
1924
+ }
1925
+ };
1926
+ SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1927
+ 1779033703,
1928
+ 4089235720,
1929
+ 3144134277,
1930
+ 2227873595,
1931
+ 1013904242,
1932
+ 4271175723,
1933
+ 2773480762,
1934
+ 1595750129,
1935
+ 1359893119,
1936
+ 2917565137,
1937
+ 2600822924,
1938
+ 725511199,
1939
+ 528734635,
1940
+ 4215389547,
1941
+ 1541459225,
1942
+ 327033209
1943
+ ]);
1944
+ }
1945
+ });
1946
+
1947
+ // ../../node_modules/@noble/hashes/sha2.js
1948
+ var K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA2_64B, _SHA512, sha512;
1949
+ var init_sha2 = __esm({
1950
+ "../../node_modules/@noble/hashes/sha2.js"() {
1951
+ "use strict";
1952
+ init_md();
1953
+ init_u64();
1954
+ init_utils();
1955
+ K512 = /* @__PURE__ */ (() => split([
1956
+ "0x428a2f98d728ae22",
1957
+ "0x7137449123ef65cd",
1958
+ "0xb5c0fbcfec4d3b2f",
1959
+ "0xe9b5dba58189dbbc",
1960
+ "0x3956c25bf348b538",
1961
+ "0x59f111f1b605d019",
1962
+ "0x923f82a4af194f9b",
1963
+ "0xab1c5ed5da6d8118",
1964
+ "0xd807aa98a3030242",
1965
+ "0x12835b0145706fbe",
1966
+ "0x243185be4ee4b28c",
1967
+ "0x550c7dc3d5ffb4e2",
1968
+ "0x72be5d74f27b896f",
1969
+ "0x80deb1fe3b1696b1",
1970
+ "0x9bdc06a725c71235",
1971
+ "0xc19bf174cf692694",
1972
+ "0xe49b69c19ef14ad2",
1973
+ "0xefbe4786384f25e3",
1974
+ "0x0fc19dc68b8cd5b5",
1975
+ "0x240ca1cc77ac9c65",
1976
+ "0x2de92c6f592b0275",
1977
+ "0x4a7484aa6ea6e483",
1978
+ "0x5cb0a9dcbd41fbd4",
1979
+ "0x76f988da831153b5",
1980
+ "0x983e5152ee66dfab",
1981
+ "0xa831c66d2db43210",
1982
+ "0xb00327c898fb213f",
1983
+ "0xbf597fc7beef0ee4",
1984
+ "0xc6e00bf33da88fc2",
1985
+ "0xd5a79147930aa725",
1986
+ "0x06ca6351e003826f",
1987
+ "0x142929670a0e6e70",
1988
+ "0x27b70a8546d22ffc",
1989
+ "0x2e1b21385c26c926",
1990
+ "0x4d2c6dfc5ac42aed",
1991
+ "0x53380d139d95b3df",
1992
+ "0x650a73548baf63de",
1993
+ "0x766a0abb3c77b2a8",
1994
+ "0x81c2c92e47edaee6",
1995
+ "0x92722c851482353b",
1996
+ "0xa2bfe8a14cf10364",
1997
+ "0xa81a664bbc423001",
1998
+ "0xc24b8b70d0f89791",
1999
+ "0xc76c51a30654be30",
2000
+ "0xd192e819d6ef5218",
2001
+ "0xd69906245565a910",
2002
+ "0xf40e35855771202a",
2003
+ "0x106aa07032bbd1b8",
2004
+ "0x19a4c116b8d2d0c8",
2005
+ "0x1e376c085141ab53",
2006
+ "0x2748774cdf8eeb99",
2007
+ "0x34b0bcb5e19b48a8",
2008
+ "0x391c0cb3c5c95a63",
2009
+ "0x4ed8aa4ae3418acb",
2010
+ "0x5b9cca4f7763e373",
2011
+ "0x682e6ff3d6b2b8a3",
2012
+ "0x748f82ee5defb2fc",
2013
+ "0x78a5636f43172f60",
2014
+ "0x84c87814a1f0ab72",
2015
+ "0x8cc702081a6439ec",
2016
+ "0x90befffa23631e28",
2017
+ "0xa4506cebde82bde9",
2018
+ "0xbef9a3f7b2c67915",
2019
+ "0xc67178f2e372532b",
2020
+ "0xca273eceea26619c",
2021
+ "0xd186b8c721c0c207",
2022
+ "0xeada7dd6cde0eb1e",
2023
+ "0xf57d4f7fee6ed178",
2024
+ "0x06f067aa72176fba",
2025
+ "0x0a637dc5a2c898a6",
2026
+ "0x113f9804bef90dae",
2027
+ "0x1b710b35131c471b",
2028
+ "0x28db77f523047d84",
2029
+ "0x32caab7b40c72493",
2030
+ "0x3c9ebe0a15c9bebc",
2031
+ "0x431d67c49c100d4c",
2032
+ "0x4cc5d4becb3e42b6",
2033
+ "0x597f299cfc657e2a",
2034
+ "0x5fcb6fab3ad6faec",
2035
+ "0x6c44198c4a475817"
2036
+ ].map((n) => BigInt(n))))();
2037
+ SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
2038
+ SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
2039
+ SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
2040
+ SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
2041
+ SHA2_64B = class extends HashMD {
2042
+ constructor(outputLen, IV) {
2043
+ super(128, outputLen, 16, false);
2044
+ // We cannot use array here since array allows indexing by variable
2045
+ // which means optimizer/compiler cannot use registers.
2046
+ // h -- high 32 bits, l -- low 32 bits
2047
+ // Numeric initializers matter: starting the fields as `undefined` changes
2048
+ // V8's field representation and slows hashing down (measured on sha256).
2049
+ __publicField(this, "Ah", 0);
2050
+ __publicField(this, "Al", 0);
2051
+ __publicField(this, "Bh", 0);
2052
+ __publicField(this, "Bl", 0);
2053
+ __publicField(this, "Ch", 0);
2054
+ __publicField(this, "Cl", 0);
2055
+ __publicField(this, "Dh", 0);
2056
+ __publicField(this, "Dl", 0);
2057
+ __publicField(this, "Eh", 0);
2058
+ __publicField(this, "El", 0);
2059
+ __publicField(this, "Fh", 0);
2060
+ __publicField(this, "Fl", 0);
2061
+ __publicField(this, "Gh", 0);
2062
+ __publicField(this, "Gl", 0);
2063
+ __publicField(this, "Hh", 0);
2064
+ __publicField(this, "Hl", 0);
2065
+ this.Ah = IV[0] | 0;
2066
+ this.Al = IV[1] | 0;
2067
+ this.Bh = IV[2] | 0;
2068
+ this.Bl = IV[3] | 0;
2069
+ this.Ch = IV[4] | 0;
2070
+ this.Cl = IV[5] | 0;
2071
+ this.Dh = IV[6] | 0;
2072
+ this.Dl = IV[7] | 0;
2073
+ this.Eh = IV[8] | 0;
2074
+ this.El = IV[9] | 0;
2075
+ this.Fh = IV[10] | 0;
2076
+ this.Fl = IV[11] | 0;
2077
+ this.Gh = IV[12] | 0;
2078
+ this.Gl = IV[13] | 0;
2079
+ this.Hh = IV[14] | 0;
2080
+ this.Hl = IV[15] | 0;
2081
+ }
2082
+ // prettier-ignore
2083
+ get() {
2084
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
2085
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
2086
+ }
2087
+ // prettier-ignore
2088
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
2089
+ this.Ah = Ah | 0;
2090
+ this.Al = Al | 0;
2091
+ this.Bh = Bh | 0;
2092
+ this.Bl = Bl | 0;
2093
+ this.Ch = Ch | 0;
2094
+ this.Cl = Cl | 0;
2095
+ this.Dh = Dh | 0;
2096
+ this.Dl = Dl | 0;
2097
+ this.Eh = Eh | 0;
2098
+ this.El = El | 0;
2099
+ this.Fh = Fh | 0;
2100
+ this.Fl = Fl | 0;
2101
+ this.Gh = Gh | 0;
2102
+ this.Gl = Gl | 0;
2103
+ this.Hh = Hh | 0;
2104
+ this.Hl = Hl | 0;
2105
+ }
2106
+ _cloneInto(to) {
2107
+ (to ||= new this.constructor()).set(...this.get());
2108
+ return this._cloneIntoMeta(to);
2109
+ }
2110
+ process(view, offset) {
2111
+ for (let i = 0; i < 16; i++, offset += 4) {
2112
+ SHA512_W_H[i] = view.getUint32(offset);
2113
+ SHA512_W_L[i] = view.getUint32(offset += 4);
2114
+ }
2115
+ for (let i = 16; i < 80; i++) {
2116
+ const W15h = SHA512_W_H[i - 15] | 0;
2117
+ const W15l = SHA512_W_L[i - 15] | 0;
2118
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
2119
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
2120
+ const W2h = SHA512_W_H[i - 2] | 0;
2121
+ const W2l = SHA512_W_L[i - 2] | 0;
2122
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
2123
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
2124
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
2125
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
2126
+ SHA512_W_H[i] = SUMh | 0;
2127
+ SHA512_W_L[i] = SUMl | 0;
2128
+ }
2129
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
2130
+ for (let i = 0; i < 80; i++) {
2131
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
2132
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
2133
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
2134
+ const CHIl = El & Fl ^ ~El & Gl;
2135
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
2136
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
2137
+ const T1l = T1ll | 0;
2138
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
2139
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
2140
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
2141
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
2142
+ Hh = Gh | 0;
2143
+ Hl = Gl | 0;
2144
+ Gh = Fh | 0;
2145
+ Gl = Fl | 0;
2146
+ Fh = Eh | 0;
2147
+ Fl = El | 0;
2148
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
2149
+ Dh = Ch | 0;
2150
+ Dl = Cl | 0;
2151
+ Ch = Bh | 0;
2152
+ Cl = Bl | 0;
2153
+ Bh = Ah | 0;
2154
+ Bl = Al | 0;
2155
+ const All = add3L(T1l, sigma0l, MAJl);
2156
+ Ah = add3H(All, T1h, sigma0h, MAJh);
2157
+ Al = All | 0;
2158
+ }
2159
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
2160
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
2161
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
2162
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
2163
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
2164
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
2165
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
2166
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
2167
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
2168
+ }
2169
+ roundClean() {
2170
+ clean(SHA512_W_H, SHA512_W_L);
2171
+ }
2172
+ destroy() {
2173
+ this.destroyed = true;
2174
+ clean(this.buffer);
2175
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2176
+ }
2177
+ };
2178
+ _SHA512 = class extends SHA2_64B {
2179
+ constructor() {
2180
+ super(64, SHA512_IV);
2181
+ }
2182
+ };
2183
+ sha512 = /* @__PURE__ */ createHasher(
2184
+ () => new _SHA512(),
2185
+ /* @__PURE__ */ oidNist(3)
2186
+ );
1667
2187
  }
1668
2188
  });
1669
2189
 
@@ -1770,6 +2290,351 @@ var init_fft = __esm({
1770
2290
  }
1771
2291
  });
1772
2292
 
2293
+ // ../../node_modules/@noble/curves/abstract/hash-to-curve.js
2294
+ function i2osp(value, length) {
2295
+ asafenumber(value);
2296
+ asafenumber(length);
2297
+ if (length < 0 || length > 4)
2298
+ throw new Error("invalid I2OSP length: " + length);
2299
+ if (value < 0 || value > 2 ** (8 * length) - 1)
2300
+ throw new Error("invalid I2OSP input: " + value);
2301
+ const res = Array.from({ length }).fill(0);
2302
+ for (let i = length - 1; i >= 0; i--) {
2303
+ res[i] = value & 255;
2304
+ value >>>= 8;
2305
+ }
2306
+ return new Uint8Array(res);
2307
+ }
2308
+ function strxor(a, b) {
2309
+ const arr = new Uint8Array(a.length);
2310
+ for (let i = 0; i < a.length; i++) {
2311
+ arr[i] = a[i] ^ b[i];
2312
+ }
2313
+ return arr;
2314
+ }
2315
+ function normDST(DST) {
2316
+ if (!isBytes2(DST) && typeof DST !== "string")
2317
+ throw new Error("DST must be Uint8Array or ascii string");
2318
+ const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
2319
+ if (dst.length === 0)
2320
+ throw new Error("DST must be non-empty");
2321
+ return dst;
2322
+ }
2323
+ function expand_message_xmd(msg, DST, lenInBytes, H) {
2324
+ abytes2(msg);
2325
+ asafenumber(lenInBytes);
2326
+ if (typeof H !== "function")
2327
+ throw new Error("expand_message_xmd: expected hash function");
2328
+ asafenumber(H.outputLen, "hash.outputLen");
2329
+ asafenumber(H.blockLen, "hash.blockLen");
2330
+ DST = normDST(DST);
2331
+ if (DST.length > 255)
2332
+ DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
2333
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
2334
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
2335
+ if (lenInBytes > 65535 || ell > 255)
2336
+ throw new Error("expand_message_xmd: invalid lenInBytes");
2337
+ const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
2338
+ const Z_pad = new Uint8Array(r_in_bytes);
2339
+ const l_i_b_str = i2osp(lenInBytes, 2);
2340
+ const b = new Array(ell);
2341
+ const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
2342
+ b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
2343
+ for (let i = 1; i < ell; i++) {
2344
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
2345
+ b[i] = H(concatBytes2(...args));
2346
+ }
2347
+ const pseudo_random_bytes = concatBytes2(...b);
2348
+ return pseudo_random_bytes.slice(0, lenInBytes);
2349
+ }
2350
+ var _DST_scalar;
2351
+ var init_hash_to_curve = __esm({
2352
+ "../../node_modules/@noble/curves/abstract/hash-to-curve.js"() {
2353
+ "use strict";
2354
+ init_utils2();
2355
+ _DST_scalar = "HashToScalar-";
2356
+ }
2357
+ });
2358
+
2359
+ // ../../node_modules/@noble/curves/abstract/oprf.js
2360
+ function createOPRF(opts2) {
2361
+ validateObject(opts2, {
2362
+ name: "string",
2363
+ hash: "function",
2364
+ hashToScalar: "function",
2365
+ hashToGroup: "function"
2366
+ });
2367
+ validatePointCons(opts2.Point);
2368
+ const { name, Point, hash, hashToGroup: hashToGroupHook, hashToScalar } = opts2;
2369
+ const { Fn: Fn2 } = Point;
2370
+ const invertSecret = (value) => invertCt(value, Fn2.ORDER);
2371
+ const hashToGroup = (msg, ctx) => hashToGroupHook(msg, {
2372
+ DST: concatBytes2(asciiToBytes("HashToGroup-"), ctx)
2373
+ });
2374
+ const hashToScalarPrefixed = (msg, ctx) => hashToScalar(msg, { DST: concatBytes2(_DST_scalarBytes, ctx) });
2375
+ const randomScalar = (rng = randomBytes2) => {
2376
+ if (typeof rng !== "function")
2377
+ throw new TypeError('"rng" expected function, got type=' + typeof rng);
2378
+ const t = mapHashToField(rng(getMinHashLength(Fn2.ORDER)), Fn2.ORDER, Fn2.isLE);
2379
+ return Fn2.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
2380
+ };
2381
+ const msm = (points, scalars) => mulAddUnsafe(Point, points, scalars);
2382
+ const getCtx = (mode) => concatBytes2(asciiToBytes("OPRFV1-"), new Uint8Array([mode]), asciiToBytes("-" + name));
2383
+ const ctxOPRF = getCtx(0);
2384
+ const ctxVOPRF = getCtx(1);
2385
+ const ctxPOPRF = getCtx(2);
2386
+ function encode(...args) {
2387
+ const res2 = [];
2388
+ for (const a of args) {
2389
+ if (typeof a === "number")
2390
+ res2.push(numberToBytesBE(a, 2));
2391
+ else if (typeof a === "string")
2392
+ res2.push(asciiToBytes(a));
2393
+ else {
2394
+ abytes2(a);
2395
+ res2.push(numberToBytesBE(a.length, 2), a);
2396
+ }
2397
+ }
2398
+ return concatBytes2(...res2);
2399
+ }
2400
+ const inputBytes = (title, bytes) => {
2401
+ abytes2(bytes, void 0, title);
2402
+ if (bytes.length > 65535)
2403
+ throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`);
2404
+ return bytes;
2405
+ };
2406
+ const hashInput = (...bytes) => hash(encode(...bytes, "Finalize"));
2407
+ function getTranscripts(B2, C, D, ctx) {
2408
+ const Bm = B2.toBytes();
2409
+ const seed = hash(encode(Bm, concatBytes2(asciiToBytes("Seed-"), ctx)));
2410
+ const res2 = [];
2411
+ for (let i = 0; i < C.length; i++) {
2412
+ const Ci = C[i].toBytes();
2413
+ const Di = D[i].toBytes();
2414
+ const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, "Composite"), ctx);
2415
+ res2.push(di);
2416
+ }
2417
+ return res2;
2418
+ }
2419
+ function computeComposites(B2, C, D, ctx) {
2420
+ const T = getTranscripts(B2, C, D, ctx);
2421
+ const M = msm(C, T);
2422
+ const Z = msm(D, T);
2423
+ return { M, Z };
2424
+ }
2425
+ function computeCompositesFast(k, B2, C, D, ctx) {
2426
+ const T = getTranscripts(B2, C, D, ctx);
2427
+ const M = msm(C, T);
2428
+ const Z = M.multiply(k);
2429
+ return { M, Z };
2430
+ }
2431
+ function challengeTranscript(B2, M, Z, t2, t3, ctx) {
2432
+ const [Bm, a0, a1, a2, a3] = [B2, M, Z, t2, t3].map((i) => i.toBytes());
2433
+ return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, "Challenge"), ctx);
2434
+ }
2435
+ function generateProof(ctx, k, B2, C, D, rng) {
2436
+ const { M, Z } = computeCompositesFast(k, B2, C, D, ctx);
2437
+ const r = randomScalar(rng);
2438
+ const t2 = Point.BASE.multiply(r);
2439
+ const t3 = M.multiply(r);
2440
+ const c = challengeTranscript(B2, M, Z, t2, t3, ctx);
2441
+ const s = Fn2.sub(r, Fn2.mul(c, k));
2442
+ return concatBytes2(...[c, s].map((i) => Fn2.toBytes(i)));
2443
+ }
2444
+ function verifyProof(ctx, B2, C, D, proof) {
2445
+ abytes2(proof, 2 * Fn2.BYTES);
2446
+ const { M, Z } = computeComposites(B2, C, D, ctx);
2447
+ const [c, s] = [proof.subarray(0, Fn2.BYTES), proof.subarray(Fn2.BYTES)].map((f) => Fn2.fromBytes(f));
2448
+ const t2 = msm([Point.BASE, B2], [s, c]);
2449
+ const t3 = msm([M, Z], [s, c]);
2450
+ const expectedC = challengeTranscript(B2, M, Z, t2, t3, ctx);
2451
+ if (!Fn2.eql(c, expectedC))
2452
+ throw new Error("proof verification failed");
2453
+ }
2454
+ function generateKeyPair() {
2455
+ const skS = randomScalar();
2456
+ const pkS = Point.BASE.multiply(skS);
2457
+ return { secretKey: Fn2.toBytes(skS), publicKey: pkS.toBytes() };
2458
+ }
2459
+ function deriveKeyPair(ctx, seed, info) {
2460
+ abytes2(seed, 32, "seed");
2461
+ info = inputBytes("keyInfo", info);
2462
+ const dst = concatBytes2(asciiToBytes("DeriveKeyPair"), ctx);
2463
+ const msg = concatBytes2(seed, encode(info), Uint8Array.of(0));
2464
+ for (let counter = 0; counter <= 255; counter++) {
2465
+ msg[msg.length - 1] = counter;
2466
+ const skS = hashToScalar(msg, { DST: dst });
2467
+ if (Fn2.is0(skS))
2468
+ continue;
2469
+ return {
2470
+ secretKey: Fn2.toBytes(skS),
2471
+ publicKey: Point.BASE.multiply(skS).toBytes()
2472
+ };
2473
+ }
2474
+ throw new Error("Cannot derive key");
2475
+ }
2476
+ const wirePoint = (label, bytes) => {
2477
+ const point = Point.fromBytes(bytes);
2478
+ if (point.equals(Point.ZERO))
2479
+ throw new Error(label + " point at infinity");
2480
+ return point;
2481
+ };
2482
+ function blind(ctx, input, rng = randomBytes2) {
2483
+ input = inputBytes("input", input);
2484
+ const blind2 = randomScalar(rng);
2485
+ const inputPoint = hashToGroup(input, ctx);
2486
+ if (inputPoint.equals(Point.ZERO))
2487
+ throw new Error("Input point at infinity");
2488
+ const blinded = inputPoint.multiply(blind2);
2489
+ return { blind: Fn2.toBytes(blind2), blinded: blinded.toBytes() };
2490
+ }
2491
+ function evaluate(ctx, secretKey, input) {
2492
+ input = inputBytes("input", input);
2493
+ const skS = Fn2.fromBytes(secretKey);
2494
+ const inputPoint = hashToGroup(input, ctx);
2495
+ if (inputPoint.equals(Point.ZERO))
2496
+ throw new Error("Input point at infinity");
2497
+ const unblinded = inputPoint.multiply(skS).toBytes();
2498
+ return hashInput(input, unblinded);
2499
+ }
2500
+ const oprf2 = Object.freeze({
2501
+ generateKeyPair,
2502
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),
2503
+ blind: (input, rng = randomBytes2) => blind(ctxOPRF, input, rng),
2504
+ blindEvaluate(secretKey, blindedPoint) {
2505
+ const skS = Fn2.fromBytes(secretKey);
2506
+ const elm = wirePoint("blinded", blindedPoint);
2507
+ return elm.multiply(skS).toBytes();
2508
+ },
2509
+ finalize(input, blindBytes, evaluatedBytes) {
2510
+ input = inputBytes("input", input);
2511
+ const blind2 = Fn2.fromBytes(blindBytes);
2512
+ const evalPoint = wirePoint("evaluated", evaluatedBytes);
2513
+ const unblinded = evalPoint.multiply(Fn2.inv(blind2)).toBytes();
2514
+ return hashInput(input, unblinded);
2515
+ },
2516
+ evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input)
2517
+ });
2518
+ const voprf = Object.freeze({
2519
+ generateKeyPair,
2520
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),
2521
+ blind: (input, rng = randomBytes2) => blind(ctxVOPRF, input, rng),
2522
+ blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes2) {
2523
+ if (!Array.isArray(blinded))
2524
+ throw new Error("expected array");
2525
+ const skS = Fn2.fromBytes(secretKey);
2526
+ const pkS = wirePoint("public key", publicKey);
2527
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
2528
+ const evaluated = blindedPoints.map((i) => i.multiply(skS));
2529
+ const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);
2530
+ return { evaluated: evaluated.map((i) => i.toBytes()), proof };
2531
+ },
2532
+ blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes2) {
2533
+ const res2 = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);
2534
+ return { evaluated: res2.evaluated[0], proof: res2.proof };
2535
+ },
2536
+ finalizeBatch(items, publicKey, proof) {
2537
+ if (!Array.isArray(items))
2538
+ throw new Error("expected array");
2539
+ const pkS = wirePoint("public key", publicKey);
2540
+ const blindedPoints = items.map((i) => wirePoint("blinded", i.blinded));
2541
+ const evalPoints = items.map((i) => wirePoint("evaluated", i.evaluated));
2542
+ verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);
2543
+ return items.map((i, j) => {
2544
+ const input = inputBytes("input", i.input);
2545
+ const blind2 = Fn2.fromBytes(i.blind);
2546
+ const unblinded = evalPoints[j].multiply(Fn2.inv(blind2)).toBytes();
2547
+ return hashInput(input, unblinded);
2548
+ });
2549
+ },
2550
+ finalize(input, blind2, evaluated, blinded, publicKey, proof) {
2551
+ return this.finalizeBatch([{ input, blind: blind2, evaluated, blinded }], publicKey, proof)[0];
2552
+ },
2553
+ evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input)
2554
+ });
2555
+ const poprf = (info) => {
2556
+ info = copyBytes(inputBytes("info", info));
2557
+ const m = hashToScalarPrefixed(encode("Info", info), ctxPOPRF);
2558
+ const T = Point.BASE.multiply(m);
2559
+ return Object.freeze({
2560
+ generateKeyPair,
2561
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),
2562
+ blind(input, publicKey, rng = randomBytes2) {
2563
+ input = inputBytes("input", input);
2564
+ const pkS = wirePoint("public key", publicKey);
2565
+ const tweakedKey = T.add(pkS);
2566
+ if (tweakedKey.equals(Point.ZERO))
2567
+ throw new Error("tweakedKey point at infinity");
2568
+ const blind2 = randomScalar(rng);
2569
+ const inputPoint = hashToGroup(input, ctxPOPRF);
2570
+ if (inputPoint.equals(Point.ZERO))
2571
+ throw new Error("Input point at infinity");
2572
+ const blindedPoint = inputPoint.multiply(blind2);
2573
+ return {
2574
+ blind: Fn2.toBytes(blind2),
2575
+ blinded: blindedPoint.toBytes(),
2576
+ tweakedKey: tweakedKey.toBytes()
2577
+ };
2578
+ },
2579
+ blindEvaluateBatch(secretKey, blinded, rng = randomBytes2) {
2580
+ if (!Array.isArray(blinded))
2581
+ throw new Error("expected array");
2582
+ const skS = Fn2.fromBytes(secretKey);
2583
+ const t = Fn2.add(skS, m);
2584
+ const invT = invertSecret(t);
2585
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
2586
+ const evalPoints = blindedPoints.map((i) => i.multiply(invT));
2587
+ const tweakedKey = Point.BASE.multiply(t);
2588
+ const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);
2589
+ return { evaluated: evalPoints.map((i) => i.toBytes()), proof };
2590
+ },
2591
+ blindEvaluate(secretKey, blinded, rng = randomBytes2) {
2592
+ const res2 = this.blindEvaluateBatch(secretKey, [blinded], rng);
2593
+ return { evaluated: res2.evaluated[0], proof: res2.proof };
2594
+ },
2595
+ finalizeBatch(items, proof, tweakedKey) {
2596
+ if (!Array.isArray(items))
2597
+ throw new Error("expected array");
2598
+ const inputs = items.map((i) => inputBytes("input", i.input));
2599
+ const evalPoints = items.map((i) => wirePoint("evaluated", i.evaluated));
2600
+ verifyProof(ctxPOPRF, wirePoint("tweakedKey", tweakedKey), evalPoints, items.map((i) => wirePoint("blinded", i.blinded)), proof);
2601
+ return items.map((i, j) => {
2602
+ const blind2 = Fn2.fromBytes(i.blind);
2603
+ const point = evalPoints[j].multiply(Fn2.inv(blind2)).toBytes();
2604
+ return hashInput(inputs[j], info, point);
2605
+ });
2606
+ },
2607
+ finalize(input, blind2, evaluated, blinded, proof, tweakedKey) {
2608
+ return this.finalizeBatch([{ input, blind: blind2, evaluated, blinded }], proof, tweakedKey)[0];
2609
+ },
2610
+ evaluate(secretKey, input) {
2611
+ input = inputBytes("input", input);
2612
+ const skS = Fn2.fromBytes(secretKey);
2613
+ const inputPoint = hashToGroup(input, ctxPOPRF);
2614
+ if (inputPoint.equals(Point.ZERO))
2615
+ throw new Error("Input point at infinity");
2616
+ const t = Fn2.add(skS, m);
2617
+ const invT = invertSecret(t);
2618
+ const unblinded = inputPoint.multiply(invT).toBytes();
2619
+ return hashInput(input, info, unblinded);
2620
+ }
2621
+ });
2622
+ };
2623
+ const res = { name, oprf: oprf2, voprf, poprf, __tests: Object.freeze({ Fn: Fn2, invertSecret }) };
2624
+ return Object.freeze(res);
2625
+ }
2626
+ var _DST_scalarBytes;
2627
+ var init_oprf = __esm({
2628
+ "../../node_modules/@noble/curves/abstract/oprf.js"() {
2629
+ "use strict";
2630
+ init_utils2();
2631
+ init_curve();
2632
+ init_hash_to_curve();
2633
+ init_modular();
2634
+ _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar);
2635
+ }
2636
+ });
2637
+
1773
2638
  // ../../node_modules/@noble/curves/ed25519.js
1774
2639
  function ed25519_pow_2_252_3(x) {
1775
2640
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
@@ -1814,13 +2679,40 @@ function uvRatio(u, v) {
1814
2679
  x = mod(-x, P);
1815
2680
  return { isValid: useRoot1 || useRoot2, value: x };
1816
2681
  }
1817
- var _0n6, _1n6, _2n4, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, ed25519_Point, x25519;
2682
+ function calcElligatorRistrettoMap(r0) {
2683
+ const { d } = ed25519_CURVE;
2684
+ const r = Fp.mul(Fp.mulN(SQRT_M1, r0), r0);
2685
+ const Ns = Fp.mul(Fp.addN(r, _1n6), ONE_MINUS_D_SQ);
2686
+ let c = BigInt(-1);
2687
+ const D = Fp.mul(Fp.subN(c, Fp.mulN(d, r)), Fp.add(r, d));
2688
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2689
+ let s_ = Fp.mul(s, r0);
2690
+ if (!Fp.isOdd(s_))
2691
+ s_ = Fp.neg(s_);
2692
+ if (!Ns_D_is_sq)
2693
+ s = s_;
2694
+ if (!Ns_D_is_sq)
2695
+ c = r;
2696
+ const Nt = Fp.sub(Fp.mulN(Fp.mulN(c, Fp.subN(r, _1n6)), D_MINUS_ONE_SQ), D);
2697
+ const s2 = Fp.sqrN(s);
2698
+ const W0 = Fp.mul(Fp.addN(s, s), D);
2699
+ const W1 = Fp.mul(Nt, SQRT_AD_MINUS_ONE);
2700
+ const W2 = Fp.sub(_1n6, s2);
2701
+ const W3 = Fp.add(_1n6, s2);
2702
+ return new ed25519_Point(Fp.mul(W0, W3), Fp.mul(W2, W1), Fp.mul(W1, W3), Fp.mul(W0, W2));
2703
+ }
2704
+ 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, ristretto255_oprf;
1818
2705
  var init_ed25519 = __esm({
1819
2706
  "../../node_modules/@noble/curves/ed25519.js"() {
1820
2707
  "use strict";
2708
+ init_sha2();
2709
+ init_utils();
1821
2710
  init_edwards();
2711
+ init_hash_to_curve();
1822
2712
  init_modular();
1823
2713
  init_montgomery();
2714
+ init_oprf();
2715
+ init_utils2();
1824
2716
  _0n6 = /* @__PURE__ */ BigInt(0);
1825
2717
  _1n6 = /* @__PURE__ */ BigInt(1);
1826
2718
  _2n4 = /* @__PURE__ */ BigInt(2);
@@ -1839,6 +2731,8 @@ var init_ed25519 = __esm({
1839
2731
  }))();
1840
2732
  ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
1841
2733
  ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2734
+ Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2735
+ Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
1842
2736
  x25519 = /* @__PURE__ */ (() => {
1843
2737
  const P = ed25519_CURVE_p;
1844
2738
  const powPminus2 = (x) => {
@@ -1862,6 +2756,174 @@ var init_ed25519 = __esm({
1862
2756
  }
1863
2757
  });
1864
2758
  })();
2759
+ SQRT_M1 = ED25519_SQRT_M1;
2760
+ SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2761
+ INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2762
+ ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2763
+ D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2764
+ invertSqrt = (number) => uvRatio(_1n6, number);
2765
+ MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2766
+ bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
2767
+ __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2768
+ constructor(ep) {
2769
+ super(ep);
2770
+ }
2771
+ /**
2772
+ * Create one Ristretto255 point from affine Edwards coordinates.
2773
+ * This wraps the internal Edwards representative directly and is not a
2774
+ * canonical ristretto255 decoding path.
2775
+ * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
2776
+ */
2777
+ static fromAffine(ap) {
2778
+ return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2779
+ }
2780
+ assertSame(other) {
2781
+ if (!(other instanceof __RistrettoPoint))
2782
+ throw new Error("RistrettoPoint expected");
2783
+ }
2784
+ init(ep) {
2785
+ return new __RistrettoPoint(ep);
2786
+ }
2787
+ static fromBytes(bytes) {
2788
+ abytes(bytes, 32);
2789
+ const { a, d } = ed25519_CURVE;
2790
+ const s = bytes255ToNumberLE(bytes);
2791
+ if (!equalBytes(Fp.toBytes(s), bytes) || Fp.isOdd(s))
2792
+ throw new Error("invalid ristretto255 encoding 1");
2793
+ const s2 = Fp.sqr(s);
2794
+ const u1 = Fp.add(_1n6, Fp.mulN(a, s2));
2795
+ const u2 = Fp.sub(_1n6, Fp.mulN(a, s2));
2796
+ const u1_2 = Fp.sqr(u1);
2797
+ const u2_2 = Fp.sqr(u2);
2798
+ const v = Fp.sub(Fp.mulN(Fp.mulN(a, d), u1_2), u2_2);
2799
+ const { isValid, value: I } = invertSqrt(Fp.mul(v, u2_2));
2800
+ const Dx = Fp.mul(I, u2);
2801
+ const Dy = Fp.mul(Fp.mulN(I, Dx), v);
2802
+ let x = Fp.mul(Fp.addN(s, s), Dx);
2803
+ if (Fp.isOdd(x))
2804
+ x = Fp.neg(x);
2805
+ const y = Fp.mul(u1, Dy);
2806
+ const t = Fp.mul(x, y);
2807
+ if (!isValid || Fp.isOdd(t) || Fp.is0(y))
2808
+ throw new Error("invalid ristretto255 encoding 2");
2809
+ return new __RistrettoPoint(new ed25519_Point(x, y, Fp.ONE, t));
2810
+ }
2811
+ /**
2812
+ * Converts ristretto-encoded string to ristretto point.
2813
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2814
+ * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2815
+ */
2816
+ static fromHex(hex) {
2817
+ return __RistrettoPoint.fromBytes(hexToBytes(hex));
2818
+ }
2819
+ /**
2820
+ * Encodes ristretto point to Uint8Array.
2821
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2822
+ */
2823
+ toBytes() {
2824
+ let { X, Y, Z, T } = this.ep;
2825
+ const u1 = Fp.mul(Fp.add(Z, Y), Fp.sub(Z, Y));
2826
+ const u2 = Fp.mul(X, Y);
2827
+ const u2sq = Fp.sqr(u2);
2828
+ const { value: invsqrt } = invertSqrt(Fp.mul(u1, u2sq));
2829
+ const D1 = Fp.mul(invsqrt, u1);
2830
+ const D2 = Fp.mul(invsqrt, u2);
2831
+ const zInv = Fp.mul(Fp.mulN(D1, D2), T);
2832
+ let D;
2833
+ if (Fp.isOdd(Fp.mul(T, zInv))) {
2834
+ let _x = Fp.mul(Y, SQRT_M1);
2835
+ let _y = Fp.mul(X, SQRT_M1);
2836
+ X = _x;
2837
+ Y = _y;
2838
+ D = Fp.mul(D1, INVSQRT_A_MINUS_D);
2839
+ } else {
2840
+ D = D2;
2841
+ }
2842
+ if (Fp.isOdd(Fp.mul(X, zInv)))
2843
+ Y = Fp.neg(Y);
2844
+ let s = Fp.mul(Fp.subN(Z, Y), D);
2845
+ if (Fp.isOdd(s))
2846
+ s = Fp.neg(s);
2847
+ return Fp.toBytes(s);
2848
+ }
2849
+ /**
2850
+ * Compares two Ristretto points.
2851
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2852
+ */
2853
+ equals(other) {
2854
+ this.assertSame(other);
2855
+ const { X: X1, Y: Y1 } = this.ep;
2856
+ const { X: X2, Y: Y2 } = other.ep;
2857
+ const one = Fp.eql(Fp.mul(X1, Y2), Fp.mul(Y1, X2));
2858
+ const two = Fp.eql(Fp.mul(Y1, Y2), Fp.mul(X1, X2));
2859
+ return one || two;
2860
+ }
2861
+ is0() {
2862
+ return this.equals(__RistrettoPoint.ZERO);
2863
+ }
2864
+ };
2865
+ // Do NOT change syntax: the following gymnastics is done,
2866
+ // because typescript strips comments, which makes bundlers disable tree-shaking.
2867
+ // prettier-ignore
2868
+ __publicField(__RistrettoPoint, "BASE", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.BASE))());
2869
+ // prettier-ignore
2870
+ __publicField(__RistrettoPoint, "ZERO", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.ZERO))());
2871
+ // prettier-ignore
2872
+ __publicField(__RistrettoPoint, "Fp", /* @__PURE__ */ (() => Fp)());
2873
+ // prettier-ignore
2874
+ __publicField(__RistrettoPoint, "Fn", /* @__PURE__ */ (() => Fn)());
2875
+ _RistrettoPoint = __RistrettoPoint;
2876
+ ristretto255_hasher = /* @__PURE__ */ Object.freeze({
2877
+ Point: _RistrettoPoint,
2878
+ /**
2879
+ * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
2880
+ * * There are no test vectors
2881
+ * * encodeToCurve / mapToCurve is undefined
2882
+ * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
2883
+ * * hashToScalar is undefined too, so we just use OPRF implementation
2884
+ * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2885
+ (os2ip -> bytes255ToNumberLE)
2886
+ * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2887
+ * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
2888
+ version here. Using `bytes255ToNumblerLE` will create a different result
2889
+ if we use `bytes255ToNumberLE` as os2ip
2890
+ * * current version is closest to spec.
2891
+ */
2892
+ hashToCurve(msg, options) {
2893
+ const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2894
+ const xmd = expand_message_xmd(msg, DST, 64, sha512);
2895
+ return ristretto255_hasher.deriveToCurve(xmd);
2896
+ },
2897
+ hashToScalar(msg, options) {
2898
+ const DST = options?.DST === void 0 ? _DST_scalar : options.DST;
2899
+ const xmd = expand_message_xmd(msg, DST, 64, sha512);
2900
+ return Fn.create(bytesToNumberLE(xmd));
2901
+ },
2902
+ /**
2903
+ * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2904
+ * Converts 64 uniform random bytes into a curve point.
2905
+ *
2906
+ * WARNING: This represents an older hash-to-curve construction from before
2907
+ * RFC 9380 was finalized.
2908
+ * It was later reused as a component in the newer
2909
+ * `hash_to_ristretto255` function defined in RFC 9380.
2910
+ */
2911
+ deriveToCurve(bytes) {
2912
+ abytes(bytes, 64);
2913
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2914
+ const R1 = calcElligatorRistrettoMap(r1);
2915
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2916
+ const R2 = calcElligatorRistrettoMap(r2);
2917
+ return new _RistrettoPoint(R1.add(R2));
2918
+ }
2919
+ });
2920
+ ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({
2921
+ name: "ristretto255-SHA512",
2922
+ Point: _RistrettoPoint,
2923
+ hash: sha512,
2924
+ hashToGroup: ristretto255_hasher.hashToCurve,
2925
+ hashToScalar: ristretto255_hasher.hashToScalar
2926
+ }))();
1865
2927
  }
1866
2928
  });
1867
2929
 
@@ -2127,7 +3189,7 @@ function aobject3(value, title = "object") {
2127
3189
  throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
2128
3190
  return value;
2129
3191
  }
2130
- function equalBytes(a, b) {
3192
+ function equalBytes2(a, b) {
2131
3193
  a = abytes(a);
2132
3194
  b = abytes(b);
2133
3195
  if (a.length !== b.length)
@@ -2438,7 +3500,7 @@ function createKyber(opts2) {
2438
3500
  const validateModulus = (publicKey, fn) => {
2439
3501
  const eke = publicKey.subarray(0, 384 * rawOpts.K);
2440
3502
  const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2441
- const ok = equalBytes(ek, eke);
3503
+ const ok = equalBytes2(ek, eke);
2442
3504
  cleanBytes(ek);
2443
3505
  if (!ok)
2444
3506
  throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
@@ -2509,14 +3571,14 @@ function createKyber(opts2) {
2509
3571
  const k768 = secretCoder.bytesLen - 96;
2510
3572
  const start = k768 + 32;
2511
3573
  const test = HASH256(secretKey.subarray(k768 / 2, start));
2512
- if (!equalBytes(test, secretKey.subarray(start, start + 32)))
3574
+ if (!equalBytes2(test, secretKey.subarray(start, start + 32)))
2513
3575
  throw new Error("invalid secretKey: hash check failed");
2514
3576
  const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
2515
3577
  const msg = KPKE.decrypt(cipherText, sk);
2516
3578
  const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2517
3579
  const Khat = kr.subarray(0, 32);
2518
3580
  const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2519
- const isValid = equalBytes(cipherText, cipherText2);
3581
+ const isValid = equalBytes2(cipherText, cipherText2);
2520
3582
  const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2521
3583
  cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2522
3584
  return isValid ? Khat : Kbar;
@@ -2557,13 +3619,13 @@ function createKyber(opts2) {
2557
3619
  abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2558
3620
  abytesDoc(cipherText, lengths.cipherText, "cipherText");
2559
3621
  const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);
2560
- if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))
3622
+ if (!equalBytes2(ekEmbedded, ek) || !equalBytes2(storedHash, publicKeyHash))
2561
3623
  throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
2562
3624
  const msg = KPKE.decrypt(cipherText, sk);
2563
3625
  const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2564
3626
  const Khat = kr.subarray(0, 32);
2565
3627
  const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));
2566
- const isValid = equalBytes(cipherText, cipherText2);
3628
+ const isValid = equalBytes2(cipherText, cipherText2);
2567
3629
  const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2568
3630
  cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2569
3631
  return isValid ? Khat : Kbar;
@@ -2775,11 +3837,11 @@ function ecKeygen(curve, allowZeroKey = false) {
2775
3837
  if (!("getSharedSecret" in curve && "sign" in curve && "verify" in curve))
2776
3838
  throw new Error("allowZeroKey requires a Weierstrass curve");
2777
3839
  const wCurve = curve;
2778
- const Fn = wCurve.Point.Fn;
3840
+ const Fn2 = wCurve.Point.Fn;
2779
3841
  keygen = (seed = randomBytes3(lengths.seed)) => {
2780
3842
  abytes(seed, lengths.seed, "seed");
2781
- const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
2782
- const secretKey = Fn.toBytes(Fn.create(seedScalar));
3843
+ const seedScalar = Fn2.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
3844
+ const secretKey = Fn2.toBytes(Fn2.create(seedScalar));
2783
3845
  return {
2784
3846
  secretKey,
2785
3847
  publicKey: curve.getPublicKey(secretKey)
@@ -2955,9 +4017,9 @@ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
2955
4017
  const cipherText = [];
2956
4018
  try {
2957
4019
  for (let i = 0; i < rawKems.length; i++) {
2958
- const enc = rawKems[i].encapsulate(pks[i], rand[i]);
2959
- sharedSecret.push(enc.sharedSecret);
2960
- cipherText.push(enc.cipherText);
4020
+ const enc2 = rawKems[i].encapsulate(pks[i], rand[i]);
4021
+ sharedSecret.push(enc2.sharedSecret);
4022
+ cipherText.push(enc2.cipherText);
2961
4023
  }
2962
4024
  const encodedCipherText = ctCoder.encode(cipherText);
2963
4025
  return {
@@ -3084,6 +4146,69 @@ function isBlockedIPv4(host) {
3084
4146
  if (a === 192 && b === 168) return true;
3085
4147
  if (a === 169 && b === 254) return true;
3086
4148
  if (a === 100 && b >= 64 && b <= 127) return true;
4149
+ const c = octets[2];
4150
+ if (a === 192 && b === 0 && c === 0) return true;
4151
+ if (a === 198 && (b === 18 || b === 19)) return true;
4152
+ if (a >= 224 && a <= 239) return true;
4153
+ if (a >= 240) return true;
4154
+ return false;
4155
+ }
4156
+ function expandIPv6(clean2) {
4157
+ let text = clean2;
4158
+ const tail = [];
4159
+ const dotted = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4160
+ if (dotted) {
4161
+ const parts = dotted[2].split(".").map((x) => Number.parseInt(x, 10));
4162
+ if (parts.some((x) => !Number.isInteger(x) || x > 255)) return null;
4163
+ tail.push(parts[0] << 8 | parts[1], parts[2] << 8 | parts[3]);
4164
+ text = dotted[1].endsWith("::") ? dotted[1] : dotted[1].slice(0, -1);
4165
+ }
4166
+ const halves = text.split("::");
4167
+ if (halves.length > 2) return null;
4168
+ const parse = (s) => {
4169
+ if (s === "") return [];
4170
+ const out = [];
4171
+ for (const g of s.split(":")) {
4172
+ if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
4173
+ out.push(Number.parseInt(g, 16));
4174
+ }
4175
+ return out;
4176
+ };
4177
+ const head = parse(halves[0]);
4178
+ const rest = halves.length === 2 ? parse(halves[1]) : [];
4179
+ if (!head || !rest) return null;
4180
+ const known = head.length + rest.length + tail.length;
4181
+ if (halves.length === 1) {
4182
+ return known === 8 ? [...head, ...tail] : null;
4183
+ }
4184
+ if (known > 7) return null;
4185
+ return [...head, ...new Array(8 - known).fill(0), ...rest, ...tail];
4186
+ }
4187
+ function v4FromGroups(high, low) {
4188
+ return `${high >> 8 & 255}.${high & 255}.${low >> 8 & 255}.${low & 255}`;
4189
+ }
4190
+ function isBlockedIPv6Groups(g) {
4191
+ const first = g[0];
4192
+ if ((first & 65280) === 65280) return true;
4193
+ if ((first & 65472) === 65152) return true;
4194
+ if ((first & 65472) === 65216) return true;
4195
+ if ((first & 65024) === 64512) return true;
4196
+ if (first === 8194) return isBlockedIPv4(v4FromGroups(g[1], g[2]));
4197
+ if (first === 100 && g[1] === 65435) {
4198
+ if (g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0) return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4199
+ if (g[2] === 1) return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4200
+ return true;
4201
+ }
4202
+ if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0) {
4203
+ if (g[5] === 65535 || g[5] === 0) {
4204
+ if (g[5] === 0 && g[6] === 0 && g[7] <= 1) return true;
4205
+ return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4206
+ }
4207
+ return true;
4208
+ }
4209
+ if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 65535 && g[5] === 0) {
4210
+ return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4211
+ }
3087
4212
  return false;
3088
4213
  }
3089
4214
  function v4FromHexPair(highHex, lowHex) {
@@ -3103,6 +4228,9 @@ function isBlockedIPv6(host) {
3103
4228
  }
3104
4229
  clean2 = clean2.split("%")[0];
3105
4230
  if (!clean2.includes(":")) return false;
4231
+ const groups = expandIPv6(clean2);
4232
+ if (!groups) return true;
4233
+ if (isBlockedIPv6Groups(groups)) return true;
3106
4234
  if (clean2 === "::1") return true;
3107
4235
  if (clean2 === "::") return true;
3108
4236
  if (clean2.startsWith("fe80:")) return true;
@@ -3486,12 +4614,26 @@ function hexToBytes4(hex) {
3486
4614
  }
3487
4615
  return out;
3488
4616
  }
4617
+ function mapsAreCanonical(doc) {
4618
+ const canonical = (s) => typeof s === "string" && s === s.toLowerCase();
4619
+ for (const [partnerId, keyId] of Object.entries(doc.heads)) {
4620
+ if (!canonical(partnerId) || !canonical(keyId)) return false;
4621
+ }
4622
+ if (doc.staged === void 0) return true;
4623
+ if (!doc.staged || typeof doc.staged !== "object" || Array.isArray(doc.staged)) return false;
4624
+ for (const [partnerId, entry] of Object.entries(doc.staged)) {
4625
+ if (!canonical(partnerId) || !entry || typeof entry !== "object") return false;
4626
+ if (!canonical(entry.key_id) || !canonical(entry.key_sha256)) return false;
4627
+ }
4628
+ return true;
4629
+ }
3489
4630
  async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
3490
4631
  try {
3491
4632
  if (!doc || !KNOWN_VERSIONS.has(doc.version)) return "malformed";
3492
4633
  if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
3493
4634
  if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
3494
4635
  if (!doc.heads || typeof doc.heads !== "object") return "malformed";
4636
+ if (!mapsAreCanonical(doc)) return "malformed";
3495
4637
  const expires = Date.parse(doc.expires_at);
3496
4638
  const issued = Date.parse(doc.issued_at);
3497
4639
  if (Number.isNaN(expires) || Number.isNaN(issued)) return "malformed";
@@ -3873,6 +5015,54 @@ var init_sender_held_keys = __esm({
3873
5015
  }
3874
5016
  });
3875
5017
 
5018
+ // ../crypto/src/vault-pin-hardening.ts
5019
+ function toB642(bytes) {
5020
+ let s = "";
5021
+ for (const b of bytes) s += String.fromCharCode(b);
5022
+ return btoa(s);
5023
+ }
5024
+ function fromB64(b64) {
5025
+ const s = atob(b64);
5026
+ const out = new Uint8Array(s.length);
5027
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
5028
+ return out;
5029
+ }
5030
+ function isHardenedSecret(value) {
5031
+ return value.startsWith(HARDENED_PREFIX);
5032
+ }
5033
+ async function hardenPin(pin, evaluate) {
5034
+ if (isHardenedSecret(pin)) throw new Error("hardenPin was given an already-hardened secret");
5035
+ const input = enc.encode(pin);
5036
+ const { blind, blinded } = oprf.blind(input);
5037
+ const evaluated = fromB64(await evaluate(toB642(blinded)));
5038
+ const output = oprf.finalize(input, blind, evaluated);
5039
+ return HARDENED_PREFIX + toB642(output);
5040
+ }
5041
+ function parseOprfSeed(hex) {
5042
+ if (!hex) return null;
5043
+ const clean2 = hex.trim();
5044
+ if (!/^[0-9a-fA-F]{64}$/.test(clean2)) return null;
5045
+ const out = new Uint8Array(32);
5046
+ for (let i = 0; i < 32; i++) out[i] = parseInt(clean2.slice(i * 2, i * 2 + 2), 16);
5047
+ return out;
5048
+ }
5049
+ function evaluateBlindedPin(seed, userId, blindedB64) {
5050
+ if (!userId) throw new Error("userId is required");
5051
+ const { secretKey } = oprf.deriveKeyPair(seed, enc.encode(`oa-vault-pin:v1:${userId}`));
5052
+ return toB642(oprf.blindEvaluate(secretKey, fromB64(blindedB64)));
5053
+ }
5054
+ var HARDENED_PREFIX, PIN_HARDENING_VERSION, oprf, enc;
5055
+ var init_vault_pin_hardening = __esm({
5056
+ "../crypto/src/vault-pin-hardening.ts"() {
5057
+ "use strict";
5058
+ init_ed25519();
5059
+ HARDENED_PREFIX = "h1:";
5060
+ PIN_HARDENING_VERSION = 1;
5061
+ oprf = ristretto255_oprf.oprf;
5062
+ enc = new TextEncoder();
5063
+ }
5064
+ });
5065
+
3876
5066
  // ../crypto/src/index.ts
3877
5067
  var src_exports = {};
3878
5068
  __export(src_exports, {
@@ -3881,10 +5071,12 @@ __export(src_exports, {
3881
5071
  ENDPOINT_PROBE_INTERVAL_MINUTES: () => ENDPOINT_PROBE_INTERVAL_MINUTES,
3882
5072
  ENDPOINT_STALE_AFTER_MINUTES: () => ENDPOINT_STALE_AFTER_MINUTES,
3883
5073
  ENDPOINT_UNUSABLE_AFTER_MINUTES: () => ENDPOINT_UNUSABLE_AFTER_MINUTES,
5074
+ HARDENED_PREFIX: () => HARDENED_PREFIX,
3884
5075
  PARTNER_KEY_ATTESTATION_ALG: () => PARTNER_KEY_ATTESTATION_ALG,
3885
5076
  PARTNER_KEY_ATTESTATION_V1: () => PARTNER_KEY_ATTESTATION_V1,
3886
5077
  PARTNER_KEY_REFUSED_MESSAGE: () => PARTNER_KEY_REFUSED_MESSAGE,
3887
5078
  PINNED_REGISTRY_ROOTS: () => PINNED_REGISTRY_ROOTS,
5079
+ PIN_HARDENING_VERSION: () => PIN_HARDENING_VERSION,
3888
5080
  REGISTRY_HEAD_ALG: () => REGISTRY_HEAD_ALG,
3889
5081
  REGISTRY_HEAD_V1: () => REGISTRY_HEAD_V1,
3890
5082
  REGISTRY_HEAD_V2: () => REGISTRY_HEAD_V2,
@@ -3908,13 +5100,16 @@ __export(src_exports, {
3908
5100
  encryptPayloadForPartner: () => encryptPayloadForPartner,
3909
5101
  encryptSessionForAll: () => encryptSessionForAll,
3910
5102
  encryptSessionForPartner: () => encryptSessionForPartner,
5103
+ evaluateBlindedPin: () => evaluateBlindedPin,
3911
5104
  generateHybridPartnerKeyPair: () => generateHybridPartnerKeyPair,
3912
5105
  generatePartnerKeyPair: () => generatePartnerKeyPair,
5106
+ hardenPin: () => hardenPin,
3913
5107
  headNamesKey: () => headNamesKey,
3914
5108
  headNamesPartner: () => headNamesPartner,
3915
5109
  headNamesStagedKey: () => headNamesStagedKey,
3916
5110
  isEmailLike: () => isEmailLike,
3917
5111
  isFreshTimestamp: () => isFreshTimestamp,
5112
+ isHardenedSecret: () => isHardenedSecret,
3918
5113
  isIpLiteralHost: () => isIpLiteralHost,
3919
5114
  isSafeWebhookUrl: () => isSafeWebhookUrl,
3920
5115
  keyIdForPublicKey: () => keyIdForPublicKey,
@@ -3922,6 +5117,7 @@ __export(src_exports, {
3922
5117
  normaliseAddress: () => normaliseAddress,
3923
5118
  normalizeForBlindIndex: () => normalizeForBlindIndex,
3924
5119
  openSealedWithSenderHeldKey: () => openSealedWithSenderHeldKey,
5120
+ parseOprfSeed: () => parseOprfSeed,
3925
5121
  partnerKeyFingerprint: () => partnerKeyFingerprint,
3926
5122
  pinnedRegistryRoots: () => pinnedRegistryRoots,
3927
5123
  rootIsPinned: () => rootIsPinned,
@@ -4540,15 +5736,15 @@ async function verifyWebhookSignature(payload, signature, secret) {
4540
5736
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
4541
5737
  const sigBytes = new Uint8Array(32);
4542
5738
  for (let i = 0; i < 32; i++) sigBytes[i] = Number.parseInt(signature.slice(i * 2, i * 2 + 2), 16);
4543
- const enc = new TextEncoder();
5739
+ const enc2 = new TextEncoder();
4544
5740
  const key = await subtle().importKey(
4545
5741
  "raw",
4546
- enc.encode(secret),
5742
+ enc2.encode(secret),
4547
5743
  { name: "HMAC", hash: "SHA-256" },
4548
5744
  false,
4549
5745
  ["verify"]
4550
5746
  );
4551
- return subtle().verify("HMAC", key, sigBytes, enc.encode(payload));
5747
+ return subtle().verify("HMAC", key, sigBytes, enc2.encode(payload));
4552
5748
  }
4553
5749
  var subtle, AU_STATE_FULL, SESSION_KEY_BITS, SESSION_IV_LENGTH, WRAP_SALT_LENGTH, WRAP_IV_LENGTH;
4554
5750
  var init_src = __esm({
@@ -4564,6 +5760,7 @@ var init_src = __esm({
4564
5760
  init_registry_head();
4565
5761
  init_verify_partner_keys();
4566
5762
  init_sender_held_keys();
5763
+ init_vault_pin_hardening();
4567
5764
  subtle = () => {
4568
5765
  const webcrypto = globalThis.crypto;
4569
5766
  if (!webcrypto?.subtle) {
@@ -4603,12 +5800,26 @@ var init_src = __esm({
4603
5800
  var index_exports = {};
4604
5801
  __export(index_exports, {
4605
5802
  CURRENT_VERSION: () => CURRENT_VERSION,
5803
+ DEFAULT_IDEMPOTENCY_LEASE_SECS: () => DEFAULT_IDEMPOTENCY_LEASE_SECS,
5804
+ DEFAULT_MAX_BODY_BYTES: () => DEFAULT_MAX_BODY_BYTES,
4606
5805
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
5806
+ LOA_MAX_TYPED_ALIASES: () => LOA_MAX_TYPED_ALIASES,
5807
+ LOA_MIN_SHORT_FORM_LETTERS: () => LOA_MIN_SHORT_FORM_LETTERS,
5808
+ LOA_PUBLIC_KEY_CACHE_MS: () => LOA_PUBLIC_KEY_CACHE_MS,
5809
+ LOA_V2_REFUSALS: () => LOA_V2_REFUSALS,
5810
+ LoaPublicKeyUnavailableError: () => LoaPublicKeyUnavailableError,
5811
+ LoaV2RefusedError: () => LoaV2RefusedError,
5812
+ MAX_ADDRESS_FIELD_CHARS: () => MAX_ADDRESS_FIELD_CHARS,
4607
5813
  OUTBOX_LEASE_COLUMNS: () => OUTBOX_LEASE_COLUMNS,
4608
5814
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
5815
+ _resetLoaKeyCacheForTests: () => _resetLoaKeyCacheForTests,
4609
5816
  _resetOnceWarningsForTests: () => _resetOnceWarningsForTests,
5817
+ acceptTypedAliases: () => acceptTypedAliases,
4610
5818
  buildSignedTestWebhook: () => buildSignedTestWebhook,
5819
+ cachedLoaPublicKey: () => cachedLoaPublicKey,
4611
5820
  canonicalD5LoaForm: () => canonicalD5LoaForm,
5821
+ canonicalD5LoaFormV2: () => canonicalD5LoaFormV2,
5822
+ checkLoaV2: () => checkLoaV2,
4612
5823
  checkRegistryHead: () => checkRegistryHead,
4613
5824
  compareAddresses: () => compareAddresses,
4614
5825
  computeBlindIndex: () => computeBlindIndex,
@@ -4625,21 +5836,31 @@ __export(index_exports, {
4625
5836
  findMatchingStoredName: () => findMatchingStoredName,
4626
5837
  formatAddressParts: () => formatAddressParts,
4627
5838
  fromOutboxTimestamp: () => fromOutboxTimestamp,
5839
+ hasLoaV2: () => hasLoaV2,
5840
+ isAcceptableAlias: () => isAcceptableAlias,
4628
5841
  isEmailLike: () => isEmailLike2,
4629
5842
  isFreshTimestamp: () => isFreshTimestamp,
5843
+ loaEnvelopeSha256: () => loaEnvelopeSha256,
5844
+ loaFirstName: () => loaFirstName,
5845
+ loaNamesMatch: () => loaNamesMatch,
5846
+ loaSurname: () => loaSurname,
4630
5847
  namePoolMatches: () => namePoolMatches,
5848
+ normaliseLoaName: () => normaliseLoaName,
4631
5849
  normalizeForBlindIndex: () => normalizeForBlindIndex,
4632
5850
  parsePinnedRegistryRoots: () => parsePinnedRegistryRoots,
4633
5851
  readAddressParts: () => readAddressParts,
4634
5852
  sendVerifyResult: () => sendVerifyResult,
5853
+ signPullRequest: () => signPullRequest,
4635
5854
  toExpressHandler: () => toExpressHandler,
4636
5855
  toOutboxTimestamp: () => toOutboxTimestamp,
4637
5856
  transform: () => transformAddress,
4638
5857
  transformAddress: () => transformAddress,
4639
5858
  transformSession: () => transformSession,
5859
+ typedAliasesOf: () => typedAliasesOf,
4640
5860
  validateAddress: () => validateAddress,
4641
5861
  verify: () => verifySignature,
4642
5862
  verifyD5LOA: () => verifyD5LOA,
5863
+ verifyD5LOAv2: () => verifyD5LOAv2,
4643
5864
  verifyGrace: () => verifyWithGrace,
4644
5865
  verifyLOA: () => verifyLOA,
4645
5866
  verifySignature: () => verifySignature,
@@ -4662,7 +5883,6 @@ var D5_BODY_ALWAYS = [
4662
5883
  "partner_id",
4663
5884
  "session_envelope",
4664
5885
  "session_key_share",
4665
- "stripe_session_id",
4666
5886
  "timestamp",
4667
5887
  "update_id",
4668
5888
  "user_id"
@@ -4686,10 +5906,12 @@ var D5_BODY_CONDITIONAL = {
4686
5906
  crossover_key_ids: "key-crossover copy only"
4687
5907
  };
4688
5908
  var D5_BODY_DRILL_ONLY = ["conformance"];
5909
+ var D5_BODY_ADDED_AT_SEND = ["dispatch_id"];
4689
5910
  var D5_BODY_ALL_ALLOWED = [
4690
5911
  ...D5_BODY_ALWAYS,
4691
5912
  ...Object.keys(D5_BODY_CONDITIONAL),
4692
- ...D5_BODY_DRILL_ONLY
5913
+ ...D5_BODY_DRILL_ONLY,
5914
+ ...D5_BODY_ADDED_AT_SEND
4693
5915
  ];
4694
5916
 
4695
5917
  // ../protocol/src/retention.ts
@@ -4710,6 +5932,116 @@ function keyShareExpiryIso(dispatchAt, retentionPeriodDays) {
4710
5932
  return new Date(dispatchAt.getTime() + days * DAY_MS).toISOString();
4711
5933
  }
4712
5934
 
5935
+ // ../protocol/src/pull-signature.ts
5936
+ var PULL_SIGNATURE_VERSION_HEADER = "X-OneAddress-Signature-Version";
5937
+ function pullSigningStringV2(timestamp, method, pathAndQuery, body = "") {
5938
+ return `v2.${timestamp}.${method.toUpperCase()}.${pathAndQuery}.${body}`;
5939
+ }
5940
+
5941
+ // ../protocol/src/loa-v2.ts
5942
+ var LOA_V2_VERSION_TAG = "oneaddress-loa/2";
5943
+ var LOA_V2_LEGACY_ENVELOPE_TAG = "oneaddress-legacy-envelope/1";
5944
+ var LOA_V2_FIELD_ORDER = [
5945
+ "consumer_name",
5946
+ "authorisation_date",
5947
+ "scope",
5948
+ "update_uid",
5949
+ "partner_id",
5950
+ "envelope_sha256"
5951
+ ];
5952
+ var LOA_MAX_TYPED_ALIASES = 3;
5953
+ var LoaV2FieldError = class extends Error {
5954
+ constructor(field, reason) {
5955
+ super(`LOA v2 field ${field} ${reason}`);
5956
+ this.field = field;
5957
+ this.name = "LoaV2FieldError";
5958
+ }
5959
+ };
5960
+ var CONTROL_RE = /[\u0000-\u001F\u007F]/;
5961
+ var LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
5962
+ function utf8Length(s) {
5963
+ return new TextEncoder().encode(s).length;
5964
+ }
5965
+ function encodeField(name, value) {
5966
+ if (typeof value !== "string") throw new LoaV2FieldError(name, "is not a string");
5967
+ if (CONTROL_RE.test(value)) throw new LoaV2FieldError(name, "contains a control character");
5968
+ if (LONE_SURROGATE_RE.test(value)) throw new LoaV2FieldError(name, "is not well-formed Unicode");
5969
+ return `${utf8Length(value)}:${value}
5970
+ `;
5971
+ }
5972
+ function canonicalLoaV2(fields) {
5973
+ let out = encodeField("version", LOA_V2_VERSION_TAG);
5974
+ for (const f of LOA_V2_FIELD_ORDER) out += encodeField(f, fields[f]);
5975
+ const aliases = fields.consumer_typed_aliases;
5976
+ if (!Array.isArray(aliases)) throw new LoaV2FieldError("consumer_typed_aliases", "is not a list");
5977
+ if (aliases.length > LOA_MAX_TYPED_ALIASES) {
5978
+ throw new LoaV2FieldError("consumer_typed_aliases", `has more than ${LOA_MAX_TYPED_ALIASES} entries`);
5979
+ }
5980
+ out += encodeField("consumer_typed_aliases", String(aliases.length));
5981
+ for (const a of aliases) out += encodeField("consumer_typed_aliases", a);
5982
+ return out;
5983
+ }
5984
+ function loaV2EnvelopeDigestInput(envelope) {
5985
+ if (typeof envelope === "string") return envelope;
5986
+ if (!envelope || typeof envelope !== "object") {
5987
+ throw new LoaV2FieldError("envelope", "is neither a session_envelope string nor an address_encrypted object");
5988
+ }
5989
+ return encodeField("tag", LOA_V2_LEGACY_ENVELOPE_TAG) + encodeField("ephemeralPublicKey", envelope.ephemeralPublicKey) + encodeField("iv", envelope.iv) + encodeField("ciphertext", envelope.ciphertext) + encodeField("hkdfSalt", envelope.hkdfSalt ?? "");
5990
+ }
5991
+ var ASCII_WS_RE = /[ \t\n\v\f\r]+/;
5992
+ var MARK_RE = /\p{M}/gu;
5993
+ function normaliseLoaName(name) {
5994
+ return name.normalize("NFKD").replace(MARK_RE, "").toLowerCase().replace(/\u03C2/g, "\u03C3").split(ASCII_WS_RE).filter((t) => t.length > 0).join(" ");
5995
+ }
5996
+ function loaSurname(name) {
5997
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
5998
+ return tokens.length > 0 ? tokens[tokens.length - 1] : "";
5999
+ }
6000
+ function loaFirstName(name) {
6001
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
6002
+ return tokens.length > 0 ? tokens[0] : "";
6003
+ }
6004
+ function loaNamesMatch(a, b) {
6005
+ const na = normaliseLoaName(a);
6006
+ return na.length > 0 && na === normaliseLoaName(b);
6007
+ }
6008
+ var LOA_MIN_SHORT_FORM_LETTERS = 3;
6009
+ function codePoints(s) {
6010
+ return Array.from(s).length;
6011
+ }
6012
+ function isAcceptableAlias(verifiedName, alias) {
6013
+ const vFirst = loaFirstName(verifiedName);
6014
+ const aFirst = loaFirstName(alias);
6015
+ if (!vFirst || !aFirst) return false;
6016
+ if (aFirst === vFirst) return true;
6017
+ const [shorter, longer] = codePoints(aFirst) <= codePoints(vFirst) ? [aFirst, vFirst] : [vFirst, aFirst];
6018
+ return codePoints(shorter) >= LOA_MIN_SHORT_FORM_LETTERS && longer.startsWith(shorter);
6019
+ }
6020
+ function acceptTypedAliases(verifiedName, aliases) {
6021
+ const out = [];
6022
+ if (!Array.isArray(aliases)) return out;
6023
+ const seen = /* @__PURE__ */ new Set([normaliseLoaName(verifiedName)]);
6024
+ for (const a of aliases) {
6025
+ if (out.length >= LOA_MAX_TYPED_ALIASES) break;
6026
+ if (typeof a !== "string") continue;
6027
+ if (CONTROL_RE.test(a) || LONE_SURROGATE_RE.test(a)) continue;
6028
+ const n = normaliseLoaName(a);
6029
+ if (!n || seen.has(n)) continue;
6030
+ if (!isAcceptableAlias(verifiedName, a)) continue;
6031
+ seen.add(n);
6032
+ out.push(a);
6033
+ }
6034
+ return out;
6035
+ }
6036
+ var LOA_V2_REFUSALS = [
6037
+ "loa_v2_malformed",
6038
+ "loa_v2_signature_invalid",
6039
+ "loa_v2_partner_mismatch",
6040
+ "loa_v2_update_mismatch",
6041
+ "loa_v2_envelope_mismatch",
6042
+ "loa_v2_name_mismatch"
6043
+ ];
6044
+
4713
6045
  // src/app-hosts.ts
4714
6046
  function allowedAppHosts() {
4715
6047
  const hosts = ["oneaddress.io", "app.oneaddress.io"];
@@ -4718,7 +6050,7 @@ function allowedAppHosts() {
4718
6050
  }
4719
6051
  return new Set(hosts);
4720
6052
  }
4721
- function resolveAppOrigin(baseUrl, label) {
6053
+ function resolveAppOrigin(baseUrl, label, extraHosts) {
4722
6054
  let parsed;
4723
6055
  try {
4724
6056
  parsed = new URL(baseUrl);
@@ -4726,6 +6058,9 @@ function resolveAppOrigin(baseUrl, label) {
4726
6058
  throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
4727
6059
  }
4728
6060
  const allowed = allowedAppHosts();
6061
+ for (const h of extraHosts ?? []) {
6062
+ if (typeof h === "string" && h.trim() !== "") allowed.add(h.trim().toLowerCase());
6063
+ }
4729
6064
  if (!allowed.has(parsed.hostname)) {
4730
6065
  throw new Error(
4731
6066
  `[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
@@ -4761,26 +6096,38 @@ function surnameVariants(token) {
4761
6096
  if (!token.includes("-")) return [token];
4762
6097
  return [token, ...token.split("-").filter(Boolean)];
4763
6098
  }
6099
+ var MAX_ALIASES = 10;
6100
+ var MAX_TOKENS_PER_NAME = 8;
6101
+ var MAX_POOL_TOKENS = 24;
4764
6102
  function namePoolMatches(providedNames, storedName) {
4765
6103
  if (isEmailLike2(storedName)) return false;
4766
- const provided = providedNames.filter((n) => Boolean(n) && !isEmailLike2(n));
6104
+ const provided = providedNames.filter((n) => typeof n === "string" && n !== "" && !isEmailLike2(n));
4767
6105
  const primary = tokenize(provided[0] ?? "");
4768
- if (primary.length === 0) return false;
6106
+ if (primary.length === 0 || primary.length > MAX_TOKENS_PER_NAME) return false;
6107
+ const aliases = provided.slice(1, 1 + MAX_ALIASES).map(tokenize).filter((t) => t.length > 0 && t.length <= MAX_TOKENS_PER_NAME);
6108
+ const distinct = new Set(primary);
6109
+ for (const t of aliases) for (const tok of t) distinct.add(tok);
6110
+ if (distinct.size > MAX_POOL_TOKENS) return false;
4769
6111
  const surnames = new Set(surnameVariants(primary[primary.length - 1]));
4770
- for (let i = 1; i < provided.length; i++) {
4771
- const t = tokenize(provided[i]);
4772
- if (t.length >= 2) for (const v of surnameVariants(t[t.length - 1])) surnames.add(v);
4773
- }
4774
- const all = /* @__PURE__ */ new Set();
4775
- for (const n of provided) for (const t of tokenize(n)) all.add(t);
4776
- const given = [...all].filter((t) => !surnames.has(t));
6112
+ for (const t of aliases) {
6113
+ const last = t[t.length - 1];
6114
+ if (t.length >= 2 && last.length >= 2) for (const v of surnameVariants(last)) surnames.add(v);
6115
+ }
6116
+ const givenSet = /* @__PURE__ */ new Set();
6117
+ for (const tok of primary) if (!surnames.has(tok)) givenSet.add(tok);
6118
+ for (const t of aliases) for (const tok of t) if (tok.length >= 2 && !surnames.has(tok)) givenSet.add(tok);
6119
+ const given = [...givenSet];
6120
+ const fullGiven = given.filter((g) => g.length >= 2);
4777
6121
  const stored = tokenize(storedName);
4778
- if (stored.length === 0) return false;
6122
+ if (stored.length < 2) return false;
4779
6123
  const storedSurname = stored[stored.length - 1];
4780
6124
  const storedGiven = stored.slice(0, -1);
4781
6125
  if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
4782
6126
  const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
4783
- return storedGiven.every(covered);
6127
+ if (!storedGiven.every(covered)) return false;
6128
+ return storedGiven.some(
6129
+ (tok) => fullGiven.includes(tok) || tok.length === 1 && fullGiven.some((g) => g[0] === tok)
6130
+ );
4784
6131
  }
4785
6132
  function findMatchingStoredName(providedNames, storedCandidates) {
4786
6133
  return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
@@ -5226,14 +6573,21 @@ async function checkRegistryHead(opts2) {
5226
6573
 
5227
6574
  // src/index.ts
5228
6575
  var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
6576
+ var DEFAULT_IDEMPOTENCY_LEASE_SECS = 120;
5229
6577
  function createSqlIdempotencyStore(opts2) {
5230
6578
  const table = opts2.table ?? "oneaddress_dispatches";
5231
6579
  const dialect = opts2.dialect ?? "postgres";
6580
+ const leaseSeconds = opts2.leaseSeconds ?? DEFAULT_IDEMPOTENCY_LEASE_SECS;
5232
6581
  if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
5233
6582
  throw new Error(
5234
6583
  `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
5235
6584
  );
5236
6585
  }
6586
+ if (typeof leaseSeconds !== "number" || !Number.isSafeInteger(leaseSeconds) || leaseSeconds < 0 || leaseSeconds > 86400) {
6587
+ throw new Error(
6588
+ `[OneAddress SDK] createSqlIdempotencyStore: leaseSeconds must be a whole number from 0 to 86400, got ${String(leaseSeconds)}`
6589
+ );
6590
+ }
5237
6591
  const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
5238
6592
  const ph = opts2.placeholder ?? defaultPh;
5239
6593
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
@@ -5252,7 +6606,26 @@ function createSqlIdempotencyStore(opts2) {
5252
6606
  [dispatchId]
5253
6607
  );
5254
6608
  if (tokenOf(rows[0]) === token) return "fresh";
5255
- return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
6609
+ if (completedOf(rows[0])) return "duplicate";
6610
+ const takeover = import_crypto2.default.randomBytes(16).toString("hex");
6611
+ await opts2.query(
6612
+ `UPDATE ${table} SET received_at = CURRENT_TIMESTAMP, claim_token = ${ph(1)} WHERE dispatch_id = ${ph(2)} AND completed_at IS NULL AND ${staleClaim(3)}`,
6613
+ leaseParams([takeover, dispatchId])
6614
+ );
6615
+ const after = await opts2.query(
6616
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
6617
+ [dispatchId]
6618
+ );
6619
+ if (tokenOf(after[0]) === takeover) return "retry-after-incomplete";
6620
+ return completedOf(after[0]) ? "duplicate" : "in-progress";
6621
+ }
6622
+ function staleClaim(n) {
6623
+ if (leaseSeconds === 0) return "1 = 1";
6624
+ const cutoff = dialect === "postgres" ? `received_at < CURRENT_TIMESTAMP - make_interval(secs => ${ph(n)})` : dialect === "sqlite" ? `julianday(received_at) < julianday('now') - (${ph(n)} / 86400.0)` : dialect === "mysql" ? `received_at < CURRENT_TIMESTAMP - INTERVAL ${ph(n)} SECOND` : `received_at < DATEADD(second, -${ph(n)}, CURRENT_TIMESTAMP)`;
6625
+ return `(received_at IS NULL OR ${cutoff})`;
6626
+ }
6627
+ function leaseParams(params) {
6628
+ return leaseSeconds === 0 ? params : [...params, leaseSeconds];
5256
6629
  }
5257
6630
  async function setByUpsert(dispatchId) {
5258
6631
  if (dialect === "mysql") {
@@ -5286,11 +6659,22 @@ function createSqlIdempotencyStore(opts2) {
5286
6659
  [dispatchId]
5287
6660
  );
5288
6661
  if (inserted.length > 0) return "fresh";
6662
+ const took = await opts2.query(
6663
+ `UPDATE ${table} SET received_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL AND ${staleClaim(2)} RETURNING dispatch_id`,
6664
+ leaseParams([dispatchId])
6665
+ );
6666
+ if (took.length > 0) return "retry-after-incomplete";
5289
6667
  const rows = await opts2.query(
5290
6668
  `SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
5291
6669
  [dispatchId]
5292
6670
  );
5293
- return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
6671
+ return completedOf(rows[0]) ? "duplicate" : "in-progress";
6672
+ },
6673
+ async release(dispatchId) {
6674
+ await opts2.query(
6675
+ `DELETE FROM ${table} WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL`,
6676
+ [dispatchId]
6677
+ );
5294
6678
  },
5295
6679
  async complete(dispatchId) {
5296
6680
  await opts2.query(
@@ -5314,6 +6698,7 @@ function createSqlIdempotencyStore(opts2) {
5314
6698
  }
5315
6699
  function verifySignature(rawBody, signature, timestamp, secret) {
5316
6700
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
6701
+ if (!secret) return false;
5317
6702
  const sigPayload = `${timestamp}.${rawBody}`;
5318
6703
  const expected = import_crypto2.default.createHmac("sha256", secret).update(sigPayload).digest("hex");
5319
6704
  const sigBuffer = Buffer.from(signature, "hex");
@@ -5321,6 +6706,17 @@ function verifySignature(rawBody, signature, timestamp, secret) {
5321
6706
  if (sigBuffer.length !== expBuffer.length) return false;
5322
6707
  return import_crypto2.default.timingSafeEqual(sigBuffer, expBuffer);
5323
6708
  }
6709
+ function signPullRequest(opts2) {
6710
+ if (!opts2.secret) throw new Error("signPullRequest: secret is required");
6711
+ const u = new URL(opts2.url);
6712
+ const ts = String(opts2.timestamp ?? Math.floor(Date.now() / 1e3));
6713
+ const signature = import_crypto2.default.createHmac("sha256", opts2.secret).update(pullSigningStringV2(ts, opts2.method ?? "GET", `${u.pathname}${u.search}`, opts2.body ?? "")).digest("hex");
6714
+ return {
6715
+ "X-OneAddress-Timestamp": ts,
6716
+ "X-OneAddress-Signature": signature,
6717
+ [PULL_SIGNATURE_VERSION_HEADER]: "2"
6718
+ };
6719
+ }
5324
6720
  function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
5325
6721
  if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
5326
6722
  if (previousSecret && previousSecret !== currentSecret && graceUntil) {
@@ -5464,6 +6860,7 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
5464
6860
  );
5465
6861
  }
5466
6862
  var OA_APP_BASE_URL2 = "https://oneaddress.io";
6863
+ var CONFIRM_PATH = "/api/confirm";
5467
6864
  async function confirmUpdate(opts2) {
5468
6865
  const {
5469
6866
  partnerId,
@@ -5495,18 +6892,22 @@ async function confirmUpdate(opts2) {
5495
6892
  ...memberName !== void 0 ? { member_name: memberName } : {}
5496
6893
  });
5497
6894
  const timestamp = String(Math.floor(Date.now() / 1e3));
5498
- const signature = import_crypto2.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
5499
- let base = appBaseUrl;
5500
- while (base.endsWith("/")) base = base.slice(0, -1);
6895
+ const signature = import_crypto2.default.createHmac("sha256", secret).update(pullSigningStringV2(timestamp, "POST", CONFIRM_PATH, body)).digest("hex");
6896
+ let origin;
6897
+ try {
6898
+ origin = resolveAppOrigin(appBaseUrl, "confirmUpdate", opts2.allowedHosts);
6899
+ } catch (err) {
6900
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
6901
+ }
5501
6902
  let res;
5502
6903
  try {
5503
- res = await fetchImpl(`${base}/api/confirm`, {
6904
+ res = await fetchImpl(`${origin}${CONFIRM_PATH}`, {
5504
6905
  method: "POST",
5505
6906
  headers: {
5506
6907
  "Content-Type": "application/json",
5507
- "Authorization": `Bearer ${secret}`,
5508
6908
  "X-OneAddress-Timestamp": timestamp,
5509
- "X-OneAddress-Signature": signature
6909
+ "X-OneAddress-Signature": signature,
6910
+ [PULL_SIGNATURE_VERSION_HEADER]: "2"
5510
6911
  },
5511
6912
  // The SAME string that was signed. Not an object, and not re-stringified.
5512
6913
  body
@@ -5532,6 +6933,48 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2) {
5532
6933
  }
5533
6934
  return res.text();
5534
6935
  }
6936
+ var LOA_PUBLIC_KEY_CACHE_MS = 24 * 60 * 60 * 1e3;
6937
+ var loaKeyCache = /* @__PURE__ */ new Map();
6938
+ var loaKeyInFlight = /* @__PURE__ */ new Map();
6939
+ var LoaPublicKeyUnavailableError = class extends Error {
6940
+ constructor(from, cause) {
6941
+ super(
6942
+ `[OneAddress SDK] could not fetch OneAddress's LOA public key from ${from} (${cause}). requireLoa is on (the default since 2.8.0), so this dispatch is refused and OneAddress will retry it. Pin the key with loaPublicKeyPem (from fetchLoaPublicKey), or set requireLoa: false to process dispatches without verifying consent.`
6943
+ );
6944
+ this.from = from;
6945
+ this.name = "LoaPublicKeyUnavailableError";
6946
+ }
6947
+ };
6948
+ async function cachedLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2, now = Date.now()) {
6949
+ const origin = resolveAppOrigin(appBaseUrl, "cachedLoaPublicKey");
6950
+ const held = loaKeyCache.get(origin);
6951
+ if (held && now - held.at < LOA_PUBLIC_KEY_CACHE_MS) return held.pem;
6952
+ let pending = loaKeyInFlight.get(origin);
6953
+ if (!pending) {
6954
+ pending = (async () => {
6955
+ const pem = (await fetchLoaPublicKey(origin)).trim();
6956
+ if (!pem.includes("-----BEGIN PUBLIC KEY-----")) {
6957
+ throw new Error("the response is not a PEM public key");
6958
+ }
6959
+ loaKeyCache.set(origin, { pem, at: Date.now() });
6960
+ return pem;
6961
+ })().finally(() => loaKeyInFlight.delete(origin));
6962
+ loaKeyInFlight.set(origin, pending);
6963
+ }
6964
+ try {
6965
+ return await pending;
6966
+ } catch (err) {
6967
+ if (held) return held.pem;
6968
+ throw new LoaPublicKeyUnavailableError(
6969
+ `${origin}/.well-known/oneaddress-loa-key.pem`,
6970
+ err instanceof Error ? err.message : String(err)
6971
+ );
6972
+ }
6973
+ }
6974
+ function _resetLoaKeyCacheForTests() {
6975
+ loaKeyCache.clear();
6976
+ loaKeyInFlight.clear();
6977
+ }
5535
6978
  async function verifyLOA(loa, publicKeyPem) {
5536
6979
  if (loa.algorithm !== "ECDSA-P256") {
5537
6980
  console.warn(
@@ -5611,6 +7054,91 @@ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expec
5611
7054
  );
5612
7055
  return data;
5613
7056
  }
7057
+ function hasLoaV2(loa) {
7058
+ return typeof loa.oneaddress_signature_v2 === "string";
7059
+ }
7060
+ function canonicalD5LoaFormV2(loa) {
7061
+ return canonicalLoaV2({
7062
+ consumer_name: loa.consumer_name,
7063
+ authorisation_date: loa.authorisation_date,
7064
+ scope: loa.scope,
7065
+ update_uid: loa.update_uid,
7066
+ partner_id: loa.partner_id,
7067
+ envelope_sha256: loa.envelope_sha256,
7068
+ consumer_typed_aliases: loa.consumer_typed_aliases
7069
+ });
7070
+ }
7071
+ function loaEnvelopeSha256(envelope) {
7072
+ return import_crypto2.default.createHash("sha256").update(loaV2EnvelopeDigestInput(envelope), "utf8").digest("hex");
7073
+ }
7074
+ async function verifyD5LOAv2(loa, publicKeyPem) {
7075
+ if (loa.signature_algorithm !== "ECDSA-P256" || !hasLoaV2(loa)) return false;
7076
+ let text;
7077
+ try {
7078
+ text = canonicalD5LoaFormV2(loa);
7079
+ } catch {
7080
+ return false;
7081
+ }
7082
+ try {
7083
+ const key = await import_crypto2.default.subtle.importKey(
7084
+ "spki",
7085
+ pemToBuffer(publicKeyPem),
7086
+ { name: "ECDSA", namedCurve: "P-256" },
7087
+ false,
7088
+ ["verify"]
7089
+ );
7090
+ return await import_crypto2.default.subtle.verify(
7091
+ { name: "ECDSA", hash: "SHA-256" },
7092
+ key,
7093
+ Buffer.from(loa.oneaddress_signature_v2, "hex"),
7094
+ new TextEncoder().encode(text)
7095
+ );
7096
+ } catch {
7097
+ return false;
7098
+ }
7099
+ }
7100
+ function typedAliasesOf(loa) {
7101
+ if (!hasLoaV2(loa)) return [];
7102
+ return acceptTypedAliases(loa.consumer_name, loa.consumer_typed_aliases);
7103
+ }
7104
+ function bodyUpdateIdString(v) {
7105
+ if (typeof v === "string") return v;
7106
+ if (typeof v === "number" && Number.isSafeInteger(v)) return String(v);
7107
+ return null;
7108
+ }
7109
+ async function checkLoaV2(loa, ctx) {
7110
+ if (!hasLoaV2(loa) || typeof loa.partner_id !== "string" || typeof loa.envelope_sha256 !== "string") {
7111
+ return "loa_v2_malformed";
7112
+ }
7113
+ try {
7114
+ canonicalD5LoaFormV2(loa);
7115
+ } catch {
7116
+ return "loa_v2_malformed";
7117
+ }
7118
+ if (ctx.publicKeyPem !== void 0 && !await verifyD5LOAv2(loa, ctx.publicKeyPem)) {
7119
+ return "loa_v2_signature_invalid";
7120
+ }
7121
+ if (loa.partner_id !== ctx.partnerId) return "loa_v2_partner_mismatch";
7122
+ if (bodyUpdateIdString(ctx.updateId) !== loa.update_uid) return "loa_v2_update_mismatch";
7123
+ let digest;
7124
+ try {
7125
+ digest = loaEnvelopeSha256(ctx.envelope);
7126
+ } catch {
7127
+ return "loa_v2_envelope_mismatch";
7128
+ }
7129
+ if (digest !== loa.envelope_sha256) return "loa_v2_envelope_mismatch";
7130
+ if (typeof ctx.envelopeVerifiedName !== "string" || !loaNamesMatch(ctx.envelopeVerifiedName, loa.consumer_name)) {
7131
+ return "loa_v2_name_mismatch";
7132
+ }
7133
+ return null;
7134
+ }
7135
+ var LoaV2RefusedError = class extends Error {
7136
+ constructor(code) {
7137
+ super(`[OneAddress SDK] D5 LOA v2 refused (${code}); refusing rather than applying an update the consent record does not cover`);
7138
+ this.code = code;
7139
+ this.name = "LoaV2RefusedError";
7140
+ }
7141
+ };
5614
7142
  var ADDRESS_REQUIRED_FIELDS = [
5615
7143
  "street",
5616
7144
  "suburb",
@@ -5618,19 +7146,60 @@ var ADDRESS_REQUIRED_FIELDS = [
5618
7146
  "postcode",
5619
7147
  "country"
5620
7148
  ];
7149
+ var MAX_ADDRESS_FIELD_CHARS = 512;
5621
7150
  function validateAddress(raw) {
5622
- if (typeof raw !== "object" || raw === null) {
7151
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
5623
7152
  throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
5624
7153
  }
5625
7154
  const obj = raw;
5626
7155
  for (const field of ADDRESS_REQUIRED_FIELDS) {
5627
- if (typeof obj[field] !== "string" || obj[field] === "") {
7156
+ const value = obj[field];
7157
+ if (typeof value !== "string" || value === "") {
7158
+ throw new Error(
7159
+ `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change - update @oneaddress/partner-sdk.`
7160
+ );
7161
+ }
7162
+ if (value.length > MAX_ADDRESS_FIELD_CHARS) {
5628
7163
  throw new Error(
5629
- `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
7164
+ `[OneAddress SDK] Decrypted address field "${field}" is ${value.length} characters, over the ${MAX_ADDRESS_FIELD_CHARS} this SDK accepts; refusing rather than truncating`
5630
7165
  );
5631
7166
  }
5632
7167
  }
5633
- return obj;
7168
+ const rawUpdatedAt = obj.updated_at;
7169
+ let updatedAt;
7170
+ if (rawUpdatedAt === void 0 || rawUpdatedAt === null) updatedAt = "";
7171
+ else if (typeof rawUpdatedAt === "number" && Number.isFinite(rawUpdatedAt)) updatedAt = String(rawUpdatedAt);
7172
+ else if (typeof rawUpdatedAt === "string") updatedAt = rawUpdatedAt;
7173
+ else throw new Error('[OneAddress SDK] Decrypted address field "updated_at" is not a string');
7174
+ if (updatedAt.length > MAX_ADDRESS_FIELD_CHARS) {
7175
+ throw new Error(
7176
+ `[OneAddress SDK] Decrypted address field "updated_at" is over the ${MAX_ADDRESS_FIELD_CHARS} characters this SDK accepts`
7177
+ );
7178
+ }
7179
+ return {
7180
+ street: obj.street,
7181
+ suburb: obj.suburb,
7182
+ state: obj.state,
7183
+ postcode: obj.postcode,
7184
+ country: obj.country,
7185
+ updated_at: updatedAt
7186
+ };
7187
+ }
7188
+ function legacyAddressOf(blob, body) {
7189
+ return validateAddress({
7190
+ street: blob.street,
7191
+ suburb: blob.suburb,
7192
+ state: blob.state,
7193
+ postcode: blob.postcode,
7194
+ country: blob.country,
7195
+ updated_at: typeof blob.updated_at === "string" ? blob.updated_at : body.timestamp ?? ""
7196
+ });
7197
+ }
7198
+ function stringOr(value, fallback) {
7199
+ return typeof value === "string" ? value : fallback;
7200
+ }
7201
+ function stringsOf(value) {
7202
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
5634
7203
  }
5635
7204
  var ADDRESS_ALIASES = {
5636
7205
  line1: ["line1", "address_line1", "street", "streetAddress"],
@@ -5814,6 +7383,41 @@ function _resetOnceWarningsForTests() {
5814
7383
  warnedNoIdempotencyStore = false;
5815
7384
  }
5816
7385
  var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
7386
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
7387
+ var IN_PROGRESS_RETRY_AFTER_SECS = 30;
7388
+ async function readBodyCapped(req, max) {
7389
+ const declaredLength = req.headers.get("content-length");
7390
+ if (declaredLength !== null && /^\s*\d+\s*$/.test(declaredLength) && Number(declaredLength) > max) {
7391
+ return null;
7392
+ }
7393
+ const stream = req.body;
7394
+ if (stream && typeof stream.getReader === "function") {
7395
+ const reader = stream.getReader();
7396
+ const chunks = [];
7397
+ let total = 0;
7398
+ for (; ; ) {
7399
+ const { done, value } = await reader.read();
7400
+ if (done) break;
7401
+ if (!value) continue;
7402
+ total += value.byteLength;
7403
+ if (total > max) {
7404
+ await reader.cancel().catch(() => void 0);
7405
+ return null;
7406
+ }
7407
+ chunks.push(value);
7408
+ }
7409
+ const joined = new Uint8Array(total);
7410
+ let offset = 0;
7411
+ for (const c of chunks) {
7412
+ joined.set(c, offset);
7413
+ offset += c.byteLength;
7414
+ }
7415
+ return new TextDecoder("utf-8").decode(joined);
7416
+ }
7417
+ const text = await req.text();
7418
+ if (text.length > max || new TextEncoder().encode(text).byteLength > max) return null;
7419
+ return text;
7420
+ }
5817
7421
  var XWING_SEED_BYTES = 32;
5818
7422
  function assertUsablePrivateKey(privateKeyPem) {
5819
7423
  if (typeof privateKeyPem !== "string") {
@@ -5860,13 +7464,16 @@ function createOneAddressHandler(options) {
5860
7464
  expectedAlg,
5861
7465
  keyId,
5862
7466
  loaPublicKeyPem,
5863
- requireLoa = Boolean(loaPublicKeyPem),
7467
+ requireLoa = true,
7468
+ loaPublicKeyBaseUrl,
5864
7469
  confirm,
7470
+ partnerId: configuredPartnerId,
5865
7471
  onUpdate,
5866
7472
  onVerify,
5867
7473
  onAccountVerify,
5868
7474
  onTest,
5869
7475
  timestampToleranceSecs = 300,
7476
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
5870
7477
  idempotencyStore,
5871
7478
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
5872
7479
  allowedCallbackHosts
@@ -5880,6 +7487,9 @@ function createOneAddressHandler(options) {
5880
7487
  `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5881
7488
  );
5882
7489
  }
7490
+ if (typeof maxBodyBytes !== "number" || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0) {
7491
+ throw new Error(`[OneAddress SDK] maxBodyBytes must be a positive whole number of bytes, got ${String(maxBodyBytes)}`);
7492
+ }
5883
7493
  if (webhookSecretGraceUntil !== void 0) {
5884
7494
  const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5885
7495
  if (Number.isNaN(until)) {
@@ -5889,6 +7499,15 @@ function createOneAddressHandler(options) {
5889
7499
  if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5890
7500
  throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5891
7501
  }
7502
+ if (typeof requireLoa !== "boolean") {
7503
+ throw new Error(`[OneAddress SDK] requireLoa must be true or false, got ${String(requireLoa)}`);
7504
+ }
7505
+ if (loaPublicKeyBaseUrl !== void 0) resolveAppOrigin(loaPublicKeyBaseUrl, "loaPublicKeyBaseUrl");
7506
+ async function loaVerificationKey() {
7507
+ if (loaPublicKeyPem) return loaPublicKeyPem;
7508
+ if (!requireLoa) return void 0;
7509
+ return cachedLoaPublicKey(loaPublicKeyBaseUrl ?? OA_APP_BASE_URL2);
7510
+ }
5892
7511
  function enforceLoaPresence(body) {
5893
7512
  const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5894
7513
  if (present) return;
@@ -5901,7 +7520,7 @@ function createOneAddressHandler(options) {
5901
7520
  warnedConsentUnverified = true;
5902
7521
  console.warn(
5903
7522
  // NOSONAR - intentional SDK diagnostic, not user-controlled data
5904
- "[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED. Set loaPublicKeyPem (which turns requireLoa on) to refuse such dispatches. Logged once per process."
7523
+ "[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED. Remove requireLoa: false (it is on by default) to refuse such dispatches. Logged once per process."
5905
7524
  );
5906
7525
  }
5907
7526
  }
@@ -5936,9 +7555,9 @@ function createOneAddressHandler(options) {
5936
7555
  const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
5937
7556
  const customer = {
5938
7557
  email: "",
5939
- name: data.verified_name ?? "",
5940
- account_number: data.account_number ?? null,
5941
- known_names: Array.isArray(data.known_names) ? data.known_names : []
7558
+ name: stringOr(data.verified_name, ""),
7559
+ account_number: stringOr(data.account_number, null),
7560
+ known_names: stringsOf(data.known_names)
5942
7561
  };
5943
7562
  let loa;
5944
7563
  let loa_ref;
@@ -5950,11 +7569,23 @@ function createOneAddressHandler(options) {
5950
7569
  expectedAlg
5951
7570
  );
5952
7571
  loa_ref = d5LoaRef(loa);
5953
- if (loaPublicKeyPem) {
5954
- const valid = await verifyD5LOA(loa, loaPublicKeyPem);
7572
+ const loaKey = await loaVerificationKey();
7573
+ if (loaKey) {
7574
+ const valid = await verifyD5LOA(loa, loaKey);
5955
7575
  if (!valid) throw new Error("D5 LOA signature verification failed");
5956
7576
  }
5957
7577
  assertLoaBoundToEnvelope(loa, data.update_uid);
7578
+ if (hasLoaV2(loa)) {
7579
+ const refusal = await checkLoaV2(loa, {
7580
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
7581
+ updateId: body.update_id,
7582
+ envelope: body.session_envelope,
7583
+ envelopeVerifiedName: data.verified_name,
7584
+ ...loaKey ? { publicKeyPem: loaKey } : {}
7585
+ });
7586
+ if (refusal) throw new LoaV2RefusedError(refusal);
7587
+ customer.known_names = typedAliasesOf(loa);
7588
+ }
5958
7589
  }
5959
7590
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
5960
7591
  }
@@ -5970,7 +7601,13 @@ function createOneAddressHandler(options) {
5970
7601
  return Array.isArray(siblings) && siblings.includes(keyId);
5971
7602
  }
5972
7603
  return async function handler(req) {
5973
- const rawBody = await req.text();
7604
+ const rawBody = await readBodyCapped(req, maxBodyBytes);
7605
+ if (rawBody === null) {
7606
+ return new Response(JSON.stringify({ error: "Payload too large" }), {
7607
+ status: 413,
7608
+ headers: { "Content-Type": "application/json" }
7609
+ });
7610
+ }
5974
7611
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
5975
7612
  const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
5976
7613
  if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
@@ -6007,14 +7644,24 @@ function createOneAddressHandler(options) {
6007
7644
  }
6008
7645
  const partnerId = body.partner_id ?? "";
6009
7646
  const tsNum = Number(tsHeader);
6010
- const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
7647
+ const headerDispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
7648
+ const bodyDispatchId = typeof body.dispatch_id === "string" ? body.dispatch_id : "";
7649
+ if (bodyDispatchId && headerDispatchId && bodyDispatchId !== headerDispatchId) {
7650
+ return new Response(JSON.stringify({ error: "dispatch_id_mismatch" }), {
7651
+ status: 400,
7652
+ headers: { "Content-Type": "application/json" }
7653
+ });
7654
+ }
7655
+ const dispatchId = bodyDispatchId || headerDispatchId;
6011
7656
  if (isCrossoverSiblingToSkip(body)) {
6012
7657
  return declared(200, { ok: true, skipped: true, crossover: true });
6013
7658
  }
7659
+ let claimed = false;
7660
+ let completed = false;
6014
7661
  if (dispatchId) {
6015
7662
  if (!idempotencyStore) {
6016
7663
  const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
6017
- if (nodeEnv === "test") {
7664
+ if (nodeEnv === "test" && headerDispatchId) {
6018
7665
  throw new Error(
6019
7666
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
6020
7667
  );
@@ -6031,6 +7678,17 @@ function createOneAddressHandler(options) {
6031
7678
  if (claim === "duplicate") {
6032
7679
  return declared(200, { ok: true, duplicate: true });
6033
7680
  }
7681
+ if (claim === "in-progress") {
7682
+ return new Response(JSON.stringify({
7683
+ error: "dispatch_in_progress",
7684
+ detail: "Another delivery of this dispatch is being processed. Retry later.",
7685
+ accepted_update_types: acceptedUpdateTypes
7686
+ }), {
7687
+ status: 503,
7688
+ headers: { "Content-Type": "application/json", "Retry-After": String(IN_PROGRESS_RETRY_AFTER_SECS) }
7689
+ });
7690
+ }
7691
+ claimed = true;
6034
7692
  } else {
6035
7693
  const alreadySeen = await idempotencyStore.has(dispatchId);
6036
7694
  if (alreadySeen) {
@@ -6126,16 +7784,27 @@ function createOneAddressHandler(options) {
6126
7784
  expectedAlg
6127
7785
  );
6128
7786
  loa_ref = d5LoaRef(loa);
6129
- if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
7787
+ const loaKey = await loaVerificationKey();
7788
+ if (loaKey && !await verifyD5LOA(loa, loaKey)) {
6130
7789
  throw new Error("D5 LOA signature verification failed");
6131
7790
  }
6132
7791
  assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
7792
+ if (hasLoaV2(loa)) {
7793
+ const refusal = await checkLoaV2(loa, {
7794
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
7795
+ updateId: body.update_id,
7796
+ envelope: encrypted,
7797
+ envelopeVerifiedName: rawAddress.fullName,
7798
+ ...loaKey ? { publicKeyPem: loaKey } : {}
7799
+ });
7800
+ if (refusal) throw new LoaV2RefusedError(refusal);
7801
+ }
6133
7802
  }
6134
7803
  const customer = {
6135
7804
  email: "",
6136
- name: rawAddress.fullName ?? "",
6137
- account_number: rawAddress.accountReference ?? null,
6138
- known_names: Array.isArray(rawAddress.knownNames) ? rawAddress.knownNames : []
7805
+ name: stringOr(rawAddress.fullName, ""),
7806
+ account_number: stringOr(rawAddress.accountReference, null),
7807
+ known_names: loa && hasLoaV2(loa) ? typedAliasesOf(loa) : stringsOf(rawAddress.knownNames)
6139
7808
  };
6140
7809
  event = {
6141
7810
  event: "address.updated",
@@ -6147,7 +7816,8 @@ function createOneAddressHandler(options) {
6147
7816
  customer,
6148
7817
  // The legacy blob predates kinds and always carries an address.
6149
7818
  update_types: ["address"],
6150
- address: validateAddress(rawAddress),
7819
+ // Six named fields, never the blob: see validateAddress.
7820
+ address: legacyAddressOf(rawAddress, body),
6151
7821
  loa,
6152
7822
  loa_ref,
6153
7823
  id_verification: body.id_verification,
@@ -6155,6 +7825,7 @@ function createOneAddressHandler(options) {
6155
7825
  };
6156
7826
  }
6157
7827
  const result = await onUpdate(event);
7828
+ completed = true;
6158
7829
  if (dispatchId && idempotencyStore) {
6159
7830
  const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
6160
7831
  await record.catch(
@@ -6171,6 +7842,7 @@ function createOneAddressHandler(options) {
6171
7842
  status,
6172
7843
  loaRef: event.loa_ref,
6173
7844
  ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
7845
+ ...confirm.allowedHosts ? { allowedHosts: confirm.allowedHosts } : {},
6174
7846
  ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
6175
7847
  }).then(
6176
7848
  (r) => {
@@ -6207,7 +7879,7 @@ function createOneAddressHandler(options) {
6207
7879
  user_id: body.user_id ?? "",
6208
7880
  customer: body.customer,
6209
7881
  customer_match: body.customer_match,
6210
- address: validateAddress(rawAddress),
7882
+ address: legacyAddressOf(rawAddress, body),
6211
7883
  loa: body.loa,
6212
7884
  id_verification: body.id_verification,
6213
7885
  raw: rawAddress
@@ -6246,10 +7918,10 @@ function createOneAddressHandler(options) {
6246
7918
  partnerId
6247
7919
  );
6248
7920
  customer = {
6249
- email: raw.email ?? "",
6250
- name: raw.name ?? "",
6251
- account_number: raw.account_number ?? null,
6252
- known_names: Array.isArray(raw.known_names) ? raw.known_names : []
7921
+ email: stringOr(raw.email, ""),
7922
+ name: stringOr(raw.name, ""),
7923
+ account_number: stringOr(raw.account_number, null),
7924
+ known_names: stringsOf(raw.known_names)
6253
7925
  };
6254
7926
  } else {
6255
7927
  customer = body.customer ?? {};
@@ -6336,6 +8008,13 @@ function createOneAddressHandler(options) {
6336
8008
  status: 500,
6337
8009
  headers: { "Content-Type": "application/json" }
6338
8010
  });
8011
+ } finally {
8012
+ if (claimed && !completed && idempotencyStore?.release) {
8013
+ await idempotencyStore.release(dispatchId).catch(
8014
+ (err) => console.error("[OneAddress SDK] idempotency release failed:", err)
8015
+ // NOSONAR
8016
+ );
8017
+ }
6339
8018
  }
6340
8019
  };
6341
8020
  }
@@ -6409,6 +8088,10 @@ async function buildSignedTestWebhook(opts2) {
6409
8088
  oneaddress_acn: "696 078 869",
6410
8089
  oneaddress_signature: "00".repeat(64),
6411
8090
  signature_algorithm: "ECDSA-P256",
8091
+ partner_id: opts2.partnerId,
8092
+ envelope_sha256: loaEnvelopeSha256(envelope.session_envelope),
8093
+ consumer_typed_aliases: acceptTypedAliases(sessionData.verified_name, sessionData.known_names ?? []),
8094
+ oneaddress_signature_v2: "00".repeat(64),
6412
8095
  ...opts2.loa ?? {}
6413
8096
  };
6414
8097
  if (opts2.loaSigningKeyPem) {
@@ -6419,12 +8102,19 @@ async function buildSignedTestWebhook(opts2) {
6419
8102
  false,
6420
8103
  ["sign"]
6421
8104
  );
6422
- const sig2 = await import_crypto2.default.subtle.sign(
8105
+ const signHex = async (text) => Buffer.from(await import_crypto2.default.subtle.sign(
6423
8106
  { name: "ECDSA", hash: "SHA-256" },
6424
8107
  key,
6425
- new TextEncoder().encode(canonicalD5LoaForm(loa))
6426
- );
6427
- loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
8108
+ new TextEncoder().encode(text)
8109
+ )).toString("hex");
8110
+ loa.oneaddress_signature = await signHex(canonicalD5LoaForm(loa));
8111
+ let v2Text;
8112
+ try {
8113
+ v2Text = canonicalD5LoaFormV2(loa);
8114
+ } catch {
8115
+ v2Text = null;
8116
+ }
8117
+ if (hasLoaV2(loa) && v2Text !== null) loa.oneaddress_signature_v2 = await signHex(v2Text);
6428
8118
  }
6429
8119
  const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
6430
8120
  loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
@@ -6448,7 +8138,6 @@ async function buildSignedTestWebhook(opts2) {
6448
8138
  ...loa_encrypted ? { loa_encrypted } : {},
6449
8139
  // On the wire with a `null` value when no PaymentIntent backed the update,
6450
8140
  // so the KEY is present either way.
6451
- stripe_session_id: opts2.stripeSessionId ?? null,
6452
8141
  // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
6453
8142
  // by default. A test that needs them passes them through `extraBody`, which
6454
8143
  // is exactly the circumstance the relay emits them in.
@@ -6482,12 +8171,26 @@ async function buildSignedTestWebhook(opts2) {
6482
8171
  // Annotate the CommonJS export names for ESM import in node:
6483
8172
  0 && (module.exports = {
6484
8173
  CURRENT_VERSION,
8174
+ DEFAULT_IDEMPOTENCY_LEASE_SECS,
8175
+ DEFAULT_MAX_BODY_BYTES,
6485
8176
  DEFAULT_REPLAY_WINDOW_SECS,
8177
+ LOA_MAX_TYPED_ALIASES,
8178
+ LOA_MIN_SHORT_FORM_LETTERS,
8179
+ LOA_PUBLIC_KEY_CACHE_MS,
8180
+ LOA_V2_REFUSALS,
8181
+ LoaPublicKeyUnavailableError,
8182
+ LoaV2RefusedError,
8183
+ MAX_ADDRESS_FIELD_CHARS,
6486
8184
  OUTBOX_LEASE_COLUMNS,
6487
8185
  SUPPORTED_VERSIONS,
8186
+ _resetLoaKeyCacheForTests,
6488
8187
  _resetOnceWarningsForTests,
8188
+ acceptTypedAliases,
6489
8189
  buildSignedTestWebhook,
8190
+ cachedLoaPublicKey,
6490
8191
  canonicalD5LoaForm,
8192
+ canonicalD5LoaFormV2,
8193
+ checkLoaV2,
6491
8194
  checkRegistryHead,
6492
8195
  compareAddresses,
6493
8196
  computeBlindIndex,
@@ -6504,21 +8207,31 @@ async function buildSignedTestWebhook(opts2) {
6504
8207
  findMatchingStoredName,
6505
8208
  formatAddressParts,
6506
8209
  fromOutboxTimestamp,
8210
+ hasLoaV2,
8211
+ isAcceptableAlias,
6507
8212
  isEmailLike,
6508
8213
  isFreshTimestamp,
8214
+ loaEnvelopeSha256,
8215
+ loaFirstName,
8216
+ loaNamesMatch,
8217
+ loaSurname,
6509
8218
  namePoolMatches,
8219
+ normaliseLoaName,
6510
8220
  normalizeForBlindIndex,
6511
8221
  parsePinnedRegistryRoots,
6512
8222
  readAddressParts,
6513
8223
  sendVerifyResult,
8224
+ signPullRequest,
6514
8225
  toExpressHandler,
6515
8226
  toOutboxTimestamp,
6516
8227
  transform,
6517
8228
  transformAddress,
6518
8229
  transformSession,
8230
+ typedAliasesOf,
6519
8231
  validateAddress,
6520
8232
  verify,
6521
8233
  verifyD5LOA,
8234
+ verifyD5LOAv2,
6522
8235
  verifyGrace,
6523
8236
  verifyLOA,
6524
8237
  verifySignature,
@@ -6531,6 +8244,7 @@ async function buildSignedTestWebhook(opts2) {
6531
8244
  @noble/curves/abstract/curve.js:
6532
8245
  @noble/curves/abstract/edwards.js:
6533
8246
  @noble/curves/abstract/montgomery.js:
8247
+ @noble/curves/abstract/oprf.js:
6534
8248
  @noble/curves/ed25519.js:
6535
8249
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
6536
8250