@oneaddress/conformance 3.1.0 → 3.2.0

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