@oneaddress/conformance 1.0.0 → 2.1.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.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +119 -74
  3. package/dist/index.js +3704 -122
  4. package/package.json +27 -27
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
10
  var __copyProps = (to, from, except, desc) => {
10
11
  if (from && typeof from === "object" || typeof from === "function") {
11
12
  for (let key of __getOwnPropNames(from))
@@ -14,18 +15,3047 @@ var __copyProps = (to, from, except, desc) => {
14
15
  }
15
16
  return to;
16
17
  };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
18
19
  // If the importer is in node compatibility mode or this is not an ESM
19
20
  // file that has been converted to a CommonJS file using a Babel-
20
21
  // compatible transform (i.e. "__esModule" has not been set), then set
21
22
  // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
23
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
24
+ mod2
24
25
  ));
26
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
25
27
 
26
28
  // src/checks.ts
27
29
  var import_node_crypto = __toESM(require("crypto"));
28
30
 
31
+ // ../../node_modules/@noble/hashes/utils.js
32
+ function isBytes(a) {
33
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
34
+ }
35
+ function anumber(n, title = "") {
36
+ if (typeof n !== "number") {
37
+ const prefix = title && `"${title}" `;
38
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
39
+ }
40
+ if (!Number.isSafeInteger(n) || n < 0) {
41
+ const prefix = title && `"${title}" `;
42
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
43
+ }
44
+ }
45
+ function abytes(value, length, title = "") {
46
+ const bytes = isBytes(value);
47
+ const len = value?.length;
48
+ const needsLen = length !== void 0;
49
+ if (!bytes || needsLen && len !== length) {
50
+ const prefix = title && `"${title}" `;
51
+ const ofLen = needsLen ? ` of length ${length}` : "";
52
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
53
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
54
+ if (!bytes)
55
+ throw new TypeError(message);
56
+ throw new RangeError(message);
57
+ }
58
+ return value;
59
+ }
60
+ function aexists(instance, checkFinished = true) {
61
+ if (instance.destroyed)
62
+ throw new Error("Hash instance has been destroyed");
63
+ if (checkFinished && instance.finished)
64
+ throw new Error("Hash#digest() has already been called");
65
+ }
66
+ function aoutput(out, instance) {
67
+ abytes(out, void 0, "digestInto() output");
68
+ const min = instance.outputLen;
69
+ if (out.length < min) {
70
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
71
+ }
72
+ }
73
+ function u32(arr) {
74
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
75
+ }
76
+ function clean(...arrays) {
77
+ for (let i = 0; i < arrays.length; i++) {
78
+ arrays[i].fill(0);
79
+ }
80
+ }
81
+ function createView(arr) {
82
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
83
+ }
84
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
85
+ function byteSwap(word) {
86
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
87
+ }
88
+ function byteSwap32(arr) {
89
+ for (let i = 0; i < arr.length; i++) {
90
+ arr[i] = byteSwap(arr[i]);
91
+ }
92
+ return arr;
93
+ }
94
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
95
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
96
+ // @ts-ignore
97
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
98
+ ))();
99
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
100
+ function bytesToHex(bytes) {
101
+ abytes(bytes);
102
+ if (hasHexBuiltin)
103
+ return bytes.toHex();
104
+ let hex = "";
105
+ for (let i = 0; i < bytes.length; i++) {
106
+ hex += hexes[bytes[i]];
107
+ }
108
+ return hex;
109
+ }
110
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
111
+ function asciiToBase16(ch) {
112
+ if (ch >= asciis._0 && ch <= asciis._9)
113
+ return ch - asciis._0;
114
+ if (ch >= asciis.A && ch <= asciis.F)
115
+ return ch - (asciis.A - 10);
116
+ if (ch >= asciis.a && ch <= asciis.f)
117
+ return ch - (asciis.a - 10);
118
+ return;
119
+ }
120
+ function hexToBytes(hex) {
121
+ if (typeof hex !== "string")
122
+ throw new TypeError("hex string expected, got " + typeof hex);
123
+ if (hasHexBuiltin) {
124
+ try {
125
+ return Uint8Array.fromHex(hex);
126
+ } catch (error) {
127
+ if (error instanceof SyntaxError)
128
+ throw new RangeError(error.message);
129
+ throw error;
130
+ }
131
+ }
132
+ const hl = hex.length;
133
+ const al = hl / 2;
134
+ if (hl % 2)
135
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
136
+ const array = new Uint8Array(al);
137
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
138
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
139
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
140
+ if (n1 === void 0 || n2 === void 0) {
141
+ const char = hex[hi] + hex[hi + 1];
142
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
143
+ }
144
+ array[ai] = n1 * 16 + n2;
145
+ }
146
+ return array;
147
+ }
148
+ function concatBytes(...arrays) {
149
+ let sum = 0;
150
+ for (let i = 0; i < arrays.length; i++) {
151
+ const a = arrays[i];
152
+ abytes(a);
153
+ sum += a.length;
154
+ }
155
+ const res = new Uint8Array(sum);
156
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
157
+ const a = arrays[i];
158
+ res.set(a, pad);
159
+ pad += a.length;
160
+ }
161
+ return res;
162
+ }
163
+ function createHasher(hashCons, info = {}) {
164
+ const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest();
165
+ const tmp = hashCons(void 0);
166
+ hashC.outputLen = tmp.outputLen;
167
+ hashC.blockLen = tmp.blockLen;
168
+ hashC.canXOF = tmp.canXOF;
169
+ hashC.create = (opts2) => hashCons(opts2);
170
+ Object.assign(hashC, info);
171
+ return Object.freeze(hashC);
172
+ }
173
+ function randomBytes(bytesLength = 32) {
174
+ anumber(bytesLength, "bytesLength");
175
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
176
+ if (typeof cr?.getRandomValues !== "function")
177
+ throw new Error("crypto.getRandomValues must be defined");
178
+ if (bytesLength > 65536)
179
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
180
+ return cr.getRandomValues(new Uint8Array(bytesLength));
181
+ }
182
+ var oidNist = (suffix) => ({
183
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
184
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
185
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
186
+ });
187
+
188
+ // ../../node_modules/@noble/curves/utils.js
189
+ var abytes2 = (value, length, title) => abytes(value, length, title);
190
+ var anumber2 = anumber;
191
+ var bytesToHex2 = bytesToHex;
192
+ var concatBytes2 = (...arrays) => concatBytes(...arrays);
193
+ var hexToBytes2 = (hex) => hexToBytes(hex);
194
+ var isBytes2 = isBytes;
195
+ var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
196
+ var _0n = /* @__PURE__ */ BigInt(0);
197
+ var _1n = /* @__PURE__ */ BigInt(1);
198
+ function abool(value, title = "") {
199
+ if (typeof value !== "boolean") {
200
+ const prefix = title && `"${title}" `;
201
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
202
+ }
203
+ return value;
204
+ }
205
+ function abignumber(n) {
206
+ if (typeof n === "bigint") {
207
+ if (!isPosBig(n))
208
+ throw new RangeError("positive bigint expected, got " + n);
209
+ } else
210
+ anumber2(n);
211
+ return n;
212
+ }
213
+ function asafenumber(value, title = "") {
214
+ if (typeof value !== "number") {
215
+ const prefix = title && `"${title}" `;
216
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
217
+ }
218
+ if (!Number.isSafeInteger(value)) {
219
+ const prefix = title && `"${title}" `;
220
+ throw new RangeError(prefix + "expected safe integer, got " + value);
221
+ }
222
+ }
223
+ function hexToNumber(hex) {
224
+ if (typeof hex !== "string")
225
+ throw new TypeError("hex string expected, got " + typeof hex);
226
+ return hex === "" ? _0n : BigInt("0x" + hex);
227
+ }
228
+ function bytesToNumberBE(bytes) {
229
+ return hexToNumber(bytesToHex(bytes));
230
+ }
231
+ function bytesToNumberLE(bytes) {
232
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
233
+ }
234
+ function numberToBytesBE(n, len) {
235
+ anumber(len);
236
+ if (len === 0)
237
+ throw new RangeError("zero length");
238
+ n = abignumber(n);
239
+ const hex = n.toString(16);
240
+ if (hex.length > len * 2)
241
+ throw new RangeError("number too large");
242
+ return hexToBytes(hex.padStart(len * 2, "0"));
243
+ }
244
+ function numberToBytesLE(n, len) {
245
+ return numberToBytesBE(n, len).reverse();
246
+ }
247
+ function equalBytes(a, b) {
248
+ a = abytes2(a);
249
+ b = abytes2(b);
250
+ if (a.length !== b.length)
251
+ return false;
252
+ let diff = 0;
253
+ for (let i = 0; i < a.length; i++)
254
+ diff |= a[i] ^ b[i];
255
+ return diff === 0;
256
+ }
257
+ function copyBytes(bytes) {
258
+ return Uint8Array.from(abytes2(bytes));
259
+ }
260
+ function asciiToBytes(ascii) {
261
+ if (typeof ascii !== "string")
262
+ throw new TypeError("ascii string expected, got " + typeof ascii);
263
+ return Uint8Array.from(ascii, (c, i) => {
264
+ const charCode = c.charCodeAt(0);
265
+ if (c.length !== 1 || charCode > 127) {
266
+ throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
267
+ }
268
+ return charCode;
269
+ });
270
+ }
271
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
272
+ function inRange(n, min, max) {
273
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
274
+ }
275
+ function aInRange(title, n, min, max) {
276
+ if (!inRange(n, min, max))
277
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
278
+ }
279
+ function bitLen(n) {
280
+ if (n < _0n)
281
+ throw new Error("expected non-negative bigint, got " + n);
282
+ let len;
283
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
284
+ ;
285
+ return len;
286
+ }
287
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
288
+ function validateObject(object, fields = {}, optFields = {}) {
289
+ if (Object.prototype.toString.call(object) !== "[object Object]")
290
+ throw new TypeError("expected valid options object");
291
+ function checkField(fieldName, expectedType, isOpt) {
292
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
293
+ throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
294
+ const val = object[fieldName];
295
+ if (isOpt && val === void 0)
296
+ return;
297
+ const current = typeof val;
298
+ if (current !== expectedType || val === null)
299
+ throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
300
+ }
301
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
302
+ iter(fields, false);
303
+ iter(optFields, true);
304
+ }
305
+ var notImplemented = () => {
306
+ throw new Error("not implemented");
307
+ };
308
+
309
+ // ../../node_modules/@noble/curves/abstract/modular.js
310
+ var _0n2 = /* @__PURE__ */ BigInt(0);
311
+ var _1n2 = /* @__PURE__ */ BigInt(1);
312
+ var _2n = /* @__PURE__ */ BigInt(2);
313
+ var _3n = /* @__PURE__ */ BigInt(3);
314
+ var _4n = /* @__PURE__ */ BigInt(4);
315
+ var _5n = /* @__PURE__ */ BigInt(5);
316
+ var _7n = /* @__PURE__ */ BigInt(7);
317
+ var _8n = /* @__PURE__ */ BigInt(8);
318
+ var _9n = /* @__PURE__ */ BigInt(9);
319
+ var _16n = /* @__PURE__ */ BigInt(16);
320
+ function mod(a, b) {
321
+ if (b <= _0n2)
322
+ throw new Error("mod: expected positive modulus, got " + b);
323
+ const result = a % b;
324
+ return result >= _0n2 ? result : b + result;
325
+ }
326
+ function pow2(x, power, modulo) {
327
+ if (power < _0n2)
328
+ throw new Error("pow2: expected non-negative exponent, got " + power);
329
+ let res = x;
330
+ while (power-- > _0n2) {
331
+ res *= res;
332
+ res %= modulo;
333
+ }
334
+ return res;
335
+ }
336
+ function invert(number, modulo) {
337
+ if (number === _0n2)
338
+ throw new Error("invert: expected non-zero number");
339
+ if (modulo <= _0n2)
340
+ throw new Error("invert: expected positive modulus, got " + modulo);
341
+ let a = mod(number, modulo);
342
+ let b = modulo;
343
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
344
+ while (a !== _0n2) {
345
+ const q = b / a;
346
+ const r = b - a * q;
347
+ const m = x - u * q;
348
+ const n = y - v * q;
349
+ b = a, a = r, x = u, y = v, u = m, v = n;
350
+ }
351
+ const gcd = b;
352
+ if (gcd !== _1n2)
353
+ throw new Error("invert: does not exist");
354
+ return mod(x, modulo);
355
+ }
356
+ function assertIsSquare(Fp2, root, n) {
357
+ const F2 = Fp2;
358
+ if (!F2.eql(F2.sqr(root), n))
359
+ throw new Error("Cannot find square root");
360
+ }
361
+ function sqrt3mod4(Fp2, n) {
362
+ const F2 = Fp2;
363
+ const p1div4 = (F2.ORDER + _1n2) / _4n;
364
+ const root = F2.pow(n, p1div4);
365
+ assertIsSquare(F2, root, n);
366
+ return root;
367
+ }
368
+ function sqrt5mod8(Fp2, n) {
369
+ const F2 = Fp2;
370
+ const p5div8 = (F2.ORDER - _5n) / _8n;
371
+ const n2 = F2.mul(n, _2n);
372
+ const v = F2.pow(n2, p5div8);
373
+ const nv = F2.mul(n, v);
374
+ const i = F2.mul(F2.mul(nv, _2n), v);
375
+ const root = F2.mul(nv, F2.sub(i, F2.ONE));
376
+ assertIsSquare(F2, root, n);
377
+ return root;
378
+ }
379
+ function sqrt9mod16(P) {
380
+ const Fp_ = Field(P);
381
+ const tn = tonelliShanks(P);
382
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
383
+ const c2 = tn(Fp_, c1);
384
+ const c3 = tn(Fp_, Fp_.neg(c1));
385
+ const c4 = (P + _7n) / _16n;
386
+ return ((Fp2, n) => {
387
+ const F2 = Fp2;
388
+ let tv1 = F2.pow(n, c4);
389
+ let tv2 = F2.mul(tv1, c1);
390
+ const tv3 = F2.mul(tv1, c2);
391
+ const tv4 = F2.mul(tv1, c3);
392
+ const e1 = F2.eql(F2.sqr(tv2), n);
393
+ const e2 = F2.eql(F2.sqr(tv3), n);
394
+ tv1 = F2.cmov(tv1, tv2, e1);
395
+ tv2 = F2.cmov(tv4, tv3, e2);
396
+ const e3 = F2.eql(F2.sqr(tv2), n);
397
+ const root = F2.cmov(tv1, tv2, e3);
398
+ assertIsSquare(F2, root, n);
399
+ return root;
400
+ });
401
+ }
402
+ function tonelliShanks(P) {
403
+ if (P < _3n)
404
+ throw new Error("sqrt is not defined for small field");
405
+ let Q2 = P - _1n2;
406
+ let S = 0;
407
+ while (Q2 % _2n === _0n2) {
408
+ Q2 /= _2n;
409
+ S++;
410
+ }
411
+ let Z = _2n;
412
+ const _Fp = Field(P);
413
+ while (FpLegendre(_Fp, Z) === 1) {
414
+ if (Z++ > 1e3)
415
+ throw new Error("Cannot find square root: probably non-prime P");
416
+ }
417
+ if (S === 1)
418
+ return sqrt3mod4;
419
+ let cc = _Fp.pow(Z, Q2);
420
+ const Q1div2 = (Q2 + _1n2) / _2n;
421
+ return function tonelliSlow(Fp2, n) {
422
+ const F2 = Fp2;
423
+ if (F2.is0(n))
424
+ return n;
425
+ if (FpLegendre(F2, n) !== 1)
426
+ throw new Error("Cannot find square root");
427
+ let M = S;
428
+ let c = F2.mul(F2.ONE, cc);
429
+ let t = F2.pow(n, Q2);
430
+ let R = F2.pow(n, Q1div2);
431
+ while (!F2.eql(t, F2.ONE)) {
432
+ if (F2.is0(t))
433
+ return F2.ZERO;
434
+ let i = 1;
435
+ let t_tmp = F2.sqr(t);
436
+ while (!F2.eql(t_tmp, F2.ONE)) {
437
+ i++;
438
+ t_tmp = F2.sqr(t_tmp);
439
+ if (i === M)
440
+ throw new Error("Cannot find square root");
441
+ }
442
+ const exponent = _1n2 << BigInt(M - i - 1);
443
+ const b = F2.pow(c, exponent);
444
+ M = i;
445
+ c = F2.sqr(b);
446
+ t = F2.mul(t, c);
447
+ R = F2.mul(R, b);
448
+ }
449
+ return R;
450
+ };
451
+ }
452
+ function FpSqrt(P) {
453
+ if (P % _4n === _3n)
454
+ return sqrt3mod4;
455
+ if (P % _8n === _5n)
456
+ return sqrt5mod8;
457
+ if (P % _16n === _9n)
458
+ return sqrt9mod16(P);
459
+ return tonelliShanks(P);
460
+ }
461
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
462
+ var FIELD_FIELDS = [
463
+ "create",
464
+ "isValid",
465
+ "is0",
466
+ "neg",
467
+ "inv",
468
+ "sqrt",
469
+ "sqr",
470
+ "eql",
471
+ "add",
472
+ "sub",
473
+ "mul",
474
+ "pow",
475
+ "div",
476
+ "addN",
477
+ "subN",
478
+ "mulN",
479
+ "sqrN"
480
+ ];
481
+ function validateField(field) {
482
+ const initial = {
483
+ ORDER: "bigint",
484
+ BYTES: "number",
485
+ BITS: "number"
486
+ };
487
+ const opts2 = FIELD_FIELDS.reduce((map, val) => {
488
+ map[val] = "function";
489
+ return map;
490
+ }, initial);
491
+ validateObject(field, opts2);
492
+ asafenumber(field.BYTES, "BYTES");
493
+ asafenumber(field.BITS, "BITS");
494
+ if (field.BYTES < 1 || field.BITS < 1)
495
+ throw new Error("invalid field: expected BYTES/BITS > 0");
496
+ if (field.ORDER <= _1n2)
497
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
498
+ return field;
499
+ }
500
+ function FpPow(Fp2, num, power) {
501
+ const F2 = Fp2;
502
+ if (power < _0n2)
503
+ throw new Error("invalid exponent, negatives unsupported");
504
+ if (power === _0n2)
505
+ return F2.ONE;
506
+ if (power === _1n2)
507
+ return num;
508
+ let p = F2.ONE;
509
+ let d = num;
510
+ while (power > _0n2) {
511
+ if (power & _1n2)
512
+ p = F2.mul(p, d);
513
+ d = F2.sqr(d);
514
+ power >>= _1n2;
515
+ }
516
+ return p;
517
+ }
518
+ function FpInvertBatch(Fp2, nums, passZero = false) {
519
+ const F2 = Fp2;
520
+ const inverted = new Array(nums.length).fill(passZero ? F2.ZERO : void 0);
521
+ const multipliedAcc = nums.reduce((acc, num, i) => {
522
+ if (F2.is0(num))
523
+ return acc;
524
+ inverted[i] = acc;
525
+ return F2.mul(acc, num);
526
+ }, F2.ONE);
527
+ const invertedAcc = F2.inv(multipliedAcc);
528
+ nums.reduceRight((acc, num, i) => {
529
+ if (F2.is0(num))
530
+ return acc;
531
+ inverted[i] = F2.mul(acc, inverted[i]);
532
+ return F2.mul(acc, num);
533
+ }, invertedAcc);
534
+ return inverted;
535
+ }
536
+ function FpLegendre(Fp2, n) {
537
+ const F2 = Fp2;
538
+ const p1mod2 = (F2.ORDER - _1n2) / _2n;
539
+ const powered = F2.pow(n, p1mod2);
540
+ const yes = F2.eql(powered, F2.ONE);
541
+ const zero = F2.eql(powered, F2.ZERO);
542
+ const no = F2.eql(powered, F2.neg(F2.ONE));
543
+ if (!yes && !zero && !no)
544
+ throw new Error("invalid Legendre symbol result");
545
+ return yes ? 1 : zero ? 0 : -1;
546
+ }
547
+ function nLength(n, nBitLength) {
548
+ if (nBitLength !== void 0)
549
+ anumber2(nBitLength);
550
+ if (n <= _0n2)
551
+ throw new Error("invalid n length: expected positive n, got " + n);
552
+ if (nBitLength !== void 0 && nBitLength < 1)
553
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
554
+ const bits = bitLen(n);
555
+ if (nBitLength !== void 0 && nBitLength < bits)
556
+ throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
557
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
558
+ const nByteLength = Math.ceil(_nBitLength / 8);
559
+ return { nBitLength: _nBitLength, nByteLength };
560
+ }
561
+ var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
562
+ var _Field = class {
563
+ constructor(ORDER, opts2 = {}) {
564
+ __publicField(this, "ORDER");
565
+ __publicField(this, "BITS");
566
+ __publicField(this, "BYTES");
567
+ __publicField(this, "isLE");
568
+ __publicField(this, "ZERO", _0n2);
569
+ __publicField(this, "ONE", _1n2);
570
+ __publicField(this, "_lengths");
571
+ __publicField(this, "_mod");
572
+ if (ORDER <= _1n2)
573
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
574
+ let _nbitLength = void 0;
575
+ this.isLE = false;
576
+ if (opts2 != null && typeof opts2 === "object") {
577
+ if (typeof opts2.BITS === "number")
578
+ _nbitLength = opts2.BITS;
579
+ if (typeof opts2.sqrt === "function")
580
+ Object.defineProperty(this, "sqrt", { value: opts2.sqrt, enumerable: true });
581
+ if (typeof opts2.isLE === "boolean")
582
+ this.isLE = opts2.isLE;
583
+ if (opts2.allowedLengths)
584
+ this._lengths = Object.freeze(opts2.allowedLengths.slice());
585
+ if (typeof opts2.modFromBytes === "boolean")
586
+ this._mod = opts2.modFromBytes;
587
+ }
588
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
589
+ if (nByteLength > 2048)
590
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
591
+ this.ORDER = ORDER;
592
+ this.BITS = nBitLength;
593
+ this.BYTES = nByteLength;
594
+ Object.freeze(this);
595
+ }
596
+ create(num) {
597
+ return mod(num, this.ORDER);
598
+ }
599
+ isValid(num) {
600
+ if (typeof num !== "bigint")
601
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
602
+ return _0n2 <= num && num < this.ORDER;
603
+ }
604
+ is0(num) {
605
+ return num === _0n2;
606
+ }
607
+ // is valid and invertible
608
+ isValidNot0(num) {
609
+ return !this.is0(num) && this.isValid(num);
610
+ }
611
+ isOdd(num) {
612
+ return (num & _1n2) === _1n2;
613
+ }
614
+ neg(num) {
615
+ return mod(-num, this.ORDER);
616
+ }
617
+ eql(lhs, rhs) {
618
+ return lhs === rhs;
619
+ }
620
+ sqr(num) {
621
+ return mod(num * num, this.ORDER);
622
+ }
623
+ add(lhs, rhs) {
624
+ return mod(lhs + rhs, this.ORDER);
625
+ }
626
+ sub(lhs, rhs) {
627
+ return mod(lhs - rhs, this.ORDER);
628
+ }
629
+ mul(lhs, rhs) {
630
+ return mod(lhs * rhs, this.ORDER);
631
+ }
632
+ pow(num, power) {
633
+ return FpPow(this, num, power);
634
+ }
635
+ div(lhs, rhs) {
636
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
637
+ }
638
+ // Same as above, but doesn't normalize
639
+ sqrN(num) {
640
+ return num * num;
641
+ }
642
+ addN(lhs, rhs) {
643
+ return lhs + rhs;
644
+ }
645
+ subN(lhs, rhs) {
646
+ return lhs - rhs;
647
+ }
648
+ mulN(lhs, rhs) {
649
+ return lhs * rhs;
650
+ }
651
+ inv(num) {
652
+ return invert(num, this.ORDER);
653
+ }
654
+ sqrt(num) {
655
+ let sqrt = FIELD_SQRT.get(this);
656
+ if (!sqrt)
657
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
658
+ return sqrt(this, num);
659
+ }
660
+ toBytes(num) {
661
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
662
+ }
663
+ fromBytes(bytes, skipValidation = false) {
664
+ abytes2(bytes);
665
+ const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
666
+ if (allowedLengths) {
667
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
668
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
669
+ }
670
+ const padded = new Uint8Array(BYTES);
671
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
672
+ bytes = padded;
673
+ }
674
+ if (bytes.length !== BYTES)
675
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
676
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
677
+ if (modFromBytes)
678
+ scalar = mod(scalar, ORDER);
679
+ if (!skipValidation) {
680
+ if (!this.isValid(scalar))
681
+ throw new Error("invalid field element: outside of range 0..ORDER");
682
+ }
683
+ return scalar;
684
+ }
685
+ // TODO: we don't need it here, move out to separate fn
686
+ invertBatch(lst) {
687
+ return FpInvertBatch(this, lst);
688
+ }
689
+ // We can't move this out because Fp6, Fp12 implement it
690
+ // and it's unclear what to return in there.
691
+ cmov(a, b, condition) {
692
+ abool(condition, "condition");
693
+ return condition ? b : a;
694
+ }
695
+ };
696
+ Object.freeze(_Field.prototype);
697
+ function Field(ORDER, opts2 = {}) {
698
+ return new _Field(ORDER, opts2);
699
+ }
700
+
701
+ // ../../node_modules/@noble/curves/abstract/curve.js
702
+ var _0n3 = /* @__PURE__ */ BigInt(0);
703
+ var _1n3 = /* @__PURE__ */ BigInt(1);
704
+ function negateCt(condition, item) {
705
+ const neg = item.negate();
706
+ return condition ? neg : item;
707
+ }
708
+ function normalizeZ(c, points) {
709
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
710
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
711
+ }
712
+ function validateW(W, bits) {
713
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
714
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
715
+ }
716
+ function calcWOpts(W, scalarBits) {
717
+ validateW(W, scalarBits);
718
+ const windows = Math.ceil(scalarBits / W) + 1;
719
+ const windowSize = 2 ** (W - 1);
720
+ const maxNumber = 2 ** W;
721
+ const mask = bitMask(W);
722
+ const shiftBy = BigInt(W);
723
+ return { windows, windowSize, mask, maxNumber, shiftBy };
724
+ }
725
+ function calcOffsets(n, window, wOpts) {
726
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
727
+ let wbits = Number(n & mask);
728
+ let nextN = n >> shiftBy;
729
+ if (wbits > windowSize) {
730
+ wbits -= maxNumber;
731
+ nextN += _1n3;
732
+ }
733
+ const offsetStart = window * windowSize;
734
+ const offset = offsetStart + Math.abs(wbits) - 1;
735
+ const isZero = wbits === 0;
736
+ const isNeg = wbits < 0;
737
+ const isNegF = window % 2 !== 0;
738
+ const offsetF = offsetStart;
739
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
740
+ }
741
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
742
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
743
+ function getW(P) {
744
+ return pointWindowSizes.get(P) || 1;
745
+ }
746
+ function assert0(n) {
747
+ if (n !== _0n3)
748
+ throw new Error("invalid wNAF");
749
+ }
750
+ var wNAF = class {
751
+ // Parametrized with a given Point class (not individual point)
752
+ constructor(Point, bits) {
753
+ __publicField(this, "BASE");
754
+ __publicField(this, "ZERO");
755
+ __publicField(this, "Fn");
756
+ __publicField(this, "bits");
757
+ this.BASE = Point.BASE;
758
+ this.ZERO = Point.ZERO;
759
+ this.Fn = Point.Fn;
760
+ this.bits = bits;
761
+ }
762
+ // non-const time multiplication ladder
763
+ _unsafeLadder(elm, n, p = this.ZERO) {
764
+ let d = elm;
765
+ while (n > _0n3) {
766
+ if (n & _1n3)
767
+ p = p.add(d);
768
+ d = d.double();
769
+ n >>= _1n3;
770
+ }
771
+ return p;
772
+ }
773
+ /**
774
+ * Creates a wNAF precomputation window. Used for caching.
775
+ * Default window size is set by `utils.precompute()` and is equal to 8.
776
+ * Number of precomputed points depends on the curve size:
777
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
778
+ * - 𝑊 is the window size
779
+ * - 𝑛 is the bitlength of the curve order.
780
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
781
+ * @param point - Point instance
782
+ * @param W - window size
783
+ * @returns precomputed point tables flattened to a single array
784
+ */
785
+ precomputeWindow(point, W) {
786
+ const { windows, windowSize } = calcWOpts(W, this.bits);
787
+ const points = [];
788
+ let p = point;
789
+ let base = p;
790
+ for (let window = 0; window < windows; window++) {
791
+ base = p;
792
+ points.push(base);
793
+ for (let i = 1; i < windowSize; i++) {
794
+ base = base.add(p);
795
+ points.push(base);
796
+ }
797
+ p = base.double();
798
+ }
799
+ return points;
800
+ }
801
+ /**
802
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
803
+ * More compact implementation:
804
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
805
+ * @returns real and fake (for const-time) points
806
+ */
807
+ wNAF(W, precomputes, n) {
808
+ if (!this.Fn.isValid(n))
809
+ throw new Error("invalid scalar");
810
+ let p = this.ZERO;
811
+ let f = this.BASE;
812
+ const wo = calcWOpts(W, this.bits);
813
+ for (let window = 0; window < wo.windows; window++) {
814
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
815
+ n = nextN;
816
+ if (isZero) {
817
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
818
+ } else {
819
+ p = p.add(negateCt(isNeg, precomputes[offset]));
820
+ }
821
+ }
822
+ assert0(n);
823
+ return { p, f };
824
+ }
825
+ /**
826
+ * Implements unsafe EC multiplication using precomputed tables
827
+ * and w-ary non-adjacent form.
828
+ * @param acc - accumulator point to add result of multiplication
829
+ * @returns point
830
+ */
831
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
832
+ const wo = calcWOpts(W, this.bits);
833
+ for (let window = 0; window < wo.windows; window++) {
834
+ if (n === _0n3)
835
+ break;
836
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
837
+ n = nextN;
838
+ if (isZero) {
839
+ continue;
840
+ } else {
841
+ const item = precomputes[offset];
842
+ acc = acc.add(isNeg ? item.negate() : item);
843
+ }
844
+ }
845
+ assert0(n);
846
+ return acc;
847
+ }
848
+ getPrecomputes(W, point, transform) {
849
+ let comp = pointPrecomputes.get(point);
850
+ if (!comp) {
851
+ comp = this.precomputeWindow(point, W);
852
+ if (W !== 1) {
853
+ if (typeof transform === "function")
854
+ comp = transform(comp);
855
+ pointPrecomputes.set(point, comp);
856
+ }
857
+ }
858
+ return comp;
859
+ }
860
+ cached(point, scalar, transform) {
861
+ const W = getW(point);
862
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
863
+ }
864
+ unsafe(point, scalar, transform, prev) {
865
+ const W = getW(point);
866
+ if (W === 1)
867
+ return this._unsafeLadder(point, scalar, prev);
868
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
869
+ }
870
+ // We calculate precomputes for elliptic curve point multiplication
871
+ // using windowed method. This specifies window size and
872
+ // stores precomputed values. Usually only base point would be precomputed.
873
+ createCache(P, W) {
874
+ validateW(W, this.bits);
875
+ pointWindowSizes.set(P, W);
876
+ pointPrecomputes.delete(P);
877
+ }
878
+ hasCache(elm) {
879
+ return getW(elm) !== 1;
880
+ }
881
+ };
882
+ function createField(order, field, isLE2) {
883
+ if (field) {
884
+ if (field.ORDER !== order)
885
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
886
+ validateField(field);
887
+ return field;
888
+ } else {
889
+ return Field(order, { isLE: isLE2 });
890
+ }
891
+ }
892
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
893
+ if (FpFnLE === void 0)
894
+ FpFnLE = type === "edwards";
895
+ if (!CURVE || typeof CURVE !== "object")
896
+ throw new Error(`expected valid ${type} CURVE object`);
897
+ for (const p of ["p", "n", "h"]) {
898
+ const val = CURVE[p];
899
+ if (!(typeof val === "bigint" && val > _0n3))
900
+ throw new Error(`CURVE.${p} must be positive bigint`);
901
+ }
902
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
903
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
904
+ const _b = type === "weierstrass" ? "b" : "d";
905
+ const params = ["Gx", "Gy", "a", _b];
906
+ for (const p of params) {
907
+ if (!Fp2.isValid(CURVE[p]))
908
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
909
+ }
910
+ CURVE = Object.freeze(Object.assign({}, CURVE));
911
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
912
+ }
913
+ function createKeygen(randomSecretKey, getPublicKey) {
914
+ return function keygen(seed) {
915
+ const secretKey = randomSecretKey(seed);
916
+ return { secretKey, publicKey: getPublicKey(secretKey) };
917
+ };
918
+ }
919
+
920
+ // ../../node_modules/@noble/curves/abstract/edwards.js
921
+ var _0n4 = /* @__PURE__ */ BigInt(0);
922
+ var _1n4 = /* @__PURE__ */ BigInt(1);
923
+ var _2n2 = /* @__PURE__ */ BigInt(2);
924
+ var _8n2 = /* @__PURE__ */ BigInt(8);
925
+ function isEdValidXY(Fp2, CURVE, x, y) {
926
+ const x2 = Fp2.sqr(x);
927
+ const y2 = Fp2.sqr(y);
928
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
929
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
930
+ return Fp2.eql(left, right);
931
+ }
932
+ function edwards(params, extraOpts = {}) {
933
+ const opts2 = extraOpts;
934
+ const validated = createCurveFields("edwards", params, opts2, opts2.FpFnLE);
935
+ const { Fp: Fp2, Fn: Fn2 } = validated;
936
+ let CURVE = validated.CURVE;
937
+ const { h: cofactor } = CURVE;
938
+ validateObject(opts2, {}, { uvRatio: "function" });
939
+ const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
940
+ const modP = (n) => Fp2.create(n);
941
+ const uvRatio2 = opts2.uvRatio === void 0 ? (u, v) => {
942
+ try {
943
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
944
+ } catch (e) {
945
+ return { isValid: false, value: _0n4 };
946
+ }
947
+ } : opts2.uvRatio;
948
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
949
+ throw new Error("bad curve params: generator point");
950
+ function acoord(title, n, banZero = false) {
951
+ const min = banZero ? _1n4 : _0n4;
952
+ aInRange("coordinate " + title, n, min, MASK);
953
+ return n;
954
+ }
955
+ function aedpoint(other) {
956
+ if (!(other instanceof Point))
957
+ throw new Error("EdwardsPoint expected");
958
+ }
959
+ const _Point = class _Point {
960
+ constructor(X, Y, Z, T) {
961
+ __publicField(this, "X");
962
+ __publicField(this, "Y");
963
+ __publicField(this, "Z");
964
+ __publicField(this, "T");
965
+ this.X = acoord("x", X);
966
+ this.Y = acoord("y", Y);
967
+ this.Z = acoord("z", Z, true);
968
+ this.T = acoord("t", T);
969
+ Object.freeze(this);
970
+ }
971
+ static CURVE() {
972
+ return CURVE;
973
+ }
974
+ /**
975
+ * Create one extended Edwards point from affine coordinates.
976
+ * Does NOT validate that the point is on-curve or torsion-free.
977
+ * Use `.assertValidity()` on adversarial inputs.
978
+ */
979
+ static fromAffine(p) {
980
+ if (p instanceof _Point)
981
+ throw new Error("extended point not allowed");
982
+ const { x, y } = p || {};
983
+ acoord("x", x);
984
+ acoord("y", y);
985
+ return new _Point(x, y, _1n4, modP(x * y));
986
+ }
987
+ // Uses algo from RFC8032 5.1.3.
988
+ static fromBytes(bytes, zip215 = false) {
989
+ const len = Fp2.BYTES;
990
+ const { a, d } = CURVE;
991
+ bytes = copyBytes(abytes2(bytes, len, "point"));
992
+ abool(zip215, "zip215");
993
+ const normed = copyBytes(bytes);
994
+ const lastByte = bytes[len - 1];
995
+ normed[len - 1] = lastByte & ~128;
996
+ const y = bytesToNumberLE(normed);
997
+ const max = zip215 ? MASK : Fp2.ORDER;
998
+ aInRange("point.y", y, _0n4, max);
999
+ const y2 = modP(y * y);
1000
+ const u = modP(y2 - _1n4);
1001
+ const v = modP(d * y2 - a);
1002
+ let { isValid, value: x } = uvRatio2(u, v);
1003
+ if (!isValid)
1004
+ throw new Error("bad point: invalid y coordinate");
1005
+ const isXOdd = (x & _1n4) === _1n4;
1006
+ const isLastByteOdd = (lastByte & 128) !== 0;
1007
+ if (!zip215 && x === _0n4 && isLastByteOdd)
1008
+ throw new Error("bad point: x=0 and x_0=1");
1009
+ if (isLastByteOdd !== isXOdd)
1010
+ x = modP(-x);
1011
+ return _Point.fromAffine({ x, y });
1012
+ }
1013
+ static fromHex(hex, zip215 = false) {
1014
+ return _Point.fromBytes(hexToBytes2(hex), zip215);
1015
+ }
1016
+ get x() {
1017
+ return this.toAffine().x;
1018
+ }
1019
+ get y() {
1020
+ return this.toAffine().y;
1021
+ }
1022
+ precompute(windowSize = 8, isLazy = true) {
1023
+ wnaf.createCache(this, windowSize);
1024
+ if (!isLazy)
1025
+ this.multiply(_2n2);
1026
+ return this;
1027
+ }
1028
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
1029
+ assertValidity() {
1030
+ const p = this;
1031
+ const { a, d } = CURVE;
1032
+ if (p.is0())
1033
+ throw new Error("bad point: ZERO");
1034
+ const { X, Y, Z, T } = p;
1035
+ const X2 = modP(X * X);
1036
+ const Y2 = modP(Y * Y);
1037
+ const Z2 = modP(Z * Z);
1038
+ const Z4 = modP(Z2 * Z2);
1039
+ const aX2 = modP(X2 * a);
1040
+ const left = modP(Z2 * modP(aX2 + Y2));
1041
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1042
+ if (left !== right)
1043
+ throw new Error("bad point: equation left != right (1)");
1044
+ const XY = modP(X * Y);
1045
+ const ZT = modP(Z * T);
1046
+ if (XY !== ZT)
1047
+ throw new Error("bad point: equation left != right (2)");
1048
+ }
1049
+ // Compare one point to another.
1050
+ equals(other) {
1051
+ aedpoint(other);
1052
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1053
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1054
+ const X1Z2 = modP(X1 * Z2);
1055
+ const X2Z1 = modP(X2 * Z1);
1056
+ const Y1Z2 = modP(Y1 * Z2);
1057
+ const Y2Z1 = modP(Y2 * Z1);
1058
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1059
+ }
1060
+ is0() {
1061
+ return this.equals(_Point.ZERO);
1062
+ }
1063
+ negate() {
1064
+ return new _Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1065
+ }
1066
+ // Fast algo for doubling Extended Point.
1067
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1068
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1069
+ double() {
1070
+ const { a } = CURVE;
1071
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1072
+ const A = modP(X1 * X1);
1073
+ const B = modP(Y1 * Y1);
1074
+ const C = modP(_2n2 * modP(Z1 * Z1));
1075
+ const D = modP(a * A);
1076
+ const x1y1 = X1 + Y1;
1077
+ const E = modP(modP(x1y1 * x1y1) - A - B);
1078
+ const G = D + B;
1079
+ const F2 = G - C;
1080
+ const H = D - B;
1081
+ const X3 = modP(E * F2);
1082
+ const Y3 = modP(G * H);
1083
+ const T3 = modP(E * H);
1084
+ const Z3 = modP(F2 * G);
1085
+ return new _Point(X3, Y3, Z3, T3);
1086
+ }
1087
+ // Fast algo for adding 2 Extended Points.
1088
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1089
+ // Cost: 9M + 1*a + 1*d + 7add.
1090
+ add(other) {
1091
+ aedpoint(other);
1092
+ const { a, d } = CURVE;
1093
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1094
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1095
+ const A = modP(X1 * X2);
1096
+ const B = modP(Y1 * Y2);
1097
+ const C = modP(T1 * d * T2);
1098
+ const D = modP(Z1 * Z2);
1099
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1100
+ const F2 = D - C;
1101
+ const G = D + C;
1102
+ const H = modP(B - a * A);
1103
+ const X3 = modP(E * F2);
1104
+ const Y3 = modP(G * H);
1105
+ const T3 = modP(E * H);
1106
+ const Z3 = modP(F2 * G);
1107
+ return new _Point(X3, Y3, Z3, T3);
1108
+ }
1109
+ subtract(other) {
1110
+ aedpoint(other);
1111
+ return this.add(other.negate());
1112
+ }
1113
+ // Constant-time multiplication.
1114
+ multiply(scalar) {
1115
+ if (!Fn2.isValidNot0(scalar))
1116
+ throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
1117
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(_Point, p2));
1118
+ return normalizeZ(_Point, [p, f])[0];
1119
+ }
1120
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1121
+ // It's faster, but should only be used when you don't care about
1122
+ // an exposed private key e.g. sig verification.
1123
+ // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
1124
+ // n and larger values are rejected instead of being reduced mod n to the identity point.
1125
+ multiplyUnsafe(scalar) {
1126
+ if (!Fn2.isValid(scalar))
1127
+ throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
1128
+ if (scalar === _0n4)
1129
+ return _Point.ZERO;
1130
+ if (this.is0() || scalar === _1n4)
1131
+ return this;
1132
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(_Point, p));
1133
+ }
1134
+ // Checks if point is of small order.
1135
+ // If you add something to small order point, you will have "dirty"
1136
+ // point with torsion component.
1137
+ // Clears cofactor and checks if the result is 0.
1138
+ isSmallOrder() {
1139
+ return this.clearCofactor().is0();
1140
+ }
1141
+ // Multiplies point by curve order and checks if the result is 0.
1142
+ // Returns `false` is the point is dirty.
1143
+ isTorsionFree() {
1144
+ return wnaf.unsafe(this, CURVE.n).is0();
1145
+ }
1146
+ // Converts Extended point to default (x, y) coordinates.
1147
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1148
+ toAffine(invertedZ) {
1149
+ const p = this;
1150
+ let iz = invertedZ;
1151
+ const { X, Y, Z } = p;
1152
+ const is0 = p.is0();
1153
+ if (iz == null)
1154
+ iz = is0 ? _8n2 : Fp2.inv(Z);
1155
+ const x = modP(X * iz);
1156
+ const y = modP(Y * iz);
1157
+ const zz = Fp2.mul(Z, iz);
1158
+ if (is0)
1159
+ return { x: _0n4, y: _1n4 };
1160
+ if (zz !== _1n4)
1161
+ throw new Error("invZ was invalid");
1162
+ return { x, y };
1163
+ }
1164
+ clearCofactor() {
1165
+ if (cofactor === _1n4)
1166
+ return this;
1167
+ return this.multiplyUnsafe(cofactor);
1168
+ }
1169
+ toBytes() {
1170
+ const { x, y } = this.toAffine();
1171
+ const bytes = Fp2.toBytes(y);
1172
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1173
+ return bytes;
1174
+ }
1175
+ toHex() {
1176
+ return bytesToHex2(this.toBytes());
1177
+ }
1178
+ toString() {
1179
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1180
+ }
1181
+ };
1182
+ // base / generator point
1183
+ __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy)));
1184
+ // zero / infinity / identity point
1185
+ __publicField(_Point, "ZERO", new _Point(_0n4, _1n4, _1n4, _0n4));
1186
+ // 0, 1, 1, 0
1187
+ // math field
1188
+ __publicField(_Point, "Fp", Fp2);
1189
+ // scalar field
1190
+ __publicField(_Point, "Fn", Fn2);
1191
+ let Point = _Point;
1192
+ const wnaf = new wNAF(Point, Fn2.BITS);
1193
+ if (Fn2.BITS >= 8)
1194
+ Point.BASE.precompute(8);
1195
+ Object.freeze(Point.prototype);
1196
+ Object.freeze(Point);
1197
+ return Point;
1198
+ }
1199
+ var PrimeEdwardsPoint = class {
1200
+ /**
1201
+ * Wrap one internal Edwards representative directly.
1202
+ * This is not a canonical encoding boundary: alternate Edwards
1203
+ * representatives may still describe the same abstract wrapper element.
1204
+ */
1205
+ constructor(ep) {
1206
+ __publicField(this, "ep");
1207
+ this.ep = ep;
1208
+ }
1209
+ // Static methods that must be implemented by subclasses
1210
+ static fromBytes(_bytes) {
1211
+ notImplemented();
1212
+ }
1213
+ static fromHex(_hex) {
1214
+ notImplemented();
1215
+ }
1216
+ get x() {
1217
+ return this.toAffine().x;
1218
+ }
1219
+ get y() {
1220
+ return this.toAffine().y;
1221
+ }
1222
+ // Common implementations
1223
+ clearCofactor() {
1224
+ return this;
1225
+ }
1226
+ assertValidity() {
1227
+ this.ep.assertValidity();
1228
+ }
1229
+ /**
1230
+ * Return affine coordinates of the current internal Edwards representative.
1231
+ * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
1232
+ * Equal abstract elements may expose different `x` / `y`; use
1233
+ * `toBytes()` / `fromBytes()` for canonical roundtrips.
1234
+ */
1235
+ toAffine(invertedZ) {
1236
+ return this.ep.toAffine(invertedZ);
1237
+ }
1238
+ toHex() {
1239
+ return bytesToHex2(this.toBytes());
1240
+ }
1241
+ toString() {
1242
+ return this.toHex();
1243
+ }
1244
+ isTorsionFree() {
1245
+ return true;
1246
+ }
1247
+ isSmallOrder() {
1248
+ return false;
1249
+ }
1250
+ add(other) {
1251
+ this.assertSame(other);
1252
+ return this.init(this.ep.add(other.ep));
1253
+ }
1254
+ subtract(other) {
1255
+ this.assertSame(other);
1256
+ return this.init(this.ep.subtract(other.ep));
1257
+ }
1258
+ multiply(scalar) {
1259
+ return this.init(this.ep.multiply(scalar));
1260
+ }
1261
+ multiplyUnsafe(scalar) {
1262
+ return this.init(this.ep.multiplyUnsafe(scalar));
1263
+ }
1264
+ double() {
1265
+ return this.init(this.ep.double());
1266
+ }
1267
+ negate() {
1268
+ return this.init(this.ep.negate());
1269
+ }
1270
+ precompute(windowSize, isLazy) {
1271
+ this.ep.precompute(windowSize, isLazy);
1272
+ return this;
1273
+ }
1274
+ };
1275
+ __publicField(PrimeEdwardsPoint, "BASE");
1276
+ __publicField(PrimeEdwardsPoint, "ZERO");
1277
+ __publicField(PrimeEdwardsPoint, "Fp");
1278
+ __publicField(PrimeEdwardsPoint, "Fn");
1279
+
1280
+ // ../../node_modules/@noble/curves/abstract/montgomery.js
1281
+ var _0n5 = BigInt(0);
1282
+ var _1n5 = BigInt(1);
1283
+ var _2n3 = BigInt(2);
1284
+ function validateOpts(curve) {
1285
+ validateObject(curve, {
1286
+ P: "bigint",
1287
+ type: "string",
1288
+ adjustScalarBytes: "function",
1289
+ powPminus2: "function"
1290
+ }, {
1291
+ randomBytes: "function"
1292
+ });
1293
+ return Object.freeze({ ...curve });
1294
+ }
1295
+ function montgomery(curveDef) {
1296
+ const CURVE = validateOpts(curveDef);
1297
+ const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
1298
+ const is25519 = type === "x25519";
1299
+ if (!is25519 && type !== "x448")
1300
+ throw new Error("invalid type");
1301
+ const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
1302
+ const montgomeryBits = is25519 ? 255 : 448;
1303
+ const fieldLen = is25519 ? 32 : 56;
1304
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
1305
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
1306
+ const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
1307
+ const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
1308
+ const maxScalar = minScalar + maxAdded + _1n5;
1309
+ const modP = (n) => mod(n, P);
1310
+ const GuBytes = encodeU(Gu);
1311
+ function encodeU(u) {
1312
+ return numberToBytesLE(modP(u), fieldLen);
1313
+ }
1314
+ function decodeU(u) {
1315
+ const _u = copyBytes(abytes2(u, fieldLen, "uCoordinate"));
1316
+ if (is25519)
1317
+ _u[31] &= 127;
1318
+ return modP(bytesToNumberLE(_u));
1319
+ }
1320
+ function decodeScalar(scalar) {
1321
+ return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
1322
+ }
1323
+ function scalarMult(scalar, u) {
1324
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
1325
+ if (pu === _0n5)
1326
+ throw new Error("invalid private or public key received");
1327
+ return encodeU(pu);
1328
+ }
1329
+ function scalarMultBase(scalar) {
1330
+ return scalarMult(scalar, GuBytes);
1331
+ }
1332
+ const getPublicKey = scalarMultBase;
1333
+ const getSharedSecret = scalarMult;
1334
+ function cswap(swap, x_2, x_3) {
1335
+ const dummy = modP(swap * (x_2 - x_3));
1336
+ x_2 = modP(x_2 - dummy);
1337
+ x_3 = modP(x_3 + dummy);
1338
+ return { x_2, x_3 };
1339
+ }
1340
+ function montgomeryLadder(u, scalar) {
1341
+ aInRange("u", u, _0n5, P);
1342
+ aInRange("scalar", scalar, minScalar, maxScalar);
1343
+ const k = scalar;
1344
+ const x_1 = u;
1345
+ let x_2 = _1n5;
1346
+ let z_2 = _0n5;
1347
+ let x_3 = u;
1348
+ let z_3 = _1n5;
1349
+ let swap = _0n5;
1350
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
1351
+ const k_t = k >> t & _1n5;
1352
+ swap ^= k_t;
1353
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1354
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1355
+ swap = k_t;
1356
+ const A = x_2 + z_2;
1357
+ const AA = modP(A * A);
1358
+ const B = x_2 - z_2;
1359
+ const BB = modP(B * B);
1360
+ const E = AA - BB;
1361
+ const C = x_3 + z_3;
1362
+ const D = x_3 - z_3;
1363
+ const DA = modP(D * A);
1364
+ const CB = modP(C * B);
1365
+ const dacb = DA + CB;
1366
+ const da_cb = DA - CB;
1367
+ x_3 = modP(dacb * dacb);
1368
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
1369
+ x_2 = modP(AA * BB);
1370
+ z_2 = modP(E * (AA + modP(a24 * E)));
1371
+ }
1372
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
1373
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
1374
+ const z2 = powPminus2(z_2);
1375
+ return modP(x_2 * z2);
1376
+ }
1377
+ const lengths = {
1378
+ secretKey: fieldLen,
1379
+ publicKey: fieldLen,
1380
+ seed: fieldLen
1381
+ };
1382
+ const randomSecretKey = (seed) => {
1383
+ seed = seed === void 0 ? randomBytes_(fieldLen) : seed;
1384
+ abytes2(seed, lengths.seed, "seed");
1385
+ return seed;
1386
+ };
1387
+ const utils = { randomSecretKey };
1388
+ Object.freeze(lengths);
1389
+ Object.freeze(utils);
1390
+ return Object.freeze({
1391
+ keygen: createKeygen(randomSecretKey, getPublicKey),
1392
+ getSharedSecret,
1393
+ getPublicKey,
1394
+ scalarMult,
1395
+ scalarMultBase,
1396
+ utils,
1397
+ GuBytes: GuBytes.slice(),
1398
+ lengths
1399
+ });
1400
+ }
1401
+
1402
+ // ../../node_modules/@noble/hashes/_md.js
1403
+ var HashMD = class {
1404
+ constructor(blockLen, outputLen, padOffset, isLE2) {
1405
+ __publicField(this, "blockLen");
1406
+ __publicField(this, "outputLen");
1407
+ __publicField(this, "canXOF", false);
1408
+ __publicField(this, "padOffset");
1409
+ __publicField(this, "isLE");
1410
+ // For partial updates less than block size
1411
+ __publicField(this, "buffer");
1412
+ __publicField(this, "view");
1413
+ __publicField(this, "finished", false);
1414
+ __publicField(this, "length", 0);
1415
+ __publicField(this, "pos", 0);
1416
+ __publicField(this, "destroyed", false);
1417
+ this.blockLen = blockLen;
1418
+ this.outputLen = outputLen;
1419
+ this.padOffset = padOffset;
1420
+ this.isLE = isLE2;
1421
+ this.buffer = new Uint8Array(blockLen);
1422
+ this.view = createView(this.buffer);
1423
+ }
1424
+ update(data) {
1425
+ aexists(this);
1426
+ abytes(data);
1427
+ const { view, buffer, blockLen } = this;
1428
+ const len = data.length;
1429
+ for (let pos = 0; pos < len; ) {
1430
+ const take = Math.min(blockLen - this.pos, len - pos);
1431
+ if (take === blockLen) {
1432
+ const dataView = createView(data);
1433
+ for (; blockLen <= len - pos; pos += blockLen)
1434
+ this.process(dataView, pos);
1435
+ continue;
1436
+ }
1437
+ buffer.set(data.subarray(pos, pos + take), this.pos);
1438
+ this.pos += take;
1439
+ pos += take;
1440
+ if (this.pos === blockLen) {
1441
+ this.process(view, 0);
1442
+ this.pos = 0;
1443
+ }
1444
+ }
1445
+ this.length += data.length;
1446
+ this.roundClean();
1447
+ return this;
1448
+ }
1449
+ digestInto(out) {
1450
+ aexists(this);
1451
+ aoutput(out, this);
1452
+ this.finished = true;
1453
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
1454
+ let { pos } = this;
1455
+ buffer[pos++] = 128;
1456
+ clean(this.buffer.subarray(pos));
1457
+ if (this.padOffset > blockLen - pos) {
1458
+ this.process(view, 0);
1459
+ pos = 0;
1460
+ }
1461
+ for (let i = pos; i < blockLen; i++)
1462
+ buffer[i] = 0;
1463
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
1464
+ this.process(view, 0);
1465
+ const oview = createView(out);
1466
+ const len = this.outputLen;
1467
+ if (len % 4)
1468
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
1469
+ const outLen = len / 4;
1470
+ const state = this.get();
1471
+ if (outLen > state.length)
1472
+ throw new Error("_sha2: outputLen bigger than state");
1473
+ for (let i = 0; i < outLen; i++)
1474
+ oview.setUint32(4 * i, state[i], isLE2);
1475
+ }
1476
+ digest() {
1477
+ const { buffer, outputLen } = this;
1478
+ this.digestInto(buffer);
1479
+ const res = buffer.slice(0, outputLen);
1480
+ this.destroy();
1481
+ return res;
1482
+ }
1483
+ _cloneInto(to) {
1484
+ to || (to = new this.constructor());
1485
+ to.set(...this.get());
1486
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
1487
+ to.destroyed = destroyed;
1488
+ to.finished = finished;
1489
+ to.length = length;
1490
+ to.pos = pos;
1491
+ if (length % blockLen)
1492
+ to.buffer.set(buffer);
1493
+ return to;
1494
+ }
1495
+ clone() {
1496
+ return this._cloneInto();
1497
+ }
1498
+ };
1499
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1500
+ 1779033703,
1501
+ 4089235720,
1502
+ 3144134277,
1503
+ 2227873595,
1504
+ 1013904242,
1505
+ 4271175723,
1506
+ 2773480762,
1507
+ 1595750129,
1508
+ 1359893119,
1509
+ 2917565137,
1510
+ 2600822924,
1511
+ 725511199,
1512
+ 528734635,
1513
+ 4215389547,
1514
+ 1541459225,
1515
+ 327033209
1516
+ ]);
1517
+
1518
+ // ../../node_modules/@noble/hashes/_u64.js
1519
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1520
+ var _32n = /* @__PURE__ */ BigInt(32);
1521
+ function fromBig(n, le = false) {
1522
+ if (le)
1523
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
1524
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1525
+ }
1526
+ function split(lst, le = false) {
1527
+ const len = lst.length;
1528
+ let Ah = new Uint32Array(len);
1529
+ let Al = new Uint32Array(len);
1530
+ for (let i = 0; i < len; i++) {
1531
+ const { h, l } = fromBig(lst[i], le);
1532
+ [Ah[i], Al[i]] = [h, l];
1533
+ }
1534
+ return [Ah, Al];
1535
+ }
1536
+ var shrSH = (h, _l, s) => h >>> s;
1537
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
1538
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1539
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1540
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1541
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1542
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
1543
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
1544
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
1545
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
1546
+ function add(Ah, Al, Bh, Bl) {
1547
+ const l = (Al >>> 0) + (Bl >>> 0);
1548
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1549
+ }
1550
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1551
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1552
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1553
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1554
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1555
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1556
+
1557
+ // ../../node_modules/@noble/hashes/sha2.js
1558
+ var K512 = /* @__PURE__ */ (() => split([
1559
+ "0x428a2f98d728ae22",
1560
+ "0x7137449123ef65cd",
1561
+ "0xb5c0fbcfec4d3b2f",
1562
+ "0xe9b5dba58189dbbc",
1563
+ "0x3956c25bf348b538",
1564
+ "0x59f111f1b605d019",
1565
+ "0x923f82a4af194f9b",
1566
+ "0xab1c5ed5da6d8118",
1567
+ "0xd807aa98a3030242",
1568
+ "0x12835b0145706fbe",
1569
+ "0x243185be4ee4b28c",
1570
+ "0x550c7dc3d5ffb4e2",
1571
+ "0x72be5d74f27b896f",
1572
+ "0x80deb1fe3b1696b1",
1573
+ "0x9bdc06a725c71235",
1574
+ "0xc19bf174cf692694",
1575
+ "0xe49b69c19ef14ad2",
1576
+ "0xefbe4786384f25e3",
1577
+ "0x0fc19dc68b8cd5b5",
1578
+ "0x240ca1cc77ac9c65",
1579
+ "0x2de92c6f592b0275",
1580
+ "0x4a7484aa6ea6e483",
1581
+ "0x5cb0a9dcbd41fbd4",
1582
+ "0x76f988da831153b5",
1583
+ "0x983e5152ee66dfab",
1584
+ "0xa831c66d2db43210",
1585
+ "0xb00327c898fb213f",
1586
+ "0xbf597fc7beef0ee4",
1587
+ "0xc6e00bf33da88fc2",
1588
+ "0xd5a79147930aa725",
1589
+ "0x06ca6351e003826f",
1590
+ "0x142929670a0e6e70",
1591
+ "0x27b70a8546d22ffc",
1592
+ "0x2e1b21385c26c926",
1593
+ "0x4d2c6dfc5ac42aed",
1594
+ "0x53380d139d95b3df",
1595
+ "0x650a73548baf63de",
1596
+ "0x766a0abb3c77b2a8",
1597
+ "0x81c2c92e47edaee6",
1598
+ "0x92722c851482353b",
1599
+ "0xa2bfe8a14cf10364",
1600
+ "0xa81a664bbc423001",
1601
+ "0xc24b8b70d0f89791",
1602
+ "0xc76c51a30654be30",
1603
+ "0xd192e819d6ef5218",
1604
+ "0xd69906245565a910",
1605
+ "0xf40e35855771202a",
1606
+ "0x106aa07032bbd1b8",
1607
+ "0x19a4c116b8d2d0c8",
1608
+ "0x1e376c085141ab53",
1609
+ "0x2748774cdf8eeb99",
1610
+ "0x34b0bcb5e19b48a8",
1611
+ "0x391c0cb3c5c95a63",
1612
+ "0x4ed8aa4ae3418acb",
1613
+ "0x5b9cca4f7763e373",
1614
+ "0x682e6ff3d6b2b8a3",
1615
+ "0x748f82ee5defb2fc",
1616
+ "0x78a5636f43172f60",
1617
+ "0x84c87814a1f0ab72",
1618
+ "0x8cc702081a6439ec",
1619
+ "0x90befffa23631e28",
1620
+ "0xa4506cebde82bde9",
1621
+ "0xbef9a3f7b2c67915",
1622
+ "0xc67178f2e372532b",
1623
+ "0xca273eceea26619c",
1624
+ "0xd186b8c721c0c207",
1625
+ "0xeada7dd6cde0eb1e",
1626
+ "0xf57d4f7fee6ed178",
1627
+ "0x06f067aa72176fba",
1628
+ "0x0a637dc5a2c898a6",
1629
+ "0x113f9804bef90dae",
1630
+ "0x1b710b35131c471b",
1631
+ "0x28db77f523047d84",
1632
+ "0x32caab7b40c72493",
1633
+ "0x3c9ebe0a15c9bebc",
1634
+ "0x431d67c49c100d4c",
1635
+ "0x4cc5d4becb3e42b6",
1636
+ "0x597f299cfc657e2a",
1637
+ "0x5fcb6fab3ad6faec",
1638
+ "0x6c44198c4a475817"
1639
+ ].map((n) => BigInt(n))))();
1640
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1641
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1642
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1643
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1644
+ var SHA2_64B = class extends HashMD {
1645
+ constructor(outputLen) {
1646
+ super(128, outputLen, 16, false);
1647
+ }
1648
+ // prettier-ignore
1649
+ get() {
1650
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1651
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1652
+ }
1653
+ // prettier-ignore
1654
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1655
+ this.Ah = Ah | 0;
1656
+ this.Al = Al | 0;
1657
+ this.Bh = Bh | 0;
1658
+ this.Bl = Bl | 0;
1659
+ this.Ch = Ch | 0;
1660
+ this.Cl = Cl | 0;
1661
+ this.Dh = Dh | 0;
1662
+ this.Dl = Dl | 0;
1663
+ this.Eh = Eh | 0;
1664
+ this.El = El | 0;
1665
+ this.Fh = Fh | 0;
1666
+ this.Fl = Fl | 0;
1667
+ this.Gh = Gh | 0;
1668
+ this.Gl = Gl | 0;
1669
+ this.Hh = Hh | 0;
1670
+ this.Hl = Hl | 0;
1671
+ }
1672
+ process(view, offset) {
1673
+ for (let i = 0; i < 16; i++, offset += 4) {
1674
+ SHA512_W_H[i] = view.getUint32(offset);
1675
+ SHA512_W_L[i] = view.getUint32(offset += 4);
1676
+ }
1677
+ for (let i = 16; i < 80; i++) {
1678
+ const W15h = SHA512_W_H[i - 15] | 0;
1679
+ const W15l = SHA512_W_L[i - 15] | 0;
1680
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1681
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1682
+ const W2h = SHA512_W_H[i - 2] | 0;
1683
+ const W2l = SHA512_W_L[i - 2] | 0;
1684
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1685
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1686
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1687
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1688
+ SHA512_W_H[i] = SUMh | 0;
1689
+ SHA512_W_L[i] = SUMl | 0;
1690
+ }
1691
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1692
+ for (let i = 0; i < 80; i++) {
1693
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1694
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1695
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
1696
+ const CHIl = El & Fl ^ ~El & Gl;
1697
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1698
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1699
+ const T1l = T1ll | 0;
1700
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1701
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1702
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1703
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1704
+ Hh = Gh | 0;
1705
+ Hl = Gl | 0;
1706
+ Gh = Fh | 0;
1707
+ Gl = Fl | 0;
1708
+ Fh = Eh | 0;
1709
+ Fl = El | 0;
1710
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1711
+ Dh = Ch | 0;
1712
+ Dl = Cl | 0;
1713
+ Ch = Bh | 0;
1714
+ Cl = Bl | 0;
1715
+ Bh = Ah | 0;
1716
+ Bl = Al | 0;
1717
+ const All = add3L(T1l, sigma0l, MAJl);
1718
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1719
+ Al = All | 0;
1720
+ }
1721
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1722
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1723
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1724
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1725
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1726
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1727
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1728
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1729
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1730
+ }
1731
+ roundClean() {
1732
+ clean(SHA512_W_H, SHA512_W_L);
1733
+ }
1734
+ destroy() {
1735
+ this.destroyed = true;
1736
+ clean(this.buffer);
1737
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1738
+ }
1739
+ };
1740
+ var _SHA512 = class extends SHA2_64B {
1741
+ constructor() {
1742
+ super(64);
1743
+ __publicField(this, "Ah", SHA512_IV[0] | 0);
1744
+ __publicField(this, "Al", SHA512_IV[1] | 0);
1745
+ __publicField(this, "Bh", SHA512_IV[2] | 0);
1746
+ __publicField(this, "Bl", SHA512_IV[3] | 0);
1747
+ __publicField(this, "Ch", SHA512_IV[4] | 0);
1748
+ __publicField(this, "Cl", SHA512_IV[5] | 0);
1749
+ __publicField(this, "Dh", SHA512_IV[6] | 0);
1750
+ __publicField(this, "Dl", SHA512_IV[7] | 0);
1751
+ __publicField(this, "Eh", SHA512_IV[8] | 0);
1752
+ __publicField(this, "El", SHA512_IV[9] | 0);
1753
+ __publicField(this, "Fh", SHA512_IV[10] | 0);
1754
+ __publicField(this, "Fl", SHA512_IV[11] | 0);
1755
+ __publicField(this, "Gh", SHA512_IV[12] | 0);
1756
+ __publicField(this, "Gl", SHA512_IV[13] | 0);
1757
+ __publicField(this, "Hh", SHA512_IV[14] | 0);
1758
+ __publicField(this, "Hl", SHA512_IV[15] | 0);
1759
+ }
1760
+ };
1761
+ var sha512 = /* @__PURE__ */ createHasher(
1762
+ () => new _SHA512(),
1763
+ /* @__PURE__ */ oidNist(3)
1764
+ );
1765
+
1766
+ // ../../node_modules/@noble/curves/abstract/fft.js
1767
+ function checkU32(n) {
1768
+ if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
1769
+ throw new Error("wrong u32 integer:" + n);
1770
+ return n;
1771
+ }
1772
+ function isPowerOfTwo(x) {
1773
+ checkU32(x);
1774
+ return (x & x - 1) === 0 && x !== 0;
1775
+ }
1776
+ function reverseBits(n, bits) {
1777
+ checkU32(n);
1778
+ if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
1779
+ throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
1780
+ let reversed = 0;
1781
+ for (let i = 0; i < bits; i++, n >>>= 1)
1782
+ reversed = reversed << 1 | n & 1;
1783
+ return reversed >>> 0;
1784
+ }
1785
+ function log2(n) {
1786
+ checkU32(n);
1787
+ return 31 - Math.clz32(n);
1788
+ }
1789
+ function bitReversalInplace(values) {
1790
+ const n = values.length;
1791
+ if (!isPowerOfTwo(n))
1792
+ throw new Error("expected positive power-of-two length, got " + n);
1793
+ const bits = log2(n);
1794
+ for (let i = 0; i < n; i++) {
1795
+ const j = reverseBits(i, bits);
1796
+ if (i < j) {
1797
+ const tmp = values[i];
1798
+ values[i] = values[j];
1799
+ values[j] = tmp;
1800
+ }
1801
+ }
1802
+ return values;
1803
+ }
1804
+ var FFTCore = (F2, coreOpts) => {
1805
+ const { N: N2, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
1806
+ const bits = log2(N2);
1807
+ if (!isPowerOfTwo(N2))
1808
+ throw new Error("FFT: Polynomial size should be power of two");
1809
+ if (roots.length !== N2)
1810
+ throw new Error(`FFT: wrong roots length: expected ${N2}, got ${roots.length}`);
1811
+ const isDit = dit !== invertButterflies;
1812
+ isDit;
1813
+ return (values) => {
1814
+ if (values.length !== N2)
1815
+ throw new Error("FFT: wrong Polynomial length");
1816
+ if (dit && brp)
1817
+ bitReversalInplace(values);
1818
+ for (let i = 0, g = 1; i < bits - skipStages; i++) {
1819
+ const s = dit ? i + 1 + skipStages : bits - i;
1820
+ const m = 1 << s;
1821
+ const m2 = m >> 1;
1822
+ const stride = N2 >> s;
1823
+ for (let k = 0; k < N2; k += m) {
1824
+ for (let j = 0, grp = g++; j < m2; j++) {
1825
+ const rootPos = invertButterflies ? dit ? N2 - grp : grp : j * stride;
1826
+ const i0 = k + j;
1827
+ const i1 = k + j + m2;
1828
+ const omega = roots[rootPos];
1829
+ const b = values[i1];
1830
+ const a = values[i0];
1831
+ if (isDit) {
1832
+ const t = F2.mul(b, omega);
1833
+ values[i0] = F2.add(a, t);
1834
+ values[i1] = F2.sub(a, t);
1835
+ } else if (invertButterflies) {
1836
+ values[i0] = F2.add(b, a);
1837
+ values[i1] = F2.mul(F2.sub(b, a), omega);
1838
+ } else {
1839
+ values[i0] = F2.add(a, b);
1840
+ values[i1] = F2.mul(F2.sub(a, b), omega);
1841
+ }
1842
+ }
1843
+ }
1844
+ }
1845
+ if (!dit && brp)
1846
+ bitReversalInplace(values);
1847
+ return values;
1848
+ };
1849
+ };
1850
+
1851
+ // ../../node_modules/@noble/curves/abstract/hash-to-curve.js
1852
+ function i2osp(value, length) {
1853
+ asafenumber(value);
1854
+ asafenumber(length);
1855
+ if (length < 0 || length > 4)
1856
+ throw new Error("invalid I2OSP length: " + length);
1857
+ if (value < 0 || value > 2 ** (8 * length) - 1)
1858
+ throw new Error("invalid I2OSP input: " + value);
1859
+ const res = Array.from({ length }).fill(0);
1860
+ for (let i = length - 1; i >= 0; i--) {
1861
+ res[i] = value & 255;
1862
+ value >>>= 8;
1863
+ }
1864
+ return new Uint8Array(res);
1865
+ }
1866
+ function strxor(a, b) {
1867
+ const arr = new Uint8Array(a.length);
1868
+ for (let i = 0; i < a.length; i++) {
1869
+ arr[i] = a[i] ^ b[i];
1870
+ }
1871
+ return arr;
1872
+ }
1873
+ function normDST(DST) {
1874
+ if (!isBytes2(DST) && typeof DST !== "string")
1875
+ throw new Error("DST must be Uint8Array or ascii string");
1876
+ const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
1877
+ if (dst.length === 0)
1878
+ throw new Error("DST must be non-empty");
1879
+ return dst;
1880
+ }
1881
+ function expand_message_xmd(msg, DST, lenInBytes, H) {
1882
+ abytes2(msg);
1883
+ asafenumber(lenInBytes);
1884
+ DST = normDST(DST);
1885
+ if (DST.length > 255)
1886
+ DST = H(concatBytes2(asciiToBytes("H2C-OVERSIZE-DST-"), DST));
1887
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1888
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
1889
+ if (lenInBytes > 65535 || ell > 255)
1890
+ throw new Error("expand_message_xmd: invalid lenInBytes");
1891
+ const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1892
+ const Z_pad = new Uint8Array(r_in_bytes);
1893
+ const l_i_b_str = i2osp(lenInBytes, 2);
1894
+ const b = new Array(ell);
1895
+ const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1896
+ b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1897
+ for (let i = 1; i < ell; i++) {
1898
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1899
+ b[i] = H(concatBytes2(...args));
1900
+ }
1901
+ const pseudo_random_bytes = concatBytes2(...b);
1902
+ return pseudo_random_bytes.slice(0, lenInBytes);
1903
+ }
1904
+ var _DST_scalar = "HashToScalar-";
1905
+
1906
+ // ../../node_modules/@noble/curves/ed25519.js
1907
+ var _0n6 = /* @__PURE__ */ BigInt(0);
1908
+ var _1n6 = /* @__PURE__ */ BigInt(1);
1909
+ var _2n4 = /* @__PURE__ */ BigInt(2);
1910
+ var _3n2 = /* @__PURE__ */ BigInt(3);
1911
+ var _5n2 = /* @__PURE__ */ BigInt(5);
1912
+ var _8n3 = /* @__PURE__ */ BigInt(8);
1913
+ var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
1914
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
1915
+ p: ed25519_CURVE_p,
1916
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
1917
+ h: _8n3,
1918
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
1919
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
1920
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
1921
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
1922
+ }))();
1923
+ function ed25519_pow_2_252_3(x) {
1924
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1925
+ const P = ed25519_CURVE_p;
1926
+ const x2 = x * x % P;
1927
+ const b2 = x2 * x % P;
1928
+ const b4 = pow2(b2, _2n4, P) * b2 % P;
1929
+ const b5 = pow2(b4, _1n6, P) * x % P;
1930
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
1931
+ const b20 = pow2(b10, _10n, P) * b10 % P;
1932
+ const b40 = pow2(b20, _20n, P) * b20 % P;
1933
+ const b80 = pow2(b40, _40n, P) * b40 % P;
1934
+ const b160 = pow2(b80, _80n, P) * b80 % P;
1935
+ const b240 = pow2(b160, _80n, P) * b80 % P;
1936
+ const b250 = pow2(b240, _10n, P) * b10 % P;
1937
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
1938
+ return { pow_p_5_8, b2 };
1939
+ }
1940
+ function adjustScalarBytes(bytes) {
1941
+ bytes[0] &= 248;
1942
+ bytes[31] &= 127;
1943
+ bytes[31] |= 64;
1944
+ return bytes;
1945
+ }
1946
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
1947
+ function uvRatio(u, v) {
1948
+ const P = ed25519_CURVE_p;
1949
+ const v3 = mod(v * v * v, P);
1950
+ const v7 = mod(v3 * v3 * v, P);
1951
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1952
+ let x = mod(u * v3 * pow, P);
1953
+ const vx2 = mod(v * x * x, P);
1954
+ const root1 = x;
1955
+ const root2 = mod(x * ED25519_SQRT_M1, P);
1956
+ const useRoot1 = vx2 === u;
1957
+ const useRoot2 = vx2 === mod(-u, P);
1958
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
1959
+ if (useRoot1)
1960
+ x = root1;
1961
+ if (useRoot2 || noRoot)
1962
+ x = root2;
1963
+ if (isNegativeLE(x, P))
1964
+ x = mod(-x, P);
1965
+ return { isValid: useRoot1 || useRoot2, value: x };
1966
+ }
1967
+ var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
1968
+ var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
1969
+ var Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
1970
+ var x25519 = /* @__PURE__ */ (() => {
1971
+ const P = ed25519_CURVE_p;
1972
+ return montgomery({
1973
+ P,
1974
+ type: "x25519",
1975
+ powPminus2: (x) => {
1976
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
1977
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
1978
+ },
1979
+ adjustScalarBytes
1980
+ });
1981
+ })();
1982
+ var SQRT_M1 = ED25519_SQRT_M1;
1983
+ var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
1984
+ var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
1985
+ var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
1986
+ var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
1987
+ var invertSqrt = (number) => uvRatio(_1n6, number);
1988
+ var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
1989
+ var bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
1990
+ function calcElligatorRistrettoMap(r0) {
1991
+ const { d } = ed25519_CURVE;
1992
+ const P = ed25519_CURVE_p;
1993
+ const mod2 = (n) => Fp.create(n);
1994
+ const r = mod2(SQRT_M1 * r0 * r0);
1995
+ const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
1996
+ let c = BigInt(-1);
1997
+ const D = mod2((c - d * r) * mod2(r + d));
1998
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
1999
+ let s_ = mod2(s * r0);
2000
+ if (!isNegativeLE(s_, P))
2001
+ s_ = mod2(-s_);
2002
+ if (!Ns_D_is_sq)
2003
+ s = s_;
2004
+ if (!Ns_D_is_sq)
2005
+ c = r;
2006
+ const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
2007
+ const s2 = s * s;
2008
+ const W0 = mod2((s + s) * D);
2009
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
2010
+ const W2 = mod2(_1n6 - s2);
2011
+ const W3 = mod2(_1n6 + s2);
2012
+ return new ed25519_Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
2013
+ }
2014
+ var __RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
2015
+ constructor(ep) {
2016
+ super(ep);
2017
+ }
2018
+ /**
2019
+ * Create one Ristretto255 point from affine Edwards coordinates.
2020
+ * This wraps the internal Edwards representative directly and is not a
2021
+ * canonical ristretto255 decoding path.
2022
+ * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
2023
+ */
2024
+ static fromAffine(ap) {
2025
+ return new __RistrettoPoint(ed25519_Point.fromAffine(ap));
2026
+ }
2027
+ assertSame(other) {
2028
+ if (!(other instanceof __RistrettoPoint))
2029
+ throw new Error("RistrettoPoint expected");
2030
+ }
2031
+ init(ep) {
2032
+ return new __RistrettoPoint(ep);
2033
+ }
2034
+ static fromBytes(bytes) {
2035
+ abytes(bytes, 32);
2036
+ const { a, d } = ed25519_CURVE;
2037
+ const P = ed25519_CURVE_p;
2038
+ const mod2 = (n) => Fp.create(n);
2039
+ const s = bytes255ToNumberLE(bytes);
2040
+ if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
2041
+ throw new Error("invalid ristretto255 encoding 1");
2042
+ const s2 = mod2(s * s);
2043
+ const u1 = mod2(_1n6 + a * s2);
2044
+ const u2 = mod2(_1n6 - a * s2);
2045
+ const u1_2 = mod2(u1 * u1);
2046
+ const u2_2 = mod2(u2 * u2);
2047
+ const v = mod2(a * d * u1_2 - u2_2);
2048
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
2049
+ const Dx = mod2(I * u2);
2050
+ const Dy = mod2(I * Dx * v);
2051
+ let x = mod2((s + s) * Dx);
2052
+ if (isNegativeLE(x, P))
2053
+ x = mod2(-x);
2054
+ const y = mod2(u1 * Dy);
2055
+ const t = mod2(x * y);
2056
+ if (!isValid || isNegativeLE(t, P) || y === _0n6)
2057
+ throw new Error("invalid ristretto255 encoding 2");
2058
+ return new __RistrettoPoint(new ed25519_Point(x, y, _1n6, t));
2059
+ }
2060
+ /**
2061
+ * Converts ristretto-encoded string to ristretto point.
2062
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
2063
+ * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
2064
+ */
2065
+ static fromHex(hex) {
2066
+ return __RistrettoPoint.fromBytes(hexToBytes(hex));
2067
+ }
2068
+ /**
2069
+ * Encodes ristretto point to Uint8Array.
2070
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
2071
+ */
2072
+ toBytes() {
2073
+ let { X, Y, Z, T } = this.ep;
2074
+ const P = ed25519_CURVE_p;
2075
+ const mod2 = (n) => Fp.create(n);
2076
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
2077
+ const u2 = mod2(X * Y);
2078
+ const u2sq = mod2(u2 * u2);
2079
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
2080
+ const D1 = mod2(invsqrt * u1);
2081
+ const D2 = mod2(invsqrt * u2);
2082
+ const zInv = mod2(D1 * D2 * T);
2083
+ let D;
2084
+ if (isNegativeLE(T * zInv, P)) {
2085
+ let _x = mod2(Y * SQRT_M1);
2086
+ let _y = mod2(X * SQRT_M1);
2087
+ X = _x;
2088
+ Y = _y;
2089
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
2090
+ } else {
2091
+ D = D2;
2092
+ }
2093
+ if (isNegativeLE(X * zInv, P))
2094
+ Y = mod2(-Y);
2095
+ let s = mod2((Z - Y) * D);
2096
+ if (isNegativeLE(s, P))
2097
+ s = mod2(-s);
2098
+ return Fp.toBytes(s);
2099
+ }
2100
+ /**
2101
+ * Compares two Ristretto points.
2102
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
2103
+ */
2104
+ equals(other) {
2105
+ this.assertSame(other);
2106
+ const { X: X1, Y: Y1 } = this.ep;
2107
+ const { X: X2, Y: Y2 } = other.ep;
2108
+ const mod2 = (n) => Fp.create(n);
2109
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
2110
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
2111
+ return one || two;
2112
+ }
2113
+ is0() {
2114
+ return this.equals(__RistrettoPoint.ZERO);
2115
+ }
2116
+ };
2117
+ // Do NOT change syntax: the following gymnastics is done,
2118
+ // because typescript strips comments, which makes bundlers disable tree-shaking.
2119
+ // prettier-ignore
2120
+ __publicField(__RistrettoPoint, "BASE", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.BASE))());
2121
+ // prettier-ignore
2122
+ __publicField(__RistrettoPoint, "ZERO", /* @__PURE__ */ (() => new __RistrettoPoint(ed25519_Point.ZERO))());
2123
+ // prettier-ignore
2124
+ __publicField(__RistrettoPoint, "Fp", /* @__PURE__ */ (() => Fp)());
2125
+ // prettier-ignore
2126
+ __publicField(__RistrettoPoint, "Fn", /* @__PURE__ */ (() => Fn)());
2127
+ var _RistrettoPoint = __RistrettoPoint;
2128
+ Object.freeze(_RistrettoPoint.BASE);
2129
+ Object.freeze(_RistrettoPoint.ZERO);
2130
+ Object.freeze(_RistrettoPoint.prototype);
2131
+ Object.freeze(_RistrettoPoint);
2132
+ var ristretto255_hasher = Object.freeze({
2133
+ Point: _RistrettoPoint,
2134
+ /**
2135
+ * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
2136
+ * * There are no test vectors
2137
+ * * encodeToCurve / mapToCurve is undefined
2138
+ * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
2139
+ * * hashToScalar is undefined too, so we just use OPRF implementation
2140
+ * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
2141
+ (os2ip -> bytes255ToNumberLE)
2142
+ * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
2143
+ * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
2144
+ version here. Using `bytes255ToNumblerLE` will create a different result
2145
+ if we use `bytes255ToNumberLE` as os2ip
2146
+ * * current version is closest to spec.
2147
+ */
2148
+ hashToCurve(msg, options) {
2149
+ const DST = options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST;
2150
+ const xmd = expand_message_xmd(msg, DST, 64, sha512);
2151
+ return ristretto255_hasher.deriveToCurve(xmd);
2152
+ },
2153
+ hashToScalar(msg, options = { DST: _DST_scalar }) {
2154
+ const xmd = expand_message_xmd(msg, options.DST, 64, sha512);
2155
+ return Fn.create(bytesToNumberLE(xmd));
2156
+ },
2157
+ /**
2158
+ * HashToCurve-like construction based on RFC 9496 (Element Derivation).
2159
+ * Converts 64 uniform random bytes into a curve point.
2160
+ *
2161
+ * WARNING: This represents an older hash-to-curve construction from before
2162
+ * RFC 9380 was finalized.
2163
+ * It was later reused as a component in the newer
2164
+ * `hash_to_ristretto255` function defined in RFC 9380.
2165
+ */
2166
+ deriveToCurve(bytes) {
2167
+ abytes(bytes, 64);
2168
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
2169
+ const R1 = calcElligatorRistrettoMap(r1);
2170
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
2171
+ const R2 = calcElligatorRistrettoMap(r2);
2172
+ return new _RistrettoPoint(R1.add(R2));
2173
+ }
2174
+ });
2175
+
2176
+ // ../../node_modules/@noble/hashes/sha3.js
2177
+ var _0n7 = BigInt(0);
2178
+ var _1n7 = BigInt(1);
2179
+ var _2n5 = BigInt(2);
2180
+ var _7n2 = BigInt(7);
2181
+ var _256n = BigInt(256);
2182
+ var _0x71n = BigInt(113);
2183
+ var SHA3_PI = [];
2184
+ var SHA3_ROTL = [];
2185
+ var _SHA3_IOTA = [];
2186
+ for (let round = 0, R = _1n7, x = 1, y = 0; round < 24; round++) {
2187
+ [x, y] = [y, (2 * x + 3 * y) % 5];
2188
+ SHA3_PI.push(2 * (5 * y + x));
2189
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
2190
+ let t = _0n7;
2191
+ for (let j = 0; j < 7; j++) {
2192
+ R = (R << _1n7 ^ (R >> _7n2) * _0x71n) % _256n;
2193
+ if (R & _2n5)
2194
+ t ^= _1n7 << (_1n7 << BigInt(j)) - _1n7;
2195
+ }
2196
+ _SHA3_IOTA.push(t);
2197
+ }
2198
+ var IOTAS = split(_SHA3_IOTA, true);
2199
+ var SHA3_IOTA_H = IOTAS[0];
2200
+ var SHA3_IOTA_L = IOTAS[1];
2201
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
2202
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
2203
+ function keccakP(s, rounds = 24) {
2204
+ anumber(rounds, "rounds");
2205
+ if (rounds < 1 || rounds > 24)
2206
+ throw new Error('"rounds" expected integer 1..24');
2207
+ const B = new Uint32Array(5 * 2);
2208
+ for (let round = 24 - rounds; round < 24; round++) {
2209
+ for (let x = 0; x < 10; x++)
2210
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2211
+ for (let x = 0; x < 10; x += 2) {
2212
+ const idx1 = (x + 8) % 10;
2213
+ const idx0 = (x + 2) % 10;
2214
+ const B0 = B[idx0];
2215
+ const B1 = B[idx0 + 1];
2216
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
2217
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2218
+ for (let y = 0; y < 50; y += 10) {
2219
+ s[x + y] ^= Th;
2220
+ s[x + y + 1] ^= Tl;
2221
+ }
2222
+ }
2223
+ let curH = s[2];
2224
+ let curL = s[3];
2225
+ for (let t = 0; t < 24; t++) {
2226
+ const shift = SHA3_ROTL[t];
2227
+ const Th = rotlH(curH, curL, shift);
2228
+ const Tl = rotlL(curH, curL, shift);
2229
+ const PI = SHA3_PI[t];
2230
+ curH = s[PI];
2231
+ curL = s[PI + 1];
2232
+ s[PI] = Th;
2233
+ s[PI + 1] = Tl;
2234
+ }
2235
+ for (let y = 0; y < 50; y += 10) {
2236
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
2237
+ s[y] ^= ~s[y + 2] & s[y + 4];
2238
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
2239
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
2240
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
2241
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
2242
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
2243
+ s[y + 6] ^= ~s[y + 8] & b0;
2244
+ s[y + 7] ^= ~s[y + 9] & b1;
2245
+ s[y + 8] ^= ~b0 & b2;
2246
+ s[y + 9] ^= ~b1 & b3;
2247
+ }
2248
+ s[0] ^= SHA3_IOTA_H[round];
2249
+ s[1] ^= SHA3_IOTA_L[round];
2250
+ }
2251
+ clean(B);
2252
+ }
2253
+ var Keccak = class _Keccak {
2254
+ // NOTE: we accept arguments in bytes instead of bits here.
2255
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2256
+ __publicField(this, "state");
2257
+ __publicField(this, "pos", 0);
2258
+ __publicField(this, "posOut", 0);
2259
+ __publicField(this, "finished", false);
2260
+ __publicField(this, "state32");
2261
+ __publicField(this, "destroyed", false);
2262
+ __publicField(this, "blockLen");
2263
+ __publicField(this, "suffix");
2264
+ __publicField(this, "outputLen");
2265
+ __publicField(this, "canXOF");
2266
+ __publicField(this, "enableXOF", false);
2267
+ __publicField(this, "rounds");
2268
+ this.blockLen = blockLen;
2269
+ this.suffix = suffix;
2270
+ this.outputLen = outputLen;
2271
+ this.enableXOF = enableXOF;
2272
+ this.canXOF = enableXOF;
2273
+ this.rounds = rounds;
2274
+ anumber(outputLen, "outputLen");
2275
+ if (!(0 < blockLen && blockLen < 200))
2276
+ throw new Error("only keccak-f1600 function is supported");
2277
+ this.state = new Uint8Array(200);
2278
+ this.state32 = u32(this.state);
2279
+ }
2280
+ clone() {
2281
+ return this._cloneInto();
2282
+ }
2283
+ keccak() {
2284
+ swap32IfBE(this.state32);
2285
+ keccakP(this.state32, this.rounds);
2286
+ swap32IfBE(this.state32);
2287
+ this.posOut = 0;
2288
+ this.pos = 0;
2289
+ }
2290
+ update(data) {
2291
+ aexists(this);
2292
+ abytes(data);
2293
+ const { blockLen, state } = this;
2294
+ const len = data.length;
2295
+ for (let pos = 0; pos < len; ) {
2296
+ const take = Math.min(blockLen - this.pos, len - pos);
2297
+ for (let i = 0; i < take; i++)
2298
+ state[this.pos++] ^= data[pos++];
2299
+ if (this.pos === blockLen)
2300
+ this.keccak();
2301
+ }
2302
+ return this;
2303
+ }
2304
+ finish() {
2305
+ if (this.finished)
2306
+ return;
2307
+ this.finished = true;
2308
+ const { state, suffix, pos, blockLen } = this;
2309
+ state[pos] ^= suffix;
2310
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
2311
+ this.keccak();
2312
+ state[blockLen - 1] ^= 128;
2313
+ this.keccak();
2314
+ }
2315
+ writeInto(out) {
2316
+ aexists(this, false);
2317
+ abytes(out);
2318
+ this.finish();
2319
+ const bufferOut = this.state;
2320
+ const { blockLen } = this;
2321
+ for (let pos = 0, len = out.length; pos < len; ) {
2322
+ if (this.posOut >= blockLen)
2323
+ this.keccak();
2324
+ const take = Math.min(blockLen - this.posOut, len - pos);
2325
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2326
+ this.posOut += take;
2327
+ pos += take;
2328
+ }
2329
+ return out;
2330
+ }
2331
+ xofInto(out) {
2332
+ if (!this.enableXOF)
2333
+ throw new Error("XOF is not possible for this instance");
2334
+ return this.writeInto(out);
2335
+ }
2336
+ xof(bytes) {
2337
+ anumber(bytes);
2338
+ return this.xofInto(new Uint8Array(bytes));
2339
+ }
2340
+ digestInto(out) {
2341
+ aoutput(out, this);
2342
+ if (this.finished)
2343
+ throw new Error("digest() was already called");
2344
+ this.writeInto(out.subarray(0, this.outputLen));
2345
+ this.destroy();
2346
+ }
2347
+ digest() {
2348
+ const out = new Uint8Array(this.outputLen);
2349
+ this.digestInto(out);
2350
+ return out;
2351
+ }
2352
+ destroy() {
2353
+ this.destroyed = true;
2354
+ clean(this.state);
2355
+ }
2356
+ _cloneInto(to) {
2357
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2358
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
2359
+ to.blockLen = blockLen;
2360
+ to.state32.set(this.state32);
2361
+ to.pos = this.pos;
2362
+ to.posOut = this.posOut;
2363
+ to.finished = this.finished;
2364
+ to.rounds = rounds;
2365
+ to.suffix = suffix;
2366
+ to.outputLen = outputLen;
2367
+ to.enableXOF = enableXOF;
2368
+ to.canXOF = this.canXOF;
2369
+ to.destroyed = this.destroyed;
2370
+ return to;
2371
+ }
2372
+ };
2373
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
2374
+ var sha3_256 = /* @__PURE__ */ genKeccak(
2375
+ 6,
2376
+ 136,
2377
+ 32,
2378
+ /* @__PURE__ */ oidNist(8)
2379
+ );
2380
+ var sha3_512 = /* @__PURE__ */ genKeccak(
2381
+ 6,
2382
+ 72,
2383
+ 64,
2384
+ /* @__PURE__ */ oidNist(10)
2385
+ );
2386
+ var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info);
2387
+ var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
2388
+ var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
2389
+
2390
+ // ../../node_modules/@noble/post-quantum/utils.js
2391
+ var abytesDoc = abytes;
2392
+ var randomBytes3 = randomBytes;
2393
+ function equalBytes2(a, b) {
2394
+ if (a.length !== b.length)
2395
+ return false;
2396
+ let diff = 0;
2397
+ for (let i = 0; i < a.length; i++)
2398
+ diff |= a[i] ^ b[i];
2399
+ return diff === 0;
2400
+ }
2401
+ function copyBytes2(bytes) {
2402
+ return Uint8Array.from(abytes(bytes));
2403
+ }
2404
+ function splitCoder(label, ...lengths) {
2405
+ const getLength = (c) => typeof c === "number" ? c : c.bytesLen;
2406
+ const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);
2407
+ return {
2408
+ bytesLen,
2409
+ encode: (bufs) => {
2410
+ const res = new Uint8Array(bytesLen);
2411
+ for (let i = 0, pos = 0; i < lengths.length; i++) {
2412
+ const c = lengths[i];
2413
+ const l = getLength(c);
2414
+ const b = typeof c === "number" ? bufs[i] : c.encode(bufs[i]);
2415
+ abytes(b, l, label);
2416
+ res.set(b, pos);
2417
+ if (typeof c !== "number")
2418
+ b.fill(0);
2419
+ pos += l;
2420
+ }
2421
+ return res;
2422
+ },
2423
+ decode: (buf) => {
2424
+ abytes(buf, bytesLen, label);
2425
+ const res = [];
2426
+ for (const c of lengths) {
2427
+ const l = getLength(c);
2428
+ const b = buf.subarray(0, l);
2429
+ res.push(typeof c === "number" ? b : c.decode(b));
2430
+ buf = buf.subarray(l);
2431
+ }
2432
+ return res;
2433
+ }
2434
+ };
2435
+ }
2436
+ function vecCoder(c, vecLen) {
2437
+ const coder = c;
2438
+ const bytesLen = vecLen * coder.bytesLen;
2439
+ return {
2440
+ bytesLen,
2441
+ encode: (u) => {
2442
+ if (u.length !== vecLen)
2443
+ throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
2444
+ const res = new Uint8Array(bytesLen);
2445
+ for (let i = 0, pos = 0; i < u.length; i++) {
2446
+ const b = coder.encode(u[i]);
2447
+ res.set(b, pos);
2448
+ b.fill(0);
2449
+ pos += b.length;
2450
+ }
2451
+ return res;
2452
+ },
2453
+ decode: (a) => {
2454
+ abytes(a, bytesLen);
2455
+ const r = [];
2456
+ for (let i = 0; i < a.length; i += coder.bytesLen)
2457
+ r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
2458
+ return r;
2459
+ }
2460
+ };
2461
+ }
2462
+ function cleanBytes(...list) {
2463
+ for (const t of list) {
2464
+ if (Array.isArray(t))
2465
+ for (const b of t)
2466
+ b.fill(0);
2467
+ else
2468
+ t.fill(0);
2469
+ }
2470
+ }
2471
+ function getMask(bits) {
2472
+ if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
2473
+ throw new RangeError(`expected bits in [0..32], got ${bits}`);
2474
+ return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
2475
+ }
2476
+
2477
+ // ../../node_modules/@noble/post-quantum/_crystals.js
2478
+ var genCrystals = (opts2) => {
2479
+ const { newPoly, N: N2, Q: Q2, F: F2, ROOT_OF_UNITY: ROOT_OF_UNITY2, brvBits, isKyber } = opts2;
2480
+ const mod2 = (a, modulo = Q2) => {
2481
+ const result = a % modulo | 0;
2482
+ return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
2483
+ };
2484
+ const smod = (a, modulo = Q2) => {
2485
+ const r = mod2(a, modulo) | 0;
2486
+ return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
2487
+ };
2488
+ function getZettas() {
2489
+ const out = newPoly(N2);
2490
+ for (let i = 0; i < N2; i++) {
2491
+ const b = reverseBits(i, brvBits);
2492
+ const p = BigInt(ROOT_OF_UNITY2) ** BigInt(b) % BigInt(Q2);
2493
+ out[i] = Number(p) | 0;
2494
+ }
2495
+ return out;
2496
+ }
2497
+ const nttZetas = getZettas();
2498
+ const field = {
2499
+ add: (a, b) => mod2((a | 0) + (b | 0)) | 0,
2500
+ sub: (a, b) => mod2((a | 0) - (b | 0)) | 0,
2501
+ mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
2502
+ inv: (_a) => {
2503
+ throw new Error("not implemented");
2504
+ }
2505
+ };
2506
+ const nttOpts = {
2507
+ N: N2,
2508
+ roots: nttZetas,
2509
+ invertButterflies: true,
2510
+ skipStages: isKyber ? 1 : 0,
2511
+ brp: false
2512
+ };
2513
+ const dif = FFTCore(field, { dit: false, ...nttOpts });
2514
+ const dit = FFTCore(field, { dit: true, ...nttOpts });
2515
+ const NTT = {
2516
+ encode: (r) => {
2517
+ return dif(r);
2518
+ },
2519
+ decode: (r) => {
2520
+ dit(r);
2521
+ for (let i = 0; i < r.length; i++)
2522
+ r[i] = mod2(F2 * r[i]);
2523
+ return r;
2524
+ }
2525
+ };
2526
+ const bitsCoder = (d, c) => {
2527
+ const mask = getMask(d);
2528
+ const bytesLen = d * (N2 / 8);
2529
+ return {
2530
+ bytesLen,
2531
+ encode: (poly_) => {
2532
+ const poly = poly_;
2533
+ const r = new Uint8Array(bytesLen);
2534
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
2535
+ buf |= (c.encode(poly[i]) & mask) << bufLen;
2536
+ bufLen += d;
2537
+ for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
2538
+ r[pos++] = buf & getMask(bufLen);
2539
+ }
2540
+ return r;
2541
+ },
2542
+ decode: (bytes) => {
2543
+ const r = newPoly(N2);
2544
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
2545
+ buf |= bytes[i] << bufLen;
2546
+ bufLen += 8;
2547
+ for (; bufLen >= d; bufLen -= d, buf >>= d)
2548
+ r[pos++] = c.decode(buf & mask);
2549
+ }
2550
+ return r;
2551
+ }
2552
+ };
2553
+ };
2554
+ return {
2555
+ mod: mod2,
2556
+ smod,
2557
+ nttZetas,
2558
+ NTT: {
2559
+ encode: (r) => NTT.encode(r),
2560
+ decode: (r) => NTT.decode(r)
2561
+ },
2562
+ bitsCoder
2563
+ };
2564
+ };
2565
+ var createXofShake = (shake) => (seed, blockLen) => {
2566
+ if (!blockLen)
2567
+ blockLen = shake.blockLen;
2568
+ const _seed = new Uint8Array(seed.length + 2);
2569
+ _seed.set(seed);
2570
+ const seedLen = seed.length;
2571
+ const buf = new Uint8Array(blockLen);
2572
+ let h = shake.create({});
2573
+ let calls = 0;
2574
+ let xofs = 0;
2575
+ return {
2576
+ stats: () => ({ calls, xofs }),
2577
+ get: (x, y) => {
2578
+ _seed[seedLen + 0] = x;
2579
+ _seed[seedLen + 1] = y;
2580
+ h.destroy();
2581
+ h = shake.create({}).update(_seed);
2582
+ calls++;
2583
+ return () => {
2584
+ xofs++;
2585
+ return h.xofInto(buf);
2586
+ };
2587
+ },
2588
+ clean: () => {
2589
+ h.destroy();
2590
+ cleanBytes(buf, _seed);
2591
+ }
2592
+ };
2593
+ };
2594
+ var XOF128 = /* @__PURE__ */ createXofShake(shake128);
2595
+
2596
+ // ../../node_modules/@noble/post-quantum/ml-kem.js
2597
+ var N = 256;
2598
+ var Q = 3329;
2599
+ var F = 3303;
2600
+ var ROOT_OF_UNITY = 17;
2601
+ var crystals = /* @__PURE__ */ genCrystals({
2602
+ N,
2603
+ Q,
2604
+ F,
2605
+ ROOT_OF_UNITY,
2606
+ newPoly: (n) => new Uint16Array(n),
2607
+ brvBits: 7,
2608
+ isKyber: true
2609
+ });
2610
+ var PARAMS = /* @__PURE__ */ (() => Object.freeze({
2611
+ 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
2612
+ 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
2613
+ 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
2614
+ }))();
2615
+ var compress = (d) => {
2616
+ if (d >= 12)
2617
+ return { encode: (i) => i, decode: (i) => i >= Q ? i - Q : i };
2618
+ const a = 2 ** (d - 1);
2619
+ return {
2620
+ // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).
2621
+ encode: (i) => ((i << d) + Q / 2) / Q,
2622
+ // const decompress = (i: number) => round((Q / 2 ** d) * i);
2623
+ decode: (i) => i * Q + a >>> d
2624
+ };
2625
+ };
2626
+ var byteCoder = (d) => crystals.bitsCoder(d, d === 12 ? { encode: (i) => i, decode: (i) => i >= Q ? i - Q : i } : { encode: (i) => i, decode: (i) => i });
2627
+ var polyCoder = (d) => d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d));
2628
+ function polyAdd(a_, b_) {
2629
+ const a = a_;
2630
+ const b = b_;
2631
+ for (let i = 0; i < N; i++)
2632
+ a[i] = crystals.mod(a[i] + b[i]);
2633
+ }
2634
+ function polySub(a_, b_) {
2635
+ const a = a_;
2636
+ const b = b_;
2637
+ for (let i = 0; i < N; i++)
2638
+ a[i] = crystals.mod(a[i] - b[i]);
2639
+ }
2640
+ function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
2641
+ const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);
2642
+ const c1 = crystals.mod(a0 * b1 + a1 * b0);
2643
+ return { c0, c1 };
2644
+ }
2645
+ function MultiplyNTTs(f_, g_) {
2646
+ const f = f_;
2647
+ const g = g_;
2648
+ for (let i = 0; i < N / 2; i++) {
2649
+ let z = crystals.nttZetas[64 + (i >> 1)];
2650
+ if (i & 1)
2651
+ z = -z;
2652
+ const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);
2653
+ f[2 * i + 0] = c0;
2654
+ f[2 * i + 1] = c1;
2655
+ }
2656
+ return f;
2657
+ }
2658
+ function SampleNTT(xof_) {
2659
+ const xof = xof_;
2660
+ const r = new Uint16Array(N);
2661
+ for (let j = 0; j < N; ) {
2662
+ const b = xof();
2663
+ if (b.length % 3)
2664
+ throw new Error("SampleNTT: unaligned block");
2665
+ for (let i = 0; j < N && i + 3 <= b.length; i += 3) {
2666
+ const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095;
2667
+ const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095;
2668
+ if (d1 < Q)
2669
+ r[j++] = d1;
2670
+ if (j < N && d2 < Q)
2671
+ r[j++] = d2;
2672
+ }
2673
+ }
2674
+ return r;
2675
+ }
2676
+ var sampleCBDBytes = (buf, eta) => {
2677
+ const r = new Uint16Array(N);
2678
+ const b32 = u32(buf);
2679
+ swap32IfBE(b32);
2680
+ let len = 0;
2681
+ for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {
2682
+ let b = b32[i];
2683
+ for (let j = 0; j < 32; j++) {
2684
+ bb += b & 1;
2685
+ b >>= 1;
2686
+ len += 1;
2687
+ if (len === eta) {
2688
+ t0 = bb;
2689
+ bb = 0;
2690
+ } else if (len === 2 * eta) {
2691
+ r[p++] = crystals.mod(t0 - bb);
2692
+ bb = 0;
2693
+ len = 0;
2694
+ }
2695
+ }
2696
+ }
2697
+ swap32IfBE(b32);
2698
+ if (len)
2699
+ throw new Error(`sampleCBD: leftover bits: ${len}`);
2700
+ return r;
2701
+ };
2702
+ function sampleCBD(PRF_, seed, nonce, eta) {
2703
+ const PRF = PRF_;
2704
+ return sampleCBDBytes(PRF(eta * N / 4, seed, nonce), eta);
2705
+ }
2706
+ var genKPKE = (opts_) => {
2707
+ const opts2 = opts_;
2708
+ const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2;
2709
+ const poly1 = polyCoder(1);
2710
+ const polyV = polyCoder(dv);
2711
+ const polyU = polyCoder(du);
2712
+ const publicCoder = splitCoder("publicKey", vecCoder(polyCoder(12), K), 32);
2713
+ const secretCoder = vecCoder(polyCoder(12), K);
2714
+ const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
2715
+ const seedCoder = splitCoder("seed", 32, 32);
2716
+ return {
2717
+ secretCoder,
2718
+ lengths: {
2719
+ secretKey: secretCoder.bytesLen,
2720
+ publicKey: publicCoder.bytesLen,
2721
+ cipherText: cipherCoder.bytesLen
2722
+ },
2723
+ keygen: (seed) => {
2724
+ abytesDoc(seed, 32, "seed");
2725
+ const seedDst = new Uint8Array(33);
2726
+ seedDst.set(seed);
2727
+ seedDst[32] = K;
2728
+ const seedHash = HASH512(seedDst);
2729
+ const [rho, sigma] = seedCoder.decode(seedHash);
2730
+ const sHat = [];
2731
+ const tHat = [];
2732
+ for (let i = 0; i < K; i++)
2733
+ sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));
2734
+ const x = XOF(rho);
2735
+ for (let i = 0; i < K; i++) {
2736
+ const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));
2737
+ for (let j = 0; j < K; j++) {
2738
+ const aji = SampleNTT(x.get(j, i));
2739
+ polyAdd(e, MultiplyNTTs(aji, sHat[j]));
2740
+ }
2741
+ tHat.push(e);
2742
+ }
2743
+ x.clean();
2744
+ const res = {
2745
+ publicKey: publicCoder.encode([tHat, rho]),
2746
+ secretKey: secretCoder.encode(sHat)
2747
+ };
2748
+ cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);
2749
+ return res;
2750
+ },
2751
+ encrypt: (publicKey, msg, seed) => {
2752
+ const [tHat, rho] = publicCoder.decode(publicKey);
2753
+ const rHat = [];
2754
+ for (let i = 0; i < K; i++)
2755
+ rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2756
+ const x = XOF(rho);
2757
+ const tmp2 = new Uint16Array(N);
2758
+ const u = [];
2759
+ for (let i = 0; i < K; i++) {
2760
+ const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2761
+ const tmp = new Uint16Array(N);
2762
+ for (let j = 0; j < K; j++) {
2763
+ const aij = SampleNTT(x.get(i, j));
2764
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2765
+ }
2766
+ polyAdd(e1, crystals.NTT.decode(tmp));
2767
+ u.push(e1);
2768
+ polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2769
+ cleanBytes(tmp);
2770
+ }
2771
+ x.clean();
2772
+ const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2773
+ polyAdd(e2, crystals.NTT.decode(tmp2));
2774
+ const v = poly1.decode(msg);
2775
+ polyAdd(v, e2);
2776
+ cleanBytes(tHat, rHat, tmp2, e2);
2777
+ return cipherCoder.encode([u, v]);
2778
+ },
2779
+ decrypt: (cipherText, privateKey) => {
2780
+ const [u, v] = cipherCoder.decode(cipherText);
2781
+ const sk = secretCoder.decode(privateKey);
2782
+ const tmp = new Uint16Array(N);
2783
+ for (let i = 0; i < K; i++)
2784
+ polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
2785
+ polySub(v, crystals.NTT.decode(tmp));
2786
+ cleanBytes(tmp, sk, u);
2787
+ return poly1.encode(v);
2788
+ }
2789
+ };
2790
+ };
2791
+ function createKyber(opts2) {
2792
+ const rawOpts = opts2;
2793
+ const KPKE = genKPKE(rawOpts);
2794
+ const { HASH256, HASH512, KDF } = rawOpts;
2795
+ const { secretCoder: KPKESecretCoder, lengths } = KPKE;
2796
+ const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
2797
+ const msgLen = 32;
2798
+ const seedLen = 64;
2799
+ const kemLengths = Object.freeze({
2800
+ ...lengths,
2801
+ seed: 64,
2802
+ msg: msgLen,
2803
+ msgRand: msgLen,
2804
+ secretKey: secretCoder.bytesLen
2805
+ });
2806
+ return Object.freeze({
2807
+ info: Object.freeze({ type: "ml-kem" }),
2808
+ lengths: kemLengths,
2809
+ keygen: (seed = randomBytes3(seedLen)) => {
2810
+ abytesDoc(seed, seedLen, "seed");
2811
+ const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
2812
+ const publicKeyHash = HASH256(publicKey);
2813
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
2814
+ cleanBytes(sk, publicKeyHash);
2815
+ return {
2816
+ publicKey,
2817
+ secretKey
2818
+ };
2819
+ },
2820
+ getPublicKey: (secretKey) => {
2821
+ const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
2822
+ return Uint8Array.from(publicKey);
2823
+ },
2824
+ encapsulate: (publicKey, msg = randomBytes3(msgLen)) => {
2825
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2826
+ abytesDoc(msg, msgLen, "message");
2827
+ const eke = publicKey.subarray(0, 384 * opts2.K);
2828
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
2829
+ if (!equalBytes2(ek, eke)) {
2830
+ cleanBytes(ek);
2831
+ throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
2832
+ }
2833
+ cleanBytes(ek);
2834
+ const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
2835
+ const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2836
+ cleanBytes(kr.subarray(32));
2837
+ return {
2838
+ cipherText,
2839
+ sharedSecret: kr.subarray(0, 32)
2840
+ };
2841
+ },
2842
+ decapsulate: (cipherText, secretKey) => {
2843
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2844
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2845
+ const k768 = secretCoder.bytesLen - 96;
2846
+ const start = k768 + 32;
2847
+ const test = HASH256(secretKey.subarray(k768 / 2, start));
2848
+ if (!equalBytes2(test, secretKey.subarray(start, start + 32)))
2849
+ throw new Error("invalid secretKey: hash check failed");
2850
+ const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
2851
+ const msg = KPKE.decrypt(cipherText, sk);
2852
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2853
+ const Khat = kr.subarray(0, 32);
2854
+ const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2855
+ const isValid = equalBytes2(cipherText, cipherText2);
2856
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2857
+ cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
2858
+ return isValid ? Khat : Kbar;
2859
+ }
2860
+ });
2861
+ }
2862
+ function shakePRF(dkLen, key, nonce) {
2863
+ return shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
2864
+ }
2865
+ var opts = /* @__PURE__ */ (() => ({
2866
+ HASH256: sha3_256,
2867
+ HASH512: sha3_512,
2868
+ KDF: shake256,
2869
+ XOF: XOF128,
2870
+ PRF: shakePRF
2871
+ }))();
2872
+ var mk = (params) => createKyber({
2873
+ ...opts,
2874
+ ...params
2875
+ });
2876
+ var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
2877
+
2878
+ // ../../node_modules/@noble/post-quantum/hybrid.js
2879
+ function ecKeygen(curve, allowZeroKey = false) {
2880
+ const lengths = curve.lengths;
2881
+ let keygen = curve.keygen;
2882
+ if (allowZeroKey) {
2883
+ if (!("getSharedSecret" in curve && "sign" in curve && "verify" in curve))
2884
+ throw new Error("allowZeroKey requires a Weierstrass curve");
2885
+ const wCurve = curve;
2886
+ const Fn2 = wCurve.Point.Fn;
2887
+ keygen = (seed = randomBytes3(lengths.seed)) => {
2888
+ abytes(seed, lengths.seed, "seed");
2889
+ const seedScalar = Fn2.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
2890
+ const secretKey = Fn2.toBytes(Fn2.create(seedScalar));
2891
+ return {
2892
+ secretKey,
2893
+ publicKey: curve.getPublicKey(secretKey)
2894
+ };
2895
+ };
2896
+ }
2897
+ return {
2898
+ lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },
2899
+ keygen: (seed) => keygen(seed),
2900
+ getPublicKey: (secretKey) => curve.getPublicKey(secretKey)
2901
+ };
2902
+ }
2903
+ function ecdhKem(curve, allowZeroKey = false) {
2904
+ const kg = ecKeygen(curve, allowZeroKey);
2905
+ if (!curve.getSharedSecret)
2906
+ throw new Error("wrong curve");
2907
+ return {
2908
+ lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },
2909
+ keygen: kg.keygen,
2910
+ getPublicKey: kg.getPublicKey,
2911
+ encapsulate(publicKey, rand = randomBytes3(curve.lengths.seed)) {
2912
+ const seed = copyBytes2(rand);
2913
+ let ek = void 0;
2914
+ try {
2915
+ ek = this.keygen(seed).secretKey;
2916
+ const sharedSecret = this.decapsulate(publicKey, ek);
2917
+ const cipherText = curve.getPublicKey(ek);
2918
+ return { sharedSecret, cipherText };
2919
+ } finally {
2920
+ cleanBytes(seed);
2921
+ if (ek)
2922
+ cleanBytes(ek);
2923
+ }
2924
+ },
2925
+ decapsulate(cipherText, secretKey) {
2926
+ const res = curve.getSharedSecret(secretKey, cipherText);
2927
+ return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
2928
+ }
2929
+ };
2930
+ }
2931
+ function splitLengths(lst, name) {
2932
+ return splitCoder(name, ...lst.map((i) => {
2933
+ if (typeof i.lengths[name] !== "number")
2934
+ throw new Error("wrong length: " + name);
2935
+ return i.lengths[name];
2936
+ }));
2937
+ }
2938
+ function expandSeedXof(xof) {
2939
+ return ((seed, seedLen) => xof(seed, { dkLen: seedLen }));
2940
+ }
2941
+ function combineKeys(realSeedLen, expandSeed_, ...ck_) {
2942
+ const expandSeed = expandSeed_;
2943
+ const ck = ck_;
2944
+ const seedCoder = splitLengths(ck, "seed");
2945
+ const pkCoder = splitLengths(ck, "publicKey");
2946
+ if (realSeedLen === void 0)
2947
+ realSeedLen = seedCoder.bytesLen;
2948
+ anumber(realSeedLen);
2949
+ function expandDecapsulationKey(seed) {
2950
+ abytes(seed, realSeedLen);
2951
+ const expandedRaw = expandSeed(seed, seedCoder.bytesLen);
2952
+ const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes2(expandedRaw) : expandedRaw;
2953
+ const expanded = [];
2954
+ const keySecret = [];
2955
+ const secretKey = [];
2956
+ const publicKey = [];
2957
+ let ok = false;
2958
+ try {
2959
+ for (const part of seedCoder.decode(expandedSeed))
2960
+ expanded.push(copyBytes2(part));
2961
+ for (let i = 0; i < ck.length; i++) {
2962
+ const keys = ck[i].keygen(expanded[i]);
2963
+ keySecret.push(keys.secretKey);
2964
+ secretKey.push(copyBytes2(keys.secretKey));
2965
+ publicKey.push(keys.publicKey);
2966
+ }
2967
+ ok = true;
2968
+ return { secretKey, publicKey };
2969
+ } finally {
2970
+ cleanBytes(expandedSeed, expanded, keySecret);
2971
+ if (!ok)
2972
+ cleanBytes(secretKey);
2973
+ }
2974
+ }
2975
+ return {
2976
+ info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },
2977
+ getPublicKey(secretKey) {
2978
+ return this.keygen(secretKey).publicKey;
2979
+ },
2980
+ keygen(seed = randomBytes3(realSeedLen)) {
2981
+ const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);
2982
+ try {
2983
+ const publicKey = pkCoder.encode(pk);
2984
+ return { secretKey: seed, publicKey };
2985
+ } finally {
2986
+ cleanBytes(pk);
2987
+ cleanBytes(secretKey);
2988
+ }
2989
+ },
2990
+ expandDecapsulationKey,
2991
+ realSeedLen
2992
+ };
2993
+ }
2994
+ function combineKEMS(realSeedLen, realMsgLen, expandSeed, combiner, ...kems) {
2995
+ const rawCombiner = combiner;
2996
+ const rawKems = kems;
2997
+ const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);
2998
+ const ctCoder = splitLengths(rawKems, "cipherText");
2999
+ const pkCoder = splitLengths(rawKems, "publicKey");
3000
+ const msgCoder = splitLengths(rawKems, "msg");
3001
+ if (realMsgLen === void 0)
3002
+ realMsgLen = msgCoder.bytesLen;
3003
+ anumber(realMsgLen);
3004
+ const lengths = Object.freeze({
3005
+ ...keys.info.lengths,
3006
+ msg: realMsgLen,
3007
+ msgRand: msgCoder.bytesLen,
3008
+ cipherText: ctCoder.bytesLen
3009
+ });
3010
+ return Object.freeze({
3011
+ lengths,
3012
+ getPublicKey: keys.getPublicKey,
3013
+ keygen: keys.keygen,
3014
+ encapsulate(pk, randomness = randomBytes3(msgCoder.bytesLen)) {
3015
+ const pks = pkCoder.decode(pk);
3016
+ const rand = msgCoder.decode(randomness);
3017
+ const sharedSecret = [];
3018
+ const cipherText = [];
3019
+ try {
3020
+ for (let i = 0; i < rawKems.length; i++) {
3021
+ const enc = rawKems[i].encapsulate(pks[i], rand[i]);
3022
+ sharedSecret.push(enc.sharedSecret);
3023
+ cipherText.push(enc.cipherText);
3024
+ }
3025
+ return {
3026
+ // Detach the combiner result before cleanup: a caller-provided combiner may alias one of
3027
+ // the child sharedSecret buffers, and those child buffers are zeroized immediately below.
3028
+ sharedSecret: copyBytes2(rawCombiner(pks, cipherText, sharedSecret)),
3029
+ cipherText: ctCoder.encode(cipherText)
3030
+ };
3031
+ } finally {
3032
+ cleanBytes(sharedSecret, cipherText);
3033
+ }
3034
+ },
3035
+ decapsulate(ct, seed) {
3036
+ const cts = ctCoder.decode(ct);
3037
+ const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);
3038
+ const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
3039
+ try {
3040
+ return copyBytes2(rawCombiner(publicKey, cts, sharedSecret));
3041
+ } finally {
3042
+ cleanBytes(secretKey, sharedSecret);
3043
+ }
3044
+ }
3045
+ });
3046
+ }
3047
+ var x25519kem = /* @__PURE__ */ ecdhKem(x25519);
3048
+ var ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(
3049
+ 32,
3050
+ 32,
3051
+ expandSeedXof(shake256),
3052
+ // Awesome label, so much escaping hell in a single line.
3053
+ (pk, ct, ss) => sha3_256(concatBytes2(ss[0], ss[1], ct[1], pk[1], asciiToBytes("\\.//^\\"))),
3054
+ ml_kem768,
3055
+ x25519kem
3056
+ ))();
3057
+ var XWing = /* @__PURE__ */ (() => ml_kem768_x25519)();
3058
+
29
3059
  // ../crypto/src/index.ts
