@oneaddress/partner-sdk 1.2.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,8 +5,14 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __esm = (fn, res, err) => function __init() {
10
+ if (err) throw err[0];
11
+ try {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
+ } catch (e) {
14
+ throw err = [e], e;
15
+ }
10
16
  };
11
17
  var __export = (target, all) => {
12
18
  for (var name in all)
@@ -18,17 +24,3185 @@ var __copyProps = (to, from, except, desc) => {
18
24
  if (!__hasOwnProp.call(to, key) && key !== except)
19
25
  __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
26
  }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ return to;
28
+ };
29
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
30
+ // If the importer is in node compatibility mode or this is not an ESM
31
+ // file that has been converted to a CommonJS file using a Babel-
32
+ // compatible transform (i.e. "__esModule" has not been set), then set
33
+ // "default" to the CommonJS "module.exports" for node compatibility.
34
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
35
+ mod2
36
+ ));
37
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
38
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
39
+
40
+ // ../../node_modules/@noble/hashes/utils.js
41
+ function isBytes(a) {
42
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
43
+ }
44
+ function anumber(n, title = "") {
45
+ if (typeof n !== "number") {
46
+ const prefix = title && `"${title}" `;
47
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
48
+ }
49
+ if (!Number.isSafeInteger(n) || n < 0) {
50
+ const prefix = title && `"${title}" `;
51
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
52
+ }
53
+ }
54
+ function abytes(value, length, title = "") {
55
+ const bytes = isBytes(value);
56
+ const len = value?.length;
57
+ const needsLen = length !== void 0;
58
+ if (!bytes || needsLen && len !== length) {
59
+ const prefix = title && `"${title}" `;
60
+ const ofLen = needsLen ? ` of length ${length}` : "";
61
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
62
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
63
+ if (!bytes)
64
+ throw new TypeError(message);
65
+ throw new RangeError(message);
66
+ }
67
+ return value;
68
+ }
69
+ function aexists(instance, checkFinished = true) {
70
+ if (instance.destroyed)
71
+ throw new Error("Hash instance has been destroyed");
72
+ if (checkFinished && instance.finished)
73
+ throw new Error("Hash#digest() has already been called");
74
+ }
75
+ function aoutput(out, instance) {
76
+ abytes(out, void 0, "digestInto() output");
77
+ const min = instance.outputLen;
78
+ if (out.length < min) {
79
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
80
+ }
81
+ }
82
+ function u32(arr) {
83
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
84
+ }
85
+ function clean(...arrays) {
86
+ for (let i = 0; i < arrays.length; i++) {
87
+ arrays[i].fill(0);
88
+ }
89
+ }
90
+ function createView(arr) {
91
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
92
+ }
93
+ function byteSwap(word) {
94
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
95
+ }
96
+ function byteSwap32(arr) {
97
+ for (let i = 0; i < arr.length; i++) {
98
+ arr[i] = byteSwap(arr[i]);
99
+ }
100
+ return arr;
101
+ }
102
+ function bytesToHex(bytes) {
103
+ abytes(bytes);
104
+ if (hasHexBuiltin)
105
+ return bytes.toHex();
106
+ let hex = "";
107
+ for (let i = 0; i < bytes.length; i++) {
108
+ hex += hexes[bytes[i]];
109
+ }
110
+ return hex;
111
+ }
112
+ function asciiToBase16(ch) {
113
+ if (ch >= asciis._0 && ch <= asciis._9)
114
+ return ch - asciis._0;
115
+ if (ch >= asciis.A && ch <= asciis.F)
116
+ return ch - (asciis.A - 10);
117
+ if (ch >= asciis.a && ch <= asciis.f)
118
+ return ch - (asciis.a - 10);
119
+ return;
120
+ }
121
+ function hexToBytes(hex) {
122
+ if (typeof hex !== "string")
123
+ throw new TypeError("hex string expected, got " + typeof hex);
124
+ if (hasHexBuiltin) {
125
+ try {
126
+ return Uint8Array.fromHex(hex);
127
+ } catch (error) {
128
+ if (error instanceof SyntaxError)
129
+ throw new RangeError(error.message);
130
+ throw error;
131
+ }
132
+ }
133
+ const hl = hex.length;
134
+ const al = hl / 2;
135
+ if (hl % 2)
136
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
137
+ const array = new Uint8Array(al);
138
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
139
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
140
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
141
+ if (n1 === void 0 || n2 === void 0) {
142
+ const char = hex[hi] + hex[hi + 1];
143
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
144
+ }
145
+ array[ai] = n1 * 16 + n2;
146
+ }
147
+ return array;
148
+ }
149
+ function concatBytes(...arrays) {
150
+ let sum = 0;
151
+ for (let i = 0; i < arrays.length; i++) {
152
+ const a = arrays[i];
153
+ abytes(a);
154
+ sum += a.length;
155
+ }
156
+ const res = new Uint8Array(sum);
157
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
158
+ const a = arrays[i];
159
+ res.set(a, pad);
160
+ pad += a.length;
161
+ }
162
+ return res;
163
+ }
164
+ function createHasher(hashCons, info = {}) {
165
+ const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest();
166
+ const tmp = hashCons(void 0);
167
+ hashC.outputLen = tmp.outputLen;
168
+ hashC.blockLen = tmp.blockLen;
169
+ hashC.canXOF = tmp.canXOF;
170
+ hashC.create = (opts2) => hashCons(opts2);
171
+ Object.assign(hashC, info);
172
+ return Object.freeze(hashC);
173
+ }
174
+ function randomBytes(bytesLength = 32) {
175
+ anumber(bytesLength, "bytesLength");
176
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
177
+ if (typeof cr?.getRandomValues !== "function")
178
+ throw new Error("crypto.getRandomValues must be defined");
179
+ if (bytesLength > 65536)
180
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
181
+ return cr.getRandomValues(new Uint8Array(bytesLength));
182
+ }
183
+ var isLE, swap32IfBE, hasHexBuiltin, hexes, asciis, oidNist;
184
+ var init_utils = __esm({
185
+ "../../node_modules/@noble/hashes/utils.js"() {
186
+ "use strict";
187
+ isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
188
+ swap32IfBE = isLE ? (u) => u : byteSwap32;
189
+ hasHexBuiltin = /* @__PURE__ */ (() => (
190
+ // @ts-ignore
191
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
192
+ ))();
193
+ hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
194
+ asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
195
+ oidNist = (suffix) => ({
196
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
197
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
198
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
199
+ });
200
+ }
201
+ });
202
+
203
+ // ../../node_modules/@noble/curves/utils.js
204
+ function abool(value, title = "") {
205
+ if (typeof value !== "boolean") {
206
+ const prefix = title && `"${title}" `;
207
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
208
+ }
209
+ return value;
210
+ }
211
+ function abignumber(n) {
212
+ if (typeof n === "bigint") {
213
+ if (!isPosBig(n))
214
+ throw new RangeError("positive bigint expected, got " + n);
215
+ } else
216
+ anumber2(n);
217
+ return n;
218
+ }
219
+ function asafenumber(value, title = "") {
220
+ if (typeof value !== "number") {
221
+ const prefix = title && `"${title}" `;
222
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
223
+ }
224
+ if (!Number.isSafeInteger(value)) {
225
+ const prefix = title && `"${title}" `;
226
+ throw new RangeError(prefix + "expected safe integer, got " + value);
227
+ }
228
+ }
229
+ function hexToNumber(hex) {
230
+ if (typeof hex !== "string")
231
+ throw new TypeError("hex string expected, got " + typeof hex);
232
+ return hex === "" ? _0n : BigInt("0x" + hex);
233
+ }
234
+ function bytesToNumberBE(bytes) {
235
+ return hexToNumber(bytesToHex(bytes));
236
+ }
237
+ function bytesToNumberLE(bytes) {
238
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
239
+ }
240
+ function numberToBytesBE(n, len) {
241
+ anumber(len);
242
+ if (len === 0)
243
+ throw new RangeError("zero length");
244
+ n = abignumber(n);
245
+ const hex = n.toString(16);
246
+ if (hex.length > len * 2)
247
+ throw new RangeError("number too large");
248
+ return hexToBytes(hex.padStart(len * 2, "0"));
249
+ }
250
+ function numberToBytesLE(n, len) {
251
+ return numberToBytesBE(n, len).reverse();
252
+ }
253
+ function equalBytes(a, b) {
254
+ a = abytes2(a);
255
+ b = abytes2(b);
256
+ if (a.length !== b.length)
257
+ return false;
258
+ let diff = 0;
259
+ for (let i = 0; i < a.length; i++)
260
+ diff |= a[i] ^ b[i];
261
+ return diff === 0;
262
+ }
263
+ function copyBytes(bytes) {
264
+ return Uint8Array.from(abytes2(bytes));
265
+ }
266
+ function asciiToBytes(ascii) {
267
+ if (typeof ascii !== "string")
268
+ throw new TypeError("ascii string expected, got " + typeof ascii);
269
+ return Uint8Array.from(ascii, (c, i) => {
270
+ const charCode = c.charCodeAt(0);
271
+ if (c.length !== 1 || charCode > 127) {
272
+ throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
273
+ }
274
+ return charCode;
275
+ });
276
+ }
277
+ function inRange(n, min, max) {
278
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
279
+ }
280
+ function aInRange(title, n, min, max) {
281
+ if (!inRange(n, min, max))
282
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
283
+ }
284
+ function bitLen(n) {
285
+ if (n < _0n)
286
+ throw new Error("expected non-negative bigint, got " + n);
287
+ let len;
288
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
289
+ ;
290
+ return len;
291
+ }
292
+ function validateObject(object, fields = {}, optFields = {}) {
293
+ if (Object.prototype.toString.call(object) !== "[object Object]")
294
+ throw new TypeError("expected valid options object");
295
+ function checkField(fieldName, expectedType, isOpt) {
296
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
297
+ throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
298
+ const val = object[fieldName];
299
+ if (isOpt && val === void 0)
300
+ return;
301
+ const current = typeof val;
302
+ if (current !== expectedType || val === null)
303
+ throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
304
+ }
305
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
306
+ iter(fields, false);
307
+ iter(optFields, true);
308
+ }
309
+ var abytes2, anumber2, bytesToHex2, concatBytes2, hexToBytes2, isBytes2, randomBytes2, _0n, _1n, isPosBig, bitMask, notImplemented;
310
+ var init_utils2 = __esm({
311
+ "../../node_modules/@noble/curves/utils.js"() {
312
+ "use strict";
313
+ init_utils();
314
+ abytes2 = (value, length, title) => abytes(value, length, title);
315
+ anumber2 = anumber;
316
+ bytesToHex2 = bytesToHex;
317
+ concatBytes2 = (...arrays) => concatBytes(...arrays);
318
+ hexToBytes2 = (hex) => hexToBytes(hex);
319
+ isBytes2 = isBytes;
320
+ randomBytes2 = (bytesLength) => randomBytes(bytesLength);
321
+ _0n = /* @__PURE__ */ BigInt(0);
322
+ _1n = /* @__PURE__ */ BigInt(1);
323
+ isPosBig = (n) => typeof n === "bigint" && _0n <= n;
324
+ bitMask = (n) => (_1n << BigInt(n)) - _1n;
325
+ notImplemented = () => {
326
+ throw new Error("not implemented");
327
+ };
328
+ }
329
+ });
330
+
331
+ // ../../node_modules/@noble/curves/abstract/modular.js
332
+ function mod(a, b) {
333
+ if (b <= _0n2)
334
+ throw new Error("mod: expected positive modulus, got " + b);
335
+ const result = a % b;
336
+ return result >= _0n2 ? result : b + result;
337
+ }
338
+ function pow2(x, power, modulo) {
339
+ if (power < _0n2)
340
+ throw new Error("pow2: expected non-negative exponent, got " + power);
341
+ let res = x;
342
+ while (power-- > _0n2) {
343
+ res *= res;
344
+ res %= modulo;
345
+ }
346
+ return res;
347
+ }
348
+ function invert(number, modulo) {
349
+ if (number === _0n2)
350
+ throw new Error("invert: expected non-zero number");
351
+ if (modulo <= _0n2)
352
+ throw new Error("invert: expected positive modulus, got " + modulo);
353
+ let a = mod(number, modulo);
354
+ let b = modulo;
355
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
356
+ while (a !== _0n2) {
357
+ const q = b / a;
358
+ const r = b - a * q;
359
+ const m = x - u * q;
360
+ const n = y - v * q;
361
+ b = a, a = r, x = u, y = v, u = m, v = n;
362
+ }
363
+ const gcd = b;
364
+ if (gcd !== _1n2)
365
+ throw new Error("invert: does not exist");
366
+ return mod(x, modulo);
367
+ }
368
+ function assertIsSquare(Fp2, root, n) {
369
+ const F2 = Fp2;
370
+ if (!F2.eql(F2.sqr(root), n))
371
+ throw new Error("Cannot find square root");
372
+ }
373
+ function sqrt3mod4(Fp2, n) {
374
+ const F2 = Fp2;
375
+ const p1div4 = (F2.ORDER + _1n2) / _4n;
376
+ const root = F2.pow(n, p1div4);
377
+ assertIsSquare(F2, root, n);
378
+ return root;
379
+ }
380
+ function sqrt5mod8(Fp2, n) {
381
+ const F2 = Fp2;
382
+ const p5div8 = (F2.ORDER - _5n) / _8n;
383
+ const n2 = F2.mul(n, _2n);
384
+ const v = F2.pow(n2, p5div8);
385
+ const nv = F2.mul(n, v);
386
+ const i = F2.mul(F2.mul(nv, _2n), v);
387
+ const root = F2.mul(nv, F2.sub(i, F2.ONE));
388
+ assertIsSquare(F2, root, n);
389
+ return root;
390
+ }
391
+ function sqrt9mod16(P) {
392
+ const Fp_ = Field(P);
393
+ const tn = tonelliShanks(P);
394
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
395
+ const c2 = tn(Fp_, c1);
396
+ const c3 = tn(Fp_, Fp_.neg(c1));
397
+ const c4 = (P + _7n) / _16n;
398
+ return ((Fp2, n) => {
399
+ const F2 = Fp2;
400
+ let tv1 = F2.pow(n, c4);
401
+ let tv2 = F2.mul(tv1, c1);
402
+ const tv3 = F2.mul(tv1, c2);
403
+ const tv4 = F2.mul(tv1, c3);
404
+ const e1 = F2.eql(F2.sqr(tv2), n);
405
+ const e2 = F2.eql(F2.sqr(tv3), n);
406
+ tv1 = F2.cmov(tv1, tv2, e1);
407
+ tv2 = F2.cmov(tv4, tv3, e2);
408
+ const e3 = F2.eql(F2.sqr(tv2), n);
409
+ const root = F2.cmov(tv1, tv2, e3);
410
+ assertIsSquare(F2, root, n);
411
+ return root;
412
+ });
413
+ }
414
+ function tonelliShanks(P) {
415
+ if (P < _3n)
416
+ throw new Error("sqrt is not defined for small field");
417
+ let Q2 = P - _1n2;
418
+ let S = 0;
419
+ while (Q2 % _2n === _0n2) {
420
+ Q2 /= _2n;
421
+ S++;
422
+ }
423
+ let Z = _2n;
424
+ const _Fp = Field(P);
425
+ while (FpLegendre(_Fp, Z) === 1) {
426
+ if (Z++ > 1e3)
427
+ throw new Error("Cannot find square root: probably non-prime P");
428
+ }
429
+ if (S === 1)
430
+ return sqrt3mod4;
431
+ let cc = _Fp.pow(Z, Q2);
432
+ const Q1div2 = (Q2 + _1n2) / _2n;
433
+ return function tonelliSlow(Fp2, n) {
434
+ const F2 = Fp2;
435
+ if (F2.is0(n))
436
+ return n;
437
+ if (FpLegendre(F2, n) !== 1)
438
+ throw new Error("Cannot find square root");
439
+ let M = S;
440
+ let c = F2.mul(F2.ONE, cc);
441
+ let t = F2.pow(n, Q2);
442
+ let R = F2.pow(n, Q1div2);
443
+ while (!F2.eql(t, F2.ONE)) {
444
+ if (F2.is0(t))
445
+ return F2.ZERO;
446
+ let i = 1;
447
+ let t_tmp = F2.sqr(t);
448
+ while (!F2.eql(t_tmp, F2.ONE)) {
449
+ i++;
450
+ t_tmp = F2.sqr(t_tmp);
451
+ if (i === M)
452
+ throw new Error("Cannot find square root");
453
+ }
454
+ const exponent = _1n2 << BigInt(M - i - 1);
455
+ const b = F2.pow(c, exponent);
456
+ M = i;
457
+ c = F2.sqr(b);
458
+ t = F2.mul(t, c);
459
+ R = F2.mul(R, b);
460
+ }
461
+ return R;
462
+ };
463
+ }
464
+ function FpSqrt(P) {
465
+ if (P % _4n === _3n)
466
+ return sqrt3mod4;
467
+ if (P % _8n === _5n)
468
+ return sqrt5mod8;
469
+ if (P % _16n === _9n)
470
+ return sqrt9mod16(P);
471
+ return tonelliShanks(P);
472
+ }
473
+ function validateField(field) {
474
+ const initial = {
475
+ ORDER: "bigint",
476
+ BYTES: "number",
477
+ BITS: "number"
478
+ };
479
+ const opts2 = FIELD_FIELDS.reduce((map, val) => {
480
+ map[val] = "function";
481
+ return map;
482
+ }, initial);
483
+ validateObject(field, opts2);
484
+ asafenumber(field.BYTES, "BYTES");
485
+ asafenumber(field.BITS, "BITS");
486
+ if (field.BYTES < 1 || field.BITS < 1)
487
+ throw new Error("invalid field: expected BYTES/BITS > 0");
488
+ if (field.ORDER <= _1n2)
489
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
490
+ return field;
491
+ }
492
+ function FpPow(Fp2, num, power) {
493
+ const F2 = Fp2;
494
+ if (power < _0n2)
495
+ throw new Error("invalid exponent, negatives unsupported");
496
+ if (power === _0n2)
497
+ return F2.ONE;
498
+ if (power === _1n2)
499
+ return num;
500
+ let p = F2.ONE;
501
+ let d = num;
502
+ while (power > _0n2) {
503
+ if (power & _1n2)
504
+ p = F2.mul(p, d);
505
+ d = F2.sqr(d);
506
+ power >>= _1n2;
507
+ }
508
+ return p;
509
+ }
510
+ function FpInvertBatch(Fp2, nums, passZero = false) {
511
+ const F2 = Fp2;
512
+ const inverted = new Array(nums.length).fill(passZero ? F2.ZERO : void 0);
513
+ const multipliedAcc = nums.reduce((acc, num, i) => {
514
+ if (F2.is0(num))
515
+ return acc;
516
+ inverted[i] = acc;
517
+ return F2.mul(acc, num);
518
+ }, F2.ONE);
519
+ const invertedAcc = F2.inv(multipliedAcc);
520
+ nums.reduceRight((acc, num, i) => {
521
+ if (F2.is0(num))
522
+ return acc;
523
+ inverted[i] = F2.mul(acc, inverted[i]);
524
+ return F2.mul(acc, num);
525
+ }, invertedAcc);
526
+ return inverted;
527
+ }
528
+ function FpLegendre(Fp2, n) {
529
+ const F2 = Fp2;
530
+ const p1mod2 = (F2.ORDER - _1n2) / _2n;
531
+ const powered = F2.pow(n, p1mod2);
532
+ const yes = F2.eql(powered, F2.ONE);
533
+ const zero = F2.eql(powered, F2.ZERO);
534
+ const no = F2.eql(powered, F2.neg(F2.ONE));
535
+ if (!yes && !zero && !no)
536
+ throw new Error("invalid Legendre symbol result");
537
+ return yes ? 1 : zero ? 0 : -1;
538
+ }
539
+ function nLength(n, nBitLength) {
540
+ if (nBitLength !== void 0)
541
+ anumber2(nBitLength);
542
+ if (n <= _0n2)
543
+ throw new Error("invalid n length: expected positive n, got " + n);
544
+ if (nBitLength !== void 0 && nBitLength < 1)
545
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
546
+ const bits = bitLen(n);
547
+ if (nBitLength !== void 0 && nBitLength < bits)
548
+ throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
549
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
550
+ const nByteLength = Math.ceil(_nBitLength / 8);
551
+ return { nBitLength: _nBitLength, nByteLength };
552
+ }
553
+ function Field(ORDER, opts2 = {}) {
554
+ return new _Field(ORDER, opts2);
555
+ }
556
+ var _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _16n, isNegativeLE, FIELD_FIELDS, FIELD_SQRT, _Field;
557
+ var init_modular = __esm({
558
+ "../../node_modules/@noble/curves/abstract/modular.js"() {
559
+ "use strict";
560
+ init_utils2();
561
+ _0n2 = /* @__PURE__ */ BigInt(0);
562
+ _1n2 = /* @__PURE__ */ BigInt(1);
563
+ _2n = /* @__PURE__ */ BigInt(2);
564
+ _3n = /* @__PURE__ */ BigInt(3);
565
+ _4n = /* @__PURE__ */ BigInt(4);
566
+ _5n = /* @__PURE__ */ BigInt(5);
567
+ _7n = /* @__PURE__ */ BigInt(7);
568
+ _8n = /* @__PURE__ */ BigInt(8);
569
+ _9n = /* @__PURE__ */ BigInt(9);
570
+ _16n = /* @__PURE__ */ BigInt(16);
571
+ isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
572
+ FIELD_FIELDS = [
573
+ "create",
574
+ "isValid",
575
+ "is0",
576
+ "neg",
577
+ "inv",
578
+ "sqrt",
579
+ "sqr",
580
+ "eql",
581
+ "add",
582
+ "sub",
583
+ "mul",
584
+ "pow",
585
+ "div",
586
+ "addN",
587
+ "subN",
588
+ "mulN",
589
+ "sqrN"
590
+ ];
591
+ FIELD_SQRT = /* @__PURE__ */ new WeakMap();
592
+ _Field = class {
593
+ constructor(ORDER, opts2 = {}) {
594
+ __publicField(this, "ORDER");
595
+ __publicField(this, "BITS");
596
+ __publicField(this, "BYTES");
597
+ __publicField(this, "isLE");
598
+ __publicField(this, "ZERO", _0n2);
599
+ __publicField(this, "ONE", _1n2);
600
+ __publicField(this, "_lengths");
601
+ __publicField(this, "_mod");
602
+ if (ORDER <= _1n2)
603
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
604
+ let _nbitLength = void 0;
605
+ this.isLE = false;
606
+ if (opts2 != null && typeof opts2 === "object") {
607
+ if (typeof opts2.BITS === "number")
608
+ _nbitLength = opts2.BITS;
609
+ if (typeof opts2.sqrt === "function")
610
+ Object.defineProperty(this, "sqrt", { value: opts2.sqrt, enumerable: true });
611
+ if (typeof opts2.isLE === "boolean")
612
+ this.isLE = opts2.isLE;
613
+ if (opts2.allowedLengths)
614
+ this._lengths = Object.freeze(opts2.allowedLengths.slice());
615
+ if (typeof opts2.modFromBytes === "boolean")
616
+ this._mod = opts2.modFromBytes;
617
+ }
618
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
619
+ if (nByteLength > 2048)
620
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
621
+ this.ORDER = ORDER;
622
+ this.BITS = nBitLength;
623
+ this.BYTES = nByteLength;
624
+ Object.freeze(this);
625
+ }
626
+ create(num) {
627
+ return mod(num, this.ORDER);
628
+ }
629
+ isValid(num) {
630
+ if (typeof num !== "bigint")
631
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
632
+ return _0n2 <= num && num < this.ORDER;
633
+ }
634
+ is0(num) {
635
+ return num === _0n2;
636
+ }
637
+ // is valid and invertible
638
+ isValidNot0(num) {
639
+ return !this.is0(num) && this.isValid(num);
640
+ }
641
+ isOdd(num) {
642
+ return (num & _1n2) === _1n2;
643
+ }
644
+ neg(num) {
645
+ return mod(-num, this.ORDER);
646
+ }
647
+ eql(lhs, rhs) {
648
+ return lhs === rhs;
649
+ }
650
+ sqr(num) {
651
+ return mod(num * num, this.ORDER);
652
+ }
653
+ add(lhs, rhs) {
654
+ return mod(lhs + rhs, this.ORDER);
655
+ }
656
+ sub(lhs, rhs) {
657
+ return mod(lhs - rhs, this.ORDER);
658
+ }
659
+ mul(lhs, rhs) {
660
+ return mod(lhs * rhs, this.ORDER);
661
+ }
662
+ pow(num, power) {
663
+ return FpPow(this, num, power);
664
+ }
665
+ div(lhs, rhs) {
666
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
667
+ }
668
+ // Same as above, but doesn't normalize
669
+ sqrN(num) {
670
+ return num * num;
671
+ }
672
+ addN(lhs, rhs) {
673
+ return lhs + rhs;
674
+ }
675
+ subN(lhs, rhs) {
676
+ return lhs - rhs;
677
+ }
678
+ mulN(lhs, rhs) {
679
+ return lhs * rhs;
680
+ }
681
+ inv(num) {
682
+ return invert(num, this.ORDER);
683
+ }
684
+ sqrt(num) {
685
+ let sqrt = FIELD_SQRT.get(this);
686
+ if (!sqrt)
687
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
688
+ return sqrt(this, num);
689
+ }
690
+ toBytes(num) {
691
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
692
+ }
693
+ fromBytes(bytes, skipValidation = false) {
694
+ abytes2(bytes);
695
+ const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
696
+ if (allowedLengths) {
697
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
698
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
699
+ }
700
+ const padded = new Uint8Array(BYTES);
701
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
702
+ bytes = padded;
703
+ }
704
+ if (bytes.length !== BYTES)
705
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
706
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
707
+ if (modFromBytes)
708
+ scalar = mod(scalar, ORDER);
709
+ if (!skipValidation) {
710
+ if (!this.isValid(scalar))
711
+ throw new Error("invalid field element: outside of range 0..ORDER");
712
+ }
713
+ return scalar;
714
+ }
715
+ // TODO: we don't need it here, move out to separate fn
716
+ invertBatch(lst) {
717
+ return FpInvertBatch(this, lst);
718
+ }
719
+ // We can't move this out because Fp6, Fp12 implement it
720
+ // and it's unclear what to return in there.
721
+ cmov(a, b, condition) {
722
+ abool(condition, "condition");
723
+ return condition ? b : a;
724
+ }
725
+ };
726
+ Object.freeze(_Field.prototype);
727
+ }
728
+ });
729
+
730
+ // ../../node_modules/@noble/curves/abstract/curve.js
731
+ function negateCt(condition, item) {
732
+ const neg = item.negate();
733
+ return condition ? neg : item;
734
+ }
735
+ function normalizeZ(c, points) {
736
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
737
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
738
+ }
739
+ function validateW(W, bits) {
740
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
741
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
742
+ }
743
+ function calcWOpts(W, scalarBits) {
744
+ validateW(W, scalarBits);
745
+ const windows = Math.ceil(scalarBits / W) + 1;
746
+ const windowSize = 2 ** (W - 1);
747
+ const maxNumber = 2 ** W;
748
+ const mask = bitMask(W);
749
+ const shiftBy = BigInt(W);
750
+ return { windows, windowSize, mask, maxNumber, shiftBy };
751
+ }
752
+ function calcOffsets(n, window, wOpts) {
753
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
754
+ let wbits = Number(n & mask);
755
+ let nextN = n >> shiftBy;
756
+ if (wbits > windowSize) {
757
+ wbits -= maxNumber;
758
+ nextN += _1n3;
759
+ }
760
+ const offsetStart = window * windowSize;
761
+ const offset = offsetStart + Math.abs(wbits) - 1;
762
+ const isZero = wbits === 0;
763
+ const isNeg = wbits < 0;
764
+ const isNegF = window % 2 !== 0;
765
+ const offsetF = offsetStart;
766
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
767
+ }
768
+ function getW(P) {
769
+ return pointWindowSizes.get(P) || 1;
770
+ }
771
+ function assert0(n) {
772
+ if (n !== _0n3)
773
+ throw new Error("invalid wNAF");
774
+ }
775
+ function createField(order, field, isLE2) {
776
+ if (field) {
777
+ if (field.ORDER !== order)
778
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
779
+ validateField(field);
780
+ return field;
781
+ } else {
782
+ return Field(order, { isLE: isLE2 });
783
+ }
784
+ }
785
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
786
+ if (FpFnLE === void 0)
787
+ FpFnLE = type === "edwards";
788
+ if (!CURVE || typeof CURVE !== "object")
789
+ throw new Error(`expected valid ${type} CURVE object`);
790
+ for (const p of ["p", "n", "h"]) {
791
+ const val = CURVE[p];
792
+ if (!(typeof val === "bigint" && val > _0n3))
793
+ throw new Error(`CURVE.${p} must be positive bigint`);
794
+ }
795
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
796
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
797
+ const _b = type === "weierstrass" ? "b" : "d";
798
+ const params = ["Gx", "Gy", "a", _b];
799
+ for (const p of params) {
800
+ if (!Fp2.isValid(CURVE[p]))
801
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
802
+ }
803
+ CURVE = Object.freeze(Object.assign({}, CURVE));
804
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
805
+ }
806
+ function createKeygen(randomSecretKey, getPublicKey) {
807
+ return function keygen(seed) {
808
+ const secretKey = randomSecretKey(seed);
809
+ return { secretKey, publicKey: getPublicKey(secretKey) };
810
+ };
811
+ }
812
+ var _0n3, _1n3, pointPrecomputes, pointWindowSizes, wNAF;
813
+ var init_curve = __esm({
814
+ "../../node_modules/@noble/curves/abstract/curve.js"() {
815
+ "use strict";
816
+ init_utils2();
817
+ init_modular();
818
+ _0n3 = /* @__PURE__ */ BigInt(0);
819
+ _1n3 = /* @__PURE__ */ BigInt(1);
820
+ pointPrecomputes = /* @__PURE__ */ new WeakMap();
821
+ pointWindowSizes = /* @__PURE__ */ new WeakMap();
822
+ wNAF = class {
823
+ // Parametrized with a given Point class (not individual point)
824
+ constructor(Point, bits) {
825
+ __publicField(this, "BASE");
826
+ __publicField(this, "ZERO");
827
+ __publicField(this, "Fn");
828
+ __publicField(this, "bits");
829
+ this.BASE = Point.BASE;
830
+ this.ZERO = Point.ZERO;
831
+ this.Fn = Point.Fn;
832
+ this.bits = bits;
833
+ }
834
+ // non-const time multiplication ladder
835
+ _unsafeLadder(elm, n, p = this.ZERO) {
836
+ let d = elm;
837
+ while (n > _0n3) {
838
+ if (n & _1n3)
839
+ p = p.add(d);
840
+ d = d.double();
841
+ n >>= _1n3;
842
+ }
843
+ return p;
844
+ }
845
+ /**
846
+ * Creates a wNAF precomputation window. Used for caching.
847
+ * Default window size is set by `utils.precompute()` and is equal to 8.
848
+ * Number of precomputed points depends on the curve size:
849
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
850
+ * - 𝑊 is the window size
851
+ * - 𝑛 is the bitlength of the curve order.
852
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
853
+ * @param point - Point instance
854
+ * @param W - window size
855
+ * @returns precomputed point tables flattened to a single array
856
+ */
857
+ precomputeWindow(point, W) {
858
+ const { windows, windowSize } = calcWOpts(W, this.bits);
859
+ const points = [];
860
+ let p = point;
861
+ let base = p;
862
+ for (let window = 0; window < windows; window++) {
863
+ base = p;
864
+ points.push(base);
865
+ for (let i = 1; i < windowSize; i++) {
866
+ base = base.add(p);
867
+ points.push(base);
868
+ }
869
+ p = base.double();
870
+ }
871
+ return points;
872
+ }
873
+ /**
874
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
875
+ * More compact implementation:
876
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
877
+ * @returns real and fake (for const-time) points
878
+ */
879
+ wNAF(W, precomputes, n) {
880
+ if (!this.Fn.isValid(n))
881
+ throw new Error("invalid scalar");
882
+ let p = this.ZERO;
883
+ let f = this.BASE;
884
+ const wo = calcWOpts(W, this.bits);
885
+ for (let window = 0; window < wo.windows; window++) {
886
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
887
+ n = nextN;
888
+ if (isZero) {
889
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
890
+ } else {
891
+ p = p.add(negateCt(isNeg, precomputes[offset]));
892
+ }
893
+ }
894
+ assert0(n);
895
+ return { p, f };
896
+ }
897
+ /**
898
+ * Implements unsafe EC multiplication using precomputed tables
899
+ * and w-ary non-adjacent form.
900
+ * @param acc - accumulator point to add result of multiplication
901
+ * @returns point
902
+ */
903
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
904
+ const wo = calcWOpts(W, this.bits);
905
+ for (let window = 0; window < wo.windows; window++) {
906
+ if (n === _0n3)
907
+ break;
908
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
909
+ n = nextN;
910
+ if (isZero) {
911
+ continue;
912
+ } else {
913
+ const item = precomputes[offset];
914
+ acc = acc.add(isNeg ? item.negate() : item);
915
+ }
916
+ }
917
+ assert0(n);
918
+ return acc;
919
+ }
920
+ getPrecomputes(W, point, transform) {
921
+ let comp = pointPrecomputes.get(point);
922
+ if (!comp) {
923
+ comp = this.precomputeWindow(point, W);
924
+ if (W !== 1) {
925
+ if (typeof transform === "function")
926
+ comp = transform(comp);
927
+ pointPrecomputes.set(point, comp);
928
+ }
929
+ }
930
+ return comp;
931
+ }
932
+ cached(point, scalar, transform) {
933
+ const W = getW(point);
934
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
935
+ }
936
+ unsafe(point, scalar, transform, prev) {
937
+ const W = getW(point);
938
+ if (W === 1)
939
+ return this._unsafeLadder(point, scalar, prev);
940
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
941
+ }
942
+ // We calculate precomputes for elliptic curve point multiplication
943
+ // using windowed method. This specifies window size and
944
+ // stores precomputed values. Usually only base point would be precomputed.
945
+ createCache(P, W) {
946
+ validateW(W, this.bits);
947
+ pointWindowSizes.set(P, W);
948
+ pointPrecomputes.delete(P);
949
+ }
950
+ hasCache(elm) {
951
+ return getW(elm) !== 1;
952
+ }
953
+ };
954
+ }
955
+ });
956
+
957
+ // ../../node_modules/@noble/curves/abstract/edwards.js
958
+ function isEdValidXY(Fp2, CURVE, x, y) {
959
+ const x2 = Fp2.sqr(x);
960
+ const y2 = Fp2.sqr(y);
961
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
962
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
963
+ return Fp2.eql(left, right);
964
+ }
965
+ function edwards(params, extraOpts = {}) {
966
+ const opts2 = extraOpts;
967
+ const validated = createCurveFields("edwards", params, opts2, opts2.FpFnLE);
968
+ const { Fp: Fp2, Fn: Fn2 } = validated;
969
+ let CURVE = validated.CURVE;
970
+ const { h: cofactor } = CURVE;
971
+ validateObject(opts2, {}, { uvRatio: "function" });
972
+ const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
973
+ const modP = (n) => Fp2.create(n);
974
+ const uvRatio2 = opts2.uvRatio === void 0 ? (u, v) => {
975
+ try {
976
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
977
+ } catch (e) {
978
+ return { isValid: false, value: _0n4 };
979
+ }
980
+ } : opts2.uvRatio;
981
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
982
+ throw new Error("bad curve params: generator point");
983
+ function acoord(title, n, banZero = false) {
984
+ const min = banZero ? _1n4 : _0n4;
985
+ aInRange("coordinate " + title, n, min, MASK);
986
+ return n;
987
+ }
988
+ function aedpoint(other) {
989
+ if (!(other instanceof Point))
990
+ throw new Error("EdwardsPoint expected");
991
+ }
992
+ const _Point = class _Point {
993
+ constructor(X, Y, Z, T) {
994
+ __publicField(this, "X");
995
+ __publicField(this, "Y");
996
+ __publicField(this, "Z");
997
+ __publicField(this, "T");
998
+ this.X = acoord("x", X);
999
+ this.Y = acoord("y", Y);
1000
+ this.Z = acoord("z", Z, true);
1001
+ this.T = acoord("t", T);
1002
+ Object.freeze(this);
1003
+ }
1004
+ static CURVE() {
1005
+ return CURVE;
1006
+ }
1007
+ /**
1008
+ * Create one extended Edwards point from affine coordinates.
1009
+ * Does NOT validate that the point is on-curve or torsion-free.
1010
+ * Use `.assertValidity()` on adversarial inputs.
1011
+ */
1012
+ static fromAffine(p) {
1013
+ if (p instanceof _Point)
1014
+ throw new Error("extended point not allowed");
1015
+ const { x, y } = p || {};
1016
+ acoord("x", x);
1017
+ acoord("y", y);
1018
+ return new _Point(x, y, _1n4, modP(x * y));
1019
+ }
1020
+ // Uses algo from RFC8032 5.1.3.
1021
+ static fromBytes(bytes, zip215 = false) {
1022
+ const len = Fp2.BYTES;
1023
+ const { a, d } = CURVE;
1024
+ bytes = copyBytes(abytes2(bytes, len, "point"));
1025
+ abool(zip215, "zip215");
1026
+ const normed = copyBytes(bytes);
1027
+ const lastByte = bytes[len - 1];
1028
+ normed[len - 1] = lastByte & ~128;
1029
+ const y = bytesToNumberLE(normed);
1030
+ const max = zip215 ? MASK : Fp2.ORDER;
1031
+ aInRange("point.y", y, _0n4, max);
1032
+ const y2 = modP(y * y);
1033
+ const u = modP(y2 - _1n4);
1034
+ const v = modP(d * y2 - a);
1035
+ let { isValid, value: x } = uvRatio2(u, v);
1036
+ if (!isValid)
1037
+ throw new Error("bad point: invalid y coordinate");
1038
+ const isXOdd = (x & _1n4) === _1n4;
1039
+ const isLastByteOdd = (lastByte & 128) !== 0;
1040
+ if (!zip215 && x === _0n4 && isLastByteOdd)
1041
+ throw new Error("bad point: x=0 and x_0=1");
1042
+ if (isLastByteOdd !== isXOdd)
1043
+ x = modP(-x);
1044
+ return _Point.fromAffine({ x, y });
1045
+ }
1046
+ static fromHex(hex, zip215 = false) {
1047
+ return _Point.fromBytes(hexToBytes2(hex), zip215);
1048
+ }
1049
+ get x() {
1050
+ return this.toAffine().x;
1051
+ }
1052
+ get y() {
1053
+ return this.toAffine().y;
1054
+ }
1055
+ precompute(windowSize = 8, isLazy = true) {
1056
+ wnaf.createCache(this, windowSize);
1057
+ if (!isLazy)
1058
+ this.multiply(_2n2);
1059
+ return this;
1060
+ }
1061
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
1062
+ assertValidity() {
1063
+ const p = this;
1064
+ const { a, d } = CURVE;
1065
+ if (p.is0())
1066
+ throw new Error("bad point: ZERO");
1067
+ const { X, Y, Z, T } = p;
1068
+ const X2 = modP(X * X);
1069
+ const Y2 = modP(Y * Y);
1070
+ const Z2 = modP(Z * Z);
1071
+ const Z4 = modP(Z2 * Z2);
1072
+ const aX2 = modP(X2 * a);
1073
+ const left = modP(Z2 * modP(aX2 + Y2));
1074
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1075
+ if (left !== right)
1076
+ throw new Error("bad point: equation left != right (1)");
1077
+ const XY = modP(X * Y);
1078
+ const ZT = modP(Z * T);
1079
+ if (XY !== ZT)
1080
+ throw new Error("bad point: equation left != right (2)");
1081
+ }
1082
+ // Compare one point to another.
1083
+ equals(other) {
1084
+ aedpoint(other);
1085
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1086
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1087
+ const X1Z2 = modP(X1 * Z2);
1088
+ const X2Z1 = modP(X2 * Z1);
1089
+ const Y1Z2 = modP(Y1 * Z2);
1090
+ const Y2Z1 = modP(Y2 * Z1);
1091
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1092
+ }
1093
+ is0() {
1094
+ return this.equals(_Point.ZERO);
1095
+ }
1096
+ negate() {
1097
+ return new _Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1098
+ }
1099
+ // Fast algo for doubling Extended Point.
1100
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1101
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1102
+ double() {
1103
+ const { a } = CURVE;
1104
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1105
+ const A = modP(X1 * X1);
1106
+ const B = modP(Y1 * Y1);
1107
+ const C = modP(_2n2 * modP(Z1 * Z1));
1108
+ const D = modP(a * A);
1109
+ const x1y1 = X1 + Y1;
1110
+ const E = modP(modP(x1y1 * x1y1) - A - B);
1111
+ const G = D + B;
1112
+ const F2 = G - C;
1113
+ const H = D - B;
1114
+ const X3 = modP(E * F2);
1115
+ const Y3 = modP(G * H);
1116
+ const T3 = modP(E * H);
1117
+ const Z3 = modP(F2 * G);
1118
+ return new _Point(X3, Y3, Z3, T3);
1119
+ }
1120
+ // Fast algo for adding 2 Extended Points.
1121
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1122
+ // Cost: 9M + 1*a + 1*d + 7add.
1123
+ add(other) {
1124
+ aedpoint(other);
1125
+ const { a, d } = CURVE;
1126
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1127
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1128
+ const A = modP(X1 * X2);
1129
+ const B = modP(Y1 * Y2);
1130
+ const C = modP(T1 * d * T2);
1131
+ const D = modP(Z1 * Z2);
1132
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1133
+ const F2 = D - C;
1134
+ const G = D + C;
1135
+ const H = modP(B - a * A);
1136
+ const X3 = modP(E * F2);
1137
+ const Y3 = modP(G * H);
1138
+ const T3 = modP(E * H);
1139
+ const Z3 = modP(F2 * G);
1140
+ return new _Point(X3, Y3, Z3, T3);
1141
+ }
1142
+ subtract(other) {
1143
+ aedpoint(other);
1144
+ return this.add(other.negate());
1145
+ }
1146
+ // Constant-time multiplication.
1147
+ multiply(scalar) {
1148
+ if (!Fn2.isValidNot0(scalar))
1149
+ throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1150
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(_Point, p2));
1151
+ return normalizeZ(_Point, [p, f])[0];
1152
+ }
1153
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1154
+ // It's faster, but should only be used when you don't care about
1155
+ // an exposed private key e.g. sig verification.
1156
+ // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1157
+ // n and larger values are rejected instead of being reduced mod n to the identity point.
1158
+ multiplyUnsafe(scalar) {
1159
+ if (!Fn2.isValid(scalar))
1160
+ throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1161
+ if (scalar === _0n4)
1162
+ return _Point.ZERO;
1163
+ if (this.is0() || scalar === _1n4)
1164
+ return this;
1165
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(_Point, p));
1166
+ }
1167
+ // Checks if point is of small order.
1168
+ // If you add something to small order point, you will have "dirty"
1169
+ // point with torsion component.
1170
+ // Clears cofactor and checks if the result is 0.
1171
+ isSmallOrder() {
1172
+ return this.clearCofactor().is0();
1173
+ }
1174
+ // Multiplies point by curve order and checks if the result is 0.
1175
+ // Returns `false` is the point is dirty.
1176
+ isTorsionFree() {
1177
+ return wnaf.unsafe(this, CURVE.n).is0();
1178
+ }
1179
+ // Converts Extended point to default (x, y) coordinates.
1180
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1181
+ toAffine(invertedZ) {
1182
+ const p = this;
1183
+ let iz = invertedZ;
1184
+ const { X, Y, Z } = p;
1185
+ const is0 = p.is0();
1186
+ if (iz == null)
1187
+ iz = is0 ? _8n2 : Fp2.inv(Z);
1188
+ const x = modP(X * iz);
1189
+ const y = modP(Y * iz);
1190
+ const zz = Fp2.mul(Z, iz);
1191
+ if (is0)
1192
+ return { x: _0n4, y: _1n4 };
1193
+ if (zz !== _1n4)
1194
+ throw new Error("invZ was invalid");
1195
+ return { x, y };
1196
+ }
1197
+ clearCofactor() {
1198
+ if (cofactor === _1n4)
1199
+ return this;
1200
+ return this.multiplyUnsafe(cofactor);
1201
+ }
1202
+ toBytes() {
1203
+ const { x, y } = this.toAffine();
1204
+ const bytes = Fp2.toBytes(y);
1205
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1206
+ return bytes;
1207
+ }
1208
+ toHex() {
1209
+ return bytesToHex2(this.toBytes());
1210
+ }
1211
+ toString() {
1212
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1213
+ }
1214
+ };
1215
+ // base / generator point
1216
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy)));
1217
+ // zero / infinity / identity point
1218
+ __publicField(_Point, "ZERO", new _Point(_0n4, _1n4, _1n4, _0n4));
1219
+ // 0, 1, 1, 0
1220
+ // math field
1221
+ __publicField(_Point, "Fp", Fp2);
1222
+ // scalar field
1223
+ __publicField(_Point, "Fn", Fn2);
1224
+ let Point = _Point;
1225
+ const wnaf = new wNAF(Point, Fn2.BITS);
1226
+ if (Fn2.BITS >= 8)
1227
+ Point.BASE.precompute(8);
1228
+ Object.freeze(Point.prototype);
1229
+ Object.freeze(Point);
1230
+ return Point;
1231
+ }
1232
+ var _0n4, _1n4, _2n2, _8n2, PrimeEdwardsPoint;
1233
+ var init_edwards = __esm({
1234
+ "../../node_modules/@noble/curves/abstract/edwards.js"() {
1235
+ "use strict";
1236
+ init_utils2();
1237
+ init_curve();
1238
+ _0n4 = /* @__PURE__ */ BigInt(0);
1239
+ _1n4 = /* @__PURE__ */ BigInt(1);
1240
+ _2n2 = /* @__PURE__ */ BigInt(2);
1241
+ _8n2 = /* @__PURE__ */ BigInt(8);
1242
+ PrimeEdwardsPoint = class {
1243
+ /**
1244
+ * Wrap one internal Edwards representative directly.
1245
+ * This is not a canonical encoding boundary: alternate Edwards
1246
+ * representatives may still describe the same abstract wrapper element.
1247
+ */
1248
+ constructor(ep) {
1249
+ __publicField(this, "ep");
1250
+ this.ep = ep;
1251
+ }
1252
+ // Static methods that must be implemented by subclasses
1253
+ static fromBytes(_bytes) {
1254
+ notImplemented();
1255
+ }
1256
+ static fromHex(_hex) {
1257
+ notImplemented();
1258
+ }
1259
+ get x() {
1260
+ return this.toAffine().x;
1261
+ }
1262
+ get y() {
1263
+ return this.toAffine().y;
1264
+ }
1265
+ // Common implementations
1266
+ clearCofactor() {
1267
+ return this;
1268
+ }
1269
+ assertValidity() {
1270
+ this.ep.assertValidity();
1271
+ }
1272
+ /**
1273
+ * Return affine coordinates of the current internal Edwards representative.
1274
+ * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1275
+ * Equal abstract elements may expose different `x` / `y`; use
1276
+ * `toBytes()` / `fromBytes()` for canonical roundtrips.
1277
+ */
1278
+ toAffine(invertedZ) {
1279
+ return this.ep.toAffine(invertedZ);
1280
+ }
1281
+ toHex() {
1282
+ return bytesToHex2(this.toBytes());
1283
+ }
1284
+ toString() {
1285
+ return this.toHex();
1286
+ }
1287
+ isTorsionFree() {
1288
+ return true;
1289
+ }
1290
+ isSmallOrder() {
1291
+ return false;
1292
+ }
1293
+ add(other) {
1294
+ this.assertSame(other);
1295
+ return this.init(this.ep.add(other.ep));
1296
+ }
1297
+ subtract(other) {
1298
+ this.assertSame(other);
1299
+ return this.init(this.ep.subtract(other.ep));
1300
+ }
1301
+ multiply(scalar) {
1302
+ return this.init(this.ep.multiply(scalar));
1303
+ }
1304
+ multiplyUnsafe(scalar) {
1305
+ return this.init(this.ep.multiplyUnsafe(scalar));
1306
+ }
1307
+ double() {
1308
+ return this.init(this.ep.double());
1309
+ }
1310
+ negate() {
1311
+ return this.init(this.ep.negate());
1312
+ }
1313
+ precompute(windowSize, isLazy) {
1314
+ this.ep.precompute(windowSize, isLazy);
1315
+ return this;
1316
+ }
1317
+ };
1318
+ __publicField(PrimeEdwardsPoint, "BASE");
1319
+ __publicField(PrimeEdwardsPoint, "ZERO");
1320
+ __publicField(PrimeEdwardsPoint, "Fp");
1321
+ __publicField(PrimeEdwardsPoint, "Fn");
1322
+ }
1323
+ });
1324
+
1325
+ // ../../node_modules/@noble/curves/abstract/montgomery.js
1326
+ function validateOpts(curve) {
1327
+ validateObject(curve, {
1328
+ P: "bigint",
1329
+ type: "string",
1330
+ adjustScalarBytes: "function",
1331
+ powPminus2: "function"
1332
+ }, {
1333
+ randomBytes: "function"
1334
+ });
1335
+ return Object.freeze({ ...curve });
1336
+ }
1337
+ function montgomery(curveDef) {
1338
+ const CURVE = validateOpts(curveDef);
1339
+ const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
1340
+ const is25519 = type === "x25519";
1341
+ if (!is25519 && type !== "x448")
1342
+ throw new Error("invalid type");
1343
+ const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1344
+ const montgomeryBits = is25519 ? 255 : 448;
1345
+ const fieldLen = is25519 ? 32 : 56;
1346
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
1347
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
1348
+ const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
1349
+ const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
1350
+ const maxScalar = minScalar + maxAdded + _1n5;
1351
+ const modP = (n) => mod(n, P);
1352
+ const GuBytes = encodeU(Gu);
1353
+ function encodeU(u) {
1354
+ return numberToBytesLE(modP(u), fieldLen);
1355
+ }
1356
+ function decodeU(u) {
1357
+ const _u = copyBytes(abytes2(u, fieldLen, "uCoordinate"));
1358
+ if (is25519)
1359
+ _u[31] &= 127;
1360
+ return modP(bytesToNumberLE(_u));
1361
+ }
1362
+ function decodeScalar(scalar) {
1363
+ return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
1364
+ }
1365
+ function scalarMult(scalar, u) {
1366
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
1367
+ if (pu === _0n5)
1368
+ throw new Error("invalid private or public key received");
1369
+ return encodeU(pu);
1370
+ }
1371
+ function scalarMultBase(scalar) {
1372
+ return scalarMult(scalar, GuBytes);
1373
+ }
1374
+ const getPublicKey = scalarMultBase;
1375
+ const getSharedSecret = scalarMult;
1376
+ function cswap(swap, x_2, x_3) {
1377
+ const dummy = modP(swap * (x_2 - x_3));
1378
+ x_2 = modP(x_2 - dummy);
1379
+ x_3 = modP(x_3 + dummy);
1380
+ return { x_2, x_3 };
1381
+ }
1382
+ function montgomeryLadder(u, scalar) {
1383
+ aInRange("u", u, _0n5, P);
1384
+ aInRange("scalar", scalar, minScalar, maxScalar);
1385
+ const k = scalar;
1386
+ const x_1 = u;
1387
+ let x_2 = _1n5;
1388
+ let z_2 = _0n5;
1389
+ let x_3 = u;
1390
+ let z_3 = _1n5;
1391
+ let swap = _0n5;
1392
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
1393
+ const k_t = k >> t & _1n5;
1394
+ swap ^= k_t;
1395
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1396
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1397
+ swap = k_t;
1398
+ const A = x_2 + z_2;
1399
+ const AA = modP(A * A);
1400
+ const B = x_2 - z_2;
1401
+ const BB = modP(B * B);
1402
+ const E = AA - BB;
1403
+ const C = x_3 + z_3;
1404
+ const D = x_3 - z_3;
1405
+ const DA = modP(D * A);
1406
+ const CB = modP(C * B);
1407
+ const dacb = DA + CB;
1408
+ const da_cb = DA - CB;
1409
+ x_3 = modP(dacb * dacb);
1410
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
1411
+ x_2 = modP(AA * BB);
1412
+ z_2 = modP(E * (AA + modP(a24 * E)));
1413
+ }
1414
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1415
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1416
+ const z2 = powPminus2(z_2);
1417
+ return modP(x_2 * z2);
1418
+ }
1419
+ const lengths = {
1420
+ secretKey: fieldLen,
1421
+ publicKey: fieldLen,
1422
+ seed: fieldLen
1423
+ };
1424
+ const randomSecretKey = (seed) => {
1425
+ seed = seed === void 0 ? randomBytes_(fieldLen) : seed;
1426
+ abytes2(seed, lengths.seed, "seed");
1427
+ return seed;
1428
+ };
1429
+ const utils = { randomSecretKey };
1430
+ Object.freeze(lengths);
1431
+ Object.freeze(utils);
1432
+ return Object.freeze({
1433
+ keygen: createKeygen(randomSecretKey, getPublicKey),
1434
+ getSharedSecret,
1435
+ getPublicKey,
1436
+ scalarMult,
1437
+ scalarMultBase,
1438
+ utils,
1439
+ GuBytes: GuBytes.slice(),
1440
+ lengths
1441
+ });
1442
+ }
1443
+ var _0n5, _1n5, _2n3;
1444
+ var init_montgomery = __esm({
1445
+ "../../node_modules/@noble/curves/abstract/montgomery.js"() {
1446
+ "use strict";
1447
+ init_utils2();
1448
+ init_curve();
1449
+ init_modular();
1450
+ _0n5 = BigInt(0);
1451
+ _1n5 = BigInt(1);
1452
+ _2n3 = BigInt(2);
1453
+ }
1454
+ });
1455
+
1456
+ // ../../node_modules/@noble/hashes/_md.js
1457
+ var HashMD, SHA512_IV;
1458
+ var init_md = __esm({
1459
+ "../../node_modules/@noble/hashes/_md.js"() {
1460
+ "use strict";
1461
+ init_utils();
1462
+ HashMD = class {
1463
+ constructor(blockLen, outputLen, padOffset, isLE2) {
1464
+ __publicField(this, "blockLen");
1465
+ __publicField(this, "outputLen");
1466
+ __publicField(this, "canXOF", false);
1467
+ __publicField(this, "padOffset");
1468
+ __publicField(this, "isLE");
1469
+ // For partial updates less than block size
1470
+ __publicField(this, "buffer");
1471
+ __publicField(this, "view");
1472
+ __publicField(this, "finished", false);
1473
+ __publicField(this, "length", 0);
1474
+ __publicField(this, "pos", 0);
1475
+ __publicField(this, "destroyed", false);
1476
+ this.blockLen = blockLen;
1477
+ this.outputLen = outputLen;
1478
+ this.padOffset = padOffset;
1479
+ this.isLE = isLE2;
1480
+ this.buffer = new Uint8Array(blockLen);
1481
+ this.view = createView(this.buffer);
1482
+ }
1483
+ update(data) {
1484
+ aexists(this);
1485
+ abytes(data);
1486
+ const { view, buffer, blockLen } = this;
1487
+ const len = data.length;
1488
+ for (let pos = 0; pos < len; ) {
1489
+ const take = Math.min(blockLen - this.pos, len - pos);
1490
+ if (take === blockLen) {
1491
+ const dataView = createView(data);
1492
+ for (; blockLen <= len - pos; pos += blockLen)
1493
+ this.process(dataView, pos);
1494
+ continue;
1495
+ }
1496
+ buffer.set(data.subarray(pos, pos + take), this.pos);
1497
+ this.pos += take;
1498
+ pos += take;
1499
+ if (this.pos === blockLen) {
1500
+ this.process(view, 0);
1501
+ this.pos = 0;
1502
+ }
1503
+ }
1504
+ this.length += data.length;
1505
+ this.roundClean();
1506
+ return this;
1507
+ }
1508
+ digestInto(out) {
1509
+ aexists(this);
1510
+ aoutput(out, this);
1511
+ this.finished = true;
1512
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
1513
+ let { pos } = this;
1514
+ buffer[pos++] = 128;
1515
+ clean(this.buffer.subarray(pos));
1516
+ if (this.padOffset > blockLen - pos) {
1517
+ this.process(view, 0);
1518
+ pos = 0;
1519
+ }
1520
+ for (let i = pos; i < blockLen; i++)
1521
+ buffer[i] = 0;
1522
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
1523
+ this.process(view, 0);
1524
+ const oview = createView(out);
1525
+ const len = this.outputLen;
1526
+ if (len % 4)
1527
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
1528
+ const outLen = len / 4;
1529
+ const state = this.get();
1530
+ if (outLen > state.length)
1531
+ throw new Error("_sha2: outputLen bigger than state");
1532
+ for (let i = 0; i < outLen; i++)
1533
+ oview.setUint32(4 * i, state[i], isLE2);
1534
+ }
1535
+ digest() {
1536
+ const { buffer, outputLen } = this;
1537
+ this.digestInto(buffer);
1538
+ const res = buffer.slice(0, outputLen);
1539
+ this.destroy();
1540
+ return res;
1541
+ }
1542
+ _cloneInto(to) {
1543
+ to ||= new this.constructor();
1544
+ to.set(...this.get());
1545
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
1546
+ to.destroyed = destroyed;
1547
+ to.finished = finished;
1548
+ to.length = length;
1549
+ to.pos = pos;
1550
+ if (length % blockLen)
1551
+ to.buffer.set(buffer);
1552
+ return to;
1553
+ }
1554
+ clone() {
1555
+ return this._cloneInto();
1556
+ }
1557
+ };
1558
+ SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1559
+ 1779033703,
1560
+ 4089235720,
1561
+ 3144134277,
1562
+ 2227873595,
1563
+ 1013904242,
1564
+ 4271175723,
1565
+ 2773480762,
1566
+ 1595750129,
1567
+ 1359893119,
1568
+ 2917565137,
1569
+ 2600822924,
1570
+ 725511199,
1571
+ 528734635,
1572
+ 4215389547,
1573
+ 1541459225,
1574
+ 327033209
1575
+ ]);
1576
+ }
1577
+ });
1578
+
1579
+ // ../../node_modules/@noble/hashes/_u64.js
1580
+ function fromBig(n, le = false) {
1581
+ if (le)
1582
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
1583
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1584
+ }
1585
+ function split(lst, le = false) {
1586
+ const len = lst.length;
1587
+ let Ah = new Uint32Array(len);
1588
+ let Al = new Uint32Array(len);
1589
+ for (let i = 0; i < len; i++) {
1590
+ const { h, l } = fromBig(lst[i], le);
1591
+ [Ah[i], Al[i]] = [h, l];
1592
+ }
1593
+ return [Ah, Al];
1594
+ }
1595
+ function add(Ah, Al, Bh, Bl) {
1596
+ const l = (Al >>> 0) + (Bl >>> 0);
1597
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1598
+ }
1599
+ var U32_MASK64, _32n, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotlSH, rotlSL, rotlBH, rotlBL, add3L, add3H, add4L, add4H, add5L, add5H;
1600
+ var init_u64 = __esm({
1601
+ "../../node_modules/@noble/hashes/_u64.js"() {
1602
+ "use strict";
1603
+ U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1604
+ _32n = /* @__PURE__ */ BigInt(32);
1605
+ shrSH = (h, _l, s) => h >>> s;
1606
+ shrSL = (h, l, s) => h << 32 - s | l >>> s;
1607
+ rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1608
+ rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1609
+ rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1610
+ rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1611
+ rotlSH = (h, l, s) => h << s | l >>> 32 - s;
1612
+ rotlSL = (h, l, s) => l << s | h >>> 32 - s;
1613
+ rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
1614
+ rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
1615
+ add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1616
+ add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1617
+ add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1618
+ add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1619
+ add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1620
+ add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1621
+ }
1622
+ });
1623
+
1624
+ // ../../node_modules/@noble/hashes/sha2.js
1625
+ var K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA2_64B, _SHA512, sha512;
1626
+ var init_sha2 = __esm({
1627
+ "../../node_modules/@noble/hashes/sha2.js"() {
1628
+ "use strict";
1629
+ init_md();
1630
+ init_u64();
1631
+ init_utils();
1632
+ K512 = /* @__PURE__ */ (() => split([
1633
+ "0x428a2f98d728ae22",
1634
+ "0x7137449123ef65cd",
1635
+ "0xb5c0fbcfec4d3b2f",
1636
+ "0xe9b5dba58189dbbc",
1637
+ "0x3956c25bf348b538",
1638
+ "0x59f111f1b605d019",
1639
+ "0x923f82a4af194f9b",
1640
+ "0xab1c5ed5da6d8118",
1641
+ "0xd807aa98a3030242",
1642
+ "0x12835b0145706fbe",
1643
+ "0x243185be4ee4b28c",
1644
+ "0x550c7dc3d5ffb4e2",
1645
+ "0x72be5d74f27b896f",
1646
+ "0x80deb1fe3b1696b1",
1647
+ "0x9bdc06a725c71235",
1648
+ "0xc19bf174cf692694",
1649
+ "0xe49b69c19ef14ad2",
1650
+ "0xefbe4786384f25e3",
1651
+ "0x0fc19dc68b8cd5b5",
1652
+ "0x240ca1cc77ac9c65",
1653
+ "0x2de92c6f592b0275",
1654
+ "0x4a7484aa6ea6e483",
1655
+ "0x5cb0a9dcbd41fbd4",
1656
+ "0x76f988da831153b5",
1657
+ "0x983e5152ee66dfab",
1658
+ "0xa831c66d2db43210",
1659
+ "0xb00327c898fb213f",
1660
+ "0xbf597fc7beef0ee4",
1661
+ "0xc6e00bf33da88fc2",
1662
+ "0xd5a79147930aa725",
1663
+ "0x06ca6351e003826f",
1664
+ "0x142929670a0e6e70",
1665
+ "0x27b70a8546d22ffc",
1666
+ "0x2e1b21385c26c926",
1667
+ "0x4d2c6dfc5ac42aed",
1668
+ "0x53380d139d95b3df",
1669
+ "0x650a73548baf63de",
1670
+ "0x766a0abb3c77b2a8",
1671
+ "0x81c2c92e47edaee6",
1672
+ "0x92722c851482353b",
1673
+ "0xa2bfe8a14cf10364",
1674
+ "0xa81a664bbc423001",
1675
+ "0xc24b8b70d0f89791",
1676
+ "0xc76c51a30654be30",
1677
+ "0xd192e819d6ef5218",
1678
+ "0xd69906245565a910",
1679
+ "0xf40e35855771202a",
1680
+ "0x106aa07032bbd1b8",
1681
+ "0x19a4c116b8d2d0c8",
1682
+ "0x1e376c085141ab53",
1683
+ "0x2748774cdf8eeb99",
1684
+ "0x34b0bcb5e19b48a8",
1685
+ "0x391c0cb3c5c95a63",
1686
+ "0x4ed8aa4ae3418acb",
1687
+ "0x5b9cca4f7763e373",
1688
+ "0x682e6ff3d6b2b8a3",
1689
+ "0x748f82ee5defb2fc",
1690
+ "0x78a5636f43172f60",
1691
+ "0x84c87814a1f0ab72",
1692
+ "0x8cc702081a6439ec",
1693
+ "0x90befffa23631e28",
1694
+ "0xa4506cebde82bde9",
1695
+ "0xbef9a3f7b2c67915",
1696
+ "0xc67178f2e372532b",
1697
+ "0xca273eceea26619c",
1698
+ "0xd186b8c721c0c207",
1699
+ "0xeada7dd6cde0eb1e",
1700
+ "0xf57d4f7fee6ed178",
1701
+ "0x06f067aa72176fba",
1702
+ "0x0a637dc5a2c898a6",
1703
+ "0x113f9804bef90dae",
1704
+ "0x1b710b35131c471b",
1705
+ "0x28db77f523047d84",
1706
+ "0x32caab7b40c72493",
1707
+ "0x3c9ebe0a15c9bebc",
1708
+ "0x431d67c49c100d4c",
1709
+ "0x4cc5d4becb3e42b6",
1710
+ "0x597f299cfc657e2a",
1711
+ "0x5fcb6fab3ad6faec",
1712
+ "0x6c44198c4a475817"
1713
+ ].map((n) => BigInt(n))))();
1714
+ SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1715
+ SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1716
+ SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1717
+ SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1718
+ SHA2_64B = class extends HashMD {
1719
+ constructor(outputLen) {
1720
+ super(128, outputLen, 16, false);
1721
+ }
1722
+ // prettier-ignore
1723
+ get() {
1724
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1725
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1726
+ }
1727
+ // prettier-ignore
1728
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1729
+ this.Ah = Ah | 0;
1730
+ this.Al = Al | 0;
1731
+ this.Bh = Bh | 0;
1732
+ this.Bl = Bl | 0;
1733
+ this.Ch = Ch | 0;
1734
+ this.Cl = Cl | 0;
1735
+ this.Dh = Dh | 0;
1736
+ this.Dl = Dl | 0;
1737
+ this.Eh = Eh | 0;
1738
+ this.El = El | 0;
1739
+ this.Fh = Fh | 0;
1740
+ this.Fl = Fl | 0;
1741
+ this.Gh = Gh | 0;
1742
+ this.Gl = Gl | 0;
1743
+ this.Hh = Hh | 0;
1744
+ this.Hl = Hl | 0;
1745
+ }
1746
+ process(view, offset) {
1747
+ for (let i = 0; i < 16; i++, offset += 4) {
1748
+ SHA512_W_H[i] = view.getUint32(offset);
1749
+ SHA512_W_L[i] = view.getUint32(offset += 4);
1750
+ }
1751
+ for (let i = 16; i < 80; i++) {
1752
+ const W15h = SHA512_W_H[i - 15] | 0;
1753
+ const W15l = SHA512_W_L[i - 15] | 0;
1754
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1755
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1756
+ const W2h = SHA512_W_H[i - 2] | 0;
1757
+ const W2l = SHA512_W_L[i - 2] | 0;
1758
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1759
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1760
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1761
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1762
+ SHA512_W_H[i] = SUMh | 0;
1763
+ SHA512_W_L[i] = SUMl | 0;
1764
+ }
1765
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1766
+ for (let i = 0; i < 80; i++) {
1767
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1768
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1769
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
1770
+ const CHIl = El & Fl ^ ~El & Gl;
1771
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1772
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1773
+ const T1l = T1ll | 0;
1774
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1775
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1776
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1777
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1778
+ Hh = Gh | 0;
1779
+ Hl = Gl | 0;
1780
+ Gh = Fh | 0;
1781
+ Gl = Fl | 0;
1782
+ Fh = Eh | 0;
1783
+ Fl = El | 0;
1784
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1785
+ Dh = Ch | 0;
1786
+ Dl = Cl | 0;
1787
+ Ch = Bh | 0;
1788
+ Cl = Bl | 0;
1789
+ Bh = Ah | 0;
1790
+ Bl = Al | 0;
1791
+ const All = add3L(T1l, sigma0l, MAJl);
1792
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1793
+ Al = All | 0;
1794
+ }
1795
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1796
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1797
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1798
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1799
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1800
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1801
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1802
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1803
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1804
+ }
1805
+ roundClean() {
1806
+ clean(SHA512_W_H, SHA512_W_L);
1807
+ }
1808
+ destroy() {
1809
+ this.destroyed = true;
1810
+ clean(this.buffer);
1811
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1812
+ }
1813
+ };
1814
+ _SHA512 = class extends SHA2_64B {
1815
+ constructor() {
1816
+ super(64);
1817
+ __publicField(this, "Ah", SHA512_IV[0] | 0);
1818
+ __publicField(this, "Al", SHA512_IV[1] | 0);
1819
+ __publicField(this, "Bh", SHA512_IV[2] | 0);
1820
+ __publicField(this, "Bl", SHA512_IV[3] | 0);
1821
+ __publicField(this, "Ch", SHA512_IV[4] | 0);
1822
+ __publicField(this, "Cl", SHA512_IV[5] | 0);
1823
+ __publicField(this, "Dh", SHA512_IV[6] | 0);
1824
+ __publicField(this, "Dl", SHA512_IV[7] | 0);
1825
+ __publicField(this, "Eh", SHA512_IV[8] | 0);
1826
+ __publicField(this, "El", SHA512_IV[9] | 0);
1827
+ __publicField(this, "Fh", SHA512_IV[10] | 0);
1828
+ __publicField(this, "Fl", SHA512_IV[11] | 0);
1829
+ __publicField(this, "Gh", SHA512_IV[12] | 0);
1830
+ __publicField(this, "Gl", SHA512_IV[13] | 0);
1831
+ __publicField(this, "Hh", SHA512_IV[14] | 0);
1832
+ __publicField(this, "Hl", SHA512_IV[15] | 0);
1833
+ }
1834
+ };
1835
+ sha512 = /* @__PURE__ */ createHasher(
1836
+ () => new _SHA512(),
1837
+ /* @__PURE__ */ oidNist(3)
1838
+ );
1839
+ }
1840
+ });
1841
+
1842
+ // ../../node_modules/@noble/curves/abstract/fft.js
1843
+ function checkU32(n) {
1844
+ if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
1845
+ throw new Error("wrong u32 integer:" + n);
1846
+ return n;
1847
+ }
1848
+ function isPowerOfTwo(x) {
1849
+ checkU32(x);
1850
+ return (x & x - 1) === 0 && x !== 0;
1851
+ }
1852
+ function reverseBits(n, bits) {
1853
+ checkU32(n);
1854
+ if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
1855
+ throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
1856
+ let reversed = 0;
1857
+ for (let i = 0; i < bits; i++, n >>>= 1)
1858
+ reversed = reversed << 1 | n & 1;
1859
+ return reversed >>> 0;
1860
+ }
1861
+ function log2(n) {
1862
+ checkU32(n);
1863
+ return 31 - Math.clz32(n);
1864
+ }
1865
+ function bitReversalInplace(values) {
1866
+ const n = values.length;
1867
+ if (!isPowerOfTwo(n))
1868
+ throw new Error("expected positive power-of-two length, got " + n);
1869
+ const bits = log2(n);
1870
+ for (let i = 0; i < n; i++) {
1871
+ const j = reverseBits(i, bits);
1872
+ if (i < j) {
1873
+ const tmp = values[i];
1874
+ values[i] = values[j];
1875
+ values[j] = tmp;
1876
+ }
1877
+ }
1878
+ return values;
1879
+ }
1880
+ var FFTCore;
1881
+ var init_fft = __esm({
1882
+ "../../node_modules/@noble/curves/abstract/fft.js"() {
1883
+ "use strict";
1884
+ FFTCore = (F2, coreOpts) => {
1885
+ const { N: N2, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
1886
+ const bits = log2(N2);
1887
+ if (!isPowerOfTwo(N2))
1888
+ throw new Error("FFT: Polynomial size should be power of two");
1889
+ if (roots.length !== N2)
1890
+ throw new Error(`FFT: wrong roots length: expected ${N2}, got ${roots.length}`);
1891
+ const isDit = dit !== invertButterflies;
1892
+ isDit;
1893
+ return (values) => {
1894
+ if (values.length !== N2)
1895
+ throw new Error("FFT: wrong Polynomial length");
1896
+ if (dit && brp)
1897
+ bitReversalInplace(values);
1898
+ for (let i = 0, g = 1; i < bits - skipStages; i++) {
1899
+ const s = dit ? i + 1 + skipStages : bits - i;
1900
+ const m = 1 << s;
1901
+ const m2 = m >> 1;
1902
+ const stride = N2 >> s;
1903
+ for (let k = 0; k < N2; k += m) {
1904
+ for (let j = 0, grp = g++; j < m2; j++) {
1905
+ const rootPos = invertButterflies ? dit ? N2 - grp : grp : j * stride;
1906
+ const i0 = k + j;
1907
+ const i1 = k + j + m2;
1908
+ const omega = roots[rootPos];
1909
+ const b = values[i1];
1910
+ const a = values[i0];
1911
+ if (isDit) {
1912
+ const t = F2.mul(b, omega);
1913
+ values[i0] = F2.add(a, t);
1914
+ values[i1] = F2.sub(a, t);
1915
+ } else if (invertButterflies) {
1916
+ values[i0] = F2.add(b, a);
1917
+ values[i1] = F2.mul(F2.sub(b, a), omega);
1918
+ } else {
1919
+ values[i0] = F2.add(a, b);
1920
+ values[i1] = F2.mul(F2.sub(a, b), omega);
1921
+ }
1922
+ }
1923
+ }
1924
+ }
1925
+ if (!dit && brp)
1926
+ bitReversalInplace(values);
1927
+ return values;
1928
+ };
1929
+ };
1930
+ }
1931
+ });
1932
+
1933
+ // ../../node_modules/@noble/curves/abstract/hash-to-curve.js
1934
+ function i2osp(value, length) {
1935
+ asafenumber(value);
1936
+ asafenumber(length);
1937
+ if (length < 0 || length > 4)
1938
+ throw new Error("invalid I2OSP length: " + length);
1939
+ if (value < 0 || value > 2 ** (8 * length) - 1)
1940
+ throw new Error("invalid I2OSP input: " + value);
1941
+ const res = Array.from({ length }).fill(0);
1942
+ for (let i = length - 1; i >= 0; i--) {
1943
+ res[i] = value & 255;
1944
+ value >>>= 8;
1945
+ }
1946
+ return new Uint8Array(res);
1947
+ }
1948
+ function strxor(a, b) {
1949
+ const arr = new Uint8Array(a.length);
1950
+ for (let i = 0; i < a.length; i++) {
1951
+ arr[i] = a[i] ^ b[i];
1952
+ }
1953
+ return arr;
1954
+ }
1955
+ function normDST(DST) {
1956
+ if (!isBytes2(DST) && typeof DST !== "string")
1957
+ throw new Error("DST must be Uint8Array or ascii string");
1958
+ const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
1959
+ if (dst.length === 0)
1960
+ throw new Error("DST must be non-empty");
1961
+ return dst;
1962
+ }
1963
+ function expand_message_xmd(msg, DST, lenInBytes, H) {
1964
+ abytes2(msg);
1965
+ asafenumber(lenInBytes);
1966
+ DST = normDST(DST);
1967
+ if (DST.length > 255)
1968
+ DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1969
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1970
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
1971
+ if (lenInBytes > 65535 || ell > 255)
1972
+ throw new Error("expand_message_xmd: invalid lenInBytes");
1973
+ const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1974
+ const Z_pad = new Uint8Array(r_in_bytes);
1975
+ const l_i_b_str = i2osp(lenInBytes, 2);
1976
+ const b = new Array(ell);
1977
+ const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1978
+ b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1979
+ for (let i = 1; i < ell; i++) {
1980
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1981
+ b[i] = H(concatBytes2(...args));
1982
+ }
1983
+ const pseudo_random_bytes = concatBytes2(...b);
1984
+ return pseudo_random_bytes.slice(0, lenInBytes);
1985
+ }
1986
+ var _DST_scalar;
1987
+ var init_hash_to_curve = __esm({
1988
+ "../../node_modules/@noble/curves/abstract/hash-to-curve.js"() {
1989
+ "use strict";
1990
+ init_utils2();
1991
+ _DST_scalar = "HashToScalar-";
1992
+ }
1993
+ });
1994
+
1995
+ // ../../node_modules/@noble/curves/ed25519.js
1996
+ function ed25519_pow_2_252_3(x) {
1997
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1998
+ const P = ed25519_CURVE_p;
1999
+ const x2 = x * x % P;
2000
+ const b2 = x2 * x % P;
2001
+ const b4 = pow2(b2, _2n4, P) * b2 % P;
2002
+ const b5 = pow2(b4, _1n6, P) * x % P;
2003
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
2004
+ const b20 = pow2(b10, _10n, P) * b10 % P;
2005
+ const b40 = pow2(b20, _20n, P) * b20 % P;
2006
+ const b80 = pow2(b40, _40n, P) * b40 % P;
2007
+ const b160 = pow2(b80, _80n, P) * b80 % P;
2008
+ const b240 = pow2(b160, _80n, P) * b80 % P;
2009
+ const b250 = pow2(b240, _10n, P) * b10 % P;
2010
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
2011
+ return { pow_p_5_8, b2 };
2012
+ }
2013
+ function adjustScalarBytes(bytes) {
2014
+ bytes[0] &= 248;
2015
+ bytes[31] &= 127;
2016
+ bytes[31] |= 64;
2017
+ return bytes;
2018
+ }
2019
+ function uvRatio(u, v) {
2020
+ const P = ed25519_CURVE_p;
2021
+ const v3 = mod(v * v * v, P);
2022
+ const v7 = mod(v3 * v3 * v, P);
2023
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2024
+ let x = mod(u * v3 * pow, P);
2025
+ const vx2 = mod(v * x * x, P);
2026
+ const root1 = x;
2027
+ const root2 = mod(x * ED25519_SQRT_M1, P);
2028
+ const useRoot1 = vx2 === u;
2029
+ const useRoot2 = vx2 === mod(-u, P);
2030
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2031
+ if (useRoot1)
2032
+ x = root1;
2033
+ if (useRoot2 || noRoot)
2034
+ x = root2;
2035
+ if (isNegativeLE(x, P))
2036
+ x = mod(-x, P);
2037
+ return { isValid: useRoot1 || useRoot2, value: x };
2038
+ }
2039
+ function calcElligatorRistrettoMap(r0) {
2040
+ const { d } = ed25519_CURVE;
2041
+ const P = ed25519_CURVE_p;
2042
+ const mod2 = (n) => Fp.create(n);
2043
+ const r = mod2(SQRT_M1 * r0 * r0);
2044
+ const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
2045
+ let c = BigInt(-1);
2046
+ const D = mod2((c - d * r) * mod2(r + d));
2047
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
2048
+ let s_ = mod2(s * r0);
2049
+ if (!isNegativeLE(s_, P))
2050
+ s_ = mod2(-s_);
2051
+ if (!Ns_D_is_sq)
2052
+ s = s_;
2053
+ if (!Ns_D_is_sq)
2054
+ c = r;
2055
+ const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2056
+ const s2 = s * s;
2057
+ const W0 = mod2((s + s) * D);
2058
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2059
+ const W2 = mod2(_1n6 - s2);
2060
+ const W3 = mod2(_1n6 + s2);
2061
+ return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2062
+ }
2063
+ var _0n6, _1n6, _2n4, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, ed25519_Point, Fp, Fn, x25519, SQRT_M1, SQRT_AD_MINUS_ONE, INVSQRT_A_MINUS_D, ONE_MINUS_D_SQ, D_MINUS_ONE_SQ, invertSqrt, MAX_255B, bytes255ToNumberLE, __RistrettoPoint, _RistrettoPoint, ristretto255_hasher;
2064
+ var init_ed25519 = __esm({
2065
+ "../../node_modules/@noble/curves/ed25519.js"() {
2066
+ "use strict";
2067
+ init_sha2();
2068
+ init_utils();
2069
+ init_edwards();
2070
+ init_hash_to_curve();
2071
+ init_modular();
2072
+ init_montgomery();
2073
+ init_utils2();
2074
+ _0n6 = /* @__PURE__ */ BigInt(0);
2075
+ _1n6 = /* @__PURE__ */ BigInt(1);
2076
+ _2n4 = /* @__PURE__ */ BigInt(2);
2077
+ _3n2 = /* @__PURE__ */ BigInt(3);
2078
+ _5n2 = /* @__PURE__ */ BigInt(5);
2079
+ _8n3 = /* @__PURE__ */ BigInt(8);
2080
+ ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2081
+ ed25519_CURVE = /* @__PURE__ */ (() => ({
2082
+ p: ed25519_CURVE_p,
2083
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2084
+ h: _8n3,
2085
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2086
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2087
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2088
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2089
+ }))();
2090
+ ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2091
+ ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2092
+ Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2093
+ Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
2094
+ x25519 = /* @__PURE__ */ (() => {
2095
+ const P = ed25519_CURVE_p;
2096
+ return montgomery({
2097
+ P,
2098
+ type: "x25519",
2099
+ powPminus2: (x) => {
2100
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2101
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2102
+ },
2103
+ adjustScalarBytes
2104
+ });
2105
+ })();
2106
+ SQRT_M1 = ED25519_SQRT_M1;
2107
+ SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
2108
+ INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
2109
+ ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
2110
+ D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
2111
+ invertSqrt = (number) => uvRatio(_1n6, number);
2112
+ MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2113
+ bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
2114
+ __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2115
+ constructor(ep) {
2116
+ super(ep);
2117
+ }
2118
+ /**
2119
+ * Create one Ristretto255 point from affine Edwards coordinates.
2120
+ * This wraps the internal Edwards representative directly and is not a
2121
+ * canonical ristretto255 decoding path.
2122
+ * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
2123
+ */
2124
+ static fromAffine(ap) {
2125
+ return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2126
+ }
2127
+ assertSame(other) {
2128
+ if (!(other instanceof __RistrettoPoint))
2129
+ throw new Error("RistrettoPoint expected");
2130
+ }
2131
+ init(ep) {
2132
+ return new __RistrettoPoint(ep);
2133
+ }
2134
+ static fromBytes(bytes) {
2135
+ abytes(bytes, 32);
2136
+ const { a, d } = ed25519_CURVE;
2137
+ const P = ed25519_CURVE_p;
2138
+ const mod2 = (n) => Fp.create(n);
2139
+ const s = bytes255ToNumberLE(bytes);
2140
+ if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2141
+ throw new Error("invalid ristretto255 encoding 1");
2142
+ const s2 = mod2(s * s);
2143
+ const u1 = mod2(_1n6 + a * s2);
2144
+ const u2 = mod2(_1n6 - a * s2);
2145
+ const u1_2 = mod2(u1 * u1);
2146
+ const u2_2 = mod2(u2 * u2);
2147
+ const v = mod2(a * d * u1_2 - u2_2);
2148
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2149
+ const Dx = mod2(I * u2);
2150
+ const Dy = mod2(I * Dx * v);
2151
+ let x = mod2((s + s) * Dx);
2152
+ if (isNegativeLE(x, P))
2153
+ x = mod2(-x);
2154
+ const y = mod2(u1 * Dy);
2155
+ const t = mod2(x * y);
2156
+ if (!isValid || isNegativeLE(t, P) || y === _0n6)
2157
+ throw new Error("invalid ristretto255 encoding 2");
2158
+ return new __RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2159
+ }
2160
+ /**
2161
+ * Converts ristretto-encoded string to ristretto point.
2162
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2163
+ * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2164
+ */
2165
+ static fromHex(hex) {
2166
+ return __RistrettoPoint.fromBytes(hexToBytes(hex));
2167
+ }
2168
+ /**
2169
+ * Encodes ristretto point to Uint8Array.
2170
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2171
+ */
2172
+ toBytes() {
2173
+ let { X, Y, Z, T } = this.ep;
2174
+ const P = ed25519_CURVE_p;
2175
+ const mod2 = (n) => Fp.create(n);
2176
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2177
+ const u2 = mod2(X * Y);
2178
+ const u2sq = mod2(u2 * u2);
2179
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2180
+ const D1 = mod2(invsqrt * u1);
2181
+ const D2 = mod2(invsqrt * u2);
2182
+ const zInv = mod2(D1 * D2 * T);
2183
+ let D;
2184
+ if (isNegativeLE(T * zInv, P)) {
2185
+ let _x = mod2(Y * SQRT_M1);
2186
+ let _y = mod2(X * SQRT_M1);
2187
+ X = _x;
2188
+ Y = _y;
2189
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
2190
+ } else {
2191
+ D = D2;
2192
+ }
2193
+ if (isNegativeLE(X * zInv, P))
2194
+ Y = mod2(-Y);
2195
+ let s = mod2((Z - Y) * D);
2196
+ if (isNegativeLE(s, P))
2197
+ s = mod2(-s);
2198
+ return Fp.toBytes(s);
2199
+ }
2200
+ /**
2201
+ * Compares two Ristretto points.
2202
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2203
+ */
2204
+ equals(other) {
2205
+ this.assertSame(other);
2206
+ const { X: X1, Y: Y1 } = this.ep;
2207
+ const { X: X2, Y: Y2 } = other.ep;
2208
+ const mod2 = (n) => Fp.create(n);
2209
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2210
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2211
+ return one || two;
2212
+ }
2213
+ is0() {
2214
+ return this.equals(__RistrettoPoint.ZERO);
2215
+ }
2216
+ };
2217
+ // Do NOT change syntax: the following gymnastics is done,
2218
+ // because typescript strips comments, which makes bundlers disable tree-shaking.
2219
+ // prettier-ignore
2220
+ __publicField(__RistrettoPoint, "BASE", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.BASE))());
2221
+ // prettier-ignore
2222
+ __publicField(__RistrettoPoint, "ZERO", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.ZERO))());
2223
+ // prettier-ignore
2224
+ __publicField(__RistrettoPoint, "Fp", /* @__PURE__ */ (() => Fp)());
2225
+ // prettier-ignore
2226
+ __publicField(__RistrettoPoint, "Fn", /* @__PURE__ */ (() => Fn)());
2227
+ _RistrettoPoint = __RistrettoPoint;
2228
+ Object.freeze(_RistrettoPoint.BASE);
2229
+ Object.freeze(_RistrettoPoint.ZERO);
2230
+ Object.freeze(_RistrettoPoint.prototype);
2231
+ Object.freeze(_RistrettoPoint);
2232
+ ristretto255_hasher = Object.freeze({
2233
+ Point: _RistrettoPoint,
2234
+ /**
2235
+ * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
2236
+ * * There are no test vectors
2237
+ * * encodeToCurve / mapToCurve is undefined
2238
+ * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
2239
+ * * hashToScalar is undefined too, so we just use OPRF implementation
2240
+ * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2241
+ (os2ip -> bytes255ToNumberLE)
2242
+ * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2243
+ * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
2244
+ version here. Using `bytes255ToNumblerLE` will create a different result
2245
+ if we use `bytes255ToNumberLE` as os2ip
2246
+ * * current version is closest to spec.
2247
+ */
2248
+ hashToCurve(msg, options) {
2249
+ const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2250
+ const xmd = expand_message_xmd(msg, DST, 64, sha512);
2251
+ return ristretto255_hasher.deriveToCurve(xmd);
2252
+ },
2253
+ hashToScalar(msg, options = { DST: _DST_scalar }) {
2254
+ const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2255
+ return Fn.create(bytesToNumberLE(xmd));
2256
+ },
2257
+ /**
2258
+ * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2259
+ * Converts 64 uniform random bytes into a curve point.
2260
+ *
2261
+ * WARNING: This represents an older hash-to-curve construction from before
2262
+ * RFC 9380 was finalized.
2263
+ * It was later reused as a component in the newer
2264
+ * `hash_to_ristretto255` function defined in RFC 9380.
2265
+ */
2266
+ deriveToCurve(bytes) {
2267
+ abytes(bytes, 64);
2268
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2269
+ const R1 = calcElligatorRistrettoMap(r1);
2270
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2271
+ const R2 = calcElligatorRistrettoMap(r2);
2272
+ return new _RistrettoPoint(R1.add(R2));
2273
+ }
2274
+ });
2275
+ }
2276
+ });
2277
+
2278
+ // ../../node_modules/@noble/hashes/sha3.js
2279
+ function keccakP(s, rounds = 24) {
2280
+ anumber(rounds, "rounds");
2281
+ if (rounds < 1 || rounds > 24)
2282
+ throw new Error('"rounds" expected integer 1..24');
2283
+ const B = new Uint32Array(5 * 2);
2284
+ for (let round = 24 - rounds; round < 24; round++) {
2285
+ for (let x = 0; x < 10; x++)
2286
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2287
+ for (let x = 0; x < 10; x += 2) {
2288
+ const idx1 = (x + 8) % 10;
2289
+ const idx0 = (x + 2) % 10;
2290
+ const B0 = B[idx0];
2291
+ const B1 = B[idx0 + 1];
2292
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
2293
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2294
+ for (let y = 0; y < 50; y += 10) {
2295
+ s[x + y] ^= Th;
2296
+ s[x + y + 1] ^= Tl;
2297
+ }
2298
+ }
2299
+ let curH = s[2];
2300
+ let curL = s[3];
2301
+ for (let t = 0; t < 24; t++) {
2302
+ const shift = SHA3_ROTL[t];
2303
+ const Th = rotlH(curH, curL, shift);
2304
+ const Tl = rotlL(curH, curL, shift);
2305
+ const PI = SHA3_PI[t];
2306
+ curH = s[PI];
2307
+ curL = s[PI + 1];
2308
+ s[PI] = Th;
2309
+ s[PI + 1] = Tl;
2310
+ }
2311
+ for (let y = 0; y < 50; y += 10) {
2312
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
2313
+ s[y] ^= ~s[y + 2] & s[y + 4];
2314
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
2315
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
2316
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
2317
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
2318
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
2319
+ s[y + 6] ^= ~s[y + 8] & b0;
2320
+ s[y + 7] ^= ~s[y + 9] & b1;
2321
+ s[y + 8] ^= ~b0 & b2;
2322
+ s[y + 9] ^= ~b1 & b3;
2323
+ }
2324
+ s[0] ^= SHA3_IOTA_H[round];
2325
+ s[1] ^= SHA3_IOTA_L[round];
2326
+ }
2327
+ clean(B);
2328
+ }
2329
+ var _0n7, _1n7, _2n5, _7n2, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, genKeccak, sha3_256, sha3_512, genShake, shake128, shake256;
2330
+ var init_sha3 = __esm({
2331
+ "../../node_modules/@noble/hashes/sha3.js"() {
2332
+ "use strict";
2333
+ init_u64();
2334
+ init_utils();
2335
+ _0n7 = BigInt(0);
2336
+ _1n7 = BigInt(1);
2337
+ _2n5 = BigInt(2);
2338
+ _7n2 = BigInt(7);
2339
+ _256n = BigInt(256);
2340
+ _0x71n = BigInt(113);
2341
+ SHA3_PI = [];
2342
+ SHA3_ROTL = [];
2343
+ _SHA3_IOTA = [];
2344
+ for (let round = 0, R = _1n7, x = 1, y = 0; round < 24; round++) {
2345
+ [x, y] = [y, (2 * x + 3 * y) % 5];
2346
+ SHA3_PI.push(2 * (5 * y + x));
2347
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
2348
+ let t = _0n7;
2349
+ for (let j = 0; j < 7; j++) {
2350
+ R = (R << _1n7 ^ (R >> _7n2) * _0x71n) % _256n;
2351
+ if (R & _2n5)
2352
+ t ^= _1n7 << (_1n7 << BigInt(j)) - _1n7;
2353
+ }
2354
+ _SHA3_IOTA.push(t);
2355
+ }
2356
+ IOTAS = split(_SHA3_IOTA, true);
2357
+ SHA3_IOTA_H = IOTAS[0];
2358
+ SHA3_IOTA_L = IOTAS[1];
2359
+ rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
2360
+ rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
2361
+ Keccak = class _Keccak {
2362
+ // NOTE: we accept arguments in bytes instead of bits here.
2363
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2364
+ __publicField(this, "state");
2365
+ __publicField(this, "pos", 0);
2366
+ __publicField(this, "posOut", 0);
2367
+ __publicField(this, "finished", false);
2368
+ __publicField(this, "state32");
2369
+ __publicField(this, "destroyed", false);
2370
+ __publicField(this, "blockLen");
2371
+ __publicField(this, "suffix");
2372
+ __publicField(this, "outputLen");
2373
+ __publicField(this, "canXOF");
2374
+ __publicField(this, "enableXOF", false);
2375
+ __publicField(this, "rounds");
2376
+ this.blockLen = blockLen;
2377
+ this.suffix = suffix;
2378
+ this.outputLen = outputLen;
2379
+ this.enableXOF = enableXOF;
2380
+ this.canXOF = enableXOF;
2381
+ this.rounds = rounds;
2382
+ anumber(outputLen, "outputLen");
2383
+ if (!(0 < blockLen && blockLen < 200))
2384
+ throw new Error("only keccak-f1600 function is supported");
2385
+ this.state = new Uint8Array(200);
2386
+ this.state32 = u32(this.state);
2387
+ }
2388
+ clone() {
2389
+ return this._cloneInto();
2390
+ }
2391
+ keccak() {
2392
+ swap32IfBE(this.state32);
2393
+ keccakP(this.state32, this.rounds);
2394
+ swap32IfBE(this.state32);
2395
+ this.posOut = 0;
2396
+ this.pos = 0;
2397
+ }
2398
+ update(data) {
2399
+ aexists(this);
2400
+ abytes(data);
2401
+ const { blockLen, state } = this;
2402
+ const len = data.length;
2403
+ for (let pos = 0; pos < len; ) {
2404
+ const take = Math.min(blockLen - this.pos, len - pos);
2405
+ for (let i = 0; i < take; i++)
2406
+ state[this.pos++] ^= data[pos++];
2407
+ if (this.pos === blockLen)
2408
+ this.keccak();
2409
+ }
2410
+ return this;
2411
+ }
2412
+ finish() {
2413
+ if (this.finished)
2414
+ return;
2415
+ this.finished = true;
2416
+ const { state, suffix, pos, blockLen } = this;
2417
+ state[pos] ^= suffix;
2418
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
2419
+ this.keccak();
2420
+ state[blockLen - 1] ^= 128;
2421
+ this.keccak();
2422
+ }
2423
+ writeInto(out) {
2424
+ aexists(this, false);
2425
+ abytes(out);
2426
+ this.finish();
2427
+ const bufferOut = this.state;
2428
+ const { blockLen } = this;
2429
+ for (let pos = 0, len = out.length; pos < len; ) {
2430
+ if (this.posOut >= blockLen)
2431
+ this.keccak();
2432
+ const take = Math.min(blockLen - this.posOut, len - pos);
2433
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2434
+ this.posOut += take;
2435
+ pos += take;
2436
+ }
2437
+ return out;
2438
+ }
2439
+ xofInto(out) {
2440
+ if (!this.enableXOF)
2441
+ throw new Error("XOF is not possible for this instance");
2442
+ return this.writeInto(out);
2443
+ }
2444
+ xof(bytes) {
2445
+ anumber(bytes);
2446
+ return this.xofInto(new Uint8Array(bytes));
2447
+ }
2448
+ digestInto(out) {
2449
+ aoutput(out, this);
2450
+ if (this.finished)
2451
+ throw new Error("digest() was already called");
2452
+ this.writeInto(out.subarray(0, this.outputLen));
2453
+ this.destroy();
2454
+ }
2455
+ digest() {
2456
+ const out = new Uint8Array(this.outputLen);
2457
+ this.digestInto(out);
2458
+ return out;
2459
+ }
2460
+ destroy() {
2461
+ this.destroyed = true;
2462
+ clean(this.state);
2463
+ }
2464
+ _cloneInto(to) {
2465
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2466
+ to ||= new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
2467
+ to.blockLen = blockLen;
2468
+ to.state32.set(this.state32);
2469
+ to.pos = this.pos;
2470
+ to.posOut = this.posOut;
2471
+ to.finished = this.finished;
2472
+ to.rounds = rounds;
2473
+ to.suffix = suffix;
2474
+ to.outputLen = outputLen;
2475
+ to.enableXOF = enableXOF;
2476
+ to.canXOF = this.canXOF;
2477
+ to.destroyed = this.destroyed;
2478
+ return to;
2479
+ }
2480
+ };
2481
+ genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
2482
+ sha3_256 = /* @__PURE__ */ genKeccak(
2483
+ 6,
2484
+ 136,
2485
+ 32,
2486
+ /* @__PURE__ */ oidNist(8)
2487
+ );
2488
+ sha3_512 = /* @__PURE__ */ genKeccak(
2489
+ 6,
2490
+ 72,
2491
+ 64,
2492
+ /* @__PURE__ */ oidNist(10)
2493
+ );
2494
+ genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info);
2495
+ shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2496
+ shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2497
+ }
2498
+ });
2499
+
2500
+ // ../../node_modules/@noble/post-quantum/utils.js
2501
+ function equalBytes2(a, b) {
2502
+ if (a.length !== b.length)
2503
+ return false;
2504
+ let diff = 0;
2505
+ for (let i = 0; i < a.length; i++)
2506
+ diff |= a[i] ^ b[i];
2507
+ return diff === 0;
2508
+ }
2509
+ function copyBytes2(bytes) {
2510
+ return Uint8Array.from(abytes(bytes));
2511
+ }
2512
+ function splitCoder(label, ...lengths) {
2513
+ const getLength = (c) => typeof c === "number" ? c : c.bytesLen;
2514
+ const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);
2515
+ return {
2516
+ bytesLen,
2517
+ encode: (bufs) => {
2518
+ const res = new Uint8Array(bytesLen);
2519
+ for (let i = 0, pos = 0; i < lengths.length; i++) {
2520
+ const c = lengths[i];
2521
+ const l = getLength(c);
2522
+ const b = typeof c === "number" ? bufs[i] : c.encode(bufs[i]);
2523
+ abytes(b, l, label);
2524
+ res.set(b, pos);
2525
+ if (typeof c !== "number")
2526
+ b.fill(0);
2527
+ pos += l;
2528
+ }
2529
+ return res;
2530
+ },
2531
+ decode: (buf) => {
2532
+ abytes(buf, bytesLen, label);
2533
+ const res = [];
2534
+ for (const c of lengths) {
2535
+ const l = getLength(c);
2536
+ const b = buf.subarray(0, l);
2537
+ res.push(typeof c === "number" ? b : c.decode(b));
2538
+ buf = buf.subarray(l);
2539
+ }
2540
+ return res;
2541
+ }
2542
+ };
2543
+ }
2544
+ function vecCoder(c, vecLen) {
2545
+ const coder = c;
2546
+ const bytesLen = vecLen * coder.bytesLen;
2547
+ return {
2548
+ bytesLen,
2549
+ encode: (u) => {
2550
+ if (u.length !== vecLen)
2551
+ throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
2552
+ const res = new Uint8Array(bytesLen);
2553
+ for (let i = 0, pos = 0; i < u.length; i++) {
2554
+ const b = coder.encode(u[i]);
2555
+ res.set(b, pos);
2556
+ b.fill(0);
2557
+ pos += b.length;
2558
+ }
2559
+ return res;
2560
+ },
2561
+ decode: (a) => {
2562
+ abytes(a, bytesLen);
2563
+ const r = [];
2564
+ for (let i = 0; i < a.length; i += coder.bytesLen)
2565
+ r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
2566
+ return r;
2567
+ }
2568
+ };
2569
+ }
2570
+ function cleanBytes(...list) {
2571
+ for (const t of list) {
2572
+ if (Array.isArray(t))
2573
+ for (const b of t)
2574
+ b.fill(0);
2575
+ else
2576
+ t.fill(0);
2577
+ }
2578
+ }
2579
+ function getMask(bits) {
2580
+ if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
2581
+ throw new RangeError(`expected bits in [0..32], got ${bits}`);
2582
+ return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
2583
+ }
2584
+ var abytesDoc, randomBytes3;
2585
+ var init_utils3 = __esm({
2586
+ "../../node_modules/@noble/post-quantum/utils.js"() {
2587
+ "use strict";
2588
+ init_utils();
2589
+ abytesDoc = abytes;
2590
+ randomBytes3 = randomBytes;
2591
+ }
2592
+ });
2593
+
2594
+ // ../../node_modules/@noble/post-quantum/_crystals.js
2595
+ var genCrystals, createXofShake, XOF128;
2596
+ var init_crystals = __esm({
2597
+ "../../node_modules/@noble/post-quantum/_crystals.js"() {
2598
+ "use strict";
2599
+ init_fft();
2600
+ init_sha3();
2601
+ init_utils3();
2602
+ genCrystals = (opts2) => {
2603
+ const { newPoly, N: N2, Q: Q2, F: F2, ROOT_OF_UNITY: ROOT_OF_UNITY2, brvBits, isKyber } = opts2;
2604
+ const mod2 = (a, modulo = Q2) => {
2605
+ const result = a % modulo | 0;
2606
+ return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
2607
+ };
2608
+ const smod = (a, modulo = Q2) => {
2609
+ const r = mod2(a, modulo) | 0;
2610
+ return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
2611
+ };
2612
+ function getZettas() {
2613
+ const out = newPoly(N2);
2614
+ for (let i = 0; i < N2; i++) {
2615
+ const b = reverseBits(i, brvBits);
2616
+ const p = BigInt(ROOT_OF_UNITY2) ** BigInt(b) % BigInt(Q2);
2617
+ out[i] = Number(p) | 0;
2618
+ }
2619
+ return out;
2620
+ }
2621
+ const nttZetas = getZettas();
2622
+ const field = {
2623
+ add: (a, b) => mod2((a | 0) + (b | 0)) | 0,
2624
+ sub: (a, b) => mod2((a | 0) - (b | 0)) | 0,
2625
+ mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2626
+ inv: (_a) => {
2627
+ throw new Error("not implemented");
2628
+ }
2629
+ };
2630
+ const nttOpts = {
2631
+ N: N2,
2632
+ roots: nttZetas,
2633
+ invertButterflies: true,
2634
+ skipStages: isKyber ? 1 : 0,
2635
+ brp: false
2636
+ };
2637
+ const dif = FFTCore(field, { dit: false, ...nttOpts });
2638
+ const dit = FFTCore(field, { dit: true, ...nttOpts });
2639
+ const NTT = {
2640
+ encode: (r) => {
2641
+ return dif(r);
2642
+ },
2643
+ decode: (r) => {
2644
+ dit(r);
2645
+ for (let i = 0; i < r.length; i++)
2646
+ r[i] = mod2(F2 * r[i]);
2647
+ return r;
2648
+ }
2649
+ };
2650
+ const bitsCoder = (d, c) => {
2651
+ const mask = getMask(d);
2652
+ const bytesLen = d * (N2 / 8);
2653
+ return {
2654
+ bytesLen,
2655
+ encode: (poly_) => {
2656
+ const poly = poly_;
2657
+ const r = new Uint8Array(bytesLen);
2658
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
2659
+ buf |= (c.encode(poly[i]) & mask) << bufLen;
2660
+ bufLen += d;
2661
+ for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
2662
+ r[pos++] = buf & getMask(bufLen);
2663
+ }
2664
+ return r;
2665
+ },
2666
+ decode: (bytes) => {
2667
+ const r = newPoly(N2);
2668
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
2669
+ buf |= bytes[i] << bufLen;
2670
+ bufLen += 8;
2671
+ for (; bufLen >= d; bufLen -= d, buf >>= d)
2672
+ r[pos++] = c.decode(buf & mask);
2673
+ }
2674
+ return r;
2675
+ }
2676
+ };
2677
+ };
2678
+ return {
2679
+ mod: mod2,
2680
+ smod,
2681
+ nttZetas,
2682
+ NTT: {
2683
+ encode: (r) => NTT.encode(r),
2684
+ decode: (r) => NTT.decode(r)
2685
+ },
2686
+ bitsCoder
2687
+ };
2688
+ };
2689
+ createXofShake = (shake) => (seed, blockLen) => {
2690
+ if (!blockLen)
2691
+ blockLen = shake.blockLen;
2692
+ const _seed = new Uint8Array(seed.length + 2);
2693
+ _seed.set(seed);
2694
+ const seedLen = seed.length;
2695
+ const buf = new Uint8Array(blockLen);
2696
+ let h = shake.create({});
2697
+ let calls = 0;
2698
+ let xofs = 0;
2699
+ return {
2700
+ stats: () => ({ calls, xofs }),
2701
+ get: (x, y) => {
2702
+ _seed[seedLen + 0] = x;
2703
+ _seed[seedLen + 1] = y;
2704
+ h.destroy();
2705
+ h = shake.create({}).update(_seed);
2706
+ calls++;
2707
+ return () => {
2708
+ xofs++;
2709
+ return h.xofInto(buf);
2710
+ };
2711
+ },
2712
+ clean: () => {
2713
+ h.destroy();
2714
+ cleanBytes(buf, _seed);
2715
+ }
2716
+ };
2717
+ };
2718
+ XOF128 = /* @__PURE__ */ createXofShake(shake128);
2719
+ }
2720
+ });
2721
+
2722
+ // ../../node_modules/@noble/post-quantum/ml-kem.js
2723
+ function polyAdd(a_, b_) {
2724
+ const a = a_;
2725
+ const b = b_;
2726
+ for (let i = 0; i < N; i++)
2727
+ a[i] = crystals.mod(a[i] + b[i]);
2728
+ }
2729
+ function polySub(a_, b_) {
2730
+ const a = a_;
2731
+ const b = b_;
2732
+ for (let i = 0; i < N; i++)
2733
+ a[i] = crystals.mod(a[i] - b[i]);
2734
+ }
2735
+ function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
2736
+ const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);
2737
+ const c1 = crystals.mod(a0 * b1 + a1 * b0);
2738
+ return { c0, c1 };
2739
+ }
2740
+ function MultiplyNTTs(f_, g_) {
2741
+ const f = f_;
2742
+ const g = g_;
2743
+ for (let i = 0; i < N / 2; i++) {
2744
+ let z = crystals.nttZetas[64 + (i >> 1)];
2745
+ if (i & 1)
2746
+ z = -z;
2747
+ const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);
2748
+ f[2 * i + 0] = c0;
2749
+ f[2 * i + 1] = c1;
2750
+ }
2751
+ return f;
2752
+ }
2753
+ function SampleNTT(xof_) {
2754
+ const xof = xof_;
2755
+ const r = new Uint16Array(N);
2756
+ for (let j = 0; j < N; ) {
2757
+ const b = xof();
2758
+ if (b.length % 3)
2759
+ throw new Error("SampleNTT: unaligned block");
2760
+ for (let i = 0; j < N && i + 3 <= b.length; i += 3) {
2761
+ const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095;
2762
+ const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095;
2763
+ if (d1 < Q)
2764
+ r[j++] = d1;
2765
+ if (j < N && d2 < Q)
2766
+ r[j++] = d2;
2767
+ }
2768
+ }
2769
+ return r;
2770
+ }
2771
+ function sampleCBD(PRF_, seed, nonce, eta) {
2772
+ const PRF = PRF_;
2773
+ return sampleCBDBytes(PRF(eta * N / 4, seed, nonce), eta);
2774
+ }
2775
+ function createKyber(opts2) {
2776
+ const rawOpts = opts2;
2777
+ const KPKE = genKPKE(rawOpts);
2778
+ const { HASH256, HASH512, KDF } = rawOpts;
2779
+ const { secretCoder: KPKESecretCoder, lengths } = KPKE;
2780
+ const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
2781
+ const msgLen = 32;
2782
+ const seedLen = 64;
2783
+ const kemLengths = Object.freeze({
2784
+ ...lengths,
2785
+ seed: 64,
2786
+ msg: msgLen,
2787
+ msgRand: msgLen,
2788
+ secretKey: secretCoder.bytesLen
2789
+ });
2790
+ return Object.freeze({
2791
+ info: Object.freeze({ type: "ml-kem" }),
2792
+ lengths: kemLengths,
2793
+ keygen: (seed = randomBytes3(seedLen)) => {
2794
+ abytesDoc(seed, seedLen, "seed");
2795
+ const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
2796
+ const publicKeyHash = HASH256(publicKey);
2797
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
2798
+ cleanBytes(sk, publicKeyHash);
2799
+ return {
2800
+ publicKey,
2801
+ secretKey
2802
+ };
2803
+ },
2804
+ getPublicKey: (secretKey) => {
2805
+ const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
2806
+ return Uint8Array.from(publicKey);
2807
+ },
2808
+ encapsulate: (publicKey, msg = randomBytes3(msgLen)) => {
2809
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2810
+ abytesDoc(msg, msgLen, "message");
2811
+ const eke = publicKey.subarray(0, 384 * opts2.K);
2812
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2813
+ if (!equalBytes2(ek, eke)) {
2814
+ cleanBytes(ek);
2815
+ throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
2816
+ }
2817
+ cleanBytes(ek);
2818
+ const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
2819
+ const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2820
+ cleanBytes(kr.subarray(32));
2821
+ return {
2822
+ cipherText,
2823
+ sharedSecret: kr.subarray(0, 32)
2824
+ };
2825
+ },
2826
+ decapsulate: (cipherText, secretKey) => {
2827
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2828
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2829
+ const k768 = secretCoder.bytesLen - 96;
2830
+ const start = k768 + 32;
2831
+ const test = HASH256(secretKey.subarray(k768 / 2, start));
2832
+ if (!equalBytes2(test, secretKey.subarray(start, start + 32)))
2833
+ throw new Error("invalid secretKey: hash check failed");
2834
+ const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
2835
+ const msg = KPKE.decrypt(cipherText, sk);
2836
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2837
+ const Khat = kr.subarray(0, 32);
2838
+ const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2839
+ const isValid = equalBytes2(cipherText, cipherText2);
2840
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2841
+ cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
2842
+ return isValid ? Khat : Kbar;
2843
+ }
2844
+ });
2845
+ }
2846
+ function shakePRF(dkLen, key, nonce) {
2847
+ return shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
2848
+ }
2849
+ var N, Q, F, ROOT_OF_UNITY, crystals, PARAMS, compress, byteCoder, polyCoder, sampleCBDBytes, genKPKE, opts, mk, ml_kem768;
2850
+ var init_ml_kem = __esm({
2851
+ "../../node_modules/@noble/post-quantum/ml-kem.js"() {
2852
+ "use strict";
2853
+ init_sha3();
2854
+ init_utils();
2855
+ init_crystals();
2856
+ init_utils3();
2857
+ N = 256;
2858
+ Q = 3329;
2859
+ F = 3303;
2860
+ ROOT_OF_UNITY = 17;
2861
+ crystals = /* @__PURE__ */ genCrystals({
2862
+ N,
2863
+ Q,
2864
+ F,
2865
+ ROOT_OF_UNITY,
2866
+ newPoly: (n) => new Uint16Array(n),
2867
+ brvBits: 7,
2868
+ isKyber: true
2869
+ });
2870
+ PARAMS = /* @__PURE__ */ (() => Object.freeze({
2871
+ 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
2872
+ 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
2873
+ 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
2874
+ }))();
2875
+ compress = (d) => {
2876
+ if (d >= 12)
2877
+ return { encode: (i) => i, decode: (i) => i >= Q ? i - Q : i };
2878
+ const a = 2 ** (d - 1);
2879
+ return {
2880
+ // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).
2881
+ encode: (i) => ((i << d) + Q / 2) / Q,
2882
+ // const decompress = (i: number) => round((Q / 2 ** d) * i);
2883
+ decode: (i) => i * Q + a >>> d
2884
+ };
2885
+ };
2886
+ byteCoder = (d) => crystals.bitsCoder(d, d === 12 ? { encode: (i) => i, decode: (i) => i >= Q ? i - Q : i } : { encode: (i) => i, decode: (i) => i });
2887
+ polyCoder = (d) => d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d));
2888
+ sampleCBDBytes = (buf, eta) => {
2889
+ const r = new Uint16Array(N);
2890
+ const b32 = u32(buf);
2891
+ swap32IfBE(b32);
2892
+ let len = 0;
2893
+ for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {
2894
+ let b = b32[i];
2895
+ for (let j = 0; j < 32; j++) {
2896
+ bb += b & 1;
2897
+ b >>= 1;
2898
+ len += 1;
2899
+ if (len === eta) {
2900
+ t0 = bb;
2901
+ bb = 0;
2902
+ } else if (len === 2 * eta) {
2903
+ r[p++] = crystals.mod(t0 - bb);
2904
+ bb = 0;
2905
+ len = 0;
2906
+ }
2907
+ }
2908
+ }
2909
+ swap32IfBE(b32);
2910
+ if (len)
2911
+ throw new Error(`sampleCBD: leftover bits: ${len}`);
2912
+ return r;
2913
+ };
2914
+ genKPKE = (opts_) => {
2915
+ const opts2 = opts_;
2916
+ const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2;
2917
+ const poly1 = polyCoder(1);
2918
+ const polyV = polyCoder(dv);
2919
+ const polyU = polyCoder(du);
2920
+ const publicCoder = splitCoder("publicKey", vecCoder(polyCoder(12), K), 32);
2921
+ const secretCoder = vecCoder(polyCoder(12), K);
2922
+ const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
2923
+ const seedCoder = splitCoder("seed", 32, 32);
2924
+ return {
2925
+ secretCoder,
2926
+ lengths: {
2927
+ secretKey: secretCoder.bytesLen,
2928
+ publicKey: publicCoder.bytesLen,
2929
+ cipherText: cipherCoder.bytesLen
2930
+ },
2931
+ keygen: (seed) => {
2932
+ abytesDoc(seed, 32, "seed");
2933
+ const seedDst = new Uint8Array(33);
2934
+ seedDst.set(seed);
2935
+ seedDst[32] = K;
2936
+ const seedHash = HASH512(seedDst);
2937
+ const [rho, sigma] = seedCoder.decode(seedHash);
2938
+ const sHat = [];
2939
+ const tHat = [];
2940
+ for (let i = 0; i < K; i++)
2941
+ sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));
2942
+ const x = XOF(rho);
2943
+ for (let i = 0; i < K; i++) {
2944
+ const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));
2945
+ for (let j = 0; j < K; j++) {
2946
+ const aji = SampleNTT(x.get(j, i));
2947
+ polyAdd(e, MultiplyNTTs(aji, sHat[j]));
2948
+ }
2949
+ tHat.push(e);
2950
+ }
2951
+ x.clean();
2952
+ const res = {
2953
+ publicKey: publicCoder.encode([tHat, rho]),
2954
+ secretKey: secretCoder.encode(sHat)
2955
+ };
2956
+ cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);
2957
+ return res;
2958
+ },
2959
+ encrypt: (publicKey, msg, seed) => {
2960
+ const [tHat, rho] = publicCoder.decode(publicKey);
2961
+ const rHat = [];
2962
+ for (let i = 0; i < K; i++)
2963
+ rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2964
+ const x = XOF(rho);
2965
+ const tmp2 = new Uint16Array(N);
2966
+ const u = [];
2967
+ for (let i = 0; i < K; i++) {
2968
+ const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2969
+ const tmp = new Uint16Array(N);
2970
+ for (let j = 0; j < K; j++) {
2971
+ const aij = SampleNTT(x.get(i, j));
2972
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2973
+ }
2974
+ polyAdd(e1, crystals.NTT.decode(tmp));
2975
+ u.push(e1);
2976
+ polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2977
+ cleanBytes(tmp);
2978
+ }
2979
+ x.clean();
2980
+ const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2981
+ polyAdd(e2, crystals.NTT.decode(tmp2));
2982
+ const v = poly1.decode(msg);
2983
+ polyAdd(v, e2);
2984
+ cleanBytes(tHat, rHat, tmp2, e2);
2985
+ return cipherCoder.encode([u, v]);
2986
+ },
2987
+ decrypt: (cipherText, privateKey) => {
2988
+ const [u, v] = cipherCoder.decode(cipherText);
2989
+ const sk = secretCoder.decode(privateKey);
2990
+ const tmp = new Uint16Array(N);
2991
+ for (let i = 0; i < K; i++)
2992
+ polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
2993
+ polySub(v, crystals.NTT.decode(tmp));
2994
+ cleanBytes(tmp, sk, u);
2995
+ return poly1.encode(v);
2996
+ }
2997
+ };
2998
+ };
2999
+ opts = /* @__PURE__ */ (() => ({
3000
+ HASH256: sha3_256,
3001
+ HASH512: sha3_512,
3002
+ KDF: shake256,
3003
+ XOF: XOF128,
3004
+ PRF: shakePRF
3005
+ }))();
3006
+ mk = (params) => createKyber({
3007
+ ...opts,
3008
+ ...params
3009
+ });
3010
+ ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
3011
+ }
3012
+ });
3013
+
3014
+ // ../../node_modules/@noble/post-quantum/hybrid.js
3015
+ function ecKeygen(curve, allowZeroKey = false) {
3016
+ const lengths = curve.lengths;
3017
+ let keygen = curve.keygen;
3018
+ if (allowZeroKey) {
3019
+ if (!("getSharedSecret" in curve && "sign" in curve && "verify" in curve))
3020
+ throw new Error("allowZeroKey requires a Weierstrass curve");
3021
+ const wCurve = curve;
3022
+ const Fn2 = wCurve.Point.Fn;
3023
+ keygen = (seed = randomBytes3(lengths.seed)) => {
3024
+ abytes(seed, lengths.seed, "seed");
3025
+ const seedScalar = Fn2.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
3026
+ const secretKey = Fn2.toBytes(Fn2.create(seedScalar));
3027
+ return {
3028
+ secretKey,
3029
+ publicKey: curve.getPublicKey(secretKey)
3030
+ };
3031
+ };
3032
+ }
3033
+ return {
3034
+ lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },
3035
+ keygen: (seed) => keygen(seed),
3036
+ getPublicKey: (secretKey) => curve.getPublicKey(secretKey)
3037
+ };
3038
+ }
3039
+ function ecdhKem(curve, allowZeroKey = false) {
3040
+ const kg = ecKeygen(curve, allowZeroKey);
3041
+ if (!curve.getSharedSecret)
3042
+ throw new Error("wrong curve");
3043
+ return {
3044
+ lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },
3045
+ keygen: kg.keygen,
3046
+ getPublicKey: kg.getPublicKey,
3047
+ encapsulate(publicKey, rand = randomBytes3(curve.lengths.seed)) {
3048
+ const seed = copyBytes2(rand);
3049
+ let ek = void 0;
3050
+ try {
3051
+ ek = this.keygen(seed).secretKey;
3052
+ const sharedSecret = this.decapsulate(publicKey, ek);
3053
+ const cipherText = curve.getPublicKey(ek);
3054
+ return { sharedSecret, cipherText };
3055
+ } finally {
3056
+ cleanBytes(seed);
3057
+ if (ek)
3058
+ cleanBytes(ek);
3059
+ }
3060
+ },
3061
+ decapsulate(cipherText, secretKey) {
3062
+ const res = curve.getSharedSecret(secretKey, cipherText);
3063
+ return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
3064
+ }
3065
+ };
3066
+ }
3067
+ function splitLengths(lst, name) {
3068
+ return splitCoder(name, ...lst.map((i) => {
3069
+ if (typeof i.lengths[name] !== "number")
3070
+ throw new Error("wrong length: " + name);
3071
+ return i.lengths[name];
3072
+ }));
3073
+ }
3074
+ function expandSeedXof(xof) {
3075
+ return ((seed, seedLen) => xof(seed, { dkLen: seedLen }));
3076
+ }
3077
+ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
3078
+ const expandSeed = expandSeed_;
3079
+ const ck = ck_;
3080
+ const seedCoder = splitLengths(ck, "seed");
3081
+ const pkCoder = splitLengths(ck, "publicKey");
3082
+ if (realSeedLen === void 0)
3083
+ realSeedLen = seedCoder.bytesLen;
3084
+ anumber(realSeedLen);
3085
+ function expandDecapsulationKey(seed) {
3086
+ abytes(seed, realSeedLen);
3087
+ const expandedRaw = expandSeed(seed, seedCoder.bytesLen);
3088
+ const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes2(expandedRaw) : expandedRaw;
3089
+ const expanded = [];
3090
+ const keySecret = [];
3091
+ const secretKey = [];
3092
+ const publicKey = [];
3093
+ let ok = false;
3094
+ try {
3095
+ for (const part of seedCoder.decode(expandedSeed))
3096
+ expanded.push(copyBytes2(part));
3097
+ for (let i = 0; i < ck.length; i++) {
3098
+ const keys = ck[i].keygen(expanded[i]);
3099
+ keySecret.push(keys.secretKey);
3100
+ secretKey.push(copyBytes2(keys.secretKey));
3101
+ publicKey.push(keys.publicKey);
3102
+ }
3103
+ ok = true;
3104
+ return { secretKey, publicKey };
3105
+ } finally {
3106
+ cleanBytes(expandedSeed, expanded, keySecret);
3107
+ if (!ok)
3108
+ cleanBytes(secretKey);
3109
+ }
3110
+ }
3111
+ return {
3112
+ info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },
3113
+ getPublicKey(secretKey) {
3114
+ return this.keygen(secretKey).publicKey;
3115
+ },
3116
+ keygen(seed = randomBytes3(realSeedLen)) {
3117
+ const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);
3118
+ try {
3119
+ const publicKey = pkCoder.encode(pk);
3120
+ return { secretKey: seed, publicKey };
3121
+ } finally {
3122
+ cleanBytes(pk);
3123
+ cleanBytes(secretKey);
3124
+ }
3125
+ },
3126
+ expandDecapsulationKey,
3127
+ realSeedLen
3128
+ };
3129
+ }
3130
+ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
3131
+ const rawCombiner = combiner;
3132
+ const rawKems = kems;
3133
+ const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);
3134
+ const ctCoder = splitLengths(rawKems, "cipherText");
3135
+ const pkCoder = splitLengths(rawKems, "publicKey");
3136
+ const msgCoder = splitLengths(rawKems, "msg");
3137
+ if (realMsgLen === void 0)
3138
+ realMsgLen = msgCoder.bytesLen;
3139
+ anumber(realMsgLen);
3140
+ const lengths = Object.freeze({
3141
+ ...keys.info.lengths,
3142
+ msg: realMsgLen,
3143
+ msgRand: msgCoder.bytesLen,
3144
+ cipherText: ctCoder.bytesLen
3145
+ });
3146
+ return Object.freeze({
3147
+ lengths,
3148
+ getPublicKey: keys.getPublicKey,
3149
+ keygen: keys.keygen,
3150
+ encapsulate(pk, randomness = randomBytes3(msgCoder.bytesLen)) {
3151
+ const pks = pkCoder.decode(pk);
3152
+ const rand = msgCoder.decode(randomness);
3153
+ const sharedSecret = [];
3154
+ const cipherText = [];
3155
+ try {
3156
+ for (let i = 0; i < rawKems.length; i++) {
3157
+ const enc = rawKems[i].encapsulate(pks[i], rand[i]);
3158
+ sharedSecret.push(enc.sharedSecret);
3159
+ cipherText.push(enc.cipherText);
3160
+ }
3161
+ return {
3162
+ // Detach the combiner result before cleanup: a caller-provided combiner may alias one of
3163
+ // the child sharedSecret buffers, and those child buffers are zeroized immediately below.
3164
+ sharedSecret: copyBytes2(rawCombiner(pks, cipherText, sharedSecret)),
3165
+ cipherText: ctCoder.encode(cipherText)
3166
+ };
3167
+ } finally {
3168
+ cleanBytes(sharedSecret, cipherText);
3169
+ }
3170
+ },
3171
+ decapsulate(ct, seed) {
3172
+ const cts = ctCoder.decode(ct);
3173
+ const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);
3174
+ const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
3175
+ try {
3176
+ return copyBytes2(rawCombiner(publicKey, cts, sharedSecret));
3177
+ } finally {
3178
+ cleanBytes(secretKey, sharedSecret);
3179
+ }
3180
+ }
3181
+ });
3182
+ }
3183
+ var x25519kem, ml_kem768_x25519, XWing;
3184
+ var init_hybrid = __esm({
3185
+ "../../node_modules/@noble/post-quantum/hybrid.js"() {
3186
+ "use strict";
3187
+ init_ed25519();
3188
+ init_utils2();
3189
+ init_sha3();
3190
+ init_utils();
3191
+ init_ml_kem();
3192
+ init_utils3();
3193
+ x25519kem = /* @__PURE__ */ ecdhKem(x25519);
3194
+ ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(
3195
+ 32,
3196
+ 32,
3197
+ expandSeedXof(shake256),
3198
+ // Awesome label, so much escaping hell in a single line.
3199
+ (pk, ct, ss) => sha3_256(concatBytes2(ss[0], ss[1], ct[1], pk[1], asciiToBytes("\\.//^\\"))),
3200
+ ml_kem768,
3201
+ x25519kem
3202
+ ))();
3203
+ XWing = /* @__PURE__ */ (() => ml_kem768_x25519)();
3204
+ }
3205
+ });
32
3206
 
