@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/edge.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) {
@@ -4604,8 +5801,12 @@ var edge_exports = {};
4604
5801
  __export(edge_exports, {
4605
5802
  CURRENT_VERSION: () => CURRENT_VERSION,
4606
5803
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
5804
+ LoaV2RefusedError: () => LoaV2RefusedError,
4607
5805
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
5806
+ acceptTypedAliases: () => acceptTypedAliases,
4608
5807
  canonicalD5LoaForm: () => canonicalD5LoaForm,
5808
+ canonicalD5LoaFormV2: () => canonicalD5LoaFormV2,
5809
+ checkLoaV2: () => checkLoaV2,
4609
5810
  compareAddresses: () => compareAddresses,
4610
5811
  computeBlindIndex: () => computeBlindIndex,
4611
5812
  createOneAddressHandler: () => createOneAddressHandler,
@@ -4615,15 +5816,24 @@ __export(edge_exports, {
4615
5816
  decryptSession: () => decryptSession2,
4616
5817
  fetchLoaPublicKey: () => fetchLoaPublicKey,
4617
5818
  findMatchingStoredName: () => findMatchingStoredName,
5819
+ hasLoaV2: () => hasLoaV2,
5820
+ isAcceptableAlias: () => isAcceptableAlias,
4618
5821
  isEmailLike: () => isEmailLike2,
4619
5822
  isFreshTimestamp: () => isFreshTimestamp,
5823
+ loaEnvelopeSha256: () => loaEnvelopeSha256,
5824
+ loaFirstName: () => loaFirstName,
5825
+ loaNamesMatch: () => loaNamesMatch,
5826
+ loaSurname: () => loaSurname,
4620
5827
  namePoolMatches: () => namePoolMatches,
5828
+ normaliseLoaName: () => normaliseLoaName,
4621
5829
  normalizeForBlindIndex: () => normalizeForBlindIndex,
4622
5830
  sendVerifyResult: () => sendVerifyResult,
4623
5831
  transformAddress: () => transformAddress,
4624
5832
  transformSession: () => transformSession,
5833
+ typedAliasesOf: () => typedAliasesOf,
4625
5834
  validateAddress: () => validateAddress,
4626
5835
  verifyD5LOA: () => verifyD5LOA,
5836
+ verifyD5LOAv2: () => verifyD5LOAv2,
4627
5837
  verifyLOA: () => verifyLOA,
4628
5838
  verifySignature: () => verifySignature,
4629
5839
  verifyWithGrace: () => verifyWithGrace
@@ -4647,7 +5857,6 @@ var D5_BODY_ALWAYS = [
4647
5857
  "partner_id",
4648
5858
  "session_envelope",
4649
5859
  "session_key_share",
4650
- "stripe_session_id",
4651
5860
  "timestamp",
4652
5861
  "update_id",
4653
5862
  "user_id"
@@ -4671,15 +5880,119 @@ var D5_BODY_CONDITIONAL = {
4671
5880
  crossover_key_ids: "key-crossover copy only"
4672
5881
  };
4673
5882
  var D5_BODY_DRILL_ONLY = ["conformance"];
5883
+ var D5_BODY_ADDED_AT_SEND = ["dispatch_id"];
4674
5884
  var D5_BODY_ALL_ALLOWED = [
4675
5885
  ...D5_BODY_ALWAYS,
4676
5886
  ...Object.keys(D5_BODY_CONDITIONAL),
4677
- ...D5_BODY_DRILL_ONLY
5887
+ ...D5_BODY_DRILL_ONLY,
5888
+ ...D5_BODY_ADDED_AT_SEND
4678
5889
  ];
4679
5890
 
4680
5891
  // ../protocol/src/retention.ts
4681
5892
  var DAY_MS = 24 * 60 * 60 * 1e3;
4682
5893
 
5894
+ // ../protocol/src/pull-signature.ts
5895
+ var PULL_SIGNATURE_VERSION_HEADER = "X-OneAddress-Signature-Version";
5896
+ function pullSigningStringV2(timestamp, method, pathAndQuery, body = "") {
5897
+ return `v2.${timestamp}.${method.toUpperCase()}.${pathAndQuery}.${body}`;
5898
+ }
5899
+
5900
+ // ../protocol/src/loa-v2.ts
5901
+ var LOA_V2_VERSION_TAG = "oneaddress-loa/2";
5902
+ var LOA_V2_LEGACY_ENVELOPE_TAG = "oneaddress-legacy-envelope/1";
5903
+ var LOA_V2_FIELD_ORDER = [
5904
+ "consumer_name",
5905
+ "authorisation_date",
5906
+ "scope",
5907
+ "update_uid",
5908
+ "partner_id",
5909
+ "envelope_sha256"
5910
+ ];
5911
+ var LOA_MAX_TYPED_ALIASES = 3;
5912
+ var LoaV2FieldError = class extends Error {
5913
+ constructor(field, reason) {
5914
+ super(`LOA v2 field ${field} ${reason}`);
5915
+ this.field = field;
5916
+ this.name = "LoaV2FieldError";
5917
+ }
5918
+ };
5919
+ var CONTROL_RE = /[\u0000-\u001F\u007F]/;
5920
+ var LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
5921
+ function utf8Length(s) {
5922
+ return new TextEncoder().encode(s).length;
5923
+ }
5924
+ function encodeField(name, value) {
5925
+ if (typeof value !== "string") throw new LoaV2FieldError(name, "is not a string");
5926
+ if (CONTROL_RE.test(value)) throw new LoaV2FieldError(name, "contains a control character");
5927
+ if (LONE_SURROGATE_RE.test(value)) throw new LoaV2FieldError(name, "is not well-formed Unicode");
5928
+ return `${utf8Length(value)}:${value}
5929
+ `;
5930
+ }
5931
+ function canonicalLoaV2(fields) {
5932
+ let out = encodeField("version", LOA_V2_VERSION_TAG);
5933
+ for (const f of LOA_V2_FIELD_ORDER) out += encodeField(f, fields[f]);
5934
+ const aliases = fields.consumer_typed_aliases;
5935
+ if (!Array.isArray(aliases)) throw new LoaV2FieldError("consumer_typed_aliases", "is not a list");
5936
+ if (aliases.length > LOA_MAX_TYPED_ALIASES) {
5937
+ throw new LoaV2FieldError("consumer_typed_aliases", `has more than ${LOA_MAX_TYPED_ALIASES} entries`);
5938
+ }
5939
+ out += encodeField("consumer_typed_aliases", String(aliases.length));
5940
+ for (const a of aliases) out += encodeField("consumer_typed_aliases", a);
5941
+ return out;
5942
+ }
5943
+ function loaV2EnvelopeDigestInput(envelope) {
5944
+ if (typeof envelope === "string") return envelope;
5945
+ if (!envelope || typeof envelope !== "object") {
5946
+ throw new LoaV2FieldError("envelope", "is neither a session_envelope string nor an address_encrypted object");
5947
+ }
5948
+ return encodeField("tag", LOA_V2_LEGACY_ENVELOPE_TAG) + encodeField("ephemeralPublicKey", envelope.ephemeralPublicKey) + encodeField("iv", envelope.iv) + encodeField("ciphertext", envelope.ciphertext) + encodeField("hkdfSalt", envelope.hkdfSalt ?? "");
5949
+ }
5950
+ var ASCII_WS_RE = /[ \t\n\v\f\r]+/;
5951
+ var MARK_RE = /\p{M}/gu;
5952
+ function normaliseLoaName(name) {
5953
+ return name.normalize("NFKD").replace(MARK_RE, "").toLowerCase().replace(/\u03C2/g, "\u03C3").split(ASCII_WS_RE).filter((t) => t.length > 0).join(" ");
5954
+ }
5955
+ function loaSurname(name) {
5956
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
5957
+ return tokens.length > 0 ? tokens[tokens.length - 1] : "";
5958
+ }
5959
+ function loaFirstName(name) {
5960
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
5961
+ return tokens.length > 0 ? tokens[0] : "";
5962
+ }
5963
+ function loaNamesMatch(a, b) {
5964
+ const na = normaliseLoaName(a);
5965
+ return na.length > 0 && na === normaliseLoaName(b);
5966
+ }
5967
+ var LOA_MIN_SHORT_FORM_LETTERS = 3;
5968
+ function codePoints(s) {
5969
+ return Array.from(s).length;
5970
+ }
5971
+ function isAcceptableAlias(verifiedName, alias) {
5972
+ const vFirst = loaFirstName(verifiedName);
5973
+ const aFirst = loaFirstName(alias);
5974
+ if (!vFirst || !aFirst) return false;
5975
+ if (aFirst === vFirst) return true;
5976
+ const [shorter, longer] = codePoints(aFirst) <= codePoints(vFirst) ? [aFirst, vFirst] : [vFirst, aFirst];
5977
+ return codePoints(shorter) >= LOA_MIN_SHORT_FORM_LETTERS && longer.startsWith(shorter);
5978
+ }
5979
+ function acceptTypedAliases(verifiedName, aliases) {
5980
+ const out = [];
5981
+ if (!Array.isArray(aliases)) return out;
5982
+ const seen = /* @__PURE__ */ new Set([normaliseLoaName(verifiedName)]);
5983
+ for (const a of aliases) {
5984
+ if (out.length >= LOA_MAX_TYPED_ALIASES) break;
5985
+ if (typeof a !== "string") continue;
5986
+ if (CONTROL_RE.test(a) || LONE_SURROGATE_RE.test(a)) continue;
5987
+ const n = normaliseLoaName(a);
5988
+ if (!n || seen.has(n)) continue;
5989
+ if (!isAcceptableAlias(verifiedName, a)) continue;
5990
+ seen.add(n);
5991
+ out.push(a);
5992
+ }
5993
+ return out;
5994
+ }
5995
+
4683
5996
  // src/app-hosts.ts
4684
5997
  function allowedAppHosts() {
4685
5998
  const hosts = ["oneaddress.io", "app.oneaddress.io"];
@@ -4688,7 +6001,7 @@ function allowedAppHosts() {
4688
6001
  }
4689
6002
  return new Set(hosts);
4690
6003
  }
4691
- function resolveAppOrigin(baseUrl, label) {
6004
+ function resolveAppOrigin(baseUrl, label, extraHosts) {
4692
6005
  let parsed;
4693
6006
  try {
4694
6007
  parsed = new URL(baseUrl);
@@ -4696,6 +6009,9 @@ function resolveAppOrigin(baseUrl, label) {
4696
6009
  throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
4697
6010
  }
4698
6011
  const allowed = allowedAppHosts();
6012
+ for (const h of extraHosts ?? []) {
6013
+ if (typeof h === "string" && h.trim() !== "") allowed.add(h.trim().toLowerCase());
6014
+ }
4699
6015
  if (!allowed.has(parsed.hostname)) {
4700
6016
  throw new Error(
4701
6017
  `[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
@@ -4731,26 +6047,38 @@ function surnameVariants(token) {
4731
6047
  if (!token.includes("-")) return [token];
4732
6048
  return [token, ...token.split("-").filter(Boolean)];
4733
6049
  }
6050
+ var MAX_ALIASES = 10;
6051
+ var MAX_TOKENS_PER_NAME = 8;
6052
+ var MAX_POOL_TOKENS = 24;
4734
6053
  function namePoolMatches(providedNames, storedName) {
4735
6054
  if (isEmailLike2(storedName)) return false;
4736
- const provided = providedNames.filter((n) => Boolean(n) && !isEmailLike2(n));
6055
+ const provided = providedNames.filter((n) => typeof n === "string" && n !== "" && !isEmailLike2(n));
4737
6056
  const primary = tokenize(provided[0] ?? "");
4738
- if (primary.length === 0) return false;
6057
+ if (primary.length === 0 || primary.length > MAX_TOKENS_PER_NAME) return false;
6058
+ const aliases = provided.slice(1, 1 + MAX_ALIASES).map(tokenize).filter((t) => t.length > 0 && t.length <= MAX_TOKENS_PER_NAME);
6059
+ const distinct = new Set(primary);
6060
+ for (const t of aliases) for (const tok of t) distinct.add(tok);
6061
+ if (distinct.size > MAX_POOL_TOKENS) return false;
4739
6062
  const surnames = new Set(surnameVariants(primary[primary.length - 1]));
4740
- for (let i = 1; i < provided.length; i++) {
4741
- const t = tokenize(provided[i]);
4742
- if (t.length >= 2) for (const v of surnameVariants(t[t.length - 1])) surnames.add(v);
4743
- }
4744
- const all = /* @__PURE__ */ new Set();
4745
- for (const n of provided) for (const t of tokenize(n)) all.add(t);
4746
- const given = [...all].filter((t) => !surnames.has(t));
6063
+ for (const t of aliases) {
6064
+ const last = t[t.length - 1];
6065
+ if (t.length >= 2 && last.length >= 2) for (const v of surnameVariants(last)) surnames.add(v);
6066
+ }
6067
+ const givenSet = /* @__PURE__ */ new Set();
6068
+ for (const tok of primary) if (!surnames.has(tok)) givenSet.add(tok);
6069
+ for (const t of aliases) for (const tok of t) if (tok.length >= 2 && !surnames.has(tok)) givenSet.add(tok);
6070
+ const given = [...givenSet];
6071
+ const fullGiven = given.filter((g) => g.length >= 2);
4747
6072
  const stored = tokenize(storedName);
4748
- if (stored.length === 0) return false;
6073
+ if (stored.length < 2) return false;
4749
6074
  const storedSurname = stored[stored.length - 1];
4750
6075
  const storedGiven = stored.slice(0, -1);
4751
6076
  if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
4752
6077
  const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
4753
- return storedGiven.every(covered);
6078
+ if (!storedGiven.every(covered)) return false;
6079
+ return storedGiven.some(
6080
+ (tok) => fullGiven.includes(tok) || tok.length === 1 && fullGiven.some((g) => g[0] === tok)
6081
+ );
4754
6082
  }
4755
6083
  function findMatchingStoredName(providedNames, storedCandidates) {
4756
6084
  return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
@@ -4765,6 +6093,7 @@ init_src();
4765
6093
  // src/index.ts
4766
6094
  function verifySignature(rawBody, signature, timestamp, secret) {
4767
6095
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
6096
+ if (!secret) return false;
4768
6097
  const sigPayload = `${timestamp}.${rawBody}`;
4769
6098
  const expected = import_crypto2.default.createHmac("sha256", secret).update(sigPayload).digest("hex");
4770
6099
  const sigBuffer = Buffer.from(signature, "hex");
@@ -4915,6 +6244,7 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
4915
6244
  );
4916
6245
  }
4917
6246
  var OA_APP_BASE_URL = "https://oneaddress.io";
6247
+ var CONFIRM_PATH = "/api/confirm";
4918
6248
  async function confirmUpdate(opts2) {
4919
6249
  const {
4920
6250
  partnerId,
@@ -4946,18 +6276,22 @@ async function confirmUpdate(opts2) {
4946
6276
  ...memberName !== void 0 ? { member_name: memberName } : {}
4947
6277
  });
4948
6278
  const timestamp = String(Math.floor(Date.now() / 1e3));
4949
- const signature = import_crypto2.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
4950
- let base = appBaseUrl;
4951
- while (base.endsWith("/")) base = base.slice(0, -1);
6279
+ const signature = import_crypto2.default.createHmac("sha256", secret).update(pullSigningStringV2(timestamp, "POST", CONFIRM_PATH, body)).digest("hex");
6280
+ let origin;
6281
+ try {
6282
+ origin = resolveAppOrigin(appBaseUrl, "confirmUpdate", opts2.allowedHosts);
6283
+ } catch (err) {
6284
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
6285
+ }
4952
6286
  let res;
4953
6287
  try {
4954
- res = await fetchImpl(`${base}/api/confirm`, {
6288
+ res = await fetchImpl(`${origin}${CONFIRM_PATH}`, {
4955
6289
  method: "POST",
4956
6290
  headers: {
4957
6291
  "Content-Type": "application/json",
4958
- "Authorization": `Bearer ${secret}`,
4959
6292
  "X-OneAddress-Timestamp": timestamp,
4960
- "X-OneAddress-Signature": signature
6293
+ "X-OneAddress-Signature": signature,
6294
+ [PULL_SIGNATURE_VERSION_HEADER]: "2"
4961
6295
  },
4962
6296
  // The SAME string that was signed. Not an object, and not re-stringified.
4963
6297
  body
@@ -4983,6 +6317,44 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
4983
6317
  }
4984
6318
  return res.text();
4985
6319
  }
6320
+ var LOA_PUBLIC_KEY_CACHE_MS = 24 * 60 * 60 * 1e3;
6321
+ var loaKeyCache = /* @__PURE__ */ new Map();
6322
+ var loaKeyInFlight = /* @__PURE__ */ new Map();
6323
+ var LoaPublicKeyUnavailableError = class extends Error {
6324
+ constructor(from, cause) {
6325
+ super(
6326
+ `[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.`
6327
+ );
6328
+ this.from = from;
6329
+ this.name = "LoaPublicKeyUnavailableError";
6330
+ }
6331
+ };
6332
+ async function cachedLoaPublicKey(appBaseUrl = OA_APP_BASE_URL, now = Date.now()) {
6333
+ const origin = resolveAppOrigin(appBaseUrl, "cachedLoaPublicKey");
6334
+ const held = loaKeyCache.get(origin);
6335
+ if (held && now - held.at < LOA_PUBLIC_KEY_CACHE_MS) return held.pem;
6336
+ let pending = loaKeyInFlight.get(origin);
6337
+ if (!pending) {
6338
+ pending = (async () => {
6339
+ const pem = (await fetchLoaPublicKey(origin)).trim();
6340
+ if (!pem.includes("-----BEGIN PUBLIC KEY-----")) {
6341
+ throw new Error("the response is not a PEM public key");
6342
+ }
6343
+ loaKeyCache.set(origin, { pem, at: Date.now() });
6344
+ return pem;
6345
+ })().finally(() => loaKeyInFlight.delete(origin));
6346
+ loaKeyInFlight.set(origin, pending);
6347
+ }
6348
+ try {
6349
+ return await pending;
6350
+ } catch (err) {
6351
+ if (held) return held.pem;
6352
+ throw new LoaPublicKeyUnavailableError(
6353
+ `${origin}/.well-known/oneaddress-loa-key.pem`,
6354
+ err instanceof Error ? err.message : String(err)
6355
+ );
6356
+ }
6357
+ }
4986
6358
  async function verifyLOA(loa, publicKeyPem) {
4987
6359
  if (loa.algorithm !== "ECDSA-P256") {
4988
6360
  console.warn(
@@ -5062,6 +6434,91 @@ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expec
5062
6434
  );
5063
6435
  return data;
5064
6436
  }
6437
+ function hasLoaV2(loa) {
6438
+ return typeof loa.oneaddress_signature_v2 === "string";
6439
+ }
6440
+ function canonicalD5LoaFormV2(loa) {
6441
+ return canonicalLoaV2({
6442
+ consumer_name: loa.consumer_name,
6443
+ authorisation_date: loa.authorisation_date,
6444
+ scope: loa.scope,
6445
+ update_uid: loa.update_uid,
6446
+ partner_id: loa.partner_id,
6447
+ envelope_sha256: loa.envelope_sha256,
6448
+ consumer_typed_aliases: loa.consumer_typed_aliases
6449
+ });
6450
+ }
6451
+ function loaEnvelopeSha256(envelope) {
6452
+ return import_crypto2.default.createHash("sha256").update(loaV2EnvelopeDigestInput(envelope), "utf8").digest("hex");
6453
+ }
6454
+ async function verifyD5LOAv2(loa, publicKeyPem) {
6455
+ if (loa.signature_algorithm !== "ECDSA-P256" || !hasLoaV2(loa)) return false;
6456
+ let text;
6457
+ try {
6458
+ text = canonicalD5LoaFormV2(loa);
6459
+ } catch {
6460
+ return false;
6461
+ }
6462
+ try {
6463
+ const key = await import_crypto2.default.subtle.importKey(
6464
+ "spki",
6465
+ pemToBuffer(publicKeyPem),
6466
+ { name: "ECDSA", namedCurve: "P-256" },
6467
+ false,
6468
+ ["verify"]
6469
+ );
6470
+ return await import_crypto2.default.subtle.verify(
6471
+ { name: "ECDSA", hash: "SHA-256" },
6472
+ key,
6473
+ Buffer.from(loa.oneaddress_signature_v2, "hex"),
6474
+ new TextEncoder().encode(text)
6475
+ );
6476
+ } catch {
6477
+ return false;
6478
+ }
6479
+ }
6480
+ function typedAliasesOf(loa) {
6481
+ if (!hasLoaV2(loa)) return [];
6482
+ return acceptTypedAliases(loa.consumer_name, loa.consumer_typed_aliases);
6483
+ }
6484
+ function bodyUpdateIdString(v) {
6485
+ if (typeof v === "string") return v;
6486
+ if (typeof v === "number" && Number.isSafeInteger(v)) return String(v);
6487
+ return null;
6488
+ }
6489
+ async function checkLoaV2(loa, ctx) {
6490
+ if (!hasLoaV2(loa) || typeof loa.partner_id !== "string" || typeof loa.envelope_sha256 !== "string") {
6491
+ return "loa_v2_malformed";
6492
+ }
6493
+ try {
6494
+ canonicalD5LoaFormV2(loa);
6495
+ } catch {
6496
+ return "loa_v2_malformed";
6497
+ }
6498
+ if (ctx.publicKeyPem !== void 0 && !await verifyD5LOAv2(loa, ctx.publicKeyPem)) {
6499
+ return "loa_v2_signature_invalid";
6500
+ }
6501
+ if (loa.partner_id !== ctx.partnerId) return "loa_v2_partner_mismatch";
6502
+ if (bodyUpdateIdString(ctx.updateId) !== loa.update_uid) return "loa_v2_update_mismatch";
6503
+ let digest;
6504
+ try {
6505
+ digest = loaEnvelopeSha256(ctx.envelope);
6506
+ } catch {
6507
+ return "loa_v2_envelope_mismatch";
6508
+ }
6509
+ if (digest !== loa.envelope_sha256) return "loa_v2_envelope_mismatch";
6510
+ if (typeof ctx.envelopeVerifiedName !== "string" || !loaNamesMatch(ctx.envelopeVerifiedName, loa.consumer_name)) {
6511
+ return "loa_v2_name_mismatch";
6512
+ }
6513
+ return null;
6514
+ }
6515
+ var LoaV2RefusedError = class extends Error {
6516
+ constructor(code) {
6517
+ super(`[OneAddress SDK] D5 LOA v2 refused (${code}); refusing rather than applying an update the consent record does not cover`);
6518
+ this.code = code;
6519
+ this.name = "LoaV2RefusedError";
6520
+ }
6521
+ };
5065
6522
  var ADDRESS_REQUIRED_FIELDS = [
5066
6523
  "street",
5067
6524
  "suburb",
@@ -5069,19 +6526,60 @@ var ADDRESS_REQUIRED_FIELDS = [
5069
6526
  "postcode",
5070
6527
  "country"
5071
6528
  ];
6529
+ var MAX_ADDRESS_FIELD_CHARS = 512;
5072
6530
  function validateAddress(raw) {
5073
- if (typeof raw !== "object" || raw === null) {
6531
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
5074
6532
  throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
5075
6533
  }
5076
6534
  const obj = raw;
5077
6535
  for (const field of ADDRESS_REQUIRED_FIELDS) {
5078
- if (typeof obj[field] !== "string" || obj[field] === "") {
6536
+ const value = obj[field];
6537
+ if (typeof value !== "string" || value === "") {
5079
6538
  throw new Error(
5080
- `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
6539
+ `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change - update @oneaddress/partner-sdk.`
6540
+ );
6541
+ }
6542
+ if (value.length > MAX_ADDRESS_FIELD_CHARS) {
6543
+ throw new Error(
6544
+ `[OneAddress SDK] Decrypted address field "${field}" is ${value.length} characters, over the ${MAX_ADDRESS_FIELD_CHARS} this SDK accepts; refusing rather than truncating`
5081
6545
  );
5082
6546
  }
5083
6547
  }
5084
- return obj;
6548
+ const rawUpdatedAt = obj.updated_at;
6549
+ let updatedAt;
6550
+ if (rawUpdatedAt === void 0 || rawUpdatedAt === null) updatedAt = "";
6551
+ else if (typeof rawUpdatedAt === "number" && Number.isFinite(rawUpdatedAt)) updatedAt = String(rawUpdatedAt);
6552
+ else if (typeof rawUpdatedAt === "string") updatedAt = rawUpdatedAt;
6553
+ else throw new Error('[OneAddress SDK] Decrypted address field "updated_at" is not a string');
6554
+ if (updatedAt.length > MAX_ADDRESS_FIELD_CHARS) {
6555
+ throw new Error(
6556
+ `[OneAddress SDK] Decrypted address field "updated_at" is over the ${MAX_ADDRESS_FIELD_CHARS} characters this SDK accepts`
6557
+ );
6558
+ }
6559
+ return {
6560
+ street: obj.street,
6561
+ suburb: obj.suburb,
6562
+ state: obj.state,
6563
+ postcode: obj.postcode,
6564
+ country: obj.country,
6565
+ updated_at: updatedAt
6566
+ };
6567
+ }
6568
+ function legacyAddressOf(blob, body) {
6569
+ return validateAddress({
6570
+ street: blob.street,
6571
+ suburb: blob.suburb,
6572
+ state: blob.state,
6573
+ postcode: blob.postcode,
6574
+ country: blob.country,
6575
+ updated_at: typeof blob.updated_at === "string" ? blob.updated_at : body.timestamp ?? ""
6576
+ });
6577
+ }
6578
+ function stringOr(value, fallback) {
6579
+ return typeof value === "string" ? value : fallback;
6580
+ }
6581
+ function stringsOf(value) {
6582
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
5085
6583
  }
5086
6584
  var STREET_SUFFIX_MAP = {
5087
6585
  st: "street",
@@ -5233,6 +6731,41 @@ var warnedUnhandledEvents = /* @__PURE__ */ new Set();
5233
6731
  var warnedConsentUnverified = false;
5234
6732
  var warnedNoIdempotencyStore = false;
5235
6733
  var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
6734
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
6735
+ var IN_PROGRESS_RETRY_AFTER_SECS = 30;
6736
+ async function readBodyCapped(req, max) {
6737
+ const declaredLength = req.headers.get("content-length");
6738
+ if (declaredLength !== null && /^\s*\d+\s*$/.test(declaredLength) && Number(declaredLength) > max) {
6739
+ return null;
6740
+ }
6741
+ const stream = req.body;
6742
+ if (stream && typeof stream.getReader === "function") {
6743
+ const reader = stream.getReader();
6744
+ const chunks = [];
6745
+ let total = 0;
6746
+ for (; ; ) {
6747
+ const { done, value } = await reader.read();
6748
+ if (done) break;
6749
+ if (!value) continue;
6750
+ total += value.byteLength;
6751
+ if (total > max) {
6752
+ await reader.cancel().catch(() => void 0);
6753
+ return null;
6754
+ }
6755
+ chunks.push(value);
6756
+ }
6757
+ const joined = new Uint8Array(total);
6758
+ let offset = 0;
6759
+ for (const c of chunks) {
6760
+ joined.set(c, offset);
6761
+ offset += c.byteLength;
6762
+ }
6763
+ return new TextDecoder("utf-8").decode(joined);
6764
+ }
6765
+ const text = await req.text();
6766
+ if (text.length > max || new TextEncoder().encode(text).byteLength > max) return null;
6767
+ return text;
6768
+ }
5236
6769
  var XWING_SEED_BYTES = 32;
5237
6770
  function assertUsablePrivateKey(privateKeyPem) {
5238
6771
  if (typeof privateKeyPem !== "string") {
@@ -5279,13 +6812,16 @@ function createOneAddressHandler(options) {
5279
6812
  expectedAlg,
5280
6813
  keyId,
5281
6814
  loaPublicKeyPem,
5282
- requireLoa = Boolean(loaPublicKeyPem),
6815
+ requireLoa = true,
6816
+ loaPublicKeyBaseUrl,
5283
6817
  confirm,
6818
+ partnerId: configuredPartnerId,
5284
6819
  onUpdate,
5285
6820
  onVerify,
5286
6821
  onAccountVerify,
5287
6822
  onTest,
5288
6823
  timestampToleranceSecs = 300,
6824
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
5289
6825
  idempotencyStore,
5290
6826
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
5291
6827
  allowedCallbackHosts
@@ -5299,6 +6835,9 @@ function createOneAddressHandler(options) {
5299
6835
  `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5300
6836
  );
5301
6837
  }
6838
+ if (typeof maxBodyBytes !== "number" || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0) {
6839
+ throw new Error(`[OneAddress SDK] maxBodyBytes must be a positive whole number of bytes, got ${String(maxBodyBytes)}`);
6840
+ }
5302
6841
  if (webhookSecretGraceUntil !== void 0) {
5303
6842
  const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5304
6843
  if (Number.isNaN(until)) {
@@ -5308,6 +6847,15 @@ function createOneAddressHandler(options) {
5308
6847
  if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5309
6848
  throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5310
6849
  }
6850
+ if (typeof requireLoa !== "boolean") {
6851
+ throw new Error(`[OneAddress SDK] requireLoa must be true or false, got ${String(requireLoa)}`);
6852
+ }
6853
+ if (loaPublicKeyBaseUrl !== void 0) resolveAppOrigin(loaPublicKeyBaseUrl, "loaPublicKeyBaseUrl");
6854
+ async function loaVerificationKey() {
6855
+ if (loaPublicKeyPem) return loaPublicKeyPem;
6856
+ if (!requireLoa) return void 0;
6857
+ return cachedLoaPublicKey(loaPublicKeyBaseUrl ?? OA_APP_BASE_URL);
6858
+ }
5311
6859
  function enforceLoaPresence(body) {
5312
6860
  const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5313
6861
  if (present) return;
@@ -5320,7 +6868,7 @@ function createOneAddressHandler(options) {
5320
6868
  warnedConsentUnverified = true;
5321
6869
  console.warn(
5322
6870
  // NOSONAR - intentional SDK diagnostic, not user-controlled data
5323
- "[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."
6871
+ "[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."
5324
6872
  );
5325
6873
  }
5326
6874
  }
@@ -5355,9 +6903,9 @@ function createOneAddressHandler(options) {
5355
6903
  const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
5356
6904
  const customer = {
5357
6905
  email: "",
5358
- name: data.verified_name ?? "",
5359
- account_number: data.account_number ?? null,
5360
- known_names: Array.isArray(data.known_names) ? data.known_names : []
6906
+ name: stringOr(data.verified_name, ""),
6907
+ account_number: stringOr(data.account_number, null),
6908
+ known_names: stringsOf(data.known_names)
5361
6909
  };
5362
6910
  let loa;
5363
6911
  let loa_ref;
@@ -5369,11 +6917,23 @@ function createOneAddressHandler(options) {
5369
6917
  expectedAlg
5370
6918
  );
5371
6919
  loa_ref = d5LoaRef(loa);
5372
- if (loaPublicKeyPem) {
5373
- const valid = await verifyD5LOA(loa, loaPublicKeyPem);
6920
+ const loaKey = await loaVerificationKey();
6921
+ if (loaKey) {
6922
+ const valid = await verifyD5LOA(loa, loaKey);
5374
6923
  if (!valid) throw new Error("D5 LOA signature verification failed");
5375
6924
  }
5376
6925
  assertLoaBoundToEnvelope(loa, data.update_uid);
6926
+ if (hasLoaV2(loa)) {
6927
+ const refusal = await checkLoaV2(loa, {
6928
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
6929
+ updateId: body.update_id,
6930
+ envelope: body.session_envelope,
6931
+ envelopeVerifiedName: data.verified_name,
6932
+ ...loaKey ? { publicKeyPem: loaKey } : {}
6933
+ });
6934
+ if (refusal) throw new LoaV2RefusedError(refusal);
6935
+ customer.known_names = typedAliasesOf(loa);
6936
+ }
5377
6937
  }
5378
6938
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
5379
6939
  }
@@ -5389,7 +6949,13 @@ function createOneAddressHandler(options) {
5389
6949
  return Array.isArray(siblings) && siblings.includes(keyId);
5390
6950
  }
5391
6951
  return async function handler(req) {
5392
- const rawBody = await req.text();
6952
+ const rawBody = await readBodyCapped(req, maxBodyBytes);
6953
+ if (rawBody === null) {
6954
+ return new Response(JSON.stringify({ error: "Payload too large" }), {
6955
+ status: 413,
6956
+ headers: { "Content-Type": "application/json" }
6957
+ });
6958
+ }
5393
6959
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
5394
6960
  const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
5395
6961
  if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
@@ -5426,14 +6992,24 @@ function createOneAddressHandler(options) {
5426
6992
  }
5427
6993
  const partnerId = body.partner_id ?? "";
5428
6994
  const tsNum = Number(tsHeader);
5429
- const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
6995
+ const headerDispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
6996
+ const bodyDispatchId = typeof body.dispatch_id === "string" ? body.dispatch_id : "";
6997
+ if (bodyDispatchId && headerDispatchId && bodyDispatchId !== headerDispatchId) {
6998
+ return new Response(JSON.stringify({ error: "dispatch_id_mismatch" }), {
6999
+ status: 400,
7000
+ headers: { "Content-Type": "application/json" }
7001
+ });
7002
+ }
7003
+ const dispatchId = bodyDispatchId || headerDispatchId;
5430
7004
  if (isCrossoverSiblingToSkip(body)) {
5431
7005
  return declared(200, { ok: true, skipped: true, crossover: true });
5432
7006
  }
7007
+ let claimed = false;
7008
+ let completed = false;
5433
7009
  if (dispatchId) {
5434
7010
  if (!idempotencyStore) {
5435
7011
  const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
5436
- if (nodeEnv === "test") {
7012
+ if (nodeEnv === "test" && headerDispatchId) {
5437
7013
  throw new Error(
5438
7014
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
5439
7015
  );
@@ -5450,6 +7026,17 @@ function createOneAddressHandler(options) {
5450
7026
  if (claim === "duplicate") {
5451
7027
  return declared(200, { ok: true, duplicate: true });
5452
7028
  }
7029
+ if (claim === "in-progress") {
7030
+ return new Response(JSON.stringify({
7031
+ error: "dispatch_in_progress",
7032
+ detail: "Another delivery of this dispatch is being processed. Retry later.",
7033
+ accepted_update_types: acceptedUpdateTypes
7034
+ }), {
7035
+ status: 503,
7036
+ headers: { "Content-Type": "application/json", "Retry-After": String(IN_PROGRESS_RETRY_AFTER_SECS) }
7037
+ });
7038
+ }
7039
+ claimed = true;
5453
7040
  } else {
5454
7041
  const alreadySeen = await idempotencyStore.has(dispatchId);
5455
7042
  if (alreadySeen) {
@@ -5545,16 +7132,27 @@ function createOneAddressHandler(options) {
5545
7132
  expectedAlg
5546
7133
  );
5547
7134
  loa_ref = d5LoaRef(loa);
5548
- if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
7135
+ const loaKey = await loaVerificationKey();
7136
+ if (loaKey && !await verifyD5LOA(loa, loaKey)) {
5549
7137
  throw new Error("D5 LOA signature verification failed");
5550
7138
  }
5551
7139
  assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
7140
+ if (hasLoaV2(loa)) {
7141
+ const refusal = await checkLoaV2(loa, {
7142
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
7143
+ updateId: body.update_id,
7144
+ envelope: encrypted,
7145
+ envelopeVerifiedName: rawAddress.fullName,
7146
+ ...loaKey ? { publicKeyPem: loaKey } : {}
7147
+ });
7148
+ if (refusal) throw new LoaV2RefusedError(refusal);
7149
+ }
5552
7150
  }
5553
7151
  const customer = {
5554
7152
  email: "",
5555
- name: rawAddress.fullName ?? "",
5556
- account_number: rawAddress.accountReference ?? null,
5557
- known_names: Array.isArray(rawAddress.knownNames) ? rawAddress.knownNames : []
7153
+ name: stringOr(rawAddress.fullName, ""),
7154
+ account_number: stringOr(rawAddress.accountReference, null),
7155
+ known_names: loa && hasLoaV2(loa) ? typedAliasesOf(loa) : stringsOf(rawAddress.knownNames)
5558
7156
  };
5559
7157
  event = {
5560
7158
  event: "address.updated",
@@ -5566,7 +7164,8 @@ function createOneAddressHandler(options) {
5566
7164
  customer,
5567
7165
  // The legacy blob predates kinds and always carries an address.
5568
7166
  update_types: ["address"],
5569
- address: validateAddress(rawAddress),
7167
+ // Six named fields, never the blob: see validateAddress.
7168
+ address: legacyAddressOf(rawAddress, body),
5570
7169
  loa,
5571
7170
  loa_ref,
5572
7171
  id_verification: body.id_verification,
@@ -5574,6 +7173,7 @@ function createOneAddressHandler(options) {
5574
7173
  };
5575
7174
  }
5576
7175
  const result = await onUpdate(event);
7176
+ completed = true;
5577
7177
  if (dispatchId && idempotencyStore) {
5578
7178
  const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
5579
7179
  await record.catch(
@@ -5590,6 +7190,7 @@ function createOneAddressHandler(options) {
5590
7190
  status,
5591
7191
  loaRef: event.loa_ref,
5592
7192
  ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
7193
+ ...confirm.allowedHosts ? { allowedHosts: confirm.allowedHosts } : {},
5593
7194
  ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
5594
7195
  }).then(
5595
7196
  (r) => {
@@ -5626,7 +7227,7 @@ function createOneAddressHandler(options) {
5626
7227
  user_id: body.user_id ?? "",
5627
7228
  customer: body.customer,
5628
7229
  customer_match: body.customer_match,
5629
- address: validateAddress(rawAddress),
7230
+ address: legacyAddressOf(rawAddress, body),
5630
7231
  loa: body.loa,
5631
7232
  id_verification: body.id_verification,
5632
7233
  raw: rawAddress
@@ -5665,10 +7266,10 @@ function createOneAddressHandler(options) {
5665
7266
  partnerId
5666
7267
  );
5667
7268
  customer = {
5668
- email: raw.email ?? "",
5669
- name: raw.name ?? "",
5670
- account_number: raw.account_number ?? null,
5671
- known_names: Array.isArray(raw.known_names) ? raw.known_names : []
7269
+ email: stringOr(raw.email, ""),
7270
+ name: stringOr(raw.name, ""),
7271
+ account_number: stringOr(raw.account_number, null),
7272
+ known_names: stringsOf(raw.known_names)
5672
7273
  };
5673
7274
  } else {
5674
7275
  customer = body.customer ?? {};
@@ -5755,6 +7356,13 @@ function createOneAddressHandler(options) {
5755
7356
  status: 500,
5756
7357
  headers: { "Content-Type": "application/json" }
5757
7358
  });
7359
+ } finally {
7360
+ if (claimed && !completed && idempotencyStore?.release) {
7361
+ await idempotencyStore.release(dispatchId).catch(
7362
+ (err) => console.error("[OneAddress SDK] idempotency release failed:", err)
7363
+ // NOSONAR
7364
+ );
7365
+ }
5758
7366
  }
5759
7367
  };
5760
7368
  }
@@ -5762,8 +7370,12 @@ function createOneAddressHandler(options) {
5762
7370
  0 && (module.exports = {
5763
7371
  CURRENT_VERSION,
5764
7372
  DEFAULT_REPLAY_WINDOW_SECS,
7373
+ LoaV2RefusedError,
5765
7374
  SUPPORTED_VERSIONS,
7375
+ acceptTypedAliases,
5766
7376
  canonicalD5LoaForm,
7377
+ canonicalD5LoaFormV2,
7378
+ checkLoaV2,
5767
7379
  compareAddresses,
5768
7380
  computeBlindIndex,
5769
7381
  createOneAddressHandler,
@@ -5773,15 +7385,24 @@ function createOneAddressHandler(options) {
5773
7385
  decryptSession,
5774
7386
  fetchLoaPublicKey,
5775
7387
  findMatchingStoredName,
7388
+ hasLoaV2,
7389
+ isAcceptableAlias,
5776
7390
  isEmailLike,
5777
7391
  isFreshTimestamp,
7392
+ loaEnvelopeSha256,
7393
+ loaFirstName,
7394
+ loaNamesMatch,
7395
+ loaSurname,
5778
7396
  namePoolMatches,
7397
+ normaliseLoaName,
5779
7398
  normalizeForBlindIndex,
5780
7399
  sendVerifyResult,
5781
7400
  transformAddress,
5782
7401
  transformSession,
7402
+ typedAliasesOf,
5783
7403
  validateAddress,
5784
7404
  verifyD5LOA,
7405
+ verifyD5LOAv2,
5785
7406
  verifyLOA,
5786
7407
  verifySignature,
5787
7408
  verifyWithGrace
@@ -5793,6 +7414,7 @@ function createOneAddressHandler(options) {
5793
7414
  @noble/curves/abstract/curve.js:
5794
7415
  @noble/curves/abstract/edwards.js:
5795
7416
  @noble/curves/abstract/montgomery.js:
7417
+ @noble/curves/abstract/oprf.js:
5796
7418
  @noble/curves/ed25519.js:
5797
7419
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
5798
7420