30
3060
  function b64ToBytes(b64) {
31
3061
  const binary = atob(b64);
@@ -34,109 +3064,236 @@ function b64ToBytes(b64) {
34
3064
  return bytes;
35
3065
  }
36
3066
  function bytesToB64(bytes) {
37
- return btoa(String.fromCharCode(...bytes));
38
- }
39
- var subtle = () => globalThis.crypto.subtle;
40
- var AU_STATE_FULL = {
41
- "new south wales": "NSW",
42
- "victoria": "VIC",
43
- "queensland": "QLD",
44
- "south australia": "SA",
45
- "western australia": "WA",
46
- "tasmania": "TAS",
47
- "northern territory": "NT",
48
- "australian capital territory": "ACT",
49
- // Common shorthands people type
50
- "act": "ACT",
51
- "nsw": "NSW",
52
- "vic": "VIC",
53
- "qld": "QLD",
54
- "sa": "SA",
55
- "wa": "WA",
56
- "tas": "TAS",
57
- "nt": "NT"
58
- };
59
- function toTitleCase(s) {
60
- return s.trim().replace(
61
- /\S+/g,
62
- (w) => /^\d/.test(w) ? w : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
63
- );
64
- }
65
- function normaliseAddress(addr) {
66
- const rawState = (addr.state ?? "").trim();
67
- const stateKey = rawState.toLowerCase();
68
- const normState = AU_STATE_FULL[stateKey] ?? rawState.toUpperCase();
69
- const rawCountry = (addr.country ?? "").trim();
70
- const normCountry = rawCountry.toLowerCase() === "australia" ? "AU" : rawCountry.toUpperCase();
71
- return {
72
- ...addr,
73
- street: toTitleCase(addr.street ?? ""),
74
- suburb: toTitleCase(addr.suburb ?? ""),
75
- state: normState,
76
- postcode: (addr.postcode ?? "").trim(),
77
- country: normCountry
78
- };
3067
+ return btoa(String.fromCodePoint(...bytes));
79
3068
  }
80
- async function encryptAddressForPartner(address, partner) {
81
- const address_ = normaliseAddress(address);
82
- const partnerPubKey = await subtle().importKey(
3069
+ var subtle = () => {
3070
+ const webcrypto = globalThis.crypto;
3071
+ if (!webcrypto?.subtle) {
3072
+ throw new Error(
3073
+ "Web Crypto is unavailable in this runtime, so no encryption or key operation can run. In Node this needs version 19 or later, where globalThis.crypto is enabled by default (Node 18 has it behind --experimental-global-webcrypto, and is itself end-of-life). Check with `node -v` and upgrade, or re-run with NODE_OPTIONS=--experimental-global-webcrypto as a one-off."
3074
+ );
3075
+ }
3076
+ return webcrypto.subtle;
3077
+ };
3078
+ async function importP256PublicKey(keyBytes) {
3079
+ if (keyBytes.length === 65 && keyBytes[0] === 4) {
3080
+ return subtle().importKey(
3081
+ "raw",
3082
+ keyBytes,
3083
+ { name: "ECDH", namedCurve: "P-256" },
3084
+ false,
3085
+ []
3086
+ );
3087
+ }
3088
+ return subtle().importKey(
83
3089
  "spki",
84
- b64ToBytes(partner.publicKeyB64),
3090
+ keyBytes,
85
3091
  { name: "ECDH", namedCurve: "P-256" },
86
3092
  false,
87
3093
  []
88
- // public key — no usages
89
3094
  );
3095
+ }
3096
+ async function importRsaOaepPublicKey(keyBytes) {
3097
+ return subtle().importKey(
3098
+ "spki",
3099
+ keyBytes,
3100
+ { name: "RSA-OAEP", hash: "SHA-256" },
3101
+ false,
3102
+ ["encrypt"]
3103
+ );
3104
+ }
3105
+ function isRsaScheme(algorithm) {
3106
+ return (algorithm ?? "").toUpperCase().startsWith("RSA");
3107
+ }
3108
+ function isHybridScheme(algorithm) {
3109
+ return (algorithm ?? "").toUpperCase().startsWith("MLKEM");
3110
+ }
3111
+ function sessionWrapInfo(partnerId) {
3112
+ return new TextEncoder().encode(`oneaddress:session-key-wrap:${partnerId}`);
3113
+ }
3114
+ function sessionWrapInfoPq(partnerId) {
3115
+ return new TextEncoder().encode(`oneaddress:session-key-wrap:pq1:${partnerId}`);
3116
+ }
3117
+ var SESSION_KEY_BITS = 256;
3118
+ var SESSION_IV_LENGTH = 12;
3119
+ var WRAP_SALT_LENGTH = 32;
3120
+ var WRAP_IV_LENGTH = 12;
3121
+ function concat(...parts) {
3122
+ const total = parts.reduce((n, p) => n + p.length, 0);
3123
+ const out = new Uint8Array(total);
3124
+ let off = 0;
3125
+ for (const p of parts) {
3126
+ out.set(p, off);
3127
+ off += p.length;
3128
+ }
3129
+ return out;
3130
+ }
3131
+ function bytesToB64Url(bytes) {
3132
+ return bytesToB64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
3133
+ }
3134
+ async function encryptSessionForPartner(session_data, partner) {
3135
+ return encryptEnvelopeForPartner(session_data, partner);
3136
+ }
3137
+ async function encryptEnvelopeForPartner(payload, partner) {
3138
+ const sk = await subtle().generateKey(
3139
+ { name: "AES-GCM", length: SESSION_KEY_BITS },
3140
+ true,
3141
+ ["encrypt"]
3142
+ );
3143
+ const sessionIv = globalThis.crypto.getRandomValues(new Uint8Array(SESSION_IV_LENGTH));
3144
+ const plaintext = new TextEncoder().encode(JSON.stringify(payload));
3145
+ const sessionCt = new Uint8Array(
3146
+ await subtle().encrypt({ name: "AES-GCM", iv: sessionIv }, sk, plaintext)
3147
+ );
3148
+ const session_envelope = bytesToB64Url(concat(sessionIv, sessionCt));
3149
+ const skRawForWrap = new Uint8Array(await subtle().exportKey("raw", sk));
3150
+ if (isHybridScheme(partner.algorithm)) {
3151
+ const { cipherText: kemCt, sharedSecret: sharedSecret2 } = XWing.encapsulate(b64ToBytes(partner.public_key_b64));
3152
+ const wrapSalt2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_SALT_LENGTH));
3153
+ const wrapKeyRaw2 = await subtle().deriveBits(
3154
+ { name: "HKDF", hash: "SHA-256", salt: wrapSalt2, info: sessionWrapInfoPq(partner.partner_id) },
3155
+ await subtle().importKey("raw", sharedSecret2, "HKDF", false, ["deriveBits"]),
3156
+ 256
3157
+ );
3158
+ const wrapKey2 = await subtle().importKey("raw", wrapKeyRaw2, { name: "AES-GCM" }, false, ["encrypt"]);
3159
+ const wrapIv2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_IV_LENGTH));
3160
+ const wrappedSkBytes2 = new Uint8Array(
3161
+ await subtle().encrypt({ name: "AES-GCM", iv: wrapIv2 }, wrapKey2, skRawForWrap)
3162
+ );
3163
+ skRawForWrap.fill(0);
3164
+ return {
3165
+ partner_id: partner.partner_id,
3166
+ session_envelope,
3167
+ session_key_share: {
3168
+ key_id: partner.key_id,
3169
+ wrapped_key: bytesToB64Url(concat(wrapSalt2, wrapIv2, wrappedSkBytes2)),
3170
+ epk: bytesToB64Url(kemCt),
3171
+ // X-Wing KEM ciphertext (no ephemeral EC key)
3172
+ alg: "MLKEM768X25519+HKDF-SHA256+A256GCM",
3173
+ v: 2
3174
+ }
3175
+ };
3176
+ }
3177
+ if (isRsaScheme(partner.algorithm)) {
3178
+ const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes(partner.public_key_b64));
3179
+ const rsaWrapped = new Uint8Array(
3180
+ await subtle().encrypt({ name: "RSA-OAEP" }, partnerRsaPub, skRawForWrap)
3181
+ );
3182
+ skRawForWrap.fill(0);
3183
+ return {
3184
+ partner_id: partner.partner_id,
3185
+ session_envelope,
3186
+ session_key_share: {
3187
+ key_id: partner.key_id,
3188
+ wrapped_key: bytesToB64Url(rsaWrapped),
3189
+ // No epk — RSA key transport has no ephemeral key.
3190
+ alg: "RSA-OAEP-256+A256GCM",
3191
+ v: 2
3192
+ }
3193
+ };
3194
+ }
3195
+ const partnerPub = await importP256PublicKey(b64ToBytes(partner.public_key_b64));
90
3196
  const ephemeral = await subtle().generateKey(
91
3197
  { name: "ECDH", namedCurve: "P-256" },
92
3198
  true,
93
3199
  ["deriveBits"]
94
3200
  );