33
3207
  // ../crypto/src/replay-window.ts
34
3208
  function isFreshTimestamp(timestampHeader, toleranceSecs = DEFAULT_REPLAY_WINDOW_SECS, nowSecs) {
@@ -48,11 +3222,48 @@ var init_replay_window = __esm({
48
3222
  });
49
3223
 
50
3224
  // ../crypto/src/safe-url.ts
3225
+ function parseIPv4Component(raw) {
3226
+ if (raw.length === 0) return null;
3227
+ let value;
3228
+ if (/^0[xX][0-9a-fA-F]+$/.test(raw)) value = Number.parseInt(raw.slice(2), 16);
3229
+ else if (/^0[0-7]+$/.test(raw)) value = Number.parseInt(raw.slice(1), 8);
3230
+ else if (/^\d+$/.test(raw)) value = Number.parseInt(raw, 10);
3231
+ else return null;
3232
+ return Number.isSafeInteger(value) && value >= 0 ? value : null;
3233
+ }
3234
+ function canonicalIPv4Octets(host) {
3235
+ const raw = host.split(".");
3236
+ if (raw.length < 1 || raw.length > 4) return null;
3237
+ const vals = [];
3238
+ for (const part of raw) {
3239
+ const v = parseIPv4Component(part);
3240
+ if (v === null) return null;
3241
+ vals.push(v);
3242
+ }
3243
+ const n = vals.length;
3244
+ for (let i = 0; i < n - 1; i++) if (vals[i] > 255) return null;
3245
+ const remainingBytes = 4 - (n - 1);
3246
+ const max = remainingBytes >= 4 ? 4294967295 : 256 ** remainingBytes - 1;
3247
+ if (vals[n - 1] > max) return null;
3248
+ let value = 0;
3249
+ for (let i = 0; i < n - 1; i++) value += vals[i] * 256 ** (3 - i);
3250
+ value += vals[n - 1];
3251
+ if (value > 4294967295) return null;
3252
+ return [value >>> 24 & 255, value >>> 16 & 255, value >>> 8 & 255, value & 255];
3253
+ }
3254
+ function looksLikeNumericLiteral(host) {
3255
+ return /^[\d.]+$/.test(host) || /^0[xX][0-9a-fA-F.]+$/.test(host);
3256
+ }
3257
+ function isIpLiteralHost(host) {
3258
+ const clean2 = host.toLowerCase();
3259
+ if (clean2.includes(":")) return true;
3260
+ return canonicalIPv4Octets(clean2) !== null || looksLikeNumericLiteral(clean2);
3261
+ }
51
3262
  function isBlockedIPv4(host) {
52
- const parts = host.split(".");
53
- if (parts.length !== 4) return false;
54
- const octets = parts.map((p) => /^\d{1,3}$/.test(p) ? Number(p) : NaN);
55
- if (octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
3263
+ const octets = canonicalIPv4Octets(host);
3264
+ if (!octets) {
3265
+ return looksLikeNumericLiteral(host);
3266
+ }
56
3267
  const [a, b] = octets;
57
3268
  if (a === 0) return true;
58
3269
  if (a === 127) return true;
@@ -64,8 +3275,8 @@ function isBlockedIPv4(host) {
64
3275
  return false;
65
3276
  }
66
3277
  function v4FromHexPair(highHex, lowHex) {
67
- const high = parseInt(highHex, 16);
68
- const low = parseInt(lowHex, 16);
3278
+ const high = Number.parseInt(highHex, 16);
3279
+ const low = Number.parseInt(lowHex, 16);
69
3280
  if (!Number.isInteger(high) || !Number.isInteger(low)) return null;
70
3281
  const a = high >> 8 & 255;
71
3282
  const b = high & 255;
@@ -74,34 +3285,34 @@ function v4FromHexPair(highHex, lowHex) {
74
3285
  return `${a}.${b}.${c}.${d}`;
75
3286
  }
76
3287
  function isBlockedIPv6(host) {
77
- let clean = host.toLowerCase();
78
- if (clean.startsWith("[") && clean.endsWith("]")) {
79
- clean = clean.slice(1, -1);
80
- }
81
- clean = clean.split("%")[0];
82
- if (!clean.includes(":")) return false;
83
- if (clean === "::1") return true;
84
- if (clean === "::") return true;
85
- if (clean.startsWith("fe80:")) return true;
86
- if (clean.startsWith("fc") || clean.startsWith("fd")) return true;
87
- const mappedDotted = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(clean);
3288
+ let clean2 = host.toLowerCase();
3289
+ if (clean2.startsWith("[") && clean2.endsWith("]")) {
3290
+ clean2 = clean2.slice(1, -1);
3291
+ }
3292
+ clean2 = clean2.split("%")[0];
3293
+ if (!clean2.includes(":")) return false;
3294
+ if (clean2 === "::1") return true;
3295
+ if (clean2 === "::") return true;
3296
+ if (clean2.startsWith("fe80:")) return true;
3297
+ if (clean2.startsWith("fc") || clean2.startsWith("fd")) return true;
3298
+ const mappedDotted = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(clean2);
88
3299
  if (mappedDotted) return isBlockedIPv4(mappedDotted[1]);
89
- const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(clean);
3300
+ const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(clean2);
90
3301
  if (mappedHex) {
91
3302
  const v4 = v4FromHexPair(mappedHex[1], mappedHex[2]);
92
3303
  if (v4) return isBlockedIPv4(v4);
93
3304
  }
94
- const compatibleDotted = /^::(\d+\.\d+\.\d+\.\d+)$/.exec(clean);
3305
+ const compatibleDotted = /^::(\d+\.\d+\.\d+\.\d+)$/.exec(clean2);
95
3306
  if (compatibleDotted) return isBlockedIPv4(compatibleDotted[1]);
96
- const compatibleHex = /^::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(clean);
3307
+ const compatibleHex = /^::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(clean2);
97
3308
  if (compatibleHex) {
98
3309
  const v4 = v4FromHexPair(compatibleHex[1], compatibleHex[2]);
99
3310
  if (v4) return isBlockedIPv4(v4);
100
3311
  }
101
- if (clean.startsWith("64:ff9b:")) {
102
- const nat64Dotted = /^64:ff9b:(?:1:)?:(\d+\.\d+\.\d+\.\d+)$/.exec(clean);
3312
+ if (clean2.startsWith("64:ff9b:")) {
3313
+ const nat64Dotted = /^64:ff9b:(?:1:)?:(\d+\.\d+\.\d+\.\d+)$/.exec(clean2);
103
3314
  if (nat64Dotted) return isBlockedIPv4(nat64Dotted[1]);
104
- const nat64Hex = /^64:ff9b:(?:1:)?:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(clean);
3315
+ const nat64Hex = /^64:ff9b:(?:1:)?:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(clean2);
105
3316
  if (nat64Hex) {
106
3317
  const v4 = v4FromHexPair(nat64Hex[1], nat64Hex[2]);
107
3318
  if (v4) return isBlockedIPv4(v4);
@@ -110,7 +3321,7 @@ function isBlockedIPv6(host) {
110
3321
  }
111
3322
  return false;
112
3323
  }
113
- function isSafeWebhookUrl(url, opts = {}) {
3324
+ function isSafeWebhookUrl(url, opts2 = {}) {
114
3325
  let parsed;
115
3326
  try {
116
3327
  parsed = new URL(url);
@@ -120,7 +3331,7 @@ function isSafeWebhookUrl(url, opts = {}) {
120
3331
  if (!["http:", "https:"].includes(parsed.protocol)) {
121
3332
  return { ok: false, reason: `Protocol ${parsed.protocol} not allowed \u2014 use http(s)` };
122
3333
  }
123
- if (opts.requireHttps && parsed.protocol !== "https:") {
3334
+ if (opts2.requireHttps && parsed.protocol !== "https:") {
124
3335
  return { ok: false, reason: "Webhook URL must use https://" };
125
3336
  }
126
3337
  const host = parsed.hostname.toLowerCase();
@@ -153,31 +3364,290 @@ var init_safe_url = __esm({
153
3364
  }
154
3365
  });
155
3366
 
3367
+ // ../crypto/src/partner-key-attestation.ts
3368
+ function assertNoDelimiter(field, value) {
3369
+ if (typeof value !== "string" || value.length === 0) {
3370
+ throw new Error(`[partner-key-attestation] ${field} must be a non-empty string`);
3371
+ }
3372
+ if (value.includes("\n") || value.includes("\r")) {
3373
+ throw new Error(`[partner-key-attestation] ${field} must not contain a line break`);
3374
+ }
3375
+ }
3376
+ function buildPartnerKeyAttestation(input) {
3377
+ assertNoDelimiter("partnerId", input.partnerId);
3378
+ assertNoDelimiter("keyId", input.keyId);
3379
+ assertNoDelimiter("algorithm", input.algorithm);
3380
+ assertNoDelimiter("publicKeyB64", input.publicKeyB64);
3381
+ return [
3382
+ PARTNER_KEY_ATTESTATION_V1,
3383
+ `partner_id:${input.partnerId.toLowerCase()}`,
3384
+ `key_id:${input.keyId.toLowerCase()}`,
3385
+ `algorithm:${input.algorithm}`,
3386
+ `public_key:${input.publicKeyB64}`
3387
+ ].join("\n");
3388
+ }
3389
+ function b64ToBytes(b64) {
3390
+ const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3391
+ const binary = atob(normalised);
3392
+ const out = new Uint8Array(binary.length);
3393
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
3394
+ return out;
3395
+ }
3396
+ function hexToBytes3(hex) {
3397
+ if (hex.length % 2 !== 0) throw new Error("[partner-key-attestation] hex string has odd length");
3398
+ const out = new Uint8Array(hex.length / 2);
3399
+ for (let i = 0; i < out.length; i++) {
3400
+ const byte = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
3401
+ if (Number.isNaN(byte)) throw new Error("[partner-key-attestation] invalid hex");
3402
+ out[i] = byte;
3403
+ }
3404
+ return out;
3405
+ }
3406
+ function bytesToHex3(bytes) {
3407
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
3408
+ }
3409
+ async function rootKeyIdFromSpki(spki) {
3410
+ const digest = await crypto.subtle.digest("SHA-256", spki);
3411
+ return `rk1_${bytesToHex3(new Uint8Array(digest)).slice(0, 16)}`;
3412
+ }
3413
+ async function rootKeyIdFromSpkiB64(spkiB64) {
3414
+ return rootKeyIdFromSpki(b64ToBytes(spkiB64));
3415
+ }
3416
+ async function verifyPartnerKeyAttestation(input, signatureHex, rootPublicKeyB64) {
3417
+ try {
3418
+ if (typeof signatureHex !== "string" || !/^[0-9a-f]{128}$/i.test(signatureHex)) return false;
3419
+ const statement = buildPartnerKeyAttestation(input);
3420
+ const rootKey = await crypto.subtle.importKey(
3421
+ "spki",
3422
+ b64ToBytes(rootPublicKeyB64),
3423
+ { name: "ECDSA", namedCurve: "P-256" },
3424
+ false,
3425
+ ["verify"]
3426
+ );
3427
+ return await crypto.subtle.verify(
3428
+ { name: "ECDSA", hash: "SHA-256" },
3429
+ rootKey,
3430
+ hexToBytes3(signatureHex),
3431
+ new TextEncoder().encode(statement)
3432
+ );
3433
+ } catch {
3434
+ return false;
3435
+ }
3436
+ }
3437
+ async function verifyPartnerKeyAttestationWithRoots(input, signatureHex, rootKeyId, roots) {
3438
+ const root = roots.find((r) => r.root_key_id === rootKeyId);
3439
+ if (!root) return false;
3440
+ if (root.algorithm !== PARTNER_KEY_ATTESTATION_ALG) return false;
3441
+ return verifyPartnerKeyAttestation(input, signatureHex, root.public_key_b64);
3442
+ }
3443
+ var PARTNER_KEY_ATTESTATION_V1, PARTNER_KEY_ATTESTATION_ALG;
3444
+ var init_partner_key_attestation = __esm({
3445
+ "../crypto/src/partner-key-attestation.ts"() {
3446
+ "use strict";
3447
+ PARTNER_KEY_ATTESTATION_V1 = "oneaddress-partner-key-attestation:v1";
3448
+ PARTNER_KEY_ATTESTATION_ALG = "ECDSA-P256";
3449
+ }
3450
+ });
3451
+
3452
+ // ../crypto/src/registry-head.ts
3453
+ function assertNoLineBreak(field, value) {
3454
+ if (typeof value !== "string" || value.length === 0) {
3455
+ throw new Error(`[registry-head] ${field} must be a non-empty string`);
3456
+ }
3457
+ if (value.includes("\n") || value.includes("\r")) {
3458
+ throw new Error(`[registry-head] ${field} must not contain a line break`);
3459
+ }
3460
+ }
3461
+ function assertMapSafe(field, value) {
3462
+ assertNoLineBreak(field, value);
3463
+ if (value.includes(":")) {
3464
+ throw new Error(`[registry-head] ${field} must not contain a colon`);
3465
+ }
3466
+ }
3467
+ function buildRegistryHeadStatement(payload) {
3468
+ assertNoLineBreak("issued_at", payload.issued_at);
3469
+ assertNoLineBreak("expires_at", payload.expires_at);
3470
+ assertMapSafe("root_key_id", payload.root_key_id);
3471
+ const entries = Object.entries(payload.heads).map(([partnerId, keyId]) => {
3472
+ assertMapSafe("partner_id", partnerId);
3473
+ assertMapSafe("key_id", keyId);
3474
+ return [partnerId.toLowerCase(), keyId.toLowerCase()];
3475
+ });
3476
+ entries.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3477
+ const seen = /* @__PURE__ */ new Set();
3478
+ for (const [partnerId] of entries) {
3479
+ if (seen.has(partnerId)) {
3480
+ throw new Error(`[registry-head] duplicate partner_id in heads: ${partnerId}`);
3481
+ }
3482
+ seen.add(partnerId);
3483
+ }
3484
+ return [
3485
+ REGISTRY_HEAD_V1,
3486
+ `issued_at:${payload.issued_at}`,
3487
+ `expires_at:${payload.expires_at}`,
3488
+ `root_key_id:${payload.root_key_id}`,
3489
+ `heads:${entries.length}`,
3490
+ ...entries.map(([partnerId, keyId]) => `${partnerId}:${keyId}`)
3491
+ ].join("\n");
3492
+ }
3493
+ function b64ToBytes2(b64) {
3494
+ const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3495
+ const binary = atob(normalised);
3496
+ const out = new Uint8Array(binary.length);
3497
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
3498
+ return out;
3499
+ }
3500
+ function hexToBytes4(hex) {
3501
+ if (hex.length % 2 !== 0) throw new Error("[registry-head] hex string has odd length");
3502
+ const out = new Uint8Array(hex.length / 2);
3503
+ for (let i = 0; i < out.length; i++) {
3504
+ const byte = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
3505
+ if (Number.isNaN(byte)) throw new Error("[registry-head] invalid hex");
3506
+ out[i] = byte;
3507
+ }
3508
+ return out;
3509
+ }
3510
+ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
3511
+ try {
3512
+ if (doc?.version !== REGISTRY_HEAD_V1) return "malformed";
3513
+ if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
3514
+ if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
3515
+ if (!doc.heads || typeof doc.heads !== "object") return "malformed";
3516
+ const expires = Date.parse(doc.expires_at);
3517
+ const issued = Date.parse(doc.issued_at);
3518
+ if (Number.isNaN(expires) || Number.isNaN(issued)) return "malformed";
3519
+ const root = roots.find((r) => r.root_key_id === doc.root_key_id);
3520
+ if (!root) return "unknown-root";
3521
+ if (root.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
3522
+ const statement = buildRegistryHeadStatement({
3523
+ version: doc.version,
3524
+ issued_at: doc.issued_at,
3525
+ expires_at: doc.expires_at,
3526
+ root_key_id: doc.root_key_id,
3527
+ heads: doc.heads
3528
+ });
3529
+ const rootKey = await crypto.subtle.importKey(
3530
+ "spki",
3531
+ b64ToBytes2(root.public_key_b64),
3532
+ { name: "ECDSA", namedCurve: "P-256" },
3533
+ false,
3534
+ ["verify"]
3535
+ );
3536
+ const valid = await crypto.subtle.verify(
3537
+ { name: "ECDSA", hash: "SHA-256" },
3538
+ rootKey,
3539
+ hexToBytes4(doc.signature),
3540
+ new TextEncoder().encode(statement)
3541
+ );
3542
+ if (!valid) return "bad-signature";
3543
+ if (now.getTime() >= expires) return "expired";
3544
+ return "ok";
3545
+ } catch {
3546
+ return "malformed";
3547
+ }
3548
+ }
3549
+ function headNamesKey(doc, partnerId, keyId) {
3550
+ const named = doc.heads?.[partnerId.toLowerCase()];
3551
+ return typeof named === "string" && named.toLowerCase() === keyId.toLowerCase();
3552
+ }
3553
+ var REGISTRY_HEAD_V1, REGISTRY_HEAD_ALG;
3554
+ var init_registry_head = __esm({
3555
+ "../crypto/src/registry-head.ts"() {
3556
+ "use strict";
3557
+ REGISTRY_HEAD_V1 = "oneaddress-partner-key-registry-head:v1";
3558
+ REGISTRY_HEAD_ALG = "ECDSA-P256";
3559
+ }
3560
+ });
3561
+
156
3562
  // ../crypto/src/index.ts
157
3563
  var src_exports = {};
158
3564
  __export(src_exports, {
159
3565
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
3566
+ PARTNER_KEY_ATTESTATION_ALG: () => PARTNER_KEY_ATTESTATION_ALG,
3567
+ PARTNER_KEY_ATTESTATION_V1: () => PARTNER_KEY_ATTESTATION_V1,
3568
+ REGISTRY_HEAD_ALG: () => REGISTRY_HEAD_ALG,
3569
+ REGISTRY_HEAD_V1: () => REGISTRY_HEAD_V1,
3570
+ buildPartnerKeyAttestation: () => buildPartnerKeyAttestation,
3571
+ buildRegistryHeadStatement: () => buildRegistryHeadStatement,
3572
+ cleanNameAliases: () => cleanNameAliases,
3573
+ computeBlindIndex: () => computeBlindIndex,
3574
+ computeCustomerBlindIndex: () => computeCustomerBlindIndex,
160
3575
  decryptAddress: () => decryptAddress,
161
3576
  decryptSession: () => decryptSession,
162
3577
  encryptAddressForAll: () => encryptAddressForAll,
163
3578
  encryptAddressForPartner: () => encryptAddressForPartner,
3579
+ encryptEnvelopeForPartner: () => encryptEnvelopeForPartner,
3580
+ encryptPayloadForPartner: () => encryptPayloadForPartner,
164
3581
  encryptSessionForAll: () => encryptSessionForAll,
165
3582
  encryptSessionForPartner: () => encryptSessionForPartner,
3583
+ generateHybridPartnerKeyPair: () => generateHybridPartnerKeyPair,
166
3584
  generatePartnerKeyPair: () => generatePartnerKeyPair,
3585
+ headNamesKey: () => headNamesKey,
3586
+ isEmailLike: () => isEmailLike,
167
3587
  isFreshTimestamp: () => isFreshTimestamp,
3588
+ isIpLiteralHost: () => isIpLiteralHost,
168
3589
  isSafeWebhookUrl: () => isSafeWebhookUrl,
169
3590
  normaliseAddress: () => normaliseAddress,
3591
+ normalizeForBlindIndex: () => normalizeForBlindIndex,
3592
+ rootKeyIdFromSpki: () => rootKeyIdFromSpki,
3593
+ rootKeyIdFromSpkiB64: () => rootKeyIdFromSpkiB64,
170
3594
  signWebhookPayload: () => signWebhookPayload,
3595
+ verifyPartnerKeyAttestation: () => verifyPartnerKeyAttestation,
3596
+ verifyPartnerKeyAttestationWithRoots: () => verifyPartnerKeyAttestationWithRoots,
3597
+ verifyRegistryHead: () => verifyRegistryHead,
171
3598
  verifyWebhookSignature: () => verifyWebhookSignature
172
3599
  });
173
- function b64ToBytes(b64) {
3600
+ function b64ToBytes3(b64) {
174
3601
  const binary = atob(b64);
175
3602
  const bytes = new Uint8Array(binary.length);
176
3603
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.codePointAt(i) ?? 0;
177
3604
  return bytes;
178
3605
  }
3606
+ function keyB64ToBytes(key) {
3607
+ const begin = key.indexOf("-----BEGIN");
3608
+ if (begin === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3609
+ const armourEnd = key.indexOf("-----", begin + "-----BEGIN".length);
3610
+ if (armourEnd === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3611
+ const bodyStart = armourEnd + "-----".length;
3612
+ const end = key.indexOf("-----END", bodyStart);
3613
+ const body = end === -1 ? key.slice(bodyStart) : key.slice(bodyStart, end);
3614
+ return b64ToBytes3(body.replace(/\s+/g, ""));
3615
+ }
179
3616
  function bytesToB64(bytes) {
180
- return btoa(String.fromCharCode(...bytes));
3617
+ return btoa(String.fromCodePoint(...bytes));
3618
+ }
3619
+ async function importP256PublicKey(keyBytes) {
3620
+ if (keyBytes.length === 65 && keyBytes[0] === 4) {
3621
+ return subtle().importKey(
3622
+ "raw",
3623
+ keyBytes,
3624
+ { name: "ECDH", namedCurve: "P-256" },
3625
+ false,
3626
+ []
3627
+ );
3628
+ }
3629
+ return subtle().importKey(
3630
+ "spki",
3631
+ keyBytes,
3632
+ { name: "ECDH", namedCurve: "P-256" },
3633
+ false,
3634
+ []
3635
+ );
3636
+ }
3637
+ async function importRsaOaepPublicKey(keyBytes) {
3638
+ return subtle().importKey(
3639
+ "spki",
3640
+ keyBytes,
3641
+ { name: "RSA-OAEP", hash: "SHA-256" },
3642
+ false,
3643
+ ["encrypt"]
3644
+ );
3645
+ }
3646
+ function isRsaScheme(algorithm) {
3647
+ return (algorithm ?? "").toUpperCase().startsWith("RSA");
3648
+ }
3649
+ function isHybridScheme(algorithm) {
3650
+ return (algorithm ?? "").toUpperCase().startsWith("MLKEM");
181
3651
  }
182
3652
  function toTitleCase(s) {
183
3653
  return s.trim().replace(
@@ -216,16 +3686,64 @@ async function generatePartnerKeyPair() {
216
3686
  privateKeyB64: bytesToB64(new Uint8Array(privRaw))
217
3687
  };
218
3688
  }
219
- async function encryptAddressForPartner(address, partner) {
220
- const address_ = normaliseAddress(address);
221
- const partnerPubKey = await subtle().importKey(
222
- "spki",
223
- b64ToBytes(partner.publicKeyB64),
224
- { name: "ECDH", namedCurve: "P-256" },
225
- false,
226
- []
227
- // public key — no usages
228
- );
3689
+ function generateHybridPartnerKeyPair() {
3690
+ const { secretKey, publicKey } = XWing.keygen();
3691
+ return {
3692
+ publicKeyB64: bytesToB64(publicKey),
3693
+ privateKeyB64: bytesToB64(secretKey)
3694
+ };
3695
+ }
3696
+ async function encryptAddressForPartner(address, partner) {
3697
+ const address_ = normaliseAddress(address);
3698
+ const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
3699
+ const ephemeral = await subtle().generateKey(
3700
+ { name: "ECDH", namedCurve: "P-256" },
3701
+ true,
3702
+ ["deriveBits"]
3703
+ );
3704
+ const hkdfSaltBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
3705
+ const ecdhBits = await subtle().deriveBits(
3706
+ { name: "ECDH", public: partnerPubKey },
3707
+ ephemeral.privateKey,
3708
+ 256
3709
+ );
3710
+ const hkdfKey = await subtle().importKey("raw", ecdhBits, "HKDF", false, ["deriveBits"]);
3711
+ const aesRaw = await subtle().deriveBits(
3712
+ {
3713
+ name: "HKDF",
3714
+ hash: "SHA-256",
3715
+ salt: hkdfSaltBytes,
3716
+ info: new TextEncoder().encode(`oneaddress:${partner.partnerId}`)
3717
+ },
3718
+ hkdfKey,
3719
+ 256
3720
+ );
3721
+ const aesKey = await subtle().importKey(
3722
+ "raw",
3723
+ aesRaw,
3724
+ { name: "AES-GCM" },
3725
+ false,
3726
+ ["encrypt"]
3727
+ );
3728
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
3729
+ const plaintext = new TextEncoder().encode(JSON.stringify(address_));
3730
+ const ciphertextBuf = await subtle().encrypt(
3731
+ { name: "AES-GCM", iv },
3732
+ aesKey,
3733
+ plaintext
3734
+ );
3735
+ const ephPubRaw = await subtle().exportKey("raw", ephemeral.publicKey);
3736
+ return {
3737
+ ciphertext: bytesToB64(new Uint8Array(ciphertextBuf)),
3738
+ iv: bytesToB64(iv),
3739
+ ephemeralPublicKey: bytesToB64(new Uint8Array(ephPubRaw)),
3740
+ partnerId: partner.partnerId,
3741
+ encryptedAt: (/* @__PURE__ */ new Date()).toISOString(),
3742
+ hkdfSalt: bytesToB64(hkdfSaltBytes)
3743
+ };
3744
+ }
3745
+ async function encryptPayloadForPartner(payload, partner) {
3746
+ const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
229
3747
  const ephemeral = await subtle().generateKey(
230
3748
  { name: "ECDH", namedCurve: "P-256" },
231
3749
  true,
@@ -248,20 +3766,10 @@ async function encryptAddressForPartner(address, partner) {
248
3766
  hkdfKey,
249
3767
  256
250
3768
  );
251
- const aesKey = await subtle().importKey(
252
- "raw",
253
- aesRaw,
254
- { name: "AES-GCM" },
255
- false,
256
- ["encrypt"]
257
- );
3769
+ const aesKey = await subtle().importKey("raw", aesRaw, { name: "AES-GCM" }, false, ["encrypt"]);
258
3770
  const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
259
- const plaintext = new TextEncoder().encode(JSON.stringify(address_));
260
- const ciphertextBuf = await subtle().encrypt(
261
- { name: "AES-GCM", iv },
262
- aesKey,
263
- plaintext
264
- );
3771
+ const plaintext = new TextEncoder().encode(JSON.stringify(payload));
3772
+ const ciphertextBuf = await subtle().encrypt({ name: "AES-GCM", iv }, aesKey, plaintext);
265
3773
  const ephPubRaw = await subtle().exportKey("raw", ephemeral.publicKey);
266
3774
  return {
267
3775
  ciphertext: bytesToB64(new Uint8Array(ciphertextBuf)),
@@ -281,14 +3789,14 @@ async function encryptAddressForAll(address, partners) {
281
3789
  async function decryptAddress(encrypted, privateKeyB64) {
282
3790
  const privateKey = await subtle().importKey(
283
3791
  "pkcs8",
284
- b64ToBytes(privateKeyB64),
3792
+ keyB64ToBytes(privateKeyB64),
285
3793
  { name: "ECDH", namedCurve: "P-256" },
286
3794
  false,
287
3795
  ["deriveBits"]
288
3796
  );
289
3797
  const ephemeralPub = await subtle().importKey(
290
3798
  "raw",
291
- b64ToBytes(encrypted.ephemeralPublicKey),
3799
+ b64ToBytes3(encrypted.ephemeralPublicKey),
292
3800
  { name: "ECDH", namedCurve: "P-256" },
293
3801
  false,
294
3802
  []
@@ -298,7 +3806,7 @@ async function decryptAddress(encrypted, privateKeyB64) {
298
3806
  privateKey,
299
3807
  256
300
3808
  );
301
- const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes(encrypted.hkdfSalt) : new Uint8Array(32);
3809
+ const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes3(encrypted.hkdfSalt) : new Uint8Array(32);
302
3810
  const aesKey = await subtle().importKey(
303
3811
  "raw",
304
3812
  await subtle().deriveBits(
@@ -316,15 +3824,18 @@ async function decryptAddress(encrypted, privateKeyB64) {
316
3824
  ["decrypt"]
317
3825
  );
318
3826
  const plainBuf = await subtle().decrypt(
319
- { name: "AES-GCM", iv: b64ToBytes(encrypted.iv) },
3827
+ { name: "AES-GCM", iv: b64ToBytes3(encrypted.iv) },
320
3828
  aesKey,
321
- b64ToBytes(encrypted.ciphertext)
3829
+ b64ToBytes3(encrypted.ciphertext)
322
3830
  );
323
3831
  return JSON.parse(new TextDecoder().decode(plainBuf));
324
3832
  }
325
3833
  function sessionWrapInfo(partnerId) {
326
3834
  return new TextEncoder().encode(`oneaddress:session-key-wrap:${partnerId}`);
327
3835
  }
3836
+ function sessionWrapInfoPq(partnerId) {
3837
+ return new TextEncoder().encode(`oneaddress:session-key-wrap:pq1:${partnerId}`);
3838
+ }
328
3839
  function concat(...parts) {
329
3840
  const total = parts.reduce((n, p) => n + p.length, 0);
330
3841
  const out = new Uint8Array(total);
@@ -340,27 +3851,70 @@ function bytesToB64Url(bytes) {
340
3851
  }
341
3852
  function b64UrlToBytes(b64url) {
342
3853
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
343
- return b64ToBytes(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3854
+ return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
344
3855
  }
345
3856
  async function encryptSessionForPartner(session_data, partner) {
3857
+ return encryptEnvelopeForPartner(session_data, partner);
3858
+ }
3859
+ async function encryptEnvelopeForPartner(payload, partner) {
346
3860
  const sk = await subtle().generateKey(
347
3861
  { name: "AES-GCM", length: SESSION_KEY_BITS },
348
3862
  true,
349
3863
  ["encrypt"]
350
3864
  );
351
3865
  const sessionIv = globalThis.crypto.getRandomValues(new Uint8Array(SESSION_IV_LENGTH));
352
- const plaintext = new TextEncoder().encode(JSON.stringify(session_data));
3866
+ const plaintext = new TextEncoder().encode(JSON.stringify(payload));
353
3867
  const sessionCt = new Uint8Array(
354
3868
  await subtle().encrypt({ name: "AES-GCM", iv: sessionIv }, sk, plaintext)
355
3869
  );
356
3870
  const session_envelope = bytesToB64Url(concat(sessionIv, sessionCt));
357
- const partnerPub = await subtle().importKey(
358
- "spki",
359
- b64ToBytes(partner.public_key_b64),
360
- { name: "ECDH", namedCurve: "P-256" },
361
- false,
362
- []
363
- );
3871
+ const skRawForWrap = new Uint8Array(await subtle().exportKey("raw", sk));
3872
+ if (isHybridScheme(partner.algorithm)) {
3873
+ const { cipherText: kemCt, sharedSecret: sharedSecret2 } = XWing.encapsulate(b64ToBytes3(partner.public_key_b64));
3874
+ const wrapSalt2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_SALT_LENGTH));
3875
+ const wrapKeyRaw2 = await subtle().deriveBits(
3876
+ { name: "HKDF", hash: "SHA-256", salt: wrapSalt2, info: sessionWrapInfoPq(partner.partner_id) },
3877
+ await subtle().importKey("raw", sharedSecret2, "HKDF", false, ["deriveBits"]),
3878
+ 256
3879
+ );
3880
+ const wrapKey2 = await subtle().importKey("raw", wrapKeyRaw2, { name: "AES-GCM" }, false, ["encrypt"]);
3881
+ const wrapIv2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_IV_LENGTH));
3882
+ const wrappedSkBytes2 = new Uint8Array(
3883
+ await subtle().encrypt({ name: "AES-GCM", iv: wrapIv2 }, wrapKey2, skRawForWrap)
3884
+ );
3885
+ skRawForWrap.fill(0);
3886
+ return {
3887
+ partner_id: partner.partner_id,
3888
+ session_envelope,
3889
+ session_key_share: {
3890
+ key_id: partner.key_id,
3891
+ wrapped_key: bytesToB64Url(concat(wrapSalt2, wrapIv2, wrappedSkBytes2)),
3892
+ epk: bytesToB64Url(kemCt),
3893
+ // X-Wing KEM ciphertext (no ephemeral EC key)
3894
+ alg: "MLKEM768X25519+HKDF-SHA256+A256GCM",
3895
+ v: 2
3896
+ }
3897
+ };
3898
+ }
3899
+ if (isRsaScheme(partner.algorithm)) {
3900
+ const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes3(partner.public_key_b64));
3901
+ const rsaWrapped = new Uint8Array(
3902
+ await subtle().encrypt({ name: "RSA-OAEP" }, partnerRsaPub, skRawForWrap)
3903
+ );
3904
+ skRawForWrap.fill(0);
3905
+ return {
3906
+ partner_id: partner.partner_id,
3907
+ session_envelope,
3908
+ session_key_share: {
3909
+ key_id: partner.key_id,
3910
+ wrapped_key: bytesToB64Url(rsaWrapped),
3911
+ // No epk — RSA key transport has no ephemeral key.
3912
+ alg: "RSA-OAEP-256+A256GCM",
3913
+ v: 2
3914
+ }
3915
+ };
3916
+ }
3917
+ const partnerPub = await importP256PublicKey(b64ToBytes3(partner.public_key_b64));
364
3918
  const ephemeral = await subtle().generateKey(
365
3919
  { name: "ECDH", namedCurve: "P-256" },
366
3920
  true,
@@ -389,12 +3943,11 @@ async function encryptSessionForPartner(session_data, partner) {
389
3943
  false,
390
3944
  ["encrypt"]
391
3945
  );
392
- const skRaw = new Uint8Array(await subtle().exportKey("raw", sk));
393
3946
  const wrapIv = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_IV_LENGTH));
394
3947
  const wrappedSkBytes = new Uint8Array(
395
- await subtle().encrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, skRaw)
3948
+ await subtle().encrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, skRawForWrap)
396
3949
  );
397
- skRaw.fill(0);
3950
+ skRawForWrap.fill(0);
398
3951
  const wrapped_key = bytesToB64Url(concat(wrapSalt, wrapIv, wrappedSkBytes));
399
3952
  const epkSpki = new Uint8Array(await subtle().exportKey("spki", ephemeral.publicKey));
400
3953
  const epk = bytesToB64Url(epkSpki);
@@ -417,60 +3970,98 @@ async function encryptSessionForAll(partners) {
417
3970
  return Object.fromEntries(results.map((r) => [r.partner_id, r]));
418
3971
  }
419
3972
  async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
420
- if (share.alg !== "ECDH-ES+HKDF-SHA256+A256GCM") {
3973
+ if (share.alg !== "ECDH-ES+HKDF-SHA256+A256GCM" && share.alg !== "RSA-OAEP-256+A256GCM" && share.alg !== "MLKEM768X25519+HKDF-SHA256+A256GCM") {
421
3974
  throw new Error(`decryptSession: unsupported alg ${share.alg}`);
422
3975
  }
423
3976
  if (share.v !== 2) {
424
3977
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
425
3978
  }
426
- const privateKey = await subtle().importKey(
427
- "pkcs8",
428
- b64ToBytes(privateKeyB64),
429
- { name: "ECDH", namedCurve: "P-256" },
430
- false,
431
- ["deriveBits"]
432
- );
433
- const ephemeralPub = await subtle().importKey(
434
- "spki",
435
- b64UrlToBytes(share.epk),
436
- { name: "ECDH", namedCurve: "P-256" },
437
- false,
438
- []
439
- );
440
- const sharedSecret = await subtle().deriveBits(
441
- { name: "ECDH", public: ephemeralPub },
442
- privateKey,
443
- 256
444
- );
445
- const wrappedBytes = b64UrlToBytes(share.wrapped_key);
446
- if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
447
- throw new Error("decryptSession: wrapped_key too short");
3979
+ let skRawBuf;
3980
+ if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3981
+ if (!share.epk) {
3982
+ throw new Error("decryptSession: hybrid share missing epk (KEM ciphertext)");
3983
+ }
3984
+ const sharedSecret = XWing.decapsulate(b64UrlToBytes(share.epk), b64ToBytes3(privateKeyB64));
3985
+ const wrappedBytes = b64UrlToBytes(share.wrapped_key);
3986
+ if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
3987
+ throw new Error("decryptSession: wrapped_key too short");
3988
+ }
3989
+ const wrapSalt = wrappedBytes.slice(0, WRAP_SALT_LENGTH);
3990
+ const wrapIv = wrappedBytes.slice(WRAP_SALT_LENGTH, WRAP_SALT_LENGTH + WRAP_IV_LENGTH);
3991
+ const wrappedSkBytes = wrappedBytes.slice(WRAP_SALT_LENGTH + WRAP_IV_LENGTH);
3992
+ const wrapKeyRaw = await subtle().deriveBits(
3993
+ { name: "HKDF", hash: "SHA-256", salt: wrapSalt, info: sessionWrapInfoPq(partnerId) },
3994
+ await subtle().importKey("raw", sharedSecret, "HKDF", false, ["deriveBits"]),
3995
+ 256
3996
+ );
3997
+ const wrapKey = await subtle().importKey("raw", wrapKeyRaw, { name: "AES-GCM" }, false, ["decrypt"]);
3998
+ skRawBuf = await subtle().decrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, wrappedSkBytes);
3999
+ } else if (share.alg === "RSA-OAEP-256+A256GCM") {
4000
+ const rsaPrivateKey = await subtle().importKey(
4001
+ "pkcs8",
4002
+ keyB64ToBytes(privateKeyB64),
4003
+ { name: "RSA-OAEP", hash: "SHA-256" },
4004
+ false,
4005
+ ["decrypt"]
4006
+ );
4007
+ skRawBuf = await subtle().decrypt(
4008
+ { name: "RSA-OAEP" },
4009
+ rsaPrivateKey,
4010
+ b64UrlToBytes(share.wrapped_key)
4011
+ );
4012
+ } else {
4013
+ if (!share.epk) {
4014
+ throw new Error("decryptSession: ECDH-ES share missing epk");
4015
+ }
4016
+ const privateKey = await subtle().importKey(
4017
+ "pkcs8",
4018
+ keyB64ToBytes(privateKeyB64),
4019
+ { name: "ECDH", namedCurve: "P-256" },
4020
+ false,
4021
+ ["deriveBits"]
4022
+ );
4023
+ const ephemeralPub = await subtle().importKey(
4024
+ "spki",
4025
+ b64UrlToBytes(share.epk),
4026
+ { name: "ECDH", namedCurve: "P-256" },
4027
+ false,
4028
+ []
4029
+ );
4030
+ const sharedSecret = await subtle().deriveBits(
4031
+ { name: "ECDH", public: ephemeralPub },
4032
+ privateKey,
4033
+ 256
4034
+ );
4035
+ const wrappedBytes = b64UrlToBytes(share.wrapped_key);
4036
+ if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
4037
+ throw new Error("decryptSession: wrapped_key too short");
4038
+ }
4039
+ const wrapSalt = wrappedBytes.slice(0, WRAP_SALT_LENGTH);
4040
+ const wrapIv = wrappedBytes.slice(WRAP_SALT_LENGTH, WRAP_SALT_LENGTH + WRAP_IV_LENGTH);
4041
+ const wrappedSkBytes = wrappedBytes.slice(WRAP_SALT_LENGTH + WRAP_IV_LENGTH);
4042
+ const wrapKeyRaw = await subtle().deriveBits(
4043
+ {
4044
+ name: "HKDF",
4045
+ hash: "SHA-256",
4046
+ salt: wrapSalt,
4047
+ info: sessionWrapInfo(partnerId)
4048
+ },
4049
+ await subtle().importKey("raw", sharedSecret, "HKDF", false, ["deriveBits"]),
4050
+ 256
4051
+ );
4052
+ const wrapKey = await subtle().importKey(
4053
+ "raw",
4054
+ wrapKeyRaw,
4055
+ { name: "AES-GCM" },
4056
+ false,
4057
+ ["decrypt"]
4058
+ );
4059
+ skRawBuf = await subtle().decrypt(
4060
+ { name: "AES-GCM", iv: wrapIv },
4061
+ wrapKey,
4062
+ wrappedSkBytes
4063
+ );
448
4064
  }
449
- const wrapSalt = wrappedBytes.slice(0, WRAP_SALT_LENGTH);
450
- const wrapIv = wrappedBytes.slice(WRAP_SALT_LENGTH, WRAP_SALT_LENGTH + WRAP_IV_LENGTH);
451
- const wrappedSkBytes = wrappedBytes.slice(WRAP_SALT_LENGTH + WRAP_IV_LENGTH);
452
- const wrapKeyRaw = await subtle().deriveBits(
453
- {
454
- name: "HKDF",
455
- hash: "SHA-256",
456
- salt: wrapSalt,
457
- info: sessionWrapInfo(partnerId)
458
- },
459
- await subtle().importKey("raw", sharedSecret, "HKDF", false, ["deriveBits"]),
460
- 256
461
- );
462
- const wrapKey = await subtle().importKey(
463
- "raw",
464
- wrapKeyRaw,
465
- { name: "AES-GCM" },
466
- false,
467
- ["decrypt"]
468
- );
469
- const skRawBuf = await subtle().decrypt(
470
- { name: "AES-GCM", iv: wrapIv },
471
- wrapKey,
472
- wrappedSkBytes
473
- );
474
4065
  const sk = await subtle().importKey(
475
4066
  "raw",
476
4067
  skRawBuf,
@@ -491,6 +4082,74 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
491
4082
  );
492
4083
  return JSON.parse(new TextDecoder().decode(plainBuf));
493
4084
  }
4085
+ function isEmailLike(value) {
4086
+ return value.includes("@");
4087
+ }
4088
+ function cleanNameAliases(primaryName, aliases, limit = 10) {
4089
+ const out = [];
4090
+ if (!Array.isArray(aliases)) return out;
4091
+ const seen = /* @__PURE__ */ new Set();
4092
+ const primary = (primaryName ?? "").trim().toLowerCase();
4093
+ if (primary) seen.add(primary);
4094
+ for (const raw of aliases) {
4095
+ if (typeof raw !== "string") continue;
4096
+ const trimmed = raw.trim();
4097
+ if (!trimmed) continue;
4098
+ if (isEmailLike(trimmed)) continue;
4099
+ const key = trimmed.toLowerCase();
4100
+ if (seen.has(key)) continue;
4101
+ seen.add(key);
4102
+ out.push(trimmed);
4103
+ if (out.length >= limit) break;
4104
+ }
4105
+ return out;
4106
+ }
4107
+ function normalizeForBlindIndex(field, value) {
4108
+ const base = value.normalize("NFKC").trim();
4109
+ switch (field) {
4110
+ case "email":
4111
+ return base.toLowerCase();
4112
+ case "name":
4113
+ return base.toLowerCase().replace(/\s+/g, " ");
4114
+ case "account_number":
4115
+ return base.replace(/\s+/g, "");
4116
+ }
4117
+ }
4118
+ async function computeBlindIndex(secret, field, value) {
4119
+ const normalized = normalizeForBlindIndex(field, value);
4120
+ const key = await subtle().importKey(
4121
+ "raw",
4122
+ new TextEncoder().encode(secret),
4123
+ { name: "HMAC", hash: "SHA-256" },
4124
+ false,
4125
+ ["sign"]
4126
+ );
4127
+ const message = new TextEncoder().encode(`oneaddress:bidx:${field}:${normalized}`);
4128
+ const sig = await subtle().sign("HMAC", key, message);
4129
+ return bytesToB64Url(new Uint8Array(sig));
4130
+ }
4131
+ async function computeCustomerBlindIndex(secret, fields) {
4132
+ const out = { names: [] };
4133
+ if (fields.email && fields.email.trim()) {
4134
+ out.email = await computeBlindIndex(secret, "email", fields.email);
4135
+ }
4136
+ if (fields.account_number && fields.account_number.trim()) {
4137
+ out.account_number = await computeBlindIndex(secret, "account_number", fields.account_number);
4138
+ }
4139
+ const nameValues = [];
4140
+ if (fields.name && fields.name.trim() && !isEmailLike(fields.name)) nameValues.push(fields.name);
4141
+ for (const n of fields.known_names ?? []) {
4142
+ if (n && n.trim() && !isEmailLike(n)) nameValues.push(n);
4143
+ }
4144
+ const seen = /* @__PURE__ */ new Set();
4145
+ for (const v of nameValues) {
4146
+ const norm2 = normalizeForBlindIndex("name", v);
4147
+ if (seen.has(norm2)) continue;
4148
+ seen.add(norm2);
4149
+ out.names.push(await computeBlindIndex(secret, "name", v));
4150
+ }
4151
+ return out;
4152
+ }
494
4153
  async function signWebhookPayload(payload, secret) {
495
4154
  const key = await subtle().importKey(
496
4155
  "raw",
@@ -520,8 +4179,11 @@ var subtle, AU_STATE_FULL, SESSION_KEY_BITS, SESSION_IV_LENGTH, WRAP_SALT_LENGTH
520
4179
  var init_src = __esm({
521
4180
  "../crypto/src/index.ts"() {
522
4181
  "use strict";
4182
+ init_hybrid();
523
4183
  init_replay_window();
524
4184
  init_safe_url();
4185
+ init_partner_key_attestation();
4186
+ init_registry_head();
525
4187
  subtle = () => globalThis.crypto.subtle;
526
4188
  AU_STATE_FULL = {
527
4189
  "new south wales": "NSW",
@@ -555,17 +4217,33 @@ __export(index_exports, {
555
4217
  CURRENT_VERSION: () => CURRENT_VERSION,
556
4218
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
557
4219
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
4220
+ canonicalD5LoaForm: () => canonicalD5LoaForm,
558
4221
  compareAddresses: () => compareAddresses,
4222
+ computeBlindIndex: () => computeBlindIndex,
4223
+ confirmUpdate: () => confirmUpdate,
559
4224
  createOneAddressHandler: () => createOneAddressHandler,
4225
+ createSqlIdempotencyStore: () => createSqlIdempotencyStore,
4226
+ d5LoaRef: () => d5LoaRef,
560
4227
  decrypt: () => decryptAddress2,
561
4228
  decryptAddress: () => decryptAddress2,
4229
+ decryptLoaEncrypted: () => decryptLoaEncrypted,
562
4230
  decryptSession: () => decryptSession2,
563
4231
  fetchLoaPublicKey: () => fetchLoaPublicKey,
4232
+ findMatchingStoredName: () => findMatchingStoredName,
4233
+ formatAddressParts: () => formatAddressParts,
4234
+ isEmailLike: () => isEmailLike2,
564
4235
  isFreshTimestamp: () => isFreshTimestamp,
4236
+ namePoolMatches: () => namePoolMatches,
4237
+ normalizeForBlindIndex: () => normalizeForBlindIndex,
4238
+ readAddressParts: () => readAddressParts,
4239
+ sendVerifyResult: () => sendVerifyResult,
4240
+ toExpressHandler: () => toExpressHandler,
565
4241
  transform: () => transformAddress,
566
4242
  transformAddress: () => transformAddress,
4243
+ transformSession: () => transformSession,
567
4244
  validateAddress: () => validateAddress,
568
4245
  verify: () => verifySignature,
4246
+ verifyD5LOA: () => verifyD5LOA,
569
4247
  verifyGrace: () => verifyWithGrace,
570
4248
  verifyLOA: () => verifyLOA,
571
4249
  verifySignature: () => verifySignature,
@@ -581,6 +4259,94 @@ var SUPPORTED_VERSIONS = ["2026.1"];
581
4259
 
582
4260
  // src/index.ts
583
4261
  init_src();
4262
+ init_src();
4263
+
4264
+ // ../name-match/src/index.ts
4265
+ function isEmailLike2(value) {
4266
+ return value.includes("@");
4267
+ }
4268
+ function stripDiacritics(s) {
4269
+ return s.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
4270
+ }
4271
+ function norm(s) {
4272
+ return stripDiacritics(s).toLowerCase().replaceAll(".", "").trim().replaceAll(/\s+/g, " ");
4273
+ }
4274
+ function tokenize(name) {
4275
+ return norm(name).split(" ").filter(Boolean);
4276
+ }
4277
+ function surnameVariants(token) {
4278
+ if (!token.includes("-")) return [token];
4279
+ return [token, ...token.split("-").filter(Boolean)];
4280
+ }
4281
+ function namePoolMatches(providedNames, storedName) {
4282
+ if (isEmailLike2(storedName)) return false;
4283
+ const provided = providedNames.filter((n) => Boolean(n) && !isEmailLike2(n));
4284
+ const primary = tokenize(provided[0] ?? "");
4285
+ if (primary.length === 0) return false;
4286
+ const surnames = new Set(surnameVariants(primary[primary.length - 1]));
4287
+ for (let i = 1; i < provided.length; i++) {
4288
+ const t = tokenize(provided[i]);
4289
+ if (t.length >= 2) for (const v of surnameVariants(t[t.length - 1])) surnames.add(v);
4290
+ }
4291
+ const all = /* @__PURE__ */ new Set();
4292
+ for (const n of provided) for (const t of tokenize(n)) all.add(t);
4293
+ const given = [...all].filter((t) => !surnames.has(t));
4294
+ const stored = tokenize(storedName);
4295
+ if (stored.length === 0) return false;
4296
+ const storedSurname = stored[stored.length - 1];
4297
+ const storedGiven = stored.slice(0, -1);
4298
+ if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
4299
+ const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
4300
+ return storedGiven.every(covered);
4301
+ }
4302
+ function findMatchingStoredName(providedNames, storedCandidates) {
4303
+ return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
4304
+ }
4305
+
4306
+ // src/index.ts
4307
+ function createSqlIdempotencyStore(opts2) {
4308
+ const table = opts2.table ?? "oneaddress_dispatches";
4309
+ const ph = opts2.placeholder ?? ((n) => `$${n}`);
4310
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
4311
+ throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
4312
+ }
4313
+ const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
4314
+ return {
4315
+ async claim(dispatchId) {
4316
+ const inserted = await opts2.query(
4317
+ `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
4318
+ [dispatchId]
4319
+ );
4320
+ if (inserted.length > 0) return "fresh";
4321
+ const rows = await opts2.query(
4322
+ `SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
4323
+ [dispatchId]
4324
+ );
4325
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
4326
+ },
4327
+ async complete(dispatchId) {
4328
+ await opts2.query(
4329
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
4330
+ [dispatchId]
4331
+ );
4332
+ },
4333
+ // Legacy surface, implemented over the same table so a store built here
4334
+ // still satisfies callers (or SDK versions) that only know has/set.
4335
+ async has(dispatchId) {
4336
+ const rows = await opts2.query(
4337
+ `SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
4338
+ [dispatchId]
4339
+ );
4340
+ return rows.length > 0 && Boolean(completedOf(rows[0]));
4341
+ },
4342
+ async set(dispatchId) {
4343
+ await opts2.query(
4344
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
4345
+ [dispatchId]
4346
+ );
4347
+ }
4348
+ };
4349
+ }
584
4350
  function verifySignature(rawBody, signature, timestamp, secret) {
585
4351
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
586
4352
  const sigPayload = `${timestamp}.${rawBody}`;
@@ -603,8 +4369,17 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
603
4369
  function base64urlToBuffer(b64) {
604
4370
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
605
4371
  }
4372
+ function pemToBase64(pem) {
4373
+ const begin = pem.indexOf("-----BEGIN");
4374
+ if (begin === -1) return pem.replace(/\s/g, "");
4375
+ const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
4376
+ if (armourEnd === -1) return pem.replace(/\s/g, "");
4377
+ const bodyStart = armourEnd + "-----".length;
4378
+ const end = pem.indexOf("-----END", bodyStart);
4379
+ return (end === -1 ? pem.slice(bodyStart) : pem.slice(bodyStart, end)).replace(/\s/g, "");
4380
+ }
606
4381
  function pemToBuffer(pem) {
607
- return Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");
4382
+ return Buffer.from(pemToBase64(pem), "base64");
608
4383
  }
609
4384
  async function decryptAddress2(payload, privateKeyPem, partnerId) {
610
4385
  const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
@@ -656,12 +4431,18 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
656
4431
  }
657
4432
  async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId) {
658
4433
  const { decryptSession: decryptSessionCrypto } = await Promise.resolve().then(() => (init_src(), src_exports));
659
- const privateKeyB64 = privateKeyPem.replace(/-----[^-]+-----/g, "").replace(/\s/g, "");
660
- return decryptSessionCrypto(share, envelopeB64, privateKeyB64, partnerId);
4434
+ return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
661
4435
  }
662
4436
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
663
4437
  const plaintext = await decryptAddress2(payload, privateKeyPem, partnerId);
664
4438
  const plaintextBytes = new TextEncoder().encode(JSON.stringify(plaintext));
4439
+ return reEncryptForRecipient(
4440
+ plaintextBytes,
4441
+ recipientSpkiPem,
4442
+ new TextEncoder().encode(`oneaddress:transform:${partnerId}`)
4443
+ );
4444
+ }
4445
+ async function reEncryptForRecipient(plaintextBytes, recipientSpkiPem, info) {
665
4446
  const recipientKey = await import_crypto.default.subtle.importKey(
666
4447
  "spki",
667
4448
  pemToBuffer(recipientSpkiPem),
@@ -681,7 +4462,6 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
681
4462
  );
682
4463
  const hkdfSaltBytes = import_crypto.default.getRandomValues(new Uint8Array(32));
683
4464
  const hkdfKey = await import_crypto.default.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
684
- const info = new TextEncoder().encode(`oneaddress:transform:${partnerId}`);
685
4465
  const aesKeyBits = await import_crypto.default.subtle.deriveBits(
686
4466
  { name: "HKDF", hash: "SHA-256", salt: hkdfSaltBytes, info },
687
4467
  hkdfKey,
@@ -702,8 +4482,82 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
702
4482
  hkdfSalt: Buffer.from(hkdfSaltBytes).toString("base64")
703
4483
  };
704
4484
  }
4485
+ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, recipientSpkiPem) {
4486
+ const sessionData = await decryptSession2(share, envelopeB64, privateKeyPem, partnerId);
4487
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(sessionData));
4488
+ return reEncryptForRecipient(
4489
+ plaintextBytes,
4490
+ recipientSpkiPem,
4491
+ new TextEncoder().encode(`oneaddress:transform-session:${partnerId}`)
4492
+ );
4493
+ }
705
4494
  var OA_APP_BASE_URL = "https://oneaddress.io";
706
- var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["oneaddress.io", "app.oneaddress.io", "localhost", "127.0.0.1"]);
4495
+ async function confirmUpdate(opts2) {
4496
+ const {
4497
+ partnerId,
4498
+ secret,
4499
+ dispatchId,
4500
+ status = "confirmed",
4501
+ note,
4502
+ loaRef,
4503
+ memberName,
4504
+ appBaseUrl = OA_APP_BASE_URL,
4505
+ fetchImpl = fetch
4506
+ } = opts2;
4507
+ if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
4508
+ if (!secret) return { ok: false, status: 0, error: "secret is required" };
4509
+ const id = typeof dispatchId === "string" ? Number(dispatchId) : dispatchId;
4510
+ if (!Number.isInteger(id) || id <= 0) {
4511
+ return {
4512
+ ok: false,
4513
+ status: 0,
4514
+ error: `dispatchId must be a positive integer, received ${JSON.stringify(dispatchId)} \u2014 it comes from the X-OneAddress-Dispatch header on the webhook you are confirming`
4515
+ };
4516
+ }
4517
+ const body = JSON.stringify({
4518
+ dispatch_id: id,
4519
+ partner_id: partnerId,
4520
+ status,
4521
+ ...note !== void 0 ? { note } : {},
4522
+ ...loaRef !== void 0 ? { loa_ref: loaRef } : {},
4523
+ ...memberName !== void 0 ? { member_name: memberName } : {}
4524
+ });
4525
+ const timestamp = String(Math.floor(Date.now() / 1e3));
4526
+ const signature = import_crypto.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
4527
+ let base = appBaseUrl;
4528
+ while (base.endsWith("/")) base = base.slice(0, -1);
4529
+ let res;
4530
+ try {
4531
+ res = await fetchImpl(`${base}/api/confirm`, {
4532
+ method: "POST",
4533
+ headers: {
4534
+ "Content-Type": "application/json",
4535
+ "Authorization": `Bearer ${secret}`,
4536
+ "X-OneAddress-Timestamp": timestamp,
4537
+ "X-OneAddress-Signature": signature
4538
+ },
4539
+ // The SAME string that was signed. Not an object, and not re-stringified.
4540
+ body
4541
+ });
4542
+ } catch (err) {
4543
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
4544
+ }
4545
+ if (res.ok) return { ok: true, status: res.status };
4546
+ let error;
4547
+ try {
4548
+ const parsed = await res.json();
4549
+ if (typeof parsed?.error === "string") error = parsed.error;
4550
+ } catch {
4551
+ }
4552
+ return { ok: false, status: res.status, error };
4553
+ }
4554
+ function allowedLoaHosts() {
4555
+ const hosts = ["oneaddress.io", "app.oneaddress.io"];
4556
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
4557
+ hosts.push("localhost", "127.0.0.1");
4558
+ }
4559
+ return new Set(hosts);
4560
+ }
707
4561
  async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
708
4562
  let parsedBase;
709
4563
  try {
@@ -711,9 +4565,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
711
4565
  } catch {
712
4566
  throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
713
4567
  }
714
- if (!ALLOWED_LOA_HOSTS.has(parsedBase.hostname)) {
4568
+ const allowedHosts = allowedLoaHosts();
4569
+ if (!allowedHosts.has(parsedBase.hostname)) {
715
4570
  throw new Error(
716
- `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...ALLOWED_LOA_HOSTS].join(", ")}`
4571
+ `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
717
4572
  );
718
4573
  }
719
4574
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
@@ -751,6 +4606,56 @@ async function verifyLOA(loa, publicKeyPem) {
751
4606
  return false;
752
4607
  }
753
4608
  }
4609
+ function canonicalD5LoaForm(loa) {
4610
+ return [
4611
+ loa.consumer_name,
4612
+ loa.authorisation_date,
4613
+ loa.scope,
4614
+ loa.update_uid,
4615
+ loa.oneaddress_acn
4616
+ ].join("|");
4617
+ }
4618
+ function toB64Url(buf) {
4619
+ return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4620
+ }
4621
+ function d5LoaRef(loa) {
4622
+ return toB64Url(import_crypto.default.createHash("sha256").update(canonicalD5LoaForm(loa), "utf8").digest());
4623
+ }
4624
+ async function verifyD5LOA(loa, publicKeyPem) {
4625
+ if (loa.signature_algorithm !== "ECDSA-P256") {
4626
+ console.warn(
4627
+ // NOSONAR — intentional SDK diagnostic, not user-controlled data
4628
+ "[OneAddress SDK] D5 LOA algorithm is HMAC-SHA256 (deprecated) \u2014 cannot be verified by partners."
4629
+ );
4630
+ return false;
4631
+ }
4632
+ try {
4633
+ const key = await import_crypto.default.subtle.importKey(
4634
+ "spki",
4635
+ pemToBuffer(publicKeyPem),
4636
+ { name: "ECDSA", namedCurve: "P-256" },
4637
+ false,
4638
+ ["verify"]
4639
+ );
4640
+ return await import_crypto.default.subtle.verify(
4641
+ { name: "ECDSA", hash: "SHA-256" },
4642
+ key,
4643
+ Buffer.from(loa.oneaddress_signature, "hex"),
4644
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
4645
+ );
4646
+ } catch {
4647
+ return false;
4648
+ }
4649
+ }
4650
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
4651
+ const data = await decryptSession2(
4652
+ loaEncrypted.session_key_share,
4653
+ loaEncrypted.session_envelope,
4654
+ privateKeyPem,
4655
+ partnerId
4656
+ );
4657
+ return data;
4658
+ }
754
4659
  var ADDRESS_REQUIRED_FIELDS = [
755
4660
  "street",
756
4661
  "suburb",
@@ -772,6 +4677,34 @@ function validateAddress(raw) {
772
4677
  }
773
4678
  return obj;
774
4679
  }
4680
+ var ADDRESS_ALIASES = {
4681
+ line1: ["line1", "address_line1", "street", "streetAddress"],
4682
+ suburb: ["suburb", "city", "locality", "town"],
4683
+ state: ["state", "region", "province"],
4684
+ postcode: ["postcode", "postalCode", "postal_code", "zip"],
4685
+ country: ["country"]
4686
+ };
4687
+ function readAddressParts(raw) {
4688
+ const a = raw && typeof raw === "object" ? raw : {};
4689
+ const read = (part) => {
4690
+ for (const key of ADDRESS_ALIASES[part]) {
4691
+ const v = a[key];
4692
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
4693
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
4694
+ }
4695
+ return "";
4696
+ };
4697
+ return {
4698
+ line1: read("line1"),
4699
+ suburb: read("suburb"),
4700
+ state: read("state"),
4701
+ postcode: read("postcode"),
4702
+ country: read("country") || "AU"
4703
+ };
4704
+ }
4705
+ function formatAddressParts(parts) {
4706
+ return [parts.line1, parts.suburb, parts.state, parts.postcode].filter(Boolean).join(", ");
4707
+ }
775
4708
  var STREET_SUFFIX_MAP = {
776
4709
  st: "street",
777
4710
  str: "street",
@@ -829,18 +4762,80 @@ function compareAddresses(a, b) {
829
4762
  if (aCountry && bCountry && aCountry !== bCountry) return false;
830
4763
  return true;
831
4764
  }
4765
+ async function sendVerifyResult(params) {
4766
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
4767
+ const safe = isSafeWebhookUrl(callbackUrl);
4768
+ if (!safe.ok) {
4769
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
4770
+ }
4771
+ const res = await fetch(callbackUrl, {
4772
+ method: "POST",
4773
+ headers: { "Content-Type": "application/json" },
4774
+ body: JSON.stringify({
4775
+ batch_id: batchId,
4776
+ partner_id: partnerId,
4777
+ result: match ? "match" : "mismatch",
4778
+ address_match: match,
4779
+ ...note ? { note } : {},
4780
+ token: callbackToken
4781
+ })
4782
+ });
4783
+ if (!res.ok) {
4784
+ throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
4785
+ }
4786
+ }
4787
+ var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
4788
+ var warnedUnhandledEvents = /* @__PURE__ */ new Set();
832
4789
  function createOneAddressHandler(options) {
833
4790
  const {
834
4791
  webhookSecret,
835
4792
  previousWebhookSecret,
836
4793
  webhookSecretGraceUntil,
837
4794
  privateKeyPem,
4795
+ loaPublicKeyPem,
838
4796
  onUpdate,
839
4797
  onVerify,
840
4798
  onAccountVerify,
4799
+ onTest,
841
4800
  timestampToleranceSecs = 300,
842
4801
  idempotencyStore
843
4802
  } = options;
4803
+ async function buildD5Pieces(body, partnerId) {
4804
+ const share = body.session_key_share;
4805
+ const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
4806
+ const address = validateAddress({
4807
+ street: data.new_address?.street,
4808
+ suburb: data.new_address?.suburb,
4809
+ state: data.new_address?.state,
4810
+ postcode: data.new_address?.postcode,
4811
+ country: data.new_address?.country,
4812
+ updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
4813
+ });
4814
+ const customer = {
4815
+ email: "",
4816
+ name: data.verified_name ?? "",
4817
+ account_number: data.account_number ?? null,
4818
+ known_names: Array.isArray(data.known_names) ? data.known_names : []
4819
+ };
4820
+ let loa;
4821
+ let loa_ref;
4822
+ if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
4823
+ loa = await decryptLoaEncrypted(
4824
+ body.loa_encrypted,
4825
+ privateKeyPem,
4826
+ partnerId
4827
+ );
4828
+ loa_ref = d5LoaRef(loa);
4829
+ if (loaPublicKeyPem) {
4830
+ const valid = await verifyD5LOA(loa, loaPublicKeyPem);
4831
+ if (!valid) throw new Error("D5 LOA signature verification failed");
4832
+ }
4833
+ }
4834
+ return { address, customer, loa, loa_ref, raw: data };
4835
+ }
4836
+ function isD5Body(body) {
4837
+ return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
4838
+ }
844
4839
  return async function handler(req) {
845
4840
  const rawBody = await req.text();
846
4841
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -883,6 +4878,14 @@ function createOneAddressHandler(options) {
883
4878
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
884
4879
  );
885
4880
  }
4881
+ } else if (idempotencyStore.claim) {
4882
+ const claim = await idempotencyStore.claim(dispatchId);
4883
+ if (claim === "duplicate") {
4884
+ return new Response(JSON.stringify({ ok: true, duplicate: true }), {
4885
+ status: 200,
4886
+ headers: { "Content-Type": "application/json" }
4887
+ });
4888
+ }
886
4889
  } else {
887
4890
  const alreadySeen = await idempotencyStore.has(dispatchId);
888
4891
  if (alreadySeen) {
@@ -895,31 +4898,71 @@ function createOneAddressHandler(options) {
895
4898
  }
896
4899
  try {
897
4900
  if (body.event === "address.updated") {
898
- if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
899
- return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
900
- status: 400,
901
- headers: { "Content-Type": "application/json" }
902
- });
4901
+ let event;
4902
+ if (isD5Body(body)) {
4903
+ const d5 = await buildD5Pieces(body, partnerId);
4904
+ event = {
4905
+ event: "address.updated",
4906
+ version: body.oneaddress_version ?? body.version ?? "2.0",
4907
+ id: body.id ?? "",
4908
+ timestamp: tsNum,
4909
+ partner_id: partnerId,
4910
+ dispatchId,
4911
+ customer: d5.customer,
4912
+ address: d5.address,
4913
+ loa: d5.loa,
4914
+ loa_ref: d5.loa_ref,
4915
+ id_verification: body.id_verification,
4916
+ raw: d5.raw
4917
+ };
4918
+ } else {
4919
+ if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
4920
+ return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
4921
+ status: 400,
4922
+ headers: { "Content-Type": "application/json" }
4923
+ });
4924
+ }
4925
+ const encrypted = body.address_encrypted;
4926
+ const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
4927
+ let loa;
4928
+ let loa_ref;
4929
+ if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
4930
+ loa = await decryptLoaEncrypted(
4931
+ body.loa_encrypted,
4932
+ privateKeyPem,
4933
+ partnerId
4934
+ );
4935
+ loa_ref = d5LoaRef(loa);
4936
+ if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
4937
+ throw new Error("D5 LOA signature verification failed");
4938
+ }
4939
+ }
4940
+ const customer = {
4941
+ email: "",
4942
+ name: rawAddress.fullName ?? "",
4943
+ account_number: rawAddress.accountReference ?? null,
4944
+ known_names: Array.isArray(rawAddress.knownNames) ? rawAddress.knownNames : []
4945
+ };
4946
+ event = {
4947
+ event: "address.updated",
4948
+ version: body.oneaddress_version ?? body.version ?? "1",
4949
+ id: body.id ?? "",
4950
+ timestamp: tsNum,
4951
+ partner_id: partnerId,
4952
+ dispatchId,
4953
+ customer,
4954
+ address: validateAddress(rawAddress),
4955
+ loa,
4956
+ loa_ref,
4957
+ id_verification: body.id_verification,
4958
+ raw: rawAddress
4959
+ };
903
4960
  }
904
- const encrypted = body.address_encrypted;
905
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
906
- const event = {
907
- event: "address.updated",
908
- version: body.oneaddress_version ?? body.version ?? "1",
909
- id: body.id ?? "",
910
- timestamp: tsNum,
911
- partner_id: partnerId,
912
- dispatchId,
913
- customer: body.customer,
914
- address: validateAddress(rawAddress),
915
- loa: body.loa,
916
- id_verification: body.id_verification,
917
- raw: rawAddress
918
- };
919
4961
  const result = await onUpdate(event);
920
4962
  if (dispatchId && idempotencyStore) {
921
- await idempotencyStore.set(dispatchId).catch(
922
- (err) => console.error("[OneAddress SDK] idempotencyStore.set failed:", err)
4963
+ const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
4964
+ await record.catch(
4965
+ (err) => console.error("[OneAddress SDK] idempotency completion failed:", err)
923
4966
  // NOSONAR
924
4967
  );
925
4968
  }
@@ -946,19 +4989,57 @@ function createOneAddressHandler(options) {
946
4989
  dispatchId,
947
4990
  batch_id: body.batch_id ?? 0,
948
4991
  user_id: body.user_id ?? "",
949
- customer: body.customer ?? {},
4992
+ customer: body.customer,
4993
+ customer_match: body.customer_match,
950
4994
  address: validateAddress(rawAddress),
951
4995
  loa: body.loa,
952
4996
  id_verification: body.id_verification,
953
4997
  raw: rawAddress
954
4998
  };
955
4999
  const result = await onVerify(event);
956
- return new Response(JSON.stringify({ ok: true, ...result }), {
5000
+ const matched = result && typeof result.match === "boolean" ? result.match : void 0;
5001
+ const callbackUrl = typeof body.callback_url === "string" ? body.callback_url : "";
5002
+ const callbackToken = typeof body.callback_token === "string" ? body.callback_token : "";
5003
+ if (matched === void 0) {
5004
+ console.error("[OneAddress SDK] onVerify must return { match: boolean } to close the verify loop; result dropped.");
5005
+ } else if (!callbackUrl || !callbackToken) {
5006
+ console.error("[OneAddress SDK] address.verify webhook is missing callback_url/callback_token; cannot report the result.");
5007
+ } else {
5008
+ try {
5009
+ await sendVerifyResult({
5010
+ callbackUrl,
5011
+ callbackToken,
5012
+ batchId: body.batch_id ?? 0,
5013
+ partnerId,
5014
+ match: matched,
5015
+ note: result && typeof result.note === "string" ? result.note : void 0
5016
+ });
5017
+ } catch (err) {
5018
+ console.error("[OneAddress SDK] verify-result callback failed:", err);
5019
+ }
5020
+ }
5021
+ return new Response(JSON.stringify({ ok: true, match: matched }), {
957
5022
  status: 200,
958
5023
  headers: { "Content-Type": "application/json" }
959
5024
  });
960
5025
  }
961
5026
  if (body.event === "account.verify" && onAccountVerify) {
5027
+ let customer;
5028
+ if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
5029
+ const raw = await decryptAddress2(
5030
+ body.customer_encrypted,
5031
+ privateKeyPem,
5032
+ partnerId
5033
+ );
5034
+ customer = {
5035
+ email: raw.email ?? "",
5036
+ name: raw.name ?? "",
5037
+ account_number: raw.account_number ?? null,
5038
+ known_names: Array.isArray(raw.known_names) ? raw.known_names : []
5039
+ };
5040
+ } else {
5041
+ customer = body.customer ?? {};
5042
+ }
962
5043
  const event = {
963
5044
  event: "account.verify",
964
5045
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -967,7 +5048,7 @@ function createOneAddressHandler(options) {
967
5048
  partner_id: partnerId,
968
5049
  dispatchId,
969
5050
  user_id: body.user_id ?? "",
970
- customer: body.customer ?? {},
5051
+ customer,
971
5052
  raw: body
972
5053
  };
973
5054
  const result = await onAccountVerify(event);
@@ -976,7 +5057,39 @@ function createOneAddressHandler(options) {
976
5057
  headers: { "Content-Type": "application/json" }
977
5058
  });
978
5059
  }
979
- return new Response(JSON.stringify({ ok: true, skipped: true }), {
5060
+ if (body.event === "address.test" && onTest) {
5061
+ if (!isD5Body(body)) {
5062
+ return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
5063
+ status: 400,
5064
+ headers: { "Content-Type": "application/json" }
5065
+ });
5066
+ }
5067
+ const d5 = await buildD5Pieces(body, partnerId);
5068
+ await onTest({
5069
+ event: "address.test",
5070
+ index: typeof body.index === "number" ? body.index : void 0,
5071
+ total: typeof body.total === "number" ? body.total : void 0,
5072
+ verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
5073
+ timestamp: tsNum,
5074
+ partner_id: partnerId,
5075
+ customer: d5.customer,
5076
+ address: d5.address,
5077
+ raw: d5.raw
5078
+ });
5079
+ return new Response(JSON.stringify({ ok: true, test: true }), {
5080
+ status: 200,
5081
+ headers: { "Content-Type": "application/json" }
5082
+ });
5083
+ }
5084
+ const evt = typeof body.event === "string" ? body.event : "(none)";
5085
+ if (!warnedUnhandledEvents.has(evt)) {
5086
+ warnedUnhandledEvents.add(evt);
5087
+ console.warn(
5088
+ `[OneAddress SDK] Event "${evt}" is not handled by this build and was SKIPPED. It was acknowledged with 200 so OneAddress does not retry, but your onUpdate callback did NOT run. This build handles: ${HANDLED_EVENTS.join(", ")}. If you expected this event to be processed, update @oneaddress/partner-sdk.`
5089
+ // NOSONAR
5090
+ );
5091
+ }
5092
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
980
5093
  status: 200,
981
5094
  headers: { "Content-Type": "application/json" }
982
5095
  });
@@ -990,24 +5103,89 @@ function createOneAddressHandler(options) {
990
5103
  }
991
5104
  };
992
5105
  }
5106
+ function toExpressHandler(handler) {
5107
+ return async function expressHandler(req, res) {
5108
+ const raw = req.body;
5109
+ const isBuffer = typeof raw === "object" && raw !== null && typeof raw.copy === "function" && typeof raw.toString === "function";
5110
+ if (!isBuffer && typeof raw !== "string") {
5111
+ const detail = raw === void 0 ? "the body was not read at all" : `the body arrived as ${raw === null ? "null" : typeof raw}, already parsed`;
5112
+ console.error(
5113
+ `[OneAddress SDK] toExpressHandler: raw request body required, but ${detail}. Add express.raw({ type: 'application/json' }) to THIS route, before the handler, and make sure no global express.json() runs first. The webhook signature is computed over the raw bytes, so a parsed body cannot be verified.`
5114
+ // NOSONAR
5115
+ );
5116
+ res.status(500).send(JSON.stringify({ error: "Receiver misconfigured: raw body required" }));
5117
+ return;
5118
+ }
5119
+ const text = typeof raw === "string" ? raw : String(raw);
5120
+ const fetchLike = {
5121
+ text: async () => text,
5122
+ headers: {
5123
+ get(name) {
5124
+ const v = req.headers[name.toLowerCase()];
5125
+ if (v === void 0) return null;
5126
+ return Array.isArray(v) ? v.join(", ") : v;
5127
+ }
5128
+ }
5129
+ };
5130
+ const out = await handler(fetchLike);
5131
+ const bodyText = await out.text();
5132
+ res.status(out.status);
5133
+ out.headers.forEach((value, key) => {
5134
+ res.setHeader(key, value);
5135
+ });
5136
+ res.send(bodyText);
5137
+ };
5138
+ }
993
5139
  // Annotate the CommonJS export names for ESM import in node:
994
5140
  0 && (module.exports = {
995
5141
  CURRENT_VERSION,
996
5142
  DEFAULT_REPLAY_WINDOW_SECS,
997
5143
  SUPPORTED_VERSIONS,
5144
+ canonicalD5LoaForm,
998
5145
  compareAddresses,
5146
+ computeBlindIndex,
5147
+ confirmUpdate,
999
5148
  createOneAddressHandler,
5149
+ createSqlIdempotencyStore,
5150
+ d5LoaRef,
1000
5151
  decrypt,
1001
5152
  decryptAddress,
5153
+ decryptLoaEncrypted,
1002
5154
  decryptSession,
1003
5155
  fetchLoaPublicKey,
5156
+ findMatchingStoredName,
5157
+ formatAddressParts,
5158
+ isEmailLike,
1004
5159
  isFreshTimestamp,
5160
+ namePoolMatches,
5161
+ normalizeForBlindIndex,
5162
+ readAddressParts,
5163
+ sendVerifyResult,
5164
+ toExpressHandler,
1005
5165
  transform,
1006
5166
  transformAddress,
5167
+ transformSession,
1007
5168
  validateAddress,
1008
5169
  verify,
5170
+ verifyD5LOA,
1009
5171
  verifyGrace,
1010
5172
  verifyLOA,
1011
5173
  verifySignature,
1012
5174
  verifyWithGrace
1013
5175
  });
5176
+ /*! Bundled license information:
5177
+
5178
+ @noble/curves/utils.js:
5179
+ @noble/curves/abstract/modular.js:
5180
+ @noble/curves/abstract/curve.js:
5181
+ @noble/curves/abstract/edwards.js:
5182
+ @noble/curves/abstract/montgomery.js:
5183
+ @noble/curves/ed25519.js:
5184
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
5185
+
5186
+ @noble/post-quantum/utils.js:
5187
+ @noble/post-quantum/_crystals.js:
5188
+ @noble/post-quantum/ml-kem.js:
5189
+ @noble/post-quantum/hybrid.js:
5190
+ (*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *)
5191
+ */