95
- const hkdfSaltBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
96
- const ecdhBits = await subtle().deriveBits(
97
- { name: "ECDH", public: partnerPubKey },
3201
+ const sharedSecret = await subtle().deriveBits(
3202
+ { name: "ECDH", public: partnerPub },
98
3203
  ephemeral.privateKey,
99
3204
  256
100
3205
  );
101
- const hkdfKey = await subtle().importKey("raw", ecdhBits, "HKDF", false, ["deriveBits"]);
102
- const aesRaw = await subtle().deriveBits(
3206
+ const wrapSalt = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_SALT_LENGTH));
3207
+ const wrapKeyRaw = await subtle().deriveBits(
103
3208
  {
104
3209
  name: "HKDF",
105
3210
  hash: "SHA-256",
106
- salt: hkdfSaltBytes,
107
- info: new TextEncoder().encode(`oneaddress:${partner.partnerId}`)
3211
+ salt: wrapSalt,
3212
+ info: sessionWrapInfo(partner.partner_id)
108
3213
  },
109
- hkdfKey,
3214
+ await subtle().importKey("raw", sharedSecret, "HKDF", false, ["deriveBits"]),
110
3215
  256
111
3216
  );
112
- const aesKey = await subtle().importKey(
3217
+ const wrapKey = await subtle().importKey(
113
3218
  "raw",
114
- aesRaw,
3219
+ wrapKeyRaw,
115
3220
  { name: "AES-GCM" },
116
3221
  false,
117
3222
  ["encrypt"]
118
3223
  );
119
- const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
120
- const plaintext = new TextEncoder().encode(JSON.stringify(address_));
121
- const ciphertextBuf = await subtle().encrypt(
122
- { name: "AES-GCM", iv },
123
- aesKey,
124
- plaintext
3224
+ const wrapIv = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_IV_LENGTH));
3225
+ const wrappedSkBytes = new Uint8Array(
3226
+ await subtle().encrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, skRawForWrap)
125
3227
  );
126
- const ephPubRaw = await subtle().exportKey("raw", ephemeral.publicKey);
3228
+ skRawForWrap.fill(0);
3229
+ const wrapped_key = bytesToB64Url(concat(wrapSalt, wrapIv, wrappedSkBytes));
3230
+ const epkSpki = new Uint8Array(await subtle().exportKey("spki", ephemeral.publicKey));
3231
+ const epk = bytesToB64Url(epkSpki);
127
3232
  return {
128
- ciphertext: bytesToB64(new Uint8Array(ciphertextBuf)),
129
- iv: bytesToB64(iv),
130
- ephemeralPublicKey: bytesToB64(new Uint8Array(ephPubRaw)),
131
- partnerId: partner.partnerId,
132
- encryptedAt: (/* @__PURE__ */ new Date()).toISOString(),
133
- hkdfSalt: bytesToB64(hkdfSaltBytes)
3233
+ partner_id: partner.partner_id,
3234
+ session_envelope,
3235
+ session_key_share: {
3236
+ key_id: partner.key_id,
3237
+ wrapped_key,
3238
+ epk,
3239
+ alg: "ECDH-ES+HKDF-SHA256+A256GCM",
3240
+ v: 2
3241
+ }
134
3242
  };
135
3243
  }
136
3244
 
137
3245
  // ../protocol/src/types.ts
138
3246
  var CURRENT_VERSION = "2026.1";
139
3247
 
3248
+ // ../protocol/src/update-kinds.ts
3249
+ var UPDATE_KINDS = ["address", "phone", "email"];
3250
+ var CONTACT_KINDS = ["phone", "email"];
3251
+ function isUpdateKind(value) {
3252
+ return typeof value === "string" && UPDATE_KINDS.includes(value);
3253
+ }
3254
+ function normaliseUpdateKinds(raw) {
3255
+ const kept = new Set(
3256
+ (Array.isArray(raw) ? raw : []).filter((v) => typeof v === "string")
3257
+ );
3258
+ return UPDATE_KINDS.filter((k) => k === "address" || kept.has(k));
3259
+ }
3260
+ function readAcceptedUpdateKindsFromAck(body) {
3261
+ const none = (malformed = false) => ({
3262
+ declared: false,
3263
+ kinds: ["address"],
3264
+ malformed,
3265
+ ignored: []
3266
+ });
3267
+ let parsed = body;
3268
+ if (typeof body === "string") {
3269
+ try {
3270
+ parsed = JSON.parse(body);
3271
+ } catch {
3272
+ return none();
3273
+ }
3274
+ }
3275
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return none();
3276
+ const raw = parsed.accepted_update_types;
3277
+ if (raw === void 0 || raw === null) return none();
3278
+ if (!Array.isArray(raw)) return none(true);
3279
+ const ignored = [...new Set(
3280
+ raw.filter((v) => !isUpdateKind(v)).map((v) => typeof v === "string" ? v : JSON.stringify(v))
3281
+ )];
3282
+ return { declared: true, kinds: normaliseUpdateKinds(raw), malformed: false, ignored };
3283
+ }
3284
+ var UNDEFINED_PROBE_KIND = "conformance_undeclared_kind";
3285
+ function kindProbePlan(declaration, acceptedInPortal) {
3286
+ const accepted = normaliseUpdateKinds(acceptedInPortal).filter((k) => k !== "address");
3287
+ if (!declaration.declared) {
3288
+ return { accept: accepted, refuse: null, consentBeyondDeclaration: [] };
3289
+ }
3290
+ const declaredContact = declaration.kinds.filter((k) => k !== "address");
3291
+ const accept = accepted.filter((k) => declaredContact.includes(k));
3292
+ const consentBeyondDeclaration = accepted.filter((k) => !declaredContact.includes(k));
3293
+ const undeclared = CONTACT_KINDS.find((k) => !declaration.kinds.includes(k));
3294
+ return { accept, refuse: undeclared ?? UNDEFINED_PROBE_KIND, consentBeyondDeclaration };
3295
+ }
3296
+
140
3297
  // src/credentials.ts
141
3298
  var TEST_WEBHOOK_SECRET = (
142
3299
  // NOSONAR — intentional test credential, not a real secret
@@ -160,27 +3317,98 @@ function buildHeaders(partnerId, timestamp, signature, dispatchId, event = "addr
160
3317
  "X-OneAddress-Dispatch": dispatchId
161
3318
  };
162
3319
  }
163
- async function buildBody(partnerId, publicKeyB64, extraFields) {
164
- const encrypted = await encryptAddressForPartner(
165
- {
166
- street: "42 Collins Street",
167
- suburb: "Melbourne",
168
- state: "VIC",
169
- postcode: "3000",
170
- country: "AU"
171
- },
172
- { partnerId, publicKeyB64 }
173
- );
3320
+ async function buildBody(partnerId, publicKeyB64, extraFields, kind = "address", identity) {
3321
+ const partnerKey = {
3322
+ partner_id: partnerId,
3323
+ key_id: "conformance-key-1",
3324
+ public_key_b64: publicKeyB64,
3325
+ algorithm: "ECDH-P256-AES-GCM-256"
3326
+ };
3327
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
3328
+ const updateUid = import_node_crypto.default.randomUUID();
3329
+ const sessionData = {
3330
+ v: 2,
3331
+ update_uid: updateUid,
3332
+ dispatch_timestamp: nowIso,
3333
+ verified_name: "Conformance Test",
3334
+ ...kind === "address" ? {
3335
+ new_address: {
3336
+ street: "42 Collins Street",
3337
+ suburb: "Melbourne",
3338
+ state: "VIC",
3339
+ postcode: "3000",
3340
+ country: "AU"
3341
+ }
3342
+ } : {},
3343
+ ...kind === "phone" ? { new_phone: "+61412345678" } : {},
3344
+ ...kind === "email" ? { new_email: "conformance@example.com" } : {},
3345
+ update_types: [kind],
3346
+ account_number: "CONF-0001",
3347
+ id_verification_ref: import_node_crypto.default.randomUUID(),
3348
+ known_names: ["Conformance Tester"],
3349
+ // Applied last so an override wins over the defaults above, including
3350
+ // `verified_name`, which is set before the address block.
3351
+ ...identity ?? {}
3352
+ };
3353
+ const envelope = await encryptSessionForPartner(sessionData, partnerKey);
3354
+ const loa = {
3355
+ consumer_name: "Conformance Test",
3356
+ authorisation_date: nowIso,
3357
+ scope: "Authority to update address records on file.",
3358
+ update_uid: updateUid,
3359
+ oneaddress_acn: "696 078 869",
3360
+ oneaddress_signature: "00".repeat(64),
3361
+ // placeholder r||s hex (128 chars)
3362
+ signature_algorithm: "ECDSA-P256"
3363
+ };
3364
+ const loaEnvelope = await encryptEnvelopeForPartner(loa, partnerKey);
174
3365
  return JSON.stringify({
175
- event: "address.updated",
3366
+ // Body event and `X-OneAddress-Event` must agree — the relay derives both
3367
+ // from the same rule, and a receiver may route on either. An address-
3368
+ // bearing dispatch stays `address.updated` for every existing integration.
3369
+ event: kind === "address" ? "address.updated" : "contact.updated",
176
3370
  oneaddress_version: CURRENT_VERSION,
177
3371
  version: CURRENT_VERSION,
178
3372
  id: import_node_crypto.default.randomUUID(),
3373
+ update_id: updateUid,
179
3374
  timestamp: String(Math.floor(Date.now() / 1e3)),
180
3375
  partner_id: partnerId,
181
- customer: { email: "conformance@test.oneaddress.io", name: "Conformance Test" },
182
- address_encrypted: encrypted,
3376
+ // D5 per-partner encrypted address envelope (identity is INSIDE it).
3377
+ session_envelope: envelope.session_envelope,
3378
+ session_key_share: envelope.session_key_share,
3379
+ // D5 per-partner encrypted signed LOA. No cleartext letter_of_authority.
3380
+ loa_encrypted: {
3381
+ session_envelope: loaEnvelope.session_envelope,
3382
+ session_key_share: loaEnvelope.session_key_share
3383
+ },
183
3384
  encryption_status: "encrypted",
3385
+ /**
3386
+ * THIS DISPATCH IS A DRILL, AND IT SAYS SO IN THE SIGNED BODY.
3387
+ *
3388
+ * Check 11 sends a payload the receiver CANNOT open, deliberately, and
3389
+ * passes the receiver for refusing it. A receiver that quarantines held
3390
+ * dispatches therefore ends a SUCCESSFUL conformance run with a red fault
3391
+ * panel, a `failed` counter that never returns to zero, and a `decrypt_failed`
3392
+ * line naming the partner's real `key_id`. Reported from a real run: the
3393
+ * dashboard said the receiver was broken at the moment it proved it was not.
3394
+ *
3395
+ * WHY THE BODY AND NOT THE DISPATCH-ID HEADER. `X-OneAddress-Dispatch`
3396
+ * carries a recognisable prefix already (`undecryptable-…`) and keying off it
3397
+ * would be wrong: the HMAC covers `${timestamp}.${rawBody}` and NOTHING ELSE,
3398
+ * so every header except the timestamp is outside the signature and anything
3399
+ * on the path can change it without invalidating anything. A marker that
3400
+ * changes how an operator's fault panel behaves has to be inside the signed
3401
+ * material. This field is.
3402
+ *
3403
+ * PRECEDENT: `crossover_key_ids` (check 15) is already a signed-body field
3404
+ * that tells a receiver how to treat a payload it cannot decrypt. Same shape,
3405
+ * different cause.
3406
+ *
3407
+ * Sent on EVERY conformance body, not only the undecryptable one, because a
3408
+ * receiver has a legitimate interest in knowing which of its stored records
3409
+ * came from a drill rather than from a consumer.
3410
+ */
3411
+ conformance: true,
184
3412
  ...extraFields
185
3413
  });
186
3414
  }
@@ -196,9 +3424,10 @@ async function post(url, body, headers, timeoutMs = 12e3) {
196
3424
  signal: controller.signal,
197
3425
  redirect: "error"
198
3426
  });
199
- return { status: res.status, durationMs: Date.now() - start };
3427
+ const text = await res.text().catch(() => "");
3428
+ return { status: res.status, durationMs: Date.now() - start, body: text };
200
3429
  } catch (err) {
201
- return { status: 0, durationMs: Date.now() - start, error: String(err) };
3430
+ return { status: 0, durationMs: Date.now() - start, body: "", error: String(err) };
202
3431
  } finally {
203
3432
  clearTimeout(timer);
204
3433
  }
@@ -230,24 +3459,35 @@ async function get(url, headers, timeoutMs = 12e3) {
230
3459
  async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId = TEST_PARTNER_ID, publicKeyB64 = TEST_PARTNER_PUBLIC_KEY_SPKI_B64) {
231
3460
  let targetUrl;
232
3461
  let customerUrl;
3462
+ let acceptedUpdateTypes = [];
3463
+ let verifiesAccountReference = false;
3464
+ let supportsKeyCrossover = false;
233
3465
  if (typeof urlOrOptions === "object") {
234
3466
  targetUrl = urlOrOptions.targetUrl;
235
3467
  secret = urlOrOptions.secret ?? TEST_WEBHOOK_SECRET;
236
3468
  partnerId = urlOrOptions.partnerId ?? TEST_PARTNER_ID;
237
3469
  publicKeyB64 = urlOrOptions.publicKeyB64 ?? TEST_PARTNER_PUBLIC_KEY_SPKI_B64;
238
3470
  customerUrl = urlOrOptions.customerUrl;
3471
+ acceptedUpdateTypes = urlOrOptions.acceptedUpdateTypes ?? [];
3472
+ verifiesAccountReference = urlOrOptions.verifiesAccountReference === true;
3473
+ supportsKeyCrossover = urlOrOptions.supportsKeyCrossover === true;
239
3474
  } else {
240
3475
  targetUrl = urlOrOptions;
241
3476
  }
242
3477
  const results = [];
243
3478
  const sharedBody = await buildBody(partnerId, publicKeyB64);
3479
+ let declaration = readAcceptedUpdateKindsFromAck(null);
3480
+ let check1Accepted;
244
3481
  {
245
3482
  const ts = String(Math.floor(Date.now() / 1e3));
246
3483
  const sig = sign(sharedBody, ts, secret);
247
- const { status, error } = await post(targetUrl, sharedBody, buildHeaders(partnerId, ts, sig, "1"));
3484
+ const { status, error, body: ackBody } = await post(targetUrl, sharedBody, buildHeaders(partnerId, ts, sig, "1"));
248
3485
  const passed = !error && status >= 200 && status < 300;
3486
+ check1Accepted = passed;
3487
+ if (passed) declaration = readAcceptedUpdateKindsFromAck(ackBody);
249
3488
  results.push({
250
3489
  id: "check-1",
3490
+ basis: "acceptance",
251
3491
  label: "Accepts correctly signed webhook",
252
3492
  passed,
253
3493
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx`
@@ -261,6 +3501,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
261
3501
  const passed = !error && status >= 400 && status < 500;
262
3502
  results.push({
263
3503
  id: "check-2",
3504
+ basis: "rejection",
264
3505
  label: "Rejects invalid signature",
265
3506
  passed,
266
3507
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
@@ -273,6 +3514,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
273
3514
  const passed = !error && status >= 400 && status < 500;
274
3515
  results.push({
275
3516
  id: "check-3",
3517
+ basis: "rejection",
276
3518
  label: "Rejects stale timestamp (replay protection)",
277
3519
  passed,
278
3520
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
@@ -285,6 +3527,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
285
3527
  const passed = !error && status >= 400 && status < 500;
286
3528
  results.push({
287
3529
  id: "check-4",
3530
+ basis: "rejection",
288
3531
  label: "Rejects future timestamp (\xB1300s window)",
289
3532
  passed,
290
3533
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
@@ -297,6 +3540,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
297
3540
  const passed = !error && durationMs < 1e4;
298
3541
  results.push({
299
3542
  id: "check-5",
3543
+ basis: "liveness",
300
3544
  label: "Responds within 10 seconds",
301
3545
  passed,
302
3546
  detail: error ? `Network error: ${error}` : `${durationMs}ms \u2014 limit is 10 000ms`
@@ -310,6 +3554,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
310
3554
  const passed = !error && status >= 200 && status < 300;
311
3555
  results.push({
312
3556
  id: "check-6",
3557
+ basis: "acceptance",
313
3558
  label: "Handles unknown fields gracefully (forward compat)",
314
3559
  passed,
315
3560
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx`
@@ -334,6 +3579,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
334
3579
  const passed = !error && status >= 200 && status < 300;
335
3580
  results.push({
336
3581
  id: "check-7",
3582
+ basis: "acceptance",
337
3583
  label: "Accepts unknown event type gracefully",
338
3584
  passed,
339
3585
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx (acknowledge, do not error on new event types)`
@@ -368,6 +3614,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
368
3614
  const passed = bothOk && hasDupe;
369
3615
  results.push({
370
3616
  id: "check-8",
3617
+ basis: "acceptance",
371
3618
  label: "Idempotent: duplicate dispatch_id \u2192 200 + { duplicate: true }",
372
3619
  passed,
373
3620
  detail: e1 ? `Network error: ${e1}` : !bothOk ? `First: HTTP ${s1}, Second: HTTP ${s2} \u2014 both expected 2xx` : !hasDupe ? `Both returned 2xx but second response body missing { duplicate: true } \u2014 idempotency store not wired` : `First: HTTP ${s1}, Second: HTTP ${s2} with duplicate:true`
@@ -381,6 +3628,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
381
3628
  const passed = !error && status >= 400 && status < 500;
382
3629
  results.push({
383
3630
  id: "check-9",
3631
+ basis: "rejection",
384
3632
  label: "Rejects malformed JSON body with 4xx",
385
3633
  passed,
386
3634
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
@@ -397,11 +3645,201 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
397
3645
  const passed = !error && status >= 200 && status < 300;
398
3646
  results.push({
399
3647
  id: "check-10",
3648
+ basis: "acceptance",
400
3649
  label: "Accepts timestamp near replay-window edge (4m55s old)",
401
3650
  passed,
402
3651
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx (timestamp is within the \xB1300s window)`
403
3652
  });
404
3653
  }
3654
+ {
3655
+ const throwaway = import_node_crypto.default.generateKeyPairSync("ec", { namedCurve: "prime256v1" });
3656
+ const foreignKey = throwaway.publicKey.export({ type: "spki", format: "der" }).toString("base64");
3657
+ const foreignBody = await buildBody(partnerId, foreignKey);
3658
+ const ts = String(Math.floor(Date.now() / 1e3));
3659
+ const sig = sign(foreignBody, ts, secret);
3660
+ const res = await fetch(targetUrl, {
3661
+ method: "POST",
3662
+ headers: buildHeaders(partnerId, ts, sig, `undecryptable-${import_node_crypto.default.randomUUID().slice(0, 8)}`),
3663
+ body: foreignBody,
3664
+ signal: AbortSignal.timeout(12e3)
3665
+ }).catch(() => null);
3666
+ const status = res?.status ?? 0;
3667
+ const bodyText = res ? await res.text().catch(() => "") : "";
3668
+ let parsed = {};
3669
+ try {
3670
+ parsed = JSON.parse(bodyText);
3671
+ } catch {
3672
+ }
3673
+ const reachable = res !== null;
3674
+ const httpFailure = status >= 400;
3675
+ const bodyFailure = parsed.ok === false;
3676
+ const passed = reachable && (httpFailure || bodyFailure);
3677
+ results.push({
3678
+ id: "check-11",
3679
+ basis: "rejection",
3680
+ label: "Reports undecryptable payload as a failure (not 200 ok:true)",
3681
+ passed,
3682
+ detail: !reachable ? "Network error: no response" : passed ? `HTTP ${status}${bodyFailure ? " with ok:false" : ""} \u2014 correctly reported as a failed delivery. This probe is now held by your receiver, which is how the check was passed: it is one undecryptable dispatch, not a fault in your setup. Clear it with [d] on the dashboard.` : `HTTP ${status} without ok:false \u2014 a payload this receiver CANNOT decrypt was reported as delivered. OneAddress will mark it delivered and never retry it. Return a 4xx/5xx, or 200 with { ok: false }, when decryption fails.`
3683
+ });
3684
+ }
3685
+ if (verifiesAccountReference) {
3686
+ const nonce = import_node_crypto.default.randomUUID();
3687
+ const body = await buildBody(partnerId, publicKeyB64, void 0, "address", {
3688
+ account_number: `CONF-NOSUCH-${nonce}`,
3689
+ verified_name: `Nomatch ${nonce.slice(0, 8)}`,
3690
+ known_names: [`Nomatch ${nonce.slice(0, 8)}`]
3691
+ });
3692
+ const ts = String(Math.floor(Date.now() / 1e3));
3693
+ const sig = sign(body, ts, secret);
3694
+ const res = await fetch(targetUrl, {
3695
+ method: "POST",
3696
+ headers: buildHeaders(partnerId, ts, sig, `nomatch-${nonce.slice(0, 8)}`),
3697
+ body,
3698
+ signal: AbortSignal.timeout(12e3)
3699
+ }).catch(() => null);
3700
+ const status = res?.status ?? 0;
3701
+ const bodyText = res ? await res.text().catch(() => "") : "";
3702
+ let parsed = {};
3703
+ try {
3704
+ parsed = JSON.parse(bodyText);
3705
+ } catch {
3706
+ }
3707
+ const reachable = res !== null;
3708
+ const claimsuccess = status >= 200 && status < 300 && parsed.ok === true;
3709
+ const passed = reachable && !claimsuccess;
3710
+ results.push({
3711
+ id: "check-14",
3712
+ basis: "rejection",
3713
+ label: "Refuses an account reference that matches no record (no name fallback)",
3714
+ passed,
3715
+ detail: !reachable ? "Network error: no response" : passed ? `HTTP ${status}${parsed.ok === false ? " with ok:false" : ""} \u2014 an unmatchable account reference was not reported as applied` : `HTTP ${status} with ok:true \u2014 an account reference matching NO record was reported as successfully applied. If your matching falls back to the customer's NAME when the account number misses, you will write one customer's address onto another customer's record. An account number that matches nothing must be a hard no-match: do not fall back to name, and do not accept a matching account number whose name disagrees with that record. Answer the webhook with ok:false so the consumer is told, which is what they were promised before they paid, and confirm the dispatch as "no_match" rather than "failed": "failed" means YOUR system broke and makes the update refundable at your expense, while "no_match" says the person is simply not on your books. This check reads the webhook response only, so it cannot see which status you send; getting it wrong costs you money rather than failing here.`
3716
+ });
3717
+ }
3718
+ const plan = kindProbePlan(declaration, acceptedUpdateTypes);
3719
+ results.push({
3720
+ id: "check-kinds-declared",
3721
+ basis: "declaration",
3722
+ label: "Declares the update kinds its code accepts (accepted_update_types on the ack)",
3723
+ passed: check1Accepted && !declaration.malformed,
3724
+ detail: !check1Accepted ? "No acknowledgement to read: check-1 did not pass." : declaration.malformed ? "accepted_update_types was present but not an array. That is a broken receiver, not an older one: the field must be a list of kinds (address, phone, email)." : !declaration.declared ? "No declaration on the acknowledgement. This receiver predates capability declarations, so the kinds accepted in the partner portal are tested on trust and cannot be refused by the receiver when undeclared. Upgrade @oneaddress/partner-sdk and set acceptedUpdateTypes." : `Declares: ${declaration.kinds.join(", ")}` + (declaration.ignored.length > 0 ? `. Also named ${declaration.ignored.join(", ")}, which this tool does not define and did not record (newer SDK than conformance tool?).` : ".")
3725
+ });
3726
+ {
3727
+ const contactKinds = plan.accept;
3728
+ for (const kind of contactKinds) {
3729
+ const article = kind === "email" ? "an" : "a";
3730
+ const body = await buildBody(partnerId, publicKeyB64, void 0, kind);
3731
+ const ts = String(Math.floor(Date.now() / 1e3));
3732
+ const sig = sign(body, ts, secret);
3733
+ const res = await fetch(targetUrl, {
3734
+ method: "POST",
3735
+ // `contact.updated`, matching what the relay now sends for a dispatch
3736
+ // carrying no address (`dispatchEventName`). This line previously said
3737
+ // `address.updated` and was right at the time: the composer hardcoded
3738
+ // that string, and a conformance suite testing a tidier shape than
3739
+ // production sends would pass receivers that production still breaks.
3740
+ //
3741
+ // The relay changed on 14 Aug 2026, so the faithful value changed with
3742
+ // it. Note what did NOT change: an address-bearing dispatch is still
3743
+ // `address.updated`, so no existing integration sees a new event — only
3744
+ // a partner who has widened their accept-set can receive this one, and
3745
+ // by doing so they asked for it.
3746
+ headers: buildHeaders(
3747
+ partnerId,
3748
+ ts,
3749
+ sig,
3750
+ `contact-${kind}-${import_node_crypto.default.randomUUID().slice(0, 8)}`,
3751
+ "contact.updated"
3752
+ ),
3753
+ body,
3754
+ signal: AbortSignal.timeout(12e3)
3755
+ }).catch(() => null);
3756
+ const status = res?.status ?? 0;
3757
+ const bodyText = res ? await res.text().catch(() => "") : "";
3758
+ let parsed = {};
3759
+ try {
3760
+ parsed = JSON.parse(bodyText);
3761
+ } catch {
3762
+ }
3763
+ const refusedForItsAccount = verifiesAccountReference && parsed.ok === false && parsed.error === "account_not_matched";
3764
+ const passed = res !== null && status >= 200 && status < 300 && (parsed.ok !== false || refusedForItsAccount) && parsed.skipped !== true;
3765
+ results.push({
3766
+ id: `check-contact-${kind}`,
3767
+ basis: "acceptance",
3768
+ label: `Accepts ${article} ${kind}-only update (no address in the envelope)`,
3769
+ passed,
3770
+ detail: res === null ? "Network error: no response" : passed && refusedForItsAccount ? `HTTP ${status} with ok:false (account_not_matched) \u2014 handled. This probe's account is not one of yours, and you check the account reference, so refusing it is correct. It shows the envelope with no address was read and not thrown on; it does not show the ${kind} is stored.` : passed ? `HTTP ${status} \u2014 accepted. NOTE: this proves the envelope was accepted, not that the ${kind} was stored. Confirm your outbox has a column for it.` : parsed.skipped === true ? `HTTP ${status} with skipped:true \u2014 this receiver ACKNOWLEDGED the update and stored nothing. It is treating '${"contact.updated"}' as an unknown event, which means it predates contact updates. Upgrade it, or narrow your accept-set in the partner portal until you have. A 200 here would otherwise look identical to a delivery.` : `HTTP ${status}${parsed.ok === false ? " with ok:false" : ""} \u2014 this receiver did not accept ${article} ${kind}-only update, but your OneAddress accept-set says you take them. A contact update carries NO new_address: code that reads it unguarded will throw. Either handle the absent address, or narrow your accept-set in the partner portal.`
3771
+ });
3772
+ }
3773
+ }
3774
+ results.push({
3775
+ id: "check-kinds-consent-declared",
3776
+ basis: "declaration",
3777
+ label: "Every kind accepted in the partner portal is declared by the receiver",
3778
+ passed: plan.consentBeyondDeclaration.length === 0,
3779
+ detail: !declaration.declared ? "Nothing to compare: the receiver made no declaration (see check-kinds-declared)." : plan.consentBeyondDeclaration.length === 0 ? `Portal accepts ${["address", ...plan.accept].join(", ")}; the receiver declares ${declaration.kinds.join(", ")}.` : `The portal accepts ${plan.consentBeyondDeclaration.join(" and ")} but the receiver's code declares only ${declaration.kinds.join(", ")}. A dispatch of that kind would be refused (422) and retried until it gave up, after the consumer had paid. Narrow the accept-set in the partner portal, or widen acceptedUpdateTypes once onUpdate stores the value.`
3780
+ });
3781
+ if (plan.refuse !== null) {
3782
+ const probe = plan.refuse;
3783
+ const body = await buildBody(partnerId, publicKeyB64, void 0, probe);
3784
+ const ts = String(Math.floor(Date.now() / 1e3));
3785
+ const sig = sign(body, ts, secret);
3786
+ const res = await fetch(targetUrl, {
3787
+ method: "POST",
3788
+ headers: buildHeaders(
3789
+ partnerId,
3790
+ ts,
3791
+ sig,
3792
+ `refuse-${probe}-${import_node_crypto.default.randomUUID().slice(0, 8)}`,
3793
+ "contact.updated"
3794
+ ),
3795
+ body,
3796
+ signal: AbortSignal.timeout(12e3)
3797
+ }).catch(() => null);
3798
+ const status = res?.status ?? 0;
3799
+ if (res) await res.text().catch(() => "");
3800
+ const passed = res !== null && status >= 400 && status < 500;
3801
+ results.push({
3802
+ id: "check-kinds-refuses-undeclared",
3803
+ basis: "rejection",
3804
+ label: `Refuses an update kind it did not declare (${probe})`,
3805
+ passed,
3806
+ detail: res === null ? "Network error: no response" : passed ? `HTTP ${status}, a dispatch carrying an undeclared kind was refused, so nothing it did not promise to handle can be acknowledged and dropped.` : `HTTP ${status}, this receiver ACKNOWLEDGED a dispatch carrying a kind (${probe}) it never declared. That is the silent-loss shape: the consumer is told the update was delivered and the value went nowhere. Refuse it with a 4xx (the SDK answers 422 update_type_not_accepted) so OneAddress retries once you have widened acceptedUpdateTypes.`
3807
+ });
3808
+ }
3809
+ if (supportsKeyCrossover) {
3810
+ const throwaway = import_node_crypto.default.generateKeyPairSync("ec", { namedCurve: "prime256v1" });
3811
+ const foreignKey = throwaway.publicKey.export({ type: "spki", format: "der" }).toString("base64");
3812
+ const base = JSON.parse(await buildBody(partnerId, foreignKey));
3813
+ const heldKeyId = "conformance-key-1";
3814
+ const stagedKeyId = "conformance-crossover-staged";
3815
+ base.session_key_share.key_id = stagedKeyId;
3816
+ base.crossover_key_ids = [stagedKeyId, heldKeyId];
3817
+ const body = JSON.stringify(base);
3818
+ const ts = String(Math.floor(Date.now() / 1e3));
3819
+ const sig = sign(body, ts, secret);
3820
+ const res = await fetch(targetUrl, {
3821
+ method: "POST",
3822
+ headers: buildHeaders(partnerId, ts, sig, `crossover-${import_node_crypto.default.randomUUID().slice(0, 8)}`),
3823
+ body,
3824
+ signal: AbortSignal.timeout(12e3)
3825
+ }).catch(() => null);
3826
+ const status = res?.status ?? 0;
3827
+ const bodyText = res ? await res.text().catch(() => "") : "";
3828
+ let parsed = {};
3829
+ try {
3830
+ parsed = JSON.parse(bodyText);
3831
+ } catch {
3832
+ }
3833
+ const reachable = res !== null;
3834
+ const passed = reachable && status >= 200 && status < 300 && parsed.crossover === true;
3835
+ results.push({
3836
+ id: "check-15",
3837
+ basis: "acceptance",
3838
+ label: "Skips a key-crossover sibling copy it cannot decrypt (does not error)",
3839
+ passed,
3840
+ detail: !reachable ? "Network error: no response" : passed ? `HTTP ${status} with crossover:true \u2014 a copy sealed to a rotation sibling key was correctly skip-acked; the copy sealed to a held key carries the update` : `HTTP ${status} \u2014 a copy naming one of this receiver's keys as a crossover sibling was not skip-acked. During a key rotation a copy sealed to your OTHER key must be skipped (a decryptable sibling copy is coming), signalled with { ok: true, skipped: true, crossover: true }. A 500 here drops one copy of a live update; a bare 200 ok:true without crossover:true is check-11's silent-loss shape. Configure your handler's key_id (or key store) so it recognises the marker, or clear "supports key crossover" until you have.`
3841
+ });
3842
+ }
405
3843
  if (customerUrl) {
406
3844
  const pullBase = customerUrl.replace(/\/$/, "");
407
3845
  {
@@ -414,7 +3852,8 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
414
3852
  });
415
3853
  const passed = !error && status === 200;
416
3854
  results.push({
417
- id: "check-11",
3855
+ id: "check-12",
3856
+ basis: "acceptance",
418
3857
  label: "Pull /updates \u2014 authenticated GET returns 200",
419
3858
  passed,
420
3859
  detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 200`
@@ -429,7 +3868,7 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
429
3868
  "X-OneAddress-Signature": sig
430
3869
  });
431
3870
  let passed = false;
432
- let detail = "";
3871
+ let detail;
433
3872
  if (error) {
434
3873
  detail = `Network error: ${error}`;
435
3874
  } else if (status !== 200) {
@@ -450,51 +3889,139 @@ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId =
450
3889
  }
451
3890
  }
452
3891
  results.push({
453
- id: "check-12",
3892
+ id: "check-13",
3893
+ basis: "acceptance",
454
3894
  label: "Pull /audit \u2014 response is correctly signed",
455
3895
  passed,
456
3896
  detail
457
3897
  });
458
3898
  }
459
3899
  }
460
- return results;
3900
+ return markUnprovenChecks(results);
3901
+ }
3902
+ function markUnprovenChecks(results) {
3903
+ const anythingAccepted = results.some((r) => r.basis === "acceptance" && r.passed);
3904
+ if (anythingAccepted) return results;
3905
+ return results.map((r) => {
3906
+ if (!r.passed || r.basis === "acceptance") return r;
3907
+ return {
3908
+ ...r,
3909
+ passed: false,
3910
+ unproven: true,
3911
+ // Short on purpose. This line repeats on every downgraded row, and the
3912
+ // full reasoning belongs once in the summary rather than six times in
3913
+ // the body of the one artefact partners screenshot.
3914
+ detail: "Not proven: nothing was accepted, so a refusal demonstrates nothing."
3915
+ };
3916
+ });
461
3917
  }
462
3918
 
463
3919
  // src/report.ts
464
- var PASS = "\u2705";
465
- var FAIL = "\u274C";
466
- function printReport(results) {
467
- const width = 50;
468
- console.log("\n" + "\u2500".repeat(width));
469
- console.log(" OneAddress Conformance Report");
470
- console.log("\u2500".repeat(width));
471
- for (const r of results) {
472
- const icon = r.passed ? PASS : FAIL;
473
- const status = r.passed ? "PASSED" : "FAILED";
474
- const label = r.label.padEnd(40);
475
- console.log(` ${icon} ${label} ${status}`);
3920
+ var PASS = "\u2713";
3921
+ var FAIL = "\u2717";
3922
+ var UNPROVEN = "?";
3923
+ var ICON_COLUMNS = 1;
3924
+ function verdictOf(r) {
3925
+ if (r.unproven) return { icon: UNPROVEN, status: "UNPROVEN" };
3926
+ return r.passed ? { icon: PASS, status: "PASSED" } : { icon: FAIL, status: "FAILED" };
3927
+ }
3928
+ var TITLE = " OneAddress Conformance Report";
3929
+ function formatReport(results) {
3930
+ const labelWidth = Math.max(0, ...results.map((r) => r.label.length));
3931
+ const rows = results.map((r) => {
3932
+ const { icon, status } = verdictOf(r);
3933
+ return ` ${icon} ${r.label.padEnd(labelWidth)} ${status}`;
3934
+ });
3935
+ const widestRow = Math.max(0, ...rows.map((row) => row.length + ICON_COLUMNS - 1));
3936
+ const rule = "\u2500".repeat(Math.max(widestRow, TITLE.length));
3937
+ const lines = ["", rule, TITLE, rule];
3938
+ results.forEach((r, i) => {
3939
+ lines.push(rows[i]);
476
3940
  if (!r.passed) {
477
- console.log(` \u21B3 ${r.detail}`);
3941
+ lines.push(` \u21B3 ${r.detail}`);
478
3942
  }
479
- }
3943
+ });
3944
+ lines.push(rule);
480
3945
  const passed = results.filter((r) => r.passed).length;
3946
+ const unproven = results.filter((r) => r.unproven).length;
481
3947
  const total = results.length;
482
- console.log("\u2500".repeat(width));
3948
+ lines.push("");
483
3949
  if (passed === total) {
484
- console.log(`
485
- ${PASS} ${passed}/${total} checks passed. Your integration is ready.`);
486
- console.log(" Replace credentials in .env with your real portal keys to go live.\n");
3950
+ lines.push(` ${PASS} ${passed}/${total} checks passed. Your integration is ready.`);
3951
+ lines.push(" Replace credentials in .env with your real portal keys to go live.");
487
3952
  } else {
488
- console.log(`
489
- ${FAIL} ${passed}/${total} checks passed. See failures above.
490
- `);
491
- console.log(" Docs: https://docs.oneaddress.io/integration/SPEC.md\n");
3953
+ lines.push(` ${FAIL} ${passed}/${total} checks passed. See failures above.`);
3954
+ if (unproven > 0) {
3955
+ lines.push("");
3956
+ lines.push(
3957
+ ` ${unproven} check${unproven === 1 ? " was" : "s were"} UNPROVEN, not passed.`
3958
+ );
3959
+ lines.push(" This receiver never accepted a valid webhook, so refusing an invalid");
3960
+ lines.push(" one demonstrates nothing: an endpoint that is offline, at the wrong");
3961
+ lines.push(" URL, or holding the wrong webhook secret refuses them the same way.");
3962
+ lines.push(" Fix the failing acceptance checks, then re-run.");
3963
+ }
3964
+ lines.push("");
3965
+ lines.push(" Docs: https://docs.oneaddress.io/integrations/SPEC.md");
492
3966
  }
3967
+ lines.push("");
3968
+ return lines;
3969
+ }
3970
+ function printReport(results) {
3971
+ for (const line of formatReport(results)) console.log(line);
493
3972
  }
494
3973
  function exitCode(results) {
495
3974
  return results.every((r) => r.passed) ? 0 : 1;
496
3975
  }
497
3976
 
3977
+ // src/resolve-credentials.ts
3978
+ function resolveOne(flag, envVar, env, fallback) {
3979
+ if (flag !== void 0 && flag !== "") return { value: flag, source: "flag", envVar };
3980
+ const fromEnv = env[envVar]?.trim();
3981
+ if (fromEnv) return { value: fromEnv, source: "env", envVar };
3982
+ return { value: fallback, source: "built-in test value", envVar };
3983
+ }
3984
+ function resolveCredentials(flags, env = process.env) {
3985
+ const secret = resolveOne(flags.secret, "ONEADDRESS_WEBHOOK_SECRET", env, TEST_WEBHOOK_SECRET);
3986
+ const partnerId = resolveOne(flags.partnerId, "ONEADDRESS_PARTNER_ID", env, TEST_PARTNER_ID);
3987
+ const publicKeyB64 = resolveOne(
3988
+ flags.publicKey,
3989
+ "ONEADDRESS_PUBLIC_KEY",
3990
+ env,
3991
+ TEST_PARTNER_PUBLIC_KEY_SPKI_B64
3992
+ );
3993
+ return {
3994
+ secret,
3995
+ partnerId,
3996
+ publicKeyB64,
3997
+ allBuiltIn: [secret, partnerId, publicKeyB64].every((c) => c.source === "built-in test value")
3998
+ };
3999
+ }
4000
+ function describeCredentials(c) {
4001
+ if (c.allBuiltIn) {
4002
+ return [
4003
+ "Using BUILT-IN TEST CREDENTIALS: no --secret / --partner-id / --public-key,",
4004
+ "and no ONEADDRESS_WEBHOOK_SECRET / ONEADDRESS_PARTNER_ID / ONEADDRESS_PUBLIC_KEY.",
4005
+ "",
4006
+ "That is correct for a scaffold from `npx @oneaddress/setup`, which is built",
4007
+ "around these same values. A REAL receiver will reject every request, including",
4008
+ "the well-formed one, because it validates against its own secret. Your partner",
4009
+ "portal has the values, and the safer way to pass them keeps the secret out of",
4010
+ "your shell history and out of `ps`:",
4011
+ "",
4012
+ " export ONEADDRESS_WEBHOOK_SECRET=whsec_...",
4013
+ ""
4014
+ ];
4015
+ }
4016
+ const missing = [c.secret, c.partnerId, c.publicKeyB64].filter((x) => x.source === "built-in test value").map((x) => x.envVar);
4017
+ if (missing.length === 0) return [];
4018
+ return [
4019
+ `Some credentials were supplied and some were not: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} still a built-in test value.`,
4020
+ "Against a real receiver a partial set fails the same way a wrong one does.",
4021
+ ""
4022
+ ];
4023
+ }
4024
+
498
4025
  // src/index.ts
499
4026
  var USAGE = `
500
4027
  Usage: oneaddress-conformance test <webhook-url>
@@ -503,13 +4030,37 @@ Options:
503
4030
  --secret <webhook_secret> Webhook secret from the OneAddress Partner Portal (default: built-in test secret)
504
4031
  --partner-id <uuid> Partner UUID (default: built-in test ID)
505
4032
  --public-key <b64> Partner ECDH public key SPKI Base64 (default: built-in test key)
4033
+
4034
+ Each of the three can also come from the environment, which keeps a secret out
4035
+ of your shell history and out of the process list. A flag wins over a variable.
4036
+ ONEADDRESS_WEBHOOK_SECRET same as --secret
4037
+ ONEADDRESS_PARTNER_ID same as --partner-id
4038
+ ONEADDRESS_PUBLIC_KEY same as --public-key
506
4039
  --customer-url <url> Customer app URL for pull API checks (adds checks 9 + 10)
4040
+ --accept <kinds> Comma-separated update kinds you accept: address,phone,email.
4041
+ Adds a check per contact kind. Match this to your accept-set
4042
+ in the partner portal \u2014 a phone update carries NO address,
4043
+ and code that reads one unguarded will throw.
4044
+ --verifies-account-reference
4045
+ Set this when your receiver matches a dispatch to a customer
4046
+ record itself, rather than queueing it for something else to
4047
+ match later. Adds check-14, which sends an account reference
4048
+ that cannot match anything and fails a receiver that answers
4049
+ ok:true to it. Match it to the declaration in your partner
4050
+ portal \u2014 a receiver that only writes to an outbox has no way
4051
+ to know whether a reference matches, so the check would
4052
+ report a defect it cannot have.
507
4053
 
508
4054
  Example:
509
4055
  oneaddress-conformance test http://localhost:3001/webhook
4056
+ ONEADDRESS_WEBHOOK_SECRET=whsec_xxx oneaddress-conformance test https://api.mycompany.com/oneaddress
510
4057
  oneaddress-conformance test https://api.mycompany.com/oneaddress --secret whsec_real_xxx
511
4058
  oneaddress-conformance test https://api.mycompany.com/oneaddress \\
512
- --secret whsec_xxx --partner-id aaa... --customer-url https://app.oneaddress.io
4059
+ --secret whsec_xxx --accept address,phone
4060
+ oneaddress-conformance test https://api.mycompany.com/oneaddress \\
4061
+ --secret whsec_xxx --verifies-account-reference
4062
+ oneaddress-conformance test https://api.mycompany.com/oneaddress \\
4063
+ --secret whsec_xxx --partner-id aaa... --customer-url https://oneaddress.io
513
4064
  `.trim();
514
4065
  async function main() {
515
4066
  const args = process.argv.slice(2);
@@ -522,10 +4073,22 @@ async function main() {
522
4073
  const idx = args.indexOf(flag);
523
4074
  return idx !== -1 ? args[idx + 1] : void 0;
524
4075
  };
525
- const secret = getFlag("--secret");
526
- const partnerId = getFlag("--partner-id");
527
- const publicKey = getFlag("--public-key");
4076
+ const creds = resolveCredentials({
4077
+ secret: getFlag("--secret"),
4078
+ partnerId: getFlag("--partner-id"),
4079
+ publicKey: getFlag("--public-key")
4080
+ });
4081
+ const secret = creds.secret.value;
4082
+ const partnerId = creds.partnerId.value;
4083
+ const publicKey = creds.publicKeyB64.value;
528
4084
  const customerUrl = getFlag("--customer-url");
4085
+ const acceptedUpdateTypes = (getFlag("--accept") ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
4086
+ const verifiesAccountReference = args.includes("--verifies-account-reference");
4087
+ const UNKNOWN = acceptedUpdateTypes.filter((t) => !["address", "phone", "email"].includes(t));
4088
+ if (UNKNOWN.length > 0) {
4089
+ console.error(`Error: --accept has unknown kind(s): ${UNKNOWN.join(", ")}. Known: address, phone, email.`);
4090
+ process.exit(1);
4091
+ }
529
4092
  try {
530
4093
  new URL(targetUrl);
531
4094
  } catch {
@@ -553,18 +4116,21 @@ async function main() {
553
4116
  process.exit(1);
554
4117
  }
555
4118
  if (parsedTarget.protocol === "http:" && isLocalhost) {
556
- console.warn("\n \u26A0 HTTP detected \u2014 acceptable for local testing only.\n");
4119
+ console.warn("\n ! HTTP detected \u2014 acceptable for local testing only.\n");
557
4120
  }
558
4121
  console.log(`
559
4122
  Running conformance checks against: ${targetUrl}`);
560
4123
  if (customerUrl) console.log(`Pull API checks against: ${customerUrl}`);
561
4124
  console.log("");
4125
+ for (const line of describeCredentials(creds)) console.log(line ? ` ${line}` : "");
562
4126
  const results = await runChecks({
563
4127
  targetUrl,
564
4128
  secret,
565
4129
  partnerId,
566
4130
  publicKeyB64: publicKey,
567
- customerUrl
4131
+ customerUrl,
4132
+ acceptedUpdateTypes,
4133
+ verifiesAccountReference
568
4134
  });
569
4135
  printReport(results);
570
4136
  const code = exitCode(results);
@@ -576,3 +4142,19 @@ main().catch((err) => {
576
4142
  process.exitCode = 1;
577
4143
  setTimeout(() => process.exit(1), 50).unref();
578
4144
  });
4145
+ /*! Bundled license information:
4146
+
4147
+ @noble/curves/utils.js:
4148
+ @noble/curves/abstract/modular.js:
4149
+ @noble/curves/abstract/curve.js:
4150
+ @noble/curves/abstract/edwards.js:
4151
+ @noble/curves/abstract/montgomery.js:
4152
+ @noble/curves/ed25519.js:
4153
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4154
+
4155
+ @noble/post-quantum/utils.js:
4156
+ @noble/post-quantum/_crystals.js:
4157
+ @noble/post-quantum/ml-kem.js:
4158
+ @noble/post-quantum/hybrid.js:
4159
+ (*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *)
4160
+ */