@lumiapassport/ui-kit 1.0.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.
@@ -0,0 +1,2967 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/data/isHex.js
12
+ function isHex(value, { strict = true } = {}) {
13
+ if (!value)
14
+ return false;
15
+ if (typeof value !== "string")
16
+ return false;
17
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x");
18
+ }
19
+ var init_isHex = __esm({
20
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/data/isHex.js"() {
21
+ }
22
+ });
23
+
24
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/data/size.js
25
+ function size(value) {
26
+ if (isHex(value, { strict: false }))
27
+ return Math.ceil((value.length - 2) / 2);
28
+ return value.length;
29
+ }
30
+ var init_size = __esm({
31
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/data/size.js"() {
32
+ init_isHex();
33
+ }
34
+ });
35
+
36
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/version.js
37
+ var version;
38
+ var init_version = __esm({
39
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/version.js"() {
40
+ version = "2.38.0";
41
+ }
42
+ });
43
+
44
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/base.js
45
+ function walk(err, fn) {
46
+ if (fn?.(err))
47
+ return err;
48
+ if (err && typeof err === "object" && "cause" in err && err.cause !== void 0)
49
+ return walk(err.cause, fn);
50
+ return fn ? null : err;
51
+ }
52
+ var errorConfig, BaseError;
53
+ var init_base = __esm({
54
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/base.js"() {
55
+ init_version();
56
+ errorConfig = {
57
+ getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0,
58
+ version: `viem@${version}`
59
+ };
60
+ BaseError = class _BaseError extends Error {
61
+ constructor(shortMessage, args = {}) {
62
+ const details = (() => {
63
+ if (args.cause instanceof _BaseError)
64
+ return args.cause.details;
65
+ if (args.cause?.message)
66
+ return args.cause.message;
67
+ return args.details;
68
+ })();
69
+ const docsPath = (() => {
70
+ if (args.cause instanceof _BaseError)
71
+ return args.cause.docsPath || args.docsPath;
72
+ return args.docsPath;
73
+ })();
74
+ const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });
75
+ const message = [
76
+ shortMessage || "An error occurred.",
77
+ "",
78
+ ...args.metaMessages ? [...args.metaMessages, ""] : [],
79
+ ...docsUrl ? [`Docs: ${docsUrl}`] : [],
80
+ ...details ? [`Details: ${details}`] : [],
81
+ ...errorConfig.version ? [`Version: ${errorConfig.version}`] : []
82
+ ].join("\n");
83
+ super(message, args.cause ? { cause: args.cause } : void 0);
84
+ Object.defineProperty(this, "details", {
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ value: void 0
89
+ });
90
+ Object.defineProperty(this, "docsPath", {
91
+ enumerable: true,
92
+ configurable: true,
93
+ writable: true,
94
+ value: void 0
95
+ });
96
+ Object.defineProperty(this, "metaMessages", {
97
+ enumerable: true,
98
+ configurable: true,
99
+ writable: true,
100
+ value: void 0
101
+ });
102
+ Object.defineProperty(this, "shortMessage", {
103
+ enumerable: true,
104
+ configurable: true,
105
+ writable: true,
106
+ value: void 0
107
+ });
108
+ Object.defineProperty(this, "version", {
109
+ enumerable: true,
110
+ configurable: true,
111
+ writable: true,
112
+ value: void 0
113
+ });
114
+ Object.defineProperty(this, "name", {
115
+ enumerable: true,
116
+ configurable: true,
117
+ writable: true,
118
+ value: "BaseError"
119
+ });
120
+ this.details = details;
121
+ this.docsPath = docsPath;
122
+ this.metaMessages = args.metaMessages;
123
+ this.name = args.name ?? this.name;
124
+ this.shortMessage = shortMessage;
125
+ this.version = version;
126
+ }
127
+ walk(fn) {
128
+ return walk(this, fn);
129
+ }
130
+ };
131
+ }
132
+ });
133
+
134
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/data.js
135
+ var SizeExceedsPaddingSizeError;
136
+ var init_data = __esm({
137
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/data.js"() {
138
+ init_base();
139
+ SizeExceedsPaddingSizeError = class extends BaseError {
140
+ constructor({ size: size2, targetSize, type }) {
141
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
142
+ }
143
+ };
144
+ }
145
+ });
146
+
147
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/data/pad.js
148
+ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
149
+ if (typeof hexOrBytes === "string")
150
+ return padHex(hexOrBytes, { dir, size: size2 });
151
+ return padBytes(hexOrBytes, { dir, size: size2 });
152
+ }
153
+ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
154
+ if (size2 === null)
155
+ return hex_;
156
+ const hex = hex_.replace("0x", "");
157
+ if (hex.length > size2 * 2)
158
+ throw new SizeExceedsPaddingSizeError({
159
+ size: Math.ceil(hex.length / 2),
160
+ targetSize: size2,
161
+ type: "hex"
162
+ });
163
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`;
164
+ }
165
+ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
166
+ if (size2 === null)
167
+ return bytes;
168
+ if (bytes.length > size2)
169
+ throw new SizeExceedsPaddingSizeError({
170
+ size: bytes.length,
171
+ targetSize: size2,
172
+ type: "bytes"
173
+ });
174
+ const paddedBytes = new Uint8Array(size2);
175
+ for (let i = 0; i < size2; i++) {
176
+ const padEnd = dir === "right";
177
+ paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
178
+ }
179
+ return paddedBytes;
180
+ }
181
+ var init_pad = __esm({
182
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/data/pad.js"() {
183
+ init_data();
184
+ }
185
+ });
186
+
187
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/encoding.js
188
+ var IntegerOutOfRangeError, SizeOverflowError;
189
+ var init_encoding = __esm({
190
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/errors/encoding.js"() {
191
+ init_base();
192
+ IntegerOutOfRangeError = class extends BaseError {
193
+ constructor({ max, min, signed, size: size2, value }) {
194
+ super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" });
195
+ }
196
+ };
197
+ SizeOverflowError = class extends BaseError {
198
+ constructor({ givenSize, maxSize }) {
199
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" });
200
+ }
201
+ };
202
+ }
203
+ });
204
+
205
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/encoding/fromHex.js
206
+ function assertSize(hexOrBytes, { size: size2 }) {
207
+ if (size(hexOrBytes) > size2)
208
+ throw new SizeOverflowError({
209
+ givenSize: size(hexOrBytes),
210
+ maxSize: size2
211
+ });
212
+ }
213
+ var init_fromHex = __esm({
214
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/encoding/fromHex.js"() {
215
+ init_encoding();
216
+ init_size();
217
+ }
218
+ });
219
+
220
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/encoding/toHex.js
221
+ function toHex(value, opts = {}) {
222
+ if (typeof value === "number" || typeof value === "bigint")
223
+ return numberToHex(value, opts);
224
+ if (typeof value === "string") {
225
+ return stringToHex(value, opts);
226
+ }
227
+ if (typeof value === "boolean")
228
+ return boolToHex(value, opts);
229
+ return bytesToHex(value, opts);
230
+ }
231
+ function boolToHex(value, opts = {}) {
232
+ const hex = `0x${Number(value)}`;
233
+ if (typeof opts.size === "number") {
234
+ assertSize(hex, { size: opts.size });
235
+ return pad(hex, { size: opts.size });
236
+ }
237
+ return hex;
238
+ }
239
+ function bytesToHex(value, opts = {}) {
240
+ let string = "";
241
+ for (let i = 0; i < value.length; i++) {
242
+ string += hexes[value[i]];
243
+ }
244
+ const hex = `0x${string}`;
245
+ if (typeof opts.size === "number") {
246
+ assertSize(hex, { size: opts.size });
247
+ return pad(hex, { dir: "right", size: opts.size });
248
+ }
249
+ return hex;
250
+ }
251
+ function numberToHex(value_, opts = {}) {
252
+ const { signed, size: size2 } = opts;
253
+ const value = BigInt(value_);
254
+ let maxValue;
255
+ if (size2) {
256
+ if (signed)
257
+ maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
258
+ else
259
+ maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
260
+ } else if (typeof value_ === "number") {
261
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
262
+ }
263
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
264
+ if (maxValue && value > maxValue || value < minValue) {
265
+ const suffix = typeof value_ === "bigint" ? "n" : "";
266
+ throw new IntegerOutOfRangeError({
267
+ max: maxValue ? `${maxValue}${suffix}` : void 0,
268
+ min: `${minValue}${suffix}`,
269
+ signed,
270
+ size: size2,
271
+ value: `${value_}${suffix}`
272
+ });
273
+ }
274
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
275
+ if (size2)
276
+ return pad(hex, { size: size2 });
277
+ return hex;
278
+ }
279
+ function stringToHex(value_, opts = {}) {
280
+ const value = encoder.encode(value_);
281
+ return bytesToHex(value, opts);
282
+ }
283
+ var hexes, encoder;
284
+ var init_toHex = __esm({
285
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/encoding/toHex.js"() {
286
+ init_encoding();
287
+ init_pad();
288
+ init_fromHex();
289
+ hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
290
+ encoder = /* @__PURE__ */ new TextEncoder();
291
+ }
292
+ });
293
+
294
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/encoding/toBytes.js
295
+ function toBytes(value, opts = {}) {
296
+ if (typeof value === "number" || typeof value === "bigint")
297
+ return numberToBytes(value, opts);
298
+ if (typeof value === "boolean")
299
+ return boolToBytes(value, opts);
300
+ if (isHex(value))
301
+ return hexToBytes(value, opts);
302
+ return stringToBytes(value, opts);
303
+ }
304
+ function boolToBytes(value, opts = {}) {
305
+ const bytes = new Uint8Array(1);
306
+ bytes[0] = Number(value);
307
+ if (typeof opts.size === "number") {
308
+ assertSize(bytes, { size: opts.size });
309
+ return pad(bytes, { size: opts.size });
310
+ }
311
+ return bytes;
312
+ }
313
+ function charCodeToBase16(char) {
314
+ if (char >= charCodeMap.zero && char <= charCodeMap.nine)
315
+ return char - charCodeMap.zero;
316
+ if (char >= charCodeMap.A && char <= charCodeMap.F)
317
+ return char - (charCodeMap.A - 10);
318
+ if (char >= charCodeMap.a && char <= charCodeMap.f)
319
+ return char - (charCodeMap.a - 10);
320
+ return void 0;
321
+ }
322
+ function hexToBytes(hex_, opts = {}) {
323
+ let hex = hex_;
324
+ if (opts.size) {
325
+ assertSize(hex, { size: opts.size });
326
+ hex = pad(hex, { dir: "right", size: opts.size });
327
+ }
328
+ let hexString = hex.slice(2);
329
+ if (hexString.length % 2)
330
+ hexString = `0${hexString}`;
331
+ const length = hexString.length / 2;
332
+ const bytes = new Uint8Array(length);
333
+ for (let index = 0, j = 0; index < length; index++) {
334
+ const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
335
+ const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
336
+ if (nibbleLeft === void 0 || nibbleRight === void 0) {
337
+ throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
338
+ }
339
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
340
+ }
341
+ return bytes;
342
+ }
343
+ function numberToBytes(value, opts) {
344
+ const hex = numberToHex(value, opts);
345
+ return hexToBytes(hex);
346
+ }
347
+ function stringToBytes(value, opts = {}) {
348
+ const bytes = encoder2.encode(value);
349
+ if (typeof opts.size === "number") {
350
+ assertSize(bytes, { size: opts.size });
351
+ return pad(bytes, { dir: "right", size: opts.size });
352
+ }
353
+ return bytes;
354
+ }
355
+ var encoder2, charCodeMap;
356
+ var init_toBytes = __esm({
357
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/encoding/toBytes.js"() {
358
+ init_base();
359
+ init_isHex();
360
+ init_pad();
361
+ init_fromHex();
362
+ init_toHex();
363
+ encoder2 = /* @__PURE__ */ new TextEncoder();
364
+ charCodeMap = {
365
+ zero: 48,
366
+ nine: 57,
367
+ A: 65,
368
+ F: 70,
369
+ a: 97,
370
+ f: 102
371
+ };
372
+ }
373
+ });
374
+
375
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js
376
+ function fromBig(n, le = false) {
377
+ if (le)
378
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
379
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
380
+ }
381
+ function split(lst, le = false) {
382
+ const len = lst.length;
383
+ let Ah = new Uint32Array(len);
384
+ let Al = new Uint32Array(len);
385
+ for (let i = 0; i < len; i++) {
386
+ const { h, l } = fromBig(lst[i], le);
387
+ [Ah[i], Al[i]] = [h, l];
388
+ }
389
+ return [Ah, Al];
390
+ }
391
+ var U32_MASK64, _32n, rotlSH, rotlSL, rotlBH, rotlBL;
392
+ var init_u64 = __esm({
393
+ "../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js"() {
394
+ U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
395
+ _32n = /* @__PURE__ */ BigInt(32);
396
+ rotlSH = (h, l, s) => h << s | l >>> 32 - s;
397
+ rotlSL = (h, l, s) => l << s | h >>> 32 - s;
398
+ rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
399
+ rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
400
+ }
401
+ });
402
+
403
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
404
+ function isBytes(a) {
405
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
406
+ }
407
+ function anumber(n) {
408
+ if (!Number.isSafeInteger(n) || n < 0)
409
+ throw new Error("positive integer expected, got " + n);
410
+ }
411
+ function abytes(b, ...lengths) {
412
+ if (!isBytes(b))
413
+ throw new Error("Uint8Array expected");
414
+ if (lengths.length > 0 && !lengths.includes(b.length))
415
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
416
+ }
417
+ function aexists(instance, checkFinished = true) {
418
+ if (instance.destroyed)
419
+ throw new Error("Hash instance has been destroyed");
420
+ if (checkFinished && instance.finished)
421
+ throw new Error("Hash#digest() has already been called");
422
+ }
423
+ function aoutput(out, instance) {
424
+ abytes(out);
425
+ const min = instance.outputLen;
426
+ if (out.length < min) {
427
+ throw new Error("digestInto() expects output buffer of length at least " + min);
428
+ }
429
+ }
430
+ function u32(arr) {
431
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
432
+ }
433
+ function clean(...arrays) {
434
+ for (let i = 0; i < arrays.length; i++) {
435
+ arrays[i].fill(0);
436
+ }
437
+ }
438
+ function byteSwap(word) {
439
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
440
+ }
441
+ function byteSwap32(arr) {
442
+ for (let i = 0; i < arr.length; i++) {
443
+ arr[i] = byteSwap(arr[i]);
444
+ }
445
+ return arr;
446
+ }
447
+ function utf8ToBytes(str) {
448
+ if (typeof str !== "string")
449
+ throw new Error("string expected");
450
+ return new Uint8Array(new TextEncoder().encode(str));
451
+ }
452
+ function toBytes2(data) {
453
+ if (typeof data === "string")
454
+ data = utf8ToBytes(data);
455
+ abytes(data);
456
+ return data;
457
+ }
458
+ function createHasher(hashCons) {
459
+ const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
460
+ const tmp = hashCons();
461
+ hashC.outputLen = tmp.outputLen;
462
+ hashC.blockLen = tmp.blockLen;
463
+ hashC.create = () => hashCons();
464
+ return hashC;
465
+ }
466
+ var isLE, swap32IfBE, Hash;
467
+ var init_utils = __esm({
468
+ "../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js"() {
469
+ isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
470
+ swap32IfBE = isLE ? (u) => u : byteSwap32;
471
+ Hash = class {
472
+ };
473
+ }
474
+ });
475
+
476
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
477
+ function keccakP(s, rounds = 24) {
478
+ const B = new Uint32Array(5 * 2);
479
+ for (let round = 24 - rounds; round < 24; round++) {
480
+ for (let x = 0; x < 10; x++)
481
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
482
+ for (let x = 0; x < 10; x += 2) {
483
+ const idx1 = (x + 8) % 10;
484
+ const idx0 = (x + 2) % 10;
485
+ const B0 = B[idx0];
486
+ const B1 = B[idx0 + 1];
487
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
488
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
489
+ for (let y = 0; y < 50; y += 10) {
490
+ s[x + y] ^= Th;
491
+ s[x + y + 1] ^= Tl;
492
+ }
493
+ }
494
+ let curH = s[2];
495
+ let curL = s[3];
496
+ for (let t = 0; t < 24; t++) {
497
+ const shift = SHA3_ROTL[t];
498
+ const Th = rotlH(curH, curL, shift);
499
+ const Tl = rotlL(curH, curL, shift);
500
+ const PI = SHA3_PI[t];
501
+ curH = s[PI];
502
+ curL = s[PI + 1];
503
+ s[PI] = Th;
504
+ s[PI + 1] = Tl;
505
+ }
506
+ for (let y = 0; y < 50; y += 10) {
507
+ for (let x = 0; x < 10; x++)
508
+ B[x] = s[y + x];
509
+ for (let x = 0; x < 10; x++)
510
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
511
+ }
512
+ s[0] ^= SHA3_IOTA_H[round];
513
+ s[1] ^= SHA3_IOTA_L[round];
514
+ }
515
+ clean(B);
516
+ }
517
+ var _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, gen, keccak_256;
518
+ var init_sha3 = __esm({
519
+ "../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js"() {
520
+ init_u64();
521
+ init_utils();
522
+ _0n = BigInt(0);
523
+ _1n = BigInt(1);
524
+ _2n = BigInt(2);
525
+ _7n = BigInt(7);
526
+ _256n = BigInt(256);
527
+ _0x71n = BigInt(113);
528
+ SHA3_PI = [];
529
+ SHA3_ROTL = [];
530
+ _SHA3_IOTA = [];
531
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
532
+ [x, y] = [y, (2 * x + 3 * y) % 5];
533
+ SHA3_PI.push(2 * (5 * y + x));
534
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
535
+ let t = _0n;
536
+ for (let j = 0; j < 7; j++) {
537
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
538
+ if (R & _2n)
539
+ t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
540
+ }
541
+ _SHA3_IOTA.push(t);
542
+ }
543
+ IOTAS = split(_SHA3_IOTA, true);
544
+ SHA3_IOTA_H = IOTAS[0];
545
+ SHA3_IOTA_L = IOTAS[1];
546
+ rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
547
+ rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
548
+ Keccak = class _Keccak extends Hash {
549
+ // NOTE: we accept arguments in bytes instead of bits here.
550
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
551
+ super();
552
+ this.pos = 0;
553
+ this.posOut = 0;
554
+ this.finished = false;
555
+ this.destroyed = false;
556
+ this.enableXOF = false;
557
+ this.blockLen = blockLen;
558
+ this.suffix = suffix;
559
+ this.outputLen = outputLen;
560
+ this.enableXOF = enableXOF;
561
+ this.rounds = rounds;
562
+ anumber(outputLen);
563
+ if (!(0 < blockLen && blockLen < 200))
564
+ throw new Error("only keccak-f1600 function is supported");
565
+ this.state = new Uint8Array(200);
566
+ this.state32 = u32(this.state);
567
+ }
568
+ clone() {
569
+ return this._cloneInto();
570
+ }
571
+ keccak() {
572
+ swap32IfBE(this.state32);
573
+ keccakP(this.state32, this.rounds);
574
+ swap32IfBE(this.state32);
575
+ this.posOut = 0;
576
+ this.pos = 0;
577
+ }
578
+ update(data) {
579
+ aexists(this);
580
+ data = toBytes2(data);
581
+ abytes(data);
582
+ const { blockLen, state } = this;
583
+ const len = data.length;
584
+ for (let pos = 0; pos < len; ) {
585
+ const take = Math.min(blockLen - this.pos, len - pos);
586
+ for (let i = 0; i < take; i++)
587
+ state[this.pos++] ^= data[pos++];
588
+ if (this.pos === blockLen)
589
+ this.keccak();
590
+ }
591
+ return this;
592
+ }
593
+ finish() {
594
+ if (this.finished)
595
+ return;
596
+ this.finished = true;
597
+ const { state, suffix, pos, blockLen } = this;
598
+ state[pos] ^= suffix;
599
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
600
+ this.keccak();
601
+ state[blockLen - 1] ^= 128;
602
+ this.keccak();
603
+ }
604
+ writeInto(out) {
605
+ aexists(this, false);
606
+ abytes(out);
607
+ this.finish();
608
+ const bufferOut = this.state;
609
+ const { blockLen } = this;
610
+ for (let pos = 0, len = out.length; pos < len; ) {
611
+ if (this.posOut >= blockLen)
612
+ this.keccak();
613
+ const take = Math.min(blockLen - this.posOut, len - pos);
614
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
615
+ this.posOut += take;
616
+ pos += take;
617
+ }
618
+ return out;
619
+ }
620
+ xofInto(out) {
621
+ if (!this.enableXOF)
622
+ throw new Error("XOF is not possible for this instance");
623
+ return this.writeInto(out);
624
+ }
625
+ xof(bytes) {
626
+ anumber(bytes);
627
+ return this.xofInto(new Uint8Array(bytes));
628
+ }
629
+ digestInto(out) {
630
+ aoutput(out, this);
631
+ if (this.finished)
632
+ throw new Error("digest() was already called");
633
+ this.writeInto(out);
634
+ this.destroy();
635
+ return out;
636
+ }
637
+ digest() {
638
+ return this.digestInto(new Uint8Array(this.outputLen));
639
+ }
640
+ destroy() {
641
+ this.destroyed = true;
642
+ clean(this.state);
643
+ }
644
+ _cloneInto(to) {
645
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
646
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
647
+ to.state32.set(this.state32);
648
+ to.pos = this.pos;
649
+ to.posOut = this.posOut;
650
+ to.finished = this.finished;
651
+ to.rounds = rounds;
652
+ to.suffix = suffix;
653
+ to.outputLen = outputLen;
654
+ to.enableXOF = enableXOF;
655
+ to.destroyed = this.destroyed;
656
+ return to;
657
+ }
658
+ };
659
+ gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
660
+ keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
661
+ }
662
+ });
663
+
664
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/hash/keccak256.js
665
+ function keccak256(value, to_) {
666
+ const to = to_ || "hex";
667
+ const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value);
668
+ if (to === "bytes")
669
+ return bytes;
670
+ return toHex(bytes);
671
+ }
672
+ var init_keccak256 = __esm({
673
+ "../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/utils/hash/keccak256.js"() {
674
+ init_sha3();
675
+ init_isHex();
676
+ init_toBytes();
677
+ init_toHex();
678
+ }
679
+ });
680
+
681
+ // src/iframe/lib/secure-messenger.ts
682
+ var SecureMessenger = class {
683
+ constructor() {
684
+ this.allowedOrigins = /* @__PURE__ */ new Set();
685
+ this.usedNonces = /* @__PURE__ */ new Set();
686
+ this.pendingMessages = /* @__PURE__ */ new Map();
687
+ this.sessionToken = null;
688
+ this.messageHandlers = [];
689
+ this.MESSAGE_TIMEOUT = 6e4;
690
+ // 60 seconds
691
+ this.NONCE_CLEANUP_INTERVAL = 5 * 60 * 1e3;
692
+ // 5 minutes
693
+ // Debug flag: set to true to log all filtered messages (for debugging only)
694
+ this.DEBUG_FILTERED_MESSAGES = false;
695
+ setInterval(() => this.cleanupOldNonces(), this.NONCE_CLEANUP_INTERVAL);
696
+ }
697
+ /**
698
+ * Setup message listener with security validation
699
+ */
700
+ setupListener(handler) {
701
+ this.messageHandlers.push(handler);
702
+ window.addEventListener("message", async (event) => {
703
+ try {
704
+ await this.handleIncomingMessage(event);
705
+ } catch (error) {
706
+ console.error("[iframe][Messenger] Error handling message:", error);
707
+ }
708
+ });
709
+ console.log("[iframe][Messenger] Message listener setup");
710
+ }
711
+ /**
712
+ * Handle incoming postMessage
713
+ */
714
+ async handleIncomingMessage(event) {
715
+ const message = event.data;
716
+ const { origin } = event;
717
+ if (!message || typeof message !== "object" || !message.type) {
718
+ if (this.DEBUG_FILTERED_MESSAGES && message) {
719
+ console.debug("[iframe][Messenger] Filtered: no type field", message);
720
+ }
721
+ return;
722
+ }
723
+ if (!this.isLumiaMessage(message)) {
724
+ if (this.DEBUG_FILTERED_MESSAGES) {
725
+ console.debug("[iframe][Messenger] Filtered: not Lumia message", {
726
+ type: message.type,
727
+ origin
728
+ });
729
+ }
730
+ return;
731
+ }
732
+ if (!this.validateMessageStructure(message)) {
733
+ console.error("[iframe][Messenger] Invalid Lumia Passport message structure:", {
734
+ type: message.type,
735
+ hasMessageId: !!message.messageId,
736
+ hasTimestamp: !!message.timestamp,
737
+ hasNonce: !!message.nonce,
738
+ hasProjectId: !!message.projectId,
739
+ hasData: "data" in message
740
+ });
741
+ return;
742
+ }
743
+ if (message.type === "SDK_AUTH") {
744
+ const isLocalhost = origin.startsWith("http://localhost:") || origin.startsWith("http://127.0.0.1:");
745
+ const isHttps = origin.startsWith("https://");
746
+ if (!isHttps && !isLocalhost) {
747
+ console.error("[iframe][Messenger] Only HTTPS origins allowed (or localhost in dev)");
748
+ return;
749
+ }
750
+ } else {
751
+ if (!this.isAllowedOrigin(origin)) {
752
+ console.error(`[iframe][Messenger] Rejected message from unauthorized origin: ${origin}`);
753
+ return;
754
+ }
755
+ }
756
+ const messageAge = Date.now() - message.timestamp;
757
+ if (messageAge < 0 || messageAge > this.MESSAGE_TIMEOUT) {
758
+ console.error(`[iframe][Messenger] Message timestamp invalid (age: ${messageAge}ms)`);
759
+ return;
760
+ }
761
+ if (this.usedNonces.has(message.nonce)) {
762
+ console.error("[iframe][Messenger] Nonce already used (replay attack?)");
763
+ return;
764
+ }
765
+ if (this.sessionToken && message.hmac) {
766
+ const expectedHmac = await this.computeHMAC(message);
767
+ if (!this.constantTimeCompare(expectedHmac, message.hmac)) {
768
+ console.error("[iframe][Messenger] HMAC validation failed");
769
+ return;
770
+ }
771
+ }
772
+ this.usedNonces.add(message.nonce);
773
+ for (const handler of this.messageHandlers) {
774
+ await handler(message, origin);
775
+ }
776
+ }
777
+ /**
778
+ * Send response to parent
779
+ */
780
+ sendResponse(messageId, data, targetOrigin) {
781
+ if (!window.parent) {
782
+ console.error("[iframe][Messenger] No parent window");
783
+ return;
784
+ }
785
+ const response = {
786
+ type: "RESPONSE",
787
+ messageId,
788
+ timestamp: Date.now(),
789
+ data
790
+ };
791
+ window.parent.postMessage(response, targetOrigin);
792
+ console.log(`[iframe][Messenger] Sent response to ${targetOrigin}`);
793
+ }
794
+ /**
795
+ * Send error to parent
796
+ */
797
+ sendError(messageId, error, targetOrigin) {
798
+ if (!window.parent) {
799
+ console.error("[iframe][Messenger] No parent window");
800
+ return;
801
+ }
802
+ const response = {
803
+ type: "ERROR",
804
+ messageId,
805
+ timestamp: Date.now(),
806
+ error
807
+ };
808
+ window.parent.postMessage(response, targetOrigin);
809
+ console.log(`[iframe][Messenger] Sent error to ${targetOrigin}: ${error}`);
810
+ }
811
+ /**
812
+ * Add allowed origin
813
+ */
814
+ addAllowedOrigin(origin) {
815
+ this.allowedOrigins.add(origin);
816
+ console.log(`[iframe][Messenger] Added allowed origin: ${origin}`);
817
+ }
818
+ /**
819
+ * Remove allowed origin
820
+ */
821
+ removeAllowedOrigin(origin) {
822
+ this.allowedOrigins.delete(origin);
823
+ console.log(`[iframe][Messenger] Removed allowed origin: ${origin}`);
824
+ }
825
+ /**
826
+ * Set session token for HMAC
827
+ */
828
+ setSessionToken(token) {
829
+ this.sessionToken = token;
830
+ console.log("[iframe][Messenger] Session token set");
831
+ }
832
+ /**
833
+ * Quick check if message looks like Lumia Passport protocol
834
+ * This filters out browser extension messages, dev tools, etc.
835
+ */
836
+ isLumiaMessage(message) {
837
+ const validTypes = [
838
+ "SDK_AUTH",
839
+ "AUTHENTICATE",
840
+ "START_DKG",
841
+ "SIGN_TRANSACTION",
842
+ "GET_ADDRESS",
843
+ "CHECK_KEYSHARE",
844
+ "GET_TRUSTED_APPS",
845
+ "REMOVE_TRUSTED_APP",
846
+ "REQUEST_NEW_TOKEN",
847
+ "RESPONSE",
848
+ "ERROR",
849
+ "TRUSTED_APP_REMOVED",
850
+ "TOKEN_REFRESHED"
851
+ ];
852
+ if (!message.type || !validTypes.includes(message.type)) {
853
+ return false;
854
+ }
855
+ return !!(message.messageId && message.timestamp);
856
+ }
857
+ /**
858
+ * Validate message structure
859
+ */
860
+ validateMessageStructure(message) {
861
+ return message && typeof message === "object" && typeof message.type === "string" && typeof message.messageId === "string" && typeof message.timestamp === "number" && typeof message.nonce === "string" && typeof message.projectId === "string" && "data" in message;
862
+ }
863
+ /**
864
+ * Check if origin is allowed
865
+ */
866
+ isAllowedOrigin(origin) {
867
+ if (this.allowedOrigins.has(origin)) {
868
+ return true;
869
+ }
870
+ if (this.allowedOrigins.size === 0) {
871
+ const isLocalhost = origin.startsWith("http://localhost:") || origin.startsWith("http://127.0.0.1:");
872
+ const isHttps = origin.startsWith("https://");
873
+ return isHttps || isLocalhost;
874
+ }
875
+ return false;
876
+ }
877
+ /**
878
+ * Compute HMAC-SHA256 for message authentication
879
+ */
880
+ async computeHMAC(message) {
881
+ if (!this.sessionToken) {
882
+ throw new Error("No session token for HMAC");
883
+ }
884
+ const encoder3 = new TextEncoder();
885
+ const payload = JSON.stringify({
886
+ type: message.type,
887
+ messageId: message.messageId,
888
+ timestamp: message.timestamp,
889
+ nonce: message.nonce,
890
+ data: JSON.stringify(message.data)
891
+ });
892
+ const data = encoder3.encode(payload);
893
+ const key = encoder3.encode(this.sessionToken);
894
+ const cryptoKey = await crypto.subtle.importKey(
895
+ "raw",
896
+ key,
897
+ { name: "HMAC", hash: "SHA-256" },
898
+ false,
899
+ ["sign"]
900
+ );
901
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, data);
902
+ return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
903
+ }
904
+ /**
905
+ * Constant-time string comparison (prevent timing attacks)
906
+ */
907
+ constantTimeCompare(a, b) {
908
+ if (a.length !== b.length) return false;
909
+ let result = 0;
910
+ for (let i = 0; i < a.length; i++) {
911
+ result |= a.charCodeAt(i) ^ b.charCodeAt(i);
912
+ }
913
+ return result === 0;
914
+ }
915
+ /**
916
+ * Cleanup old nonces to prevent memory growth
917
+ */
918
+ cleanupOldNonces() {
919
+ if (this.usedNonces.size > 1e3) {
920
+ const noncesArray = Array.from(this.usedNonces);
921
+ this.usedNonces = new Set(noncesArray.slice(-500));
922
+ console.log("[iframe][Messenger] Cleaned up old nonces");
923
+ }
924
+ }
925
+ /**
926
+ * Get messenger statistics
927
+ */
928
+ getStats() {
929
+ return {
930
+ allowedOrigins: this.allowedOrigins.size,
931
+ usedNonces: this.usedNonces.size,
932
+ pendingMessages: this.pendingMessages.size
933
+ };
934
+ }
935
+ };
936
+
937
+ // src/iframe/lib/session-manager.ts
938
+ var SessionManager = class {
939
+ // 30 minutes
940
+ constructor() {
941
+ this.sessions = /* @__PURE__ */ new Map();
942
+ this.SESSION_TIMEOUT = 30 * 60 * 1e3;
943
+ setInterval(() => this.cleanupExpiredSessions(), 5 * 60 * 1e3);
944
+ }
945
+ /**
946
+ * Create a new session
947
+ */
948
+ createSession(projectId, origin) {
949
+ const sessionToken = this.generateSecureToken();
950
+ const session = {
951
+ token: sessionToken,
952
+ projectId,
953
+ origin,
954
+ createdAt: Date.now(),
955
+ lastActivity: Date.now()
956
+ };
957
+ this.sessions.set(sessionToken, session);
958
+ console.log(`[iframe][Session] Created session for origin: ${origin}`);
959
+ console.log(`[iframe][Session] Project ID: ${projectId}`);
960
+ return sessionToken;
961
+ }
962
+ /**
963
+ * Validate session token and origin
964
+ */
965
+ validateSession(sessionToken, origin) {
966
+ const session = this.sessions.get(sessionToken);
967
+ if (!session) {
968
+ console.warn(`[iframe][Session] Session not found: ${sessionToken}`);
969
+ return false;
970
+ }
971
+ if (session.origin !== origin) {
972
+ console.error(`[iframe][Session] Origin mismatch: expected ${session.origin}, got ${origin}`);
973
+ return false;
974
+ }
975
+ const age = Date.now() - session.lastActivity;
976
+ if (age > this.SESSION_TIMEOUT) {
977
+ console.warn(`[iframe][Session] Session expired (age: ${age}ms)`);
978
+ this.sessions.delete(sessionToken);
979
+ return false;
980
+ }
981
+ session.lastActivity = Date.now();
982
+ return true;
983
+ }
984
+ /**
985
+ * Get session by token
986
+ */
987
+ getSession(sessionToken) {
988
+ return this.sessions.get(sessionToken) || null;
989
+ }
990
+ /**
991
+ * Invalidate session
992
+ */
993
+ invalidateSession(sessionToken) {
994
+ const session = this.sessions.get(sessionToken);
995
+ if (session) {
996
+ console.log(`[iframe][Session] Invalidated session for origin: ${session.origin}`);
997
+ this.sessions.delete(sessionToken);
998
+ }
999
+ }
1000
+ /**
1001
+ * Get all sessions for a project
1002
+ */
1003
+ getProjectSessions(projectId) {
1004
+ return Array.from(this.sessions.values()).filter(
1005
+ (session) => session.projectId === projectId
1006
+ );
1007
+ }
1008
+ /**
1009
+ * Generate cryptographically secure session token
1010
+ */
1011
+ generateSecureToken() {
1012
+ const buffer = new Uint8Array(32);
1013
+ crypto.getRandomValues(buffer);
1014
+ return Array.from(buffer, (byte) => byte.toString(16).padStart(2, "0")).join("");
1015
+ }
1016
+ /**
1017
+ * Cleanup expired sessions
1018
+ */
1019
+ cleanupExpiredSessions() {
1020
+ const now = Date.now();
1021
+ let cleanedCount = 0;
1022
+ for (const [token, session] of this.sessions.entries()) {
1023
+ const age = now - session.lastActivity;
1024
+ if (age > this.SESSION_TIMEOUT) {
1025
+ this.sessions.delete(token);
1026
+ cleanedCount++;
1027
+ }
1028
+ }
1029
+ if (cleanedCount > 0) {
1030
+ console.log(`[iframe][Session] Cleaned up ${cleanedCount} expired sessions`);
1031
+ }
1032
+ }
1033
+ /**
1034
+ * Get session statistics
1035
+ */
1036
+ getStats() {
1037
+ const stats = {
1038
+ total: this.sessions.size,
1039
+ byProject: {}
1040
+ };
1041
+ for (const session of this.sessions.values()) {
1042
+ stats.byProject[session.projectId] = (stats.byProject[session.projectId] || 0) + 1;
1043
+ }
1044
+ return stats;
1045
+ }
1046
+ };
1047
+
1048
+ // ../../node_modules/.pnpm/dkls23-wasm@0.1.1/node_modules/dkls23-wasm/pkg-web/dkls23_wasm.js
1049
+ var dkls23_wasm_exports = {};
1050
+ __export(dkls23_wasm_exports, {
1051
+ default: () => dkls23_wasm_default,
1052
+ dkg_handle: () => dkg_handle,
1053
+ dkg_start: () => dkg_start,
1054
+ evm_address_from_sec1_pubkey_uncompressed: () => evm_address_from_sec1_pubkey_uncompressed,
1055
+ initSync: () => initSync,
1056
+ init_panic_hook: () => init_panic_hook,
1057
+ sign_handle: () => sign_handle,
1058
+ sign_start: () => sign_start,
1059
+ test_large_data_limits: () => test_large_data_limits,
1060
+ wasm_memory_info: () => wasm_memory_info
1061
+ });
1062
+ var wasm;
1063
+ function addToExternrefTable0(obj) {
1064
+ const idx = wasm.__externref_table_alloc();
1065
+ wasm.__wbindgen_export_2.set(idx, obj);
1066
+ return idx;
1067
+ }
1068
+ function handleError(f, args) {
1069
+ try {
1070
+ return f.apply(this, args);
1071
+ } catch (e) {
1072
+ const idx = addToExternrefTable0(e);
1073
+ wasm.__wbindgen_exn_store(idx);
1074
+ }
1075
+ }
1076
+ var cachedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }) : { decode: () => {
1077
+ throw Error("TextDecoder not available");
1078
+ } };
1079
+ if (typeof TextDecoder !== "undefined") {
1080
+ cachedTextDecoder.decode();
1081
+ }
1082
+ var cachedUint8ArrayMemory0 = null;
1083
+ function getUint8ArrayMemory0() {
1084
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
1085
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
1086
+ }
1087
+ return cachedUint8ArrayMemory0;
1088
+ }
1089
+ function getStringFromWasm0(ptr, len) {
1090
+ ptr = ptr >>> 0;
1091
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
1092
+ }
1093
+ function isLikeNone(x) {
1094
+ return x === void 0 || x === null;
1095
+ }
1096
+ function debugString(val) {
1097
+ const type = typeof val;
1098
+ if (type == "number" || type == "boolean" || val == null) {
1099
+ return `${val}`;
1100
+ }
1101
+ if (type == "string") {
1102
+ return `"${val}"`;
1103
+ }
1104
+ if (type == "symbol") {
1105
+ const description = val.description;
1106
+ if (description == null) {
1107
+ return "Symbol";
1108
+ } else {
1109
+ return `Symbol(${description})`;
1110
+ }
1111
+ }
1112
+ if (type == "function") {
1113
+ const name = val.name;
1114
+ if (typeof name == "string" && name.length > 0) {
1115
+ return `Function(${name})`;
1116
+ } else {
1117
+ return "Function";
1118
+ }
1119
+ }
1120
+ if (Array.isArray(val)) {
1121
+ const length = val.length;
1122
+ let debug = "[";
1123
+ if (length > 0) {
1124
+ debug += debugString(val[0]);
1125
+ }
1126
+ for (let i = 1; i < length; i++) {
1127
+ debug += ", " + debugString(val[i]);
1128
+ }
1129
+ debug += "]";
1130
+ return debug;
1131
+ }
1132
+ const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
1133
+ let className;
1134
+ if (builtInMatches && builtInMatches.length > 1) {
1135
+ className = builtInMatches[1];
1136
+ } else {
1137
+ return toString.call(val);
1138
+ }
1139
+ if (className == "Object") {
1140
+ try {
1141
+ return "Object(" + JSON.stringify(val) + ")";
1142
+ } catch (_) {
1143
+ return "Object";
1144
+ }
1145
+ }
1146
+ if (val instanceof Error) {
1147
+ return `${val.name}: ${val.message}
1148
+ ${val.stack}`;
1149
+ }
1150
+ return className;
1151
+ }
1152
+ var WASM_VECTOR_LEN = 0;
1153
+ var cachedTextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : { encode: () => {
1154
+ throw Error("TextEncoder not available");
1155
+ } };
1156
+ var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
1157
+ return cachedTextEncoder.encodeInto(arg, view);
1158
+ } : function(arg, view) {
1159
+ const buf = cachedTextEncoder.encode(arg);
1160
+ view.set(buf);
1161
+ return {
1162
+ read: arg.length,
1163
+ written: buf.length
1164
+ };
1165
+ };
1166
+ function passStringToWasm0(arg, malloc, realloc) {
1167
+ if (realloc === void 0) {
1168
+ const buf = cachedTextEncoder.encode(arg);
1169
+ const ptr2 = malloc(buf.length, 1) >>> 0;
1170
+ getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
1171
+ WASM_VECTOR_LEN = buf.length;
1172
+ return ptr2;
1173
+ }
1174
+ let len = arg.length;
1175
+ let ptr = malloc(len, 1) >>> 0;
1176
+ const mem = getUint8ArrayMemory0();
1177
+ let offset = 0;
1178
+ for (; offset < len; offset++) {
1179
+ const code = arg.charCodeAt(offset);
1180
+ if (code > 127) break;
1181
+ mem[ptr + offset] = code;
1182
+ }
1183
+ if (offset !== len) {
1184
+ if (offset !== 0) {
1185
+ arg = arg.slice(offset);
1186
+ }
1187
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
1188
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
1189
+ const ret = encodeString(arg, view);
1190
+ offset += ret.written;
1191
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
1192
+ }
1193
+ WASM_VECTOR_LEN = offset;
1194
+ return ptr;
1195
+ }
1196
+ var cachedDataViewMemory0 = null;
1197
+ function getDataViewMemory0() {
1198
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
1199
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
1200
+ }
1201
+ return cachedDataViewMemory0;
1202
+ }
1203
+ function init_panic_hook() {
1204
+ wasm.init_panic_hook();
1205
+ }
1206
+ function wasm_memory_info() {
1207
+ const ret = wasm.wasm_memory_info();
1208
+ return ret;
1209
+ }
1210
+ function test_large_data_limits(size_kb) {
1211
+ const ret = wasm.test_large_data_limits(size_kb);
1212
+ return ret;
1213
+ }
1214
+ function dkg_start(party_id, t, n, domain_label) {
1215
+ const ptr0 = passStringToWasm0(domain_label, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1216
+ const len0 = WASM_VECTOR_LEN;
1217
+ const ret = wasm.dkg_start(party_id, t, n, ptr0, len0);
1218
+ return ret;
1219
+ }
1220
+ function dkg_handle(state_blob_json, peer_msg_json) {
1221
+ const ptr0 = passStringToWasm0(state_blob_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1222
+ const len0 = WASM_VECTOR_LEN;
1223
+ const ptr1 = passStringToWasm0(peer_msg_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1224
+ const len1 = WASM_VECTOR_LEN;
1225
+ const ret = wasm.dkg_handle(ptr0, len0, ptr1, len1);
1226
+ return ret;
1227
+ }
1228
+ function sign_start(keyshare_b64, digest32_b64, _chain_path) {
1229
+ const ptr0 = passStringToWasm0(keyshare_b64, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1230
+ const len0 = WASM_VECTOR_LEN;
1231
+ const ptr1 = passStringToWasm0(digest32_b64, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1232
+ const len1 = WASM_VECTOR_LEN;
1233
+ const ptr2 = passStringToWasm0(_chain_path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1234
+ const len2 = WASM_VECTOR_LEN;
1235
+ const ret = wasm.sign_start(ptr0, len0, ptr1, len1, ptr2, len2);
1236
+ return ret;
1237
+ }
1238
+ function sign_handle(state_blob_json, peer_msg_json) {
1239
+ const ptr0 = passStringToWasm0(state_blob_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1240
+ const len0 = WASM_VECTOR_LEN;
1241
+ const ptr1 = passStringToWasm0(peer_msg_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1242
+ const len1 = WASM_VECTOR_LEN;
1243
+ const ret = wasm.sign_handle(ptr0, len0, ptr1, len1);
1244
+ return ret;
1245
+ }
1246
+ function evm_address_from_sec1_pubkey_uncompressed(pk_b64) {
1247
+ let deferred2_0;
1248
+ let deferred2_1;
1249
+ try {
1250
+ const ptr0 = passStringToWasm0(pk_b64, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1251
+ const len0 = WASM_VECTOR_LEN;
1252
+ const ret = wasm.evm_address_from_sec1_pubkey_uncompressed(ptr0, len0);
1253
+ deferred2_0 = ret[0];
1254
+ deferred2_1 = ret[1];
1255
+ return getStringFromWasm0(ret[0], ret[1]);
1256
+ } finally {
1257
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
1258
+ }
1259
+ }
1260
+ async function __wbg_load(module2, imports) {
1261
+ if (typeof Response === "function" && module2 instanceof Response) {
1262
+ if (typeof WebAssembly.instantiateStreaming === "function") {
1263
+ try {
1264
+ return await WebAssembly.instantiateStreaming(module2, imports);
1265
+ } catch (e) {
1266
+ if (module2.headers.get("Content-Type") != "application/wasm") {
1267
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
1268
+ } else {
1269
+ throw e;
1270
+ }
1271
+ }
1272
+ }
1273
+ const bytes = await module2.arrayBuffer();
1274
+ return await WebAssembly.instantiate(bytes, imports);
1275
+ } else {
1276
+ const instance = await WebAssembly.instantiate(module2, imports);
1277
+ if (instance instanceof WebAssembly.Instance) {
1278
+ return { instance, module: module2 };
1279
+ } else {
1280
+ return instance;
1281
+ }
1282
+ }
1283
+ }
1284
+ function __wbg_get_imports() {
1285
+ const imports = {};
1286
+ imports.wbg = {};
1287
+ imports.wbg.__wbg_buffer_609cc3eee51ed158 = function(arg0) {
1288
+ const ret = arg0.buffer;
1289
+ return ret;
1290
+ };
1291
+ imports.wbg.__wbg_call_672a4d21634d4a24 = function() {
1292
+ return handleError(function(arg0, arg1) {
1293
+ const ret = arg0.call(arg1);
1294
+ return ret;
1295
+ }, arguments);
1296
+ };
1297
+ imports.wbg.__wbg_call_7cccdd69e0791ae2 = function() {
1298
+ return handleError(function(arg0, arg1, arg2) {
1299
+ const ret = arg0.call(arg1, arg2);
1300
+ return ret;
1301
+ }, arguments);
1302
+ };
1303
+ imports.wbg.__wbg_crypto_574e78ad8b13b65f = function(arg0) {
1304
+ const ret = arg0.crypto;
1305
+ return ret;
1306
+ };
1307
+ imports.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e = function() {
1308
+ return handleError(function(arg0, arg1) {
1309
+ arg0.getRandomValues(arg1);
1310
+ }, arguments);
1311
+ };
1312
+ imports.wbg.__wbg_msCrypto_a61aeb35a24c1329 = function(arg0) {
1313
+ const ret = arg0.msCrypto;
1314
+ return ret;
1315
+ };
1316
+ imports.wbg.__wbg_new_405e22f390576ce2 = function() {
1317
+ const ret = new Object();
1318
+ return ret;
1319
+ };
1320
+ imports.wbg.__wbg_new_5e0be73521bc8c17 = function() {
1321
+ const ret = /* @__PURE__ */ new Map();
1322
+ return ret;
1323
+ };
1324
+ imports.wbg.__wbg_new_78feb108b6472713 = function() {
1325
+ const ret = new Array();
1326
+ return ret;
1327
+ };
1328
+ imports.wbg.__wbg_new_a12002a7f91c75be = function(arg0) {
1329
+ const ret = new Uint8Array(arg0);
1330
+ return ret;
1331
+ };
1332
+ imports.wbg.__wbg_newnoargs_105ed471475aaf50 = function(arg0, arg1) {
1333
+ const ret = new Function(getStringFromWasm0(arg0, arg1));
1334
+ return ret;
1335
+ };
1336
+ imports.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a = function(arg0, arg1, arg2) {
1337
+ const ret = new Uint8Array(arg0, arg1 >>> 0, arg2 >>> 0);
1338
+ return ret;
1339
+ };
1340
+ imports.wbg.__wbg_newwithlength_a381634e90c276d4 = function(arg0) {
1341
+ const ret = new Uint8Array(arg0 >>> 0);
1342
+ return ret;
1343
+ };
1344
+ imports.wbg.__wbg_node_905d3e251edff8a2 = function(arg0) {
1345
+ const ret = arg0.node;
1346
+ return ret;
1347
+ };
1348
+ imports.wbg.__wbg_process_dc0fbacc7c1c06f7 = function(arg0) {
1349
+ const ret = arg0.process;
1350
+ return ret;
1351
+ };
1352
+ imports.wbg.__wbg_randomFillSync_ac0988aba3254290 = function() {
1353
+ return handleError(function(arg0, arg1) {
1354
+ arg0.randomFillSync(arg1);
1355
+ }, arguments);
1356
+ };
1357
+ imports.wbg.__wbg_require_60cc747a6bc5215a = function() {
1358
+ return handleError(function() {
1359
+ const ret = module.require;
1360
+ return ret;
1361
+ }, arguments);
1362
+ };
1363
+ imports.wbg.__wbg_set_37837023f3d740e8 = function(arg0, arg1, arg2) {
1364
+ arg0[arg1 >>> 0] = arg2;
1365
+ };
1366
+ imports.wbg.__wbg_set_3fda3bac07393de4 = function(arg0, arg1, arg2) {
1367
+ arg0[arg1] = arg2;
1368
+ };
1369
+ imports.wbg.__wbg_set_65595bdd868b3009 = function(arg0, arg1, arg2) {
1370
+ arg0.set(arg1, arg2 >>> 0);
1371
+ };
1372
+ imports.wbg.__wbg_set_8fc6bf8a5b1071d1 = function(arg0, arg1, arg2) {
1373
+ const ret = arg0.set(arg1, arg2);
1374
+ return ret;
1375
+ };
1376
+ imports.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07 = function() {
1377
+ const ret = typeof global === "undefined" ? null : global;
1378
+ return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
1379
+ };
1380
+ imports.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0 = function() {
1381
+ const ret = typeof globalThis === "undefined" ? null : globalThis;
1382
+ return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
1383
+ };
1384
+ imports.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819 = function() {
1385
+ const ret = typeof self === "undefined" ? null : self;
1386
+ return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
1387
+ };
1388
+ imports.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40 = function() {
1389
+ const ret = typeof window === "undefined" ? null : window;
1390
+ return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
1391
+ };
1392
+ imports.wbg.__wbg_subarray_aa9065fa9dc5df96 = function(arg0, arg1, arg2) {
1393
+ const ret = arg0.subarray(arg1 >>> 0, arg2 >>> 0);
1394
+ return ret;
1395
+ };
1396
+ imports.wbg.__wbg_versions_c01dfd4722a88165 = function(arg0) {
1397
+ const ret = arg0.versions;
1398
+ return ret;
1399
+ };
1400
+ imports.wbg.__wbindgen_bigint_from_i64 = function(arg0) {
1401
+ const ret = arg0;
1402
+ return ret;
1403
+ };
1404
+ imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) {
1405
+ const ret = BigInt.asUintN(64, arg0);
1406
+ return ret;
1407
+ };
1408
+ imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {
1409
+ const ret = debugString(arg1);
1410
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
1411
+ const len1 = WASM_VECTOR_LEN;
1412
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
1413
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
1414
+ };
1415
+ imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
1416
+ const ret = new Error(getStringFromWasm0(arg0, arg1));
1417
+ return ret;
1418
+ };
1419
+ imports.wbg.__wbindgen_init_externref_table = function() {
1420
+ const table = wasm.__wbindgen_export_2;
1421
+ const offset = table.grow(4);
1422
+ table.set(0, void 0);
1423
+ table.set(offset + 0, void 0);
1424
+ table.set(offset + 1, null);
1425
+ table.set(offset + 2, true);
1426
+ table.set(offset + 3, false);
1427
+ ;
1428
+ };
1429
+ imports.wbg.__wbindgen_is_function = function(arg0) {
1430
+ const ret = typeof arg0 === "function";
1431
+ return ret;
1432
+ };
1433
+ imports.wbg.__wbindgen_is_object = function(arg0) {
1434
+ const val = arg0;
1435
+ const ret = typeof val === "object" && val !== null;
1436
+ return ret;
1437
+ };
1438
+ imports.wbg.__wbindgen_is_string = function(arg0) {
1439
+ const ret = typeof arg0 === "string";
1440
+ return ret;
1441
+ };
1442
+ imports.wbg.__wbindgen_is_undefined = function(arg0) {
1443
+ const ret = arg0 === void 0;
1444
+ return ret;
1445
+ };
1446
+ imports.wbg.__wbindgen_memory = function() {
1447
+ const ret = wasm.memory;
1448
+ return ret;
1449
+ };
1450
+ imports.wbg.__wbindgen_number_new = function(arg0) {
1451
+ const ret = arg0;
1452
+ return ret;
1453
+ };
1454
+ imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
1455
+ const ret = getStringFromWasm0(arg0, arg1);
1456
+ return ret;
1457
+ };
1458
+ imports.wbg.__wbindgen_throw = function(arg0, arg1) {
1459
+ throw new Error(getStringFromWasm0(arg0, arg1));
1460
+ };
1461
+ return imports;
1462
+ }
1463
+ function __wbg_init_memory(imports, memory) {
1464
+ }
1465
+ function __wbg_finalize_init(instance, module2) {
1466
+ wasm = instance.exports;
1467
+ __wbg_init.__wbindgen_wasm_module = module2;
1468
+ cachedDataViewMemory0 = null;
1469
+ cachedUint8ArrayMemory0 = null;
1470
+ wasm.__wbindgen_start();
1471
+ return wasm;
1472
+ }
1473
+ function initSync(module2) {
1474
+ if (wasm !== void 0) return wasm;
1475
+ if (typeof module2 !== "undefined") {
1476
+ if (Object.getPrototypeOf(module2) === Object.prototype) {
1477
+ ({ module: module2 } = module2);
1478
+ } else {
1479
+ console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
1480
+ }
1481
+ }
1482
+ const imports = __wbg_get_imports();
1483
+ __wbg_init_memory(imports);
1484
+ if (!(module2 instanceof WebAssembly.Module)) {
1485
+ module2 = new WebAssembly.Module(module2);
1486
+ }
1487
+ const instance = new WebAssembly.Instance(module2, imports);
1488
+ return __wbg_finalize_init(instance, module2);
1489
+ }
1490
+ async function __wbg_init(module_or_path) {
1491
+ if (wasm !== void 0) return wasm;
1492
+ if (typeof module_or_path !== "undefined") {
1493
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
1494
+ ({ module_or_path } = module_or_path);
1495
+ } else {
1496
+ console.warn("using deprecated parameters for the initialization function; pass a single object instead");
1497
+ }
1498
+ }
1499
+ if (typeof module_or_path === "undefined") {
1500
+ module_or_path = new URL("dkls23_wasm_bg.wasm", import.meta.url);
1501
+ }
1502
+ const imports = __wbg_get_imports();
1503
+ if (typeof module_or_path === "string" || typeof Request === "function" && module_or_path instanceof Request || typeof URL === "function" && module_or_path instanceof URL) {
1504
+ module_or_path = fetch(module_or_path);
1505
+ }
1506
+ __wbg_init_memory(imports);
1507
+ const { instance, module: module2 } = await __wbg_load(await module_or_path, imports);
1508
+ return __wbg_finalize_init(instance, module2);
1509
+ }
1510
+ var dkls23_wasm_default = __wbg_init;
1511
+
1512
+ // ../../node_modules/.pnpm/viem@2.38.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@3.22.4/node_modules/viem/_esm/index.js
1513
+ init_keccak256();
1514
+
1515
+ // src/iframe/lib/token-refresh-client.ts
1516
+ var TokenRefreshApiClient = class {
1517
+ constructor() {
1518
+ this.pendingTokenRefresh = null;
1519
+ this.tssUrl = "http://localhost:9256";
1520
+ }
1521
+ /**
1522
+ * Make API call with automatic token refresh on 401
1523
+ */
1524
+ async apiCall(method, path, body, projectId, accessToken) {
1525
+ let url = `${this.tssUrl}${path}`;
1526
+ if (projectId) {
1527
+ const separator = url.includes("?") ? "&" : "?";
1528
+ url = `${url}${separator}projectId=${encodeURIComponent(projectId)}`;
1529
+ }
1530
+ const headers = {
1531
+ "Content-Type": "application/json"
1532
+ };
1533
+ if (accessToken) {
1534
+ headers["Authorization"] = `Bearer ${accessToken}`;
1535
+ }
1536
+ try {
1537
+ const response = await fetch(url, {
1538
+ method,
1539
+ headers,
1540
+ body: body ? JSON.stringify(body) : void 0,
1541
+ credentials: "include"
1542
+ // Send cookies
1543
+ });
1544
+ if (response.status === 401 && accessToken) {
1545
+ console.log("[iframe][TokenRefresh] Got 401, checking if TOKEN_EXPIRED...");
1546
+ try {
1547
+ const errorData = await response.json();
1548
+ if (errorData.error_code === "TOKEN_EXPIRED" || errorData.action === "REFRESH_TOKEN") {
1549
+ console.log("[iframe][TokenRefresh] TOKEN_EXPIRED detected, requesting new token from parent...");
1550
+ const newToken = await this.requestNewTokenFromParent();
1551
+ if (newToken) {
1552
+ console.log("[iframe][TokenRefresh] \u2705 Got new token, retrying request...");
1553
+ headers["Authorization"] = `Bearer ${newToken}`;
1554
+ const retryResponse = await fetch(url, {
1555
+ method,
1556
+ headers,
1557
+ body: body ? JSON.stringify(body) : void 0,
1558
+ credentials: "include"
1559
+ });
1560
+ if (!retryResponse.ok) {
1561
+ const retryErrorText = await retryResponse.text();
1562
+ throw new Error(`API call failed after token refresh (${retryResponse.status}): ${retryErrorText}`);
1563
+ }
1564
+ return await retryResponse.json();
1565
+ } else {
1566
+ throw new Error("Failed to refresh access token");
1567
+ }
1568
+ }
1569
+ } catch (parseError) {
1570
+ console.error("[iframe][TokenRefresh] Failed to parse 401 response:", parseError);
1571
+ }
1572
+ throw new Error(`API call failed (401): Authentication required`);
1573
+ }
1574
+ if (!response.ok) {
1575
+ const errorText = await response.text();
1576
+ throw new Error(`API call failed (${response.status}): ${errorText}`);
1577
+ }
1578
+ return await response.json();
1579
+ } catch (error) {
1580
+ console.error(`[iframe][TokenRefresh] API call failed: ${method} ${path}`, error);
1581
+ throw error instanceof Error ? error : new Error("Unknown API error");
1582
+ }
1583
+ }
1584
+ /**
1585
+ * Request new access token from parent window
1586
+ */
1587
+ async requestNewTokenFromParent() {
1588
+ if (this.pendingTokenRefresh) {
1589
+ console.log("[iframe][TokenRefresh] Token refresh already in progress, waiting...");
1590
+ return this.pendingTokenRefresh;
1591
+ }
1592
+ this.pendingTokenRefresh = new Promise((resolve, reject) => {
1593
+ const messageId = `token_refresh_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
1594
+ const timeout = setTimeout(() => {
1595
+ cleanup();
1596
+ reject(new Error("Token refresh timeout"));
1597
+ }, 3e4);
1598
+ const messageHandler = (event) => {
1599
+ const message = event.data;
1600
+ if (message && message.type === "TOKEN_REFRESHED" && message.messageId === messageId) {
1601
+ cleanup();
1602
+ if (message.accessToken) {
1603
+ console.log("[iframe][TokenRefresh] \u2705 Received new token from parent");
1604
+ resolve(message.accessToken);
1605
+ } else if (message.error) {
1606
+ console.error("[iframe][TokenRefresh] \u274C Token refresh failed:", message.error);
1607
+ reject(new Error(message.error));
1608
+ } else {
1609
+ reject(new Error("Invalid token refresh response"));
1610
+ }
1611
+ }
1612
+ };
1613
+ const cleanup = () => {
1614
+ clearTimeout(timeout);
1615
+ window.removeEventListener("message", messageHandler);
1616
+ this.pendingTokenRefresh = null;
1617
+ };
1618
+ window.addEventListener("message", messageHandler);
1619
+ if (window.parent && window.parent !== window) {
1620
+ window.parent.postMessage(
1621
+ {
1622
+ type: "REQUEST_NEW_TOKEN",
1623
+ messageId,
1624
+ timestamp: Date.now()
1625
+ },
1626
+ "*"
1627
+ // Parent will validate origin
1628
+ );
1629
+ console.log("[iframe][TokenRefresh] \u{1F4E4} Sent REQUEST_NEW_TOKEN to parent");
1630
+ } else {
1631
+ cleanup();
1632
+ reject(new Error("No parent window available"));
1633
+ }
1634
+ });
1635
+ try {
1636
+ return await this.pendingTokenRefresh;
1637
+ } catch (error) {
1638
+ this.pendingTokenRefresh = null;
1639
+ console.error("[iframe][TokenRefresh] Token refresh failed:", error);
1640
+ return null;
1641
+ }
1642
+ }
1643
+ };
1644
+
1645
+ // src/iframe/lib/dkg-manager.ts
1646
+ var DKGManager = class extends TokenRefreshApiClient {
1647
+ constructor() {
1648
+ super();
1649
+ this.wasmLoaded = false;
1650
+ console.log("[iframe][DKG] Initialized with TSS URL:", this.tssUrl);
1651
+ }
1652
+ /**
1653
+ * Initialize WASM module
1654
+ */
1655
+ async initialize() {
1656
+ if (this.wasmLoaded) return;
1657
+ try {
1658
+ await dkls23_wasm_default();
1659
+ this.wasmLoaded = true;
1660
+ console.log("[iframe][DKG] \u2705 WASM module loaded");
1661
+ globalThis.__tss_wasm_api__ = dkls23_wasm_exports;
1662
+ globalThis.__tss_wasm_active__ = true;
1663
+ if (typeof wasm_memory_info === "function") {
1664
+ try {
1665
+ const memInfo = wasm_memory_info();
1666
+ console.log("[iframe][DKG] WASM memory:", memInfo);
1667
+ } catch {
1668
+ }
1669
+ }
1670
+ } catch (error) {
1671
+ this.wasmLoaded = true;
1672
+ console.error("[iframe][DKG] Failed to load WASM:", error);
1673
+ throw new Error("Failed to initialize TSS WASM module");
1674
+ }
1675
+ }
1676
+ /**
1677
+ * Perform complete DKG protocol
1678
+ */
1679
+ async performDKG(userId, projectId, accessToken) {
1680
+ if (!this.wasmLoaded) {
1681
+ await this.initialize();
1682
+ }
1683
+ console.log("[iframe][DKG] Starting DKG for user:", userId, "projectId:", projectId, "hasToken:", !!accessToken);
1684
+ const CLIENT_PARTY_ID = 1;
1685
+ const THRESHOLD = 2;
1686
+ const TOTAL_PARTIES = 2;
1687
+ const DOMAIN_LABEL = this.generateDomainLabel(userId);
1688
+ const clientStartResult = dkg_start(
1689
+ CLIENT_PARTY_ID,
1690
+ THRESHOLD,
1691
+ TOTAL_PARTIES,
1692
+ DOMAIN_LABEL
1693
+ );
1694
+ if (!Array.isArray(clientStartResult) || clientStartResult.length < 2) {
1695
+ throw new Error("Invalid dkg_start result format");
1696
+ }
1697
+ let clientState = clientStartResult[0];
1698
+ const clientMsg1 = clientStartResult[1];
1699
+ console.log("[iframe][DKG] Client started, sending to server...");
1700
+ const serverStartResponse = await this.apiCall("POST", `/api/tss/${userId}/dkg/start`, {
1701
+ threshold: THRESHOLD,
1702
+ parties: TOTAL_PARTIES,
1703
+ domainLabel: DOMAIN_LABEL
1704
+ }, projectId, accessToken);
1705
+ const { sessionId, msg1: serverMsg1 } = serverStartResponse;
1706
+ if (!serverMsg1?.kind || !serverMsg1.data_b64) {
1707
+ throw new Error("Invalid server msg1 format");
1708
+ }
1709
+ console.log("[iframe][DKG] Server started, sessionId:", sessionId);
1710
+ console.log("[iframe][DKG] Round 1: Exchanging messages...");
1711
+ const round1Response = await this.apiCall("POST", `/api/tss/${userId}/dkg/round`, {
1712
+ sessionId,
1713
+ clientMsg: clientMsg1
1714
+ }, projectId, accessToken);
1715
+ const serverMsg2 = this.extractServerMessage(round1Response);
1716
+ const clientR2Result = dkg_handle(
1717
+ JSON.stringify({ bytes_b64: clientState.bytes_b64 }),
1718
+ JSON.stringify(serverMsg1)
1719
+ );
1720
+ clientState = clientR2Result[0];
1721
+ const clientMsg2 = clientR2Result[1];
1722
+ console.log("[iframe][DKG] Round 2: Exchanging messages...");
1723
+ const round2Response = await this.apiCall("POST", `/api/tss/${userId}/dkg/round`, {
1724
+ sessionId,
1725
+ clientMsg: clientMsg2
1726
+ }, projectId, accessToken);
1727
+ const serverMsg3 = this.extractServerMessage(round2Response);
1728
+ const clientR3Result = dkg_handle(
1729
+ JSON.stringify({ bytes_b64: clientState.bytes_b64 }),
1730
+ JSON.stringify(serverMsg2)
1731
+ );
1732
+ clientState = clientR3Result[0];
1733
+ const clientMsg3 = clientR3Result[1];
1734
+ console.log("[iframe][DKG] Round 3 (Final): Getting public key...");
1735
+ const finalResponse = await this.apiCall("POST", `/api/tss/${userId}/dkg/round`, {
1736
+ sessionId,
1737
+ clientMsg: clientMsg3
1738
+ }, projectId, accessToken);
1739
+ if (!finalResponse.publicKey && !finalResponse.pubkey) {
1740
+ throw new Error("No public key in final response");
1741
+ }
1742
+ const publicKey = finalResponse.publicKey || finalResponse.pubkey;
1743
+ console.log("[iframe][DKG] Processing final client keyshare...");
1744
+ const clientFinalResult = dkg_handle(
1745
+ JSON.stringify({ bytes_b64: clientState.bytes_b64 }),
1746
+ JSON.stringify(serverMsg3)
1747
+ );
1748
+ if (!Array.isArray(clientFinalResult) || clientFinalResult.length < 3) {
1749
+ throw new Error("Invalid final dkg_handle result format");
1750
+ }
1751
+ const clientFinish = clientFinalResult[2];
1752
+ if (!clientFinish?.keyshare_b64) {
1753
+ throw new Error("No keyshare_b64 in final result");
1754
+ }
1755
+ const ownerAddress = this.deriveAddress(publicKey);
1756
+ console.log("[iframe][DKG] \u2705 DKG completed successfully");
1757
+ console.log("[iframe][DKG] Owner address:", ownerAddress);
1758
+ return {
1759
+ keyshare: clientFinish,
1760
+ ownerAddress,
1761
+ sessionId
1762
+ };
1763
+ }
1764
+ /**
1765
+ * Derive Ethereum address from uncompressed public key
1766
+ */
1767
+ deriveAddress(publicKeyBase64) {
1768
+ const b64decoded = atob(publicKeyBase64);
1769
+ const bytes = new Uint8Array(b64decoded.length);
1770
+ for (let i = 0; i < b64decoded.length; i++) {
1771
+ bytes[i] = b64decoded.charCodeAt(i);
1772
+ }
1773
+ const pubkeyBytes = bytes.slice(1);
1774
+ const pubkeyHex = Array.from(pubkeyBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1775
+ const hash = keccak256(`0x${pubkeyHex}`);
1776
+ const addr = hash.slice(-40);
1777
+ return this.toChecksumAddress(`0x${addr}`);
1778
+ }
1779
+ /**
1780
+ * Apply EIP-55 checksum to address
1781
+ */
1782
+ toChecksumAddress(address) {
1783
+ const addr = address.toLowerCase().replace("0x", "");
1784
+ const encoder3 = new TextEncoder();
1785
+ const addrBytes = encoder3.encode(addr);
1786
+ const hash = keccak256(addrBytes).replace("0x", "");
1787
+ let checksumAddress = "0x";
1788
+ for (let i = 0; i < addr.length; i++) {
1789
+ checksumAddress += parseInt(hash[i], 16) >= 8 ? addr[i].toUpperCase() : addr[i];
1790
+ }
1791
+ return checksumAddress;
1792
+ }
1793
+ /**
1794
+ * Generate secure domain label for DKG
1795
+ */
1796
+ generateDomainLabel(userId) {
1797
+ const timestamp = Date.now();
1798
+ const randomBytes = new Uint8Array(16);
1799
+ crypto.getRandomValues(randomBytes);
1800
+ const randomHex = Array.from(randomBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1801
+ return `dkls23:2of2:aa:${userId}:${timestamp}:${randomHex}`;
1802
+ }
1803
+ /**
1804
+ * Extract server message from response
1805
+ */
1806
+ extractServerMessage(response) {
1807
+ return response?.msgNext || response?.msg_next || response?.msg || null;
1808
+ }
1809
+ };
1810
+
1811
+ // src/iframe/lib/storage-manager.ts
1812
+ var StorageManager = class {
1813
+ constructor() {
1814
+ if (typeof window === "undefined" || !window.localStorage) {
1815
+ throw new Error("localStorage not available in iframe");
1816
+ }
1817
+ this.storage = window.localStorage;
1818
+ console.log("[iframe][Storage] Initialized");
1819
+ console.log("[iframe][Storage] Origin:", window.location.origin);
1820
+ }
1821
+ /**
1822
+ * Save keyshare to IFRAME localStorage
1823
+ * CRITICAL: This is the secure isolated storage
1824
+ */
1825
+ saveKeyshare(userId, data) {
1826
+ try {
1827
+ const keyshareKey = `tss.${userId}.keyshare`;
1828
+ this.storage.setItem(keyshareKey, JSON.stringify({
1829
+ keyshare_b64: data.keyshare_b64
1830
+ }));
1831
+ this.storage.setItem(`tss.${userId}.ownerAddress`, data.ownerAddress);
1832
+ this.storage.setItem(`tss.${userId}.sessionId`, data.sessionId);
1833
+ console.log(`[iframe][Storage] \u2705 Saved keyshare for user: ${userId}`);
1834
+ console.log(`[iframe][Storage] Storage origin: ${window.location.origin}`);
1835
+ } catch (error) {
1836
+ console.error("[iframe][Storage] Failed to save keyshare:", error);
1837
+ throw new Error(`Failed to save keyshare: ${error instanceof Error ? error.message : "Unknown error"}`);
1838
+ }
1839
+ }
1840
+ /**
1841
+ * Load keyshare from IFRAME localStorage
1842
+ */
1843
+ loadKeyshare(userId) {
1844
+ try {
1845
+ const keyshareKey = `tss.${userId}.keyshare`;
1846
+ const keyshareData = this.storage.getItem(keyshareKey);
1847
+ if (!keyshareData) {
1848
+ console.log(`[iframe][Storage] No keyshare found for user: ${userId}`);
1849
+ return null;
1850
+ }
1851
+ const parsed = JSON.parse(keyshareData);
1852
+ const ownerAddress = this.storage.getItem(`tss.${userId}.ownerAddress`);
1853
+ const sessionId = this.storage.getItem(`tss.${userId}.sessionId`);
1854
+ if (!ownerAddress || !sessionId) {
1855
+ console.error("[iframe][Storage] Missing owner address or session ID");
1856
+ return null;
1857
+ }
1858
+ return {
1859
+ keyshare_b64: parsed.keyshare_b64,
1860
+ ownerAddress,
1861
+ sessionId
1862
+ };
1863
+ } catch (error) {
1864
+ console.error("[iframe][Storage] Failed to load keyshare:", error);
1865
+ return null;
1866
+ }
1867
+ }
1868
+ /**
1869
+ * Check if keyshare exists for user
1870
+ */
1871
+ hasKeyshare(userId) {
1872
+ const keyshareKey = `tss.${userId}.keyshare`;
1873
+ const ownerAddressKey = `tss.${userId}.ownerAddress`;
1874
+ const hasKeyshare = this.storage.getItem(keyshareKey) !== null;
1875
+ const hasAddress = this.storage.getItem(ownerAddressKey) !== null;
1876
+ return hasKeyshare && hasAddress;
1877
+ }
1878
+ /**
1879
+ * Get owner address for user
1880
+ */
1881
+ getOwnerAddress(userId) {
1882
+ const address = this.storage.getItem(`tss.${userId}.ownerAddress`);
1883
+ return address ? address : null;
1884
+ }
1885
+ /**
1886
+ * Get session ID for user
1887
+ */
1888
+ getSessionId(userId) {
1889
+ return this.storage.getItem(`tss.${userId}.sessionId`);
1890
+ }
1891
+ /**
1892
+ * Remove keyshare for user
1893
+ */
1894
+ removeKeyshare(userId) {
1895
+ try {
1896
+ this.storage.removeItem(`tss.${userId}.keyshare`);
1897
+ this.storage.removeItem(`tss.${userId}.ownerAddress`);
1898
+ this.storage.removeItem(`tss.${userId}.sessionId`);
1899
+ const allKeys = Object.keys(this.storage);
1900
+ const userKeys = allKeys.filter((key) => key.startsWith(`tss.${userId}.`));
1901
+ userKeys.forEach((key) => this.storage.removeItem(key));
1902
+ console.log(`[iframe][Storage] \u2705 Removed keyshare for user: ${userId}`);
1903
+ } catch (error) {
1904
+ console.error("[iframe][Storage] Failed to remove keyshare:", error);
1905
+ throw new Error(`Failed to remove keyshare: ${error instanceof Error ? error.message : "Unknown error"}`);
1906
+ }
1907
+ }
1908
+ /**
1909
+ * List all users with keyshares (for debugging)
1910
+ */
1911
+ listUsers() {
1912
+ const allKeys = Object.keys(this.storage);
1913
+ const keyshareKeys = allKeys.filter((key) => key.endsWith(".keyshare"));
1914
+ return keyshareKeys.map((key) => {
1915
+ const match = key.match(/^tss\.(.+)\.keyshare$/);
1916
+ return match ? match[1] : null;
1917
+ }).filter(Boolean);
1918
+ }
1919
+ /**
1920
+ * Get storage statistics (for debugging)
1921
+ */
1922
+ getStats() {
1923
+ const allKeys = Object.keys(this.storage);
1924
+ const users = this.listUsers();
1925
+ let storageSize = 0;
1926
+ allKeys.forEach((key) => {
1927
+ const value = this.storage.getItem(key);
1928
+ if (value) {
1929
+ storageSize += key.length + value.length;
1930
+ }
1931
+ });
1932
+ return {
1933
+ totalKeys: allKeys.length,
1934
+ users: users.length,
1935
+ storageSize
1936
+ };
1937
+ }
1938
+ };
1939
+
1940
+ // src/iframe/lib/trusted-apps-manager.ts
1941
+ var STORAGE_KEY = "lumia_passport_trusted_apps";
1942
+ var TrustedAppsManager = class {
1943
+ /**
1944
+ * Check if app is trusted by user
1945
+ */
1946
+ isTrusted(userId, projectId, origin) {
1947
+ const trustedApps = this.getTrustedApps();
1948
+ return trustedApps.some(
1949
+ (app) => app.userId === userId && app.projectId === projectId && app.origin === origin
1950
+ );
1951
+ }
1952
+ /**
1953
+ * Add app to trusted list
1954
+ */
1955
+ addTrustedApp(userId, projectId, origin) {
1956
+ console.log("[TrustedApps] Adding trusted app:", { userId, projectId, origin });
1957
+ const trustedApps = this.getTrustedApps();
1958
+ const exists = trustedApps.some(
1959
+ (app) => app.userId === userId && app.projectId === projectId && app.origin === origin
1960
+ );
1961
+ if (exists) {
1962
+ console.log("[TrustedApps] App already trusted");
1963
+ return;
1964
+ }
1965
+ trustedApps.push({
1966
+ userId,
1967
+ projectId,
1968
+ origin,
1969
+ trustedAt: Date.now()
1970
+ });
1971
+ this.saveTrustedApps(trustedApps);
1972
+ console.log("[TrustedApps] \u2705 App added to trusted list");
1973
+ }
1974
+ /**
1975
+ * Remove app from trusted list
1976
+ */
1977
+ removeTrustedApp(userId, projectId, origin) {
1978
+ console.log("[TrustedApps] Removing trusted app:", { userId, projectId, origin });
1979
+ const trustedApps = this.getTrustedApps();
1980
+ const filtered = trustedApps.filter(
1981
+ (app) => !(app.userId === userId && app.projectId === projectId && app.origin === origin)
1982
+ );
1983
+ this.saveTrustedApps(filtered);
1984
+ console.log("[TrustedApps] \u2705 App removed from trusted list");
1985
+ }
1986
+ /**
1987
+ * Get all trusted apps for a user
1988
+ */
1989
+ getTrustedAppsForUser(userId) {
1990
+ const trustedApps = this.getTrustedApps();
1991
+ return trustedApps.filter((app) => app.userId === userId);
1992
+ }
1993
+ /**
1994
+ * Clear all trusted apps for a user
1995
+ */
1996
+ clearTrustedAppsForUser(userId) {
1997
+ console.log("[TrustedApps] Clearing all trusted apps for user:", userId);
1998
+ const trustedApps = this.getTrustedApps();
1999
+ const filtered = trustedApps.filter((app) => app.userId !== userId);
2000
+ this.saveTrustedApps(filtered);
2001
+ console.log("[TrustedApps] \u2705 Trusted apps cleared for user");
2002
+ }
2003
+ /**
2004
+ * Get all trusted apps from storage
2005
+ */
2006
+ getTrustedApps() {
2007
+ try {
2008
+ const data = localStorage.getItem(STORAGE_KEY);
2009
+ if (!data) {
2010
+ return [];
2011
+ }
2012
+ const apps = JSON.parse(data);
2013
+ return Array.isArray(apps) ? apps : [];
2014
+ } catch (error) {
2015
+ console.error("[TrustedApps] Error reading trusted apps:", error);
2016
+ return [];
2017
+ }
2018
+ }
2019
+ /**
2020
+ * Save trusted apps to storage
2021
+ */
2022
+ saveTrustedApps(apps) {
2023
+ try {
2024
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(apps));
2025
+ } catch (error) {
2026
+ console.error("[TrustedApps] Error saving trusted apps:", error);
2027
+ throw new Error("Failed to save trusted apps");
2028
+ }
2029
+ }
2030
+ };
2031
+
2032
+ // src/iframe/lib/signing-manager.ts
2033
+ var SigningManager = class extends TokenRefreshApiClient {
2034
+ constructor() {
2035
+ super();
2036
+ this.wasmLoaded = false;
2037
+ this.storage = new StorageManager();
2038
+ this.trustedApps = new TrustedAppsManager();
2039
+ console.log("[iframe][Sign] Initialized with TSS URL:", this.tssUrl);
2040
+ }
2041
+ /**
2042
+ * Initialize WASM module
2043
+ */
2044
+ async initialize() {
2045
+ if (this.wasmLoaded) return;
2046
+ try {
2047
+ await dkls23_wasm_default();
2048
+ this.wasmLoaded = true;
2049
+ console.log("[iframe][Sign] \u2705 WASM module loaded");
2050
+ globalThis.__tss_wasm_api__ = dkls23_wasm_exports;
2051
+ } catch (error) {
2052
+ console.error("[iframe][Sign] Failed to load WASM:", error);
2053
+ throw new Error("Failed to initialize signing WASM module");
2054
+ }
2055
+ }
2056
+ /**
2057
+ * Sign transaction with user confirmation
2058
+ */
2059
+ async signTransaction(userId, projectId, origin, transaction, accessToken) {
2060
+ if (!this.wasmLoaded) {
2061
+ await this.initialize();
2062
+ }
2063
+ console.log("[iframe][Sign] Signing transaction for user:", userId);
2064
+ console.log("[iframe][Sign] Transaction details:", transaction);
2065
+ console.log("[iframe][Sign] Loading keyshare...");
2066
+ const keyshareData = this.storage.loadKeyshare(userId);
2067
+ if (!keyshareData) {
2068
+ throw new Error("No keyshare found. Please complete DKG first.");
2069
+ }
2070
+ console.log("[iframe][Sign] \u2713 Keyshare loaded");
2071
+ const projectInfo = {
2072
+ id: projectId,
2073
+ name: "Application",
2074
+ logoUrl: "",
2075
+ website: origin,
2076
+ domains: [origin]
2077
+ };
2078
+ const isTrusted = this.trustedApps.isTrusted(userId, projectId, origin);
2079
+ console.log("[iframe][Sign] App trusted status:", isTrusted);
2080
+ if (!isTrusted) {
2081
+ console.log("[iframe][Sign] Assessing risk...");
2082
+ const risk = await this.assessRisk(transaction);
2083
+ console.log("[iframe][Sign] \u2713 Risk assessment:", risk);
2084
+ console.log("[iframe][Sign] Showing confirmation dialog...");
2085
+ const confirmResult = await this.showConfirmationDialog(
2086
+ userId,
2087
+ projectId,
2088
+ projectInfo,
2089
+ origin,
2090
+ transaction,
2091
+ risk
2092
+ );
2093
+ console.log("[iframe][Sign] Confirmation result:", confirmResult);
2094
+ if (!confirmResult.confirmed) {
2095
+ throw new Error("User rejected transaction");
2096
+ }
2097
+ if (confirmResult.trustApp) {
2098
+ this.trustedApps.addTrustedApp(userId, projectId, origin);
2099
+ }
2100
+ } else {
2101
+ console.log("[iframe][Sign] \u2705 App is trusted, skipping confirmation");
2102
+ }
2103
+ const digest32 = transaction.digest32 || this.computeTransactionHash(transaction);
2104
+ console.log("[iframe][Sign] Using digest for signing:", digest32);
2105
+ console.log("[iframe][Sign] Digest was pre-computed:", !!transaction.digest32);
2106
+ const signature = await this.performMPCSigning(userId, keyshareData, digest32, projectId, accessToken);
2107
+ console.log("[iframe][Sign] \u2705 Transaction signed");
2108
+ return signature;
2109
+ }
2110
+ /**
2111
+ * Perform MPC signing protocol
2112
+ */
2113
+ async performMPCSigning(userId, keyshareData, digest32, projectId, accessToken) {
2114
+ const keyshare = keyshareData.keyshare_b64;
2115
+ const sessionId = keyshareData.sessionId;
2116
+ const digestHex = digest32.startsWith("0x") ? digest32.slice(2) : digest32;
2117
+ const digestBytes = this.hexToBytes(digestHex);
2118
+ const digestB64 = btoa(String.fromCharCode(...digestBytes));
2119
+ const CHAIN_PATH = "m";
2120
+ console.log("[iframe][Sign] Starting MPC signing protocol...");
2121
+ const clientSignStartResult = sign_start(keyshare, digestB64, CHAIN_PATH);
2122
+ if (!Array.isArray(clientSignStartResult) || clientSignStartResult.length < 2) {
2123
+ throw new Error("Invalid sign_start result format");
2124
+ }
2125
+ let clientState = clientSignStartResult[0];
2126
+ const clientMsg1 = clientSignStartResult[1];
2127
+ const serverStartResponse = await this.apiCall("POST", `/api/tss/${userId}/sign/start`, {
2128
+ sessionId,
2129
+ digest32,
2130
+ chainPath: CHAIN_PATH
2131
+ }, projectId, accessToken);
2132
+ const serverMsg1 = serverStartResponse.msg1;
2133
+ if (!serverMsg1?.kind || !serverMsg1.data_b64) {
2134
+ throw new Error("Invalid server msg1 format");
2135
+ }
2136
+ const clientR2Result = sign_handle(
2137
+ JSON.stringify({ bytes_b64: clientState.bytes_b64 }),
2138
+ JSON.stringify(serverMsg1)
2139
+ );
2140
+ clientState = clientR2Result[0];
2141
+ const clientMsg2 = clientR2Result[1];
2142
+ const serverR2Response = await this.apiCall("POST", `/api/tss/${userId}/sign/round`, {
2143
+ sessionId,
2144
+ clientMsg: clientMsg1
2145
+ }, projectId, accessToken);
2146
+ const serverMsg2 = this.extractServerMessage(serverR2Response);
2147
+ const clientR3Result = sign_handle(
2148
+ JSON.stringify({ bytes_b64: clientState.bytes_b64 }),
2149
+ JSON.stringify(serverMsg2)
2150
+ );
2151
+ clientState = clientR3Result[0];
2152
+ const clientMsg3 = clientR3Result[1];
2153
+ const serverR3Response = await this.apiCall("POST", `/api/tss/${userId}/sign/round`, {
2154
+ sessionId,
2155
+ clientMsg: clientMsg2
2156
+ }, projectId, accessToken);
2157
+ const serverMsg3 = this.extractServerMessage(serverR3Response);
2158
+ const clientFinalResult = sign_handle(
2159
+ JSON.stringify({ bytes_b64: clientState.bytes_b64 }),
2160
+ JSON.stringify(serverMsg3)
2161
+ );
2162
+ if (!Array.isArray(clientFinalResult) || clientFinalResult.length < 3) {
2163
+ throw new Error("Invalid final sign_handle result");
2164
+ }
2165
+ const clientSignature = clientFinalResult[2];
2166
+ await this.apiCall("POST", `/api/tss/${userId}/sign/round`, {
2167
+ sessionId,
2168
+ clientMsg: clientMsg3
2169
+ }, projectId, accessToken);
2170
+ const signature = this.formatSignature(clientSignature);
2171
+ return signature;
2172
+ }
2173
+ /**
2174
+ * Show transaction confirmation dialog
2175
+ */
2176
+ async showConfirmationDialog(userId, projectId, project, origin, transaction, risk) {
2177
+ this.showIframe();
2178
+ return new Promise((resolve) => {
2179
+ console.log("[iframe][Sign] Creating modal element...");
2180
+ const modal = this.createConfirmationModal(userId, projectId, project, origin, transaction, risk);
2181
+ console.log("[iframe][Sign] Modal created:", modal);
2182
+ const confirmBtn = modal.querySelector(".confirm-btn");
2183
+ const cancelBtn = modal.querySelector(".cancel-btn");
2184
+ const trustCheckbox = modal.querySelector(".trust-app-checkbox");
2185
+ console.log("[iframe][Sign] Found elements:", {
2186
+ confirmBtn: !!confirmBtn,
2187
+ cancelBtn: !!cancelBtn,
2188
+ trustCheckbox: !!trustCheckbox
2189
+ });
2190
+ confirmBtn?.addEventListener("click", (e) => {
2191
+ console.log("[iframe][Sign] Confirm button clicked, isTrusted:", e.isTrusted);
2192
+ if (e.isTrusted) {
2193
+ const trustApp = trustCheckbox?.checked || false;
2194
+ console.log("[iframe][Sign] Trust app checkbox:", trustApp);
2195
+ modal.remove();
2196
+ this.hideIframe();
2197
+ resolve({ confirmed: true, trustApp });
2198
+ }
2199
+ });
2200
+ cancelBtn?.addEventListener("click", () => {
2201
+ console.log("[iframe][Sign] Cancel button clicked");
2202
+ modal.remove();
2203
+ this.hideIframe();
2204
+ resolve({ confirmed: false, trustApp: false });
2205
+ });
2206
+ console.log("[iframe][Sign] Appending modal to body...");
2207
+ document.body.appendChild(modal);
2208
+ console.log("[iframe][Sign] Modal appended, children count:", document.body.children.length);
2209
+ const computedStyle = window.getComputedStyle(modal);
2210
+ const rect = modal.getBoundingClientRect();
2211
+ console.log("[iframe][Sign] Modal computed styles:", {
2212
+ display: computedStyle.display,
2213
+ position: computedStyle.position,
2214
+ zIndex: computedStyle.zIndex,
2215
+ visibility: computedStyle.visibility,
2216
+ opacity: computedStyle.opacity,
2217
+ width: computedStyle.width,
2218
+ height: computedStyle.height
2219
+ });
2220
+ console.log("[iframe][Sign] Modal position (rect):", {
2221
+ top: rect.top,
2222
+ left: rect.left,
2223
+ width: rect.width,
2224
+ height: rect.height,
2225
+ inViewport: rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth
2226
+ });
2227
+ });
2228
+ }
2229
+ /**
2230
+ * Create confirmation modal UI
2231
+ */
2232
+ createConfirmationModal(userId, projectId, project, origin, transaction, risk) {
2233
+ const modal = document.createElement("div");
2234
+ modal.className = "transaction-confirmation-modal";
2235
+ const riskClass = risk.level.toLowerCase();
2236
+ const isUserOp = !!transaction.userOpDetails;
2237
+ const formatHex = (value, maxLength = 20) => {
2238
+ if (!value) return "N/A";
2239
+ if (value.length > maxLength) {
2240
+ return `${value.substring(0, maxLength)}...`;
2241
+ }
2242
+ return value;
2243
+ };
2244
+ const formatGas = (gasLimit, gasPrice) => {
2245
+ if (!gasLimit || !gasPrice) return "N/A";
2246
+ try {
2247
+ const gas = BigInt(gasLimit);
2248
+ const price = BigInt(gasPrice);
2249
+ const totalWei = gas * price;
2250
+ const totalEth = Number(totalWei) / 1e18;
2251
+ return totalEth.toFixed(9) + " ETH";
2252
+ } catch {
2253
+ return "N/A";
2254
+ }
2255
+ };
2256
+ const isSponsored = isUserOp && !!transaction.userOpDetails?.paymaster;
2257
+ const estimatedCost = isSponsored ? "0 (Sponsored)" : "Free (Sponsored Transaction)";
2258
+ modal.innerHTML = `
2259
+ <div class="modal-overlay">
2260
+ <div class="modal-content">
2261
+ <div class="app-identity">
2262
+ <div class="app-info">
2263
+ <h3>${project.name}</h3>
2264
+ <p class="origin">${origin}</p>
2265
+ </div>
2266
+ </div>
2267
+
2268
+ <h2>Confirm Transaction</h2>
2269
+
2270
+ ${risk.level !== "LOW" ? `
2271
+ <div class="risk-warning ${riskClass}">
2272
+ <strong>\u26A0\uFE0F ${risk.level} RISK</strong>
2273
+ ${risk.reasons.map((r) => `<p>\u2022 ${r}</p>`).join("")}
2274
+ </div>
2275
+ ` : ""}
2276
+
2277
+ <div class="tx-details">
2278
+ <div class="detail-row">
2279
+ <span><strong>From:</strong></span>
2280
+ <code>${formatHex(transaction.userOpDetails?.sender || transaction.to, 16)}</code>
2281
+ </div>
2282
+
2283
+ ${isUserOp && transaction.userOpDetails?.callData && transaction.userOpDetails.callData !== "0x" ? `
2284
+ <div class="detail-row">
2285
+ <span><strong>Action:</strong></span>
2286
+ <span>Contract Interaction</span>
2287
+ </div>
2288
+ ` : ""}
2289
+
2290
+ <div class="detail-row">
2291
+ <span><strong>Estimated Cost:</strong></span>
2292
+ <strong style="color: #10b981;">${estimatedCost}</strong>
2293
+ </div>
2294
+
2295
+ ${isSponsored ? `
2296
+ <div class="security-notice" style="background: #d1fae5; border-left-color: #10b981; margin-top: 1rem;">
2297
+ <p>\u2713 Gas fees will be paid by the application (no cost to you)</p>
2298
+ </div>
2299
+ ` : ""}
2300
+ </div>
2301
+
2302
+ <div class="security-notice">
2303
+ <p>\u26A0\uFE0F Please verify this transaction carefully before confirming.</p>
2304
+ </div>
2305
+
2306
+ <div class="trust-app-section">
2307
+ <label class="trust-app-label">
2308
+ <input type="checkbox" class="trust-app-checkbox" />
2309
+ <span>Trust this application and skip confirmation for future transactions</span>
2310
+ </label>
2311
+ </div>
2312
+
2313
+ <div class="actions">
2314
+ <button class="cancel-btn">Reject</button>
2315
+ <button class="confirm-btn">Confirm</button>
2316
+ </div>
2317
+ </div>
2318
+ </div>
2319
+ `;
2320
+ return modal;
2321
+ }
2322
+ /**
2323
+ * Assess transaction risk
2324
+ */
2325
+ async assessRisk(transaction) {
2326
+ const reasons = [];
2327
+ let score = 0;
2328
+ const valueEth = parseFloat(transaction.value);
2329
+ if (valueEth > 1) {
2330
+ score += 20;
2331
+ reasons.push(`High value transaction (${valueEth} ETH)`);
2332
+ }
2333
+ if (transaction.data && transaction.data !== "0x" && transaction.data.length > 2) {
2334
+ score += 10;
2335
+ reasons.push("Contract interaction detected");
2336
+ }
2337
+ let level;
2338
+ if (score >= 50) level = "CRITICAL";
2339
+ else if (score >= 30) level = "HIGH";
2340
+ else if (score >= 15) level = "MEDIUM";
2341
+ else level = "LOW";
2342
+ return { level, score, reasons };
2343
+ }
2344
+ /**
2345
+ * Compute transaction hash (simplified, adjust for your needs)
2346
+ */
2347
+ computeTransactionHash(transaction) {
2348
+ const encoder3 = new TextEncoder();
2349
+ const data = encoder3.encode(JSON.stringify(transaction));
2350
+ let hash = 0;
2351
+ for (let i = 0; i < data.length; i++) {
2352
+ hash = (hash << 5) - hash + data[i];
2353
+ hash = hash & hash;
2354
+ }
2355
+ const hashHex = Math.abs(hash).toString(16).padStart(64, "0");
2356
+ return `0x${hashHex}`;
2357
+ }
2358
+ formatValue(value) {
2359
+ try {
2360
+ const eth = parseFloat(value);
2361
+ return eth.toFixed(6);
2362
+ } catch {
2363
+ return value;
2364
+ }
2365
+ }
2366
+ formatSignature(sig) {
2367
+ if (typeof sig === "string") return sig;
2368
+ if (sig && typeof sig === "object" && sig.r_b64 && sig.s_b64) {
2369
+ const rBytes = Uint8Array.from(atob(sig.r_b64), (c) => c.charCodeAt(0));
2370
+ const sBytes = Uint8Array.from(atob(sig.s_b64), (c) => c.charCodeAt(0));
2371
+ const r = Array.from(rBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2372
+ const s = Array.from(sBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2373
+ const v = (Number(sig.recid) + 27).toString(16).padStart(2, "0");
2374
+ return `0x${r}${s}${v}`;
2375
+ }
2376
+ throw new Error("Invalid signature format");
2377
+ }
2378
+ hexToBytes(hex) {
2379
+ const bytes = new Uint8Array(hex.length / 2);
2380
+ for (let i = 0; i < hex.length; i += 2) {
2381
+ bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
2382
+ }
2383
+ return bytes;
2384
+ }
2385
+ extractServerMessage(response) {
2386
+ return response?.msgNext || response?.msg_next || response?.msg || null;
2387
+ }
2388
+ /**
2389
+ * Show iframe (notify parent)
2390
+ */
2391
+ showIframe() {
2392
+ if (window.parent !== window) {
2393
+ window.parent.postMessage({ type: "SHOW_IFRAME", timestamp: Date.now() }, "*");
2394
+ console.log("[iframe][Sign] Requested parent to show iframe");
2395
+ }
2396
+ }
2397
+ /**
2398
+ * Hide iframe (notify parent)
2399
+ */
2400
+ hideIframe() {
2401
+ if (window.parent !== window) {
2402
+ window.parent.postMessage({ type: "HIDE_IFRAME", timestamp: Date.now() }, "*");
2403
+ console.log("[iframe][Sign] Requested parent to hide iframe");
2404
+ }
2405
+ }
2406
+ };
2407
+
2408
+ // src/iframe/lib/authorization-manager.ts
2409
+ var AuthorizationManager = class {
2410
+ constructor() {
2411
+ this.STORAGE_KEY_PREFIX = "auth";
2412
+ console.log("[iframe][Auth] Initialized");
2413
+ }
2414
+ /**
2415
+ * Check if user has authorized a project
2416
+ */
2417
+ async checkAuthorization(userId, projectId) {
2418
+ const key = this.getAuthKey(userId, projectId);
2419
+ const authData = localStorage.getItem(key);
2420
+ if (!authData) {
2421
+ return false;
2422
+ }
2423
+ try {
2424
+ const auth = JSON.parse(authData);
2425
+ console.log(`[iframe][Auth] User ${userId} authorized for project ${projectId}`);
2426
+ return true;
2427
+ } catch (error) {
2428
+ console.error("[iframe][Auth] Failed to parse authorization:", error);
2429
+ return false;
2430
+ }
2431
+ }
2432
+ /**
2433
+ * Store user authorization for a project
2434
+ */
2435
+ async storeAuthorization(userId, projectId, origin) {
2436
+ const auth = {
2437
+ userId,
2438
+ projectId,
2439
+ authorizedAt: Date.now(),
2440
+ origin
2441
+ };
2442
+ const key = this.getAuthKey(userId, projectId);
2443
+ localStorage.setItem(key, JSON.stringify(auth));
2444
+ console.log(`[iframe][Auth] \u2705 Stored authorization: ${userId} -> ${projectId}`);
2445
+ }
2446
+ /**
2447
+ * Revoke user authorization for a project
2448
+ */
2449
+ async revokeAuthorization(userId, projectId) {
2450
+ const key = this.getAuthKey(userId, projectId);
2451
+ localStorage.removeItem(key);
2452
+ console.log(`[iframe][Auth] \u2705 Revoked authorization: ${userId} -> ${projectId}`);
2453
+ }
2454
+ /**
2455
+ * Get all authorizations for a user
2456
+ */
2457
+ async getUserAuthorizations(userId) {
2458
+ const authorizations = [];
2459
+ const prefix = `${this.STORAGE_KEY_PREFIX}.${userId}.`;
2460
+ for (let i = 0; i < localStorage.length; i++) {
2461
+ const key = localStorage.key(i);
2462
+ if (key && key.startsWith(prefix)) {
2463
+ try {
2464
+ const authData = localStorage.getItem(key);
2465
+ if (authData) {
2466
+ const auth = JSON.parse(authData);
2467
+ authorizations.push(auth);
2468
+ }
2469
+ } catch (error) {
2470
+ console.error(`[iframe][Auth] Failed to parse auth for key ${key}:`, error);
2471
+ }
2472
+ }
2473
+ }
2474
+ return authorizations;
2475
+ }
2476
+ /**
2477
+ * Request user authorization with consent screen
2478
+ */
2479
+ async requestAuthorization(project, origin) {
2480
+ this.showIframe();
2481
+ return new Promise((resolve) => {
2482
+ const modal = this.createAuthorizationModal(project, origin);
2483
+ const authorizeBtn = modal.querySelector(".authorize-btn");
2484
+ const cancelBtn = modal.querySelector(".cancel-btn");
2485
+ const cleanup = (result) => {
2486
+ console.log(`[iframe][Auth] Cleaning up modal, result: ${result}`);
2487
+ modal.remove();
2488
+ this.hideIframe();
2489
+ console.log(`[iframe][Auth] Resolving with result: ${result}`);
2490
+ resolve(result);
2491
+ };
2492
+ authorizeBtn?.addEventListener("click", (e) => {
2493
+ console.log(`[iframe][Auth] Authorize button clicked, isTrusted: ${e.isTrusted}`);
2494
+ if (e.isTrusted) {
2495
+ console.log(`[iframe][Auth] User authorized project: ${project.id}`);
2496
+ cleanup(true);
2497
+ } else {
2498
+ console.warn(`[iframe][Auth] Untrusted click event ignored`);
2499
+ }
2500
+ });
2501
+ cancelBtn?.addEventListener("click", () => {
2502
+ console.log(`[iframe][Auth] Cancel button clicked`);
2503
+ console.log(`[iframe][Auth] User denied authorization for project: ${project.id}`);
2504
+ cleanup(false);
2505
+ });
2506
+ document.body.appendChild(modal);
2507
+ });
2508
+ }
2509
+ /**
2510
+ * Show iframe (notify parent)
2511
+ */
2512
+ showIframe() {
2513
+ if (window.parent !== window) {
2514
+ window.parent.postMessage({ type: "SHOW_IFRAME", timestamp: Date.now() }, "*");
2515
+ console.log("[iframe][Auth] Requested parent to show iframe");
2516
+ }
2517
+ }
2518
+ /**
2519
+ * Hide iframe (notify parent)
2520
+ */
2521
+ hideIframe() {
2522
+ if (window.parent !== window) {
2523
+ window.parent.postMessage({ type: "HIDE_IFRAME", timestamp: Date.now() }, "*");
2524
+ console.log("[iframe][Auth] Requested parent to hide iframe");
2525
+ }
2526
+ }
2527
+ /**
2528
+ * Create authorization consent modal
2529
+ */
2530
+ createAuthorizationModal(project, origin) {
2531
+ const modal = document.createElement("div");
2532
+ modal.className = "authorization-modal";
2533
+ const isVerifiedOrigin = project.domains.includes(origin);
2534
+ modal.innerHTML = `
2535
+ <div class="modal-overlay">
2536
+ <div class="modal-content">
2537
+ <div class="app-identity">
2538
+ ${project.logoUrl ? `<img src="${project.logoUrl}" alt="${project.name}" class="app-logo" />` : ""}
2539
+ <h2>${project.name}</h2>
2540
+ <div class="app-origin ${isVerifiedOrigin ? "verified" : "unverified"}">
2541
+ ${isVerifiedOrigin ? "\u2713" : "\u26A0\uFE0F"} ${origin}
2542
+ </div>
2543
+ </div>
2544
+
2545
+ <div class="consent-message">
2546
+ <p><strong>${project.name}</strong> wants to use your Lumia wallet.</p>
2547
+ </div>
2548
+
2549
+ <div class="permissions-list">
2550
+ <h3>This application will be able to:</h3>
2551
+ <ul>
2552
+ <li>\u2713 View your wallet address</li>
2553
+ <li>\u2713 Request transaction signatures</li>
2554
+ <li>\u2713 View your public transaction history</li>
2555
+ </ul>
2556
+ </div>
2557
+
2558
+ ${!isVerifiedOrigin ? `
2559
+ <div class="security-warning">
2560
+ <p>\u26A0\uFE0F <strong>Warning:</strong> This domain is not verified for ${project.name}</p>
2561
+ <p>Expected: ${project.domains.join(", ")}</p>
2562
+ <p>Actual: ${origin}</p>
2563
+ </div>
2564
+ ` : ""}
2565
+
2566
+ <div class="security-notice">
2567
+ <p>\u26A0\uFE0F Only authorize applications you trust. You can revoke access at any time in settings.</p>
2568
+ </div>
2569
+
2570
+ <div class="actions">
2571
+ <button class="cancel-btn">Cancel</button>
2572
+ <button class="authorize-btn" ${!isVerifiedOrigin ? "disabled" : ""}>
2573
+ Authorize
2574
+ </button>
2575
+ </div>
2576
+ </div>
2577
+ </div>
2578
+ `;
2579
+ return modal;
2580
+ }
2581
+ /**
2582
+ * Get storage key for authorization
2583
+ */
2584
+ getAuthKey(userId, projectId) {
2585
+ return `${this.STORAGE_KEY_PREFIX}.${userId}.${projectId}`;
2586
+ }
2587
+ /**
2588
+ * Clear all authorizations for a user (for logout/cleanup)
2589
+ */
2590
+ async clearUserAuthorizations(userId) {
2591
+ const prefix = `${this.STORAGE_KEY_PREFIX}.${userId}.`;
2592
+ const keysToRemove = [];
2593
+ for (let i = 0; i < localStorage.length; i++) {
2594
+ const key = localStorage.key(i);
2595
+ if (key && key.startsWith(prefix)) {
2596
+ keysToRemove.push(key);
2597
+ }
2598
+ }
2599
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
2600
+ console.log(`[iframe][Auth] \u2705 Cleared ${keysToRemove.length} authorizations for user ${userId}`);
2601
+ }
2602
+ /**
2603
+ * Get authorization statistics
2604
+ */
2605
+ getStats() {
2606
+ const stats = {
2607
+ total: 0,
2608
+ byUser: {}
2609
+ };
2610
+ for (let i = 0; i < localStorage.length; i++) {
2611
+ const key = localStorage.key(i);
2612
+ if (key && key.startsWith(this.STORAGE_KEY_PREFIX)) {
2613
+ stats.total++;
2614
+ const parts = key.split(".");
2615
+ if (parts.length >= 2) {
2616
+ const userId = parts[1];
2617
+ stats.byUser[userId] = (stats.byUser[userId] || 0) + 1;
2618
+ }
2619
+ }
2620
+ }
2621
+ return stats;
2622
+ }
2623
+ };
2624
+
2625
+ // src/iframe/main.ts
2626
+ var IframeWallet = class {
2627
+ constructor() {
2628
+ console.log("=".repeat(60));
2629
+ console.log(" Lumia Passport Secure Wallet - iframe version 0.1.8");
2630
+ console.log("=".repeat(60));
2631
+ this.messenger = new SecureMessenger();
2632
+ this.sessionManager = new SessionManager();
2633
+ this.dkgManager = new DKGManager();
2634
+ this.signingManager = new SigningManager();
2635
+ this.authManager = new AuthorizationManager();
2636
+ this.storage = new StorageManager();
2637
+ this.trustedApps = new TrustedAppsManager();
2638
+ }
2639
+ async initialize() {
2640
+ console.log("[iframe] Initializing Lumia Passport Secure Wallet...");
2641
+ console.log("[iframe] Origin:", window.location.origin);
2642
+ console.log("[iframe] Expected: auth.lumiapassport.com");
2643
+ if (window.location.hostname !== "localhost" && window.location.hostname !== "127.0.0.1" && !window.location.hostname.includes("lumiapassport.com")) {
2644
+ console.warn("[iframe] \u26A0\uFE0F Running on unexpected origin!");
2645
+ }
2646
+ console.log("[iframe] Loading WASM modules...");
2647
+ await Promise.all([
2648
+ this.dkgManager.initialize(),
2649
+ this.signingManager.initialize()
2650
+ ]);
2651
+ this.messenger.setupListener(async (message, origin) => {
2652
+ await this.handleMessage(message, origin);
2653
+ });
2654
+ this.displayReadyIndicator();
2655
+ if (window.parent !== window) {
2656
+ window.parent.postMessage(
2657
+ {
2658
+ type: "IFRAME_READY",
2659
+ timestamp: Date.now()
2660
+ },
2661
+ "*"
2662
+ // Initial broadcast, will validate origin in subsequent messages
2663
+ );
2664
+ }
2665
+ console.log("[iframe] \u2705 Wallet ready and listening for messages");
2666
+ }
2667
+ async handleMessage(message, origin) {
2668
+ const { type, messageId, projectId } = message;
2669
+ console.log(`[iframe] \u{1F4E8} Message: ${type} from ${origin.substring(0, 30)}...`);
2670
+ try {
2671
+ switch (type) {
2672
+ case "SDK_AUTH":
2673
+ await this.handleSDKAuth(message, origin);
2674
+ break;
2675
+ case "AUTHENTICATE":
2676
+ await this.handleAuthenticate(message, origin);
2677
+ break;
2678
+ case "START_DKG":
2679
+ await this.handleStartDKG(message, origin);
2680
+ break;
2681
+ case "SIGN_TRANSACTION":
2682
+ await this.handleSignTransaction(message, origin);
2683
+ break;
2684
+ case "GET_ADDRESS":
2685
+ await this.handleGetAddress(message, origin);
2686
+ break;
2687
+ case "CHECK_KEYSHARE":
2688
+ await this.handleCheckKeyshare(message, origin);
2689
+ break;
2690
+ case "GET_TRUSTED_APPS":
2691
+ await this.handleGetTrustedApps(message, origin);
2692
+ break;
2693
+ case "REMOVE_TRUSTED_APP":
2694
+ await this.handleRemoveTrustedApp(message, origin);
2695
+ break;
2696
+ default:
2697
+ throw new Error(`Unknown message type: ${type}`);
2698
+ }
2699
+ } catch (error) {
2700
+ console.error(`[iframe] \u274C Error handling ${type}:`, error);
2701
+ this.messenger.sendError(
2702
+ messageId,
2703
+ error instanceof Error ? error.message : "Unknown error",
2704
+ origin
2705
+ );
2706
+ }
2707
+ }
2708
+ async handleSDKAuth(message, origin) {
2709
+ const { projectId } = message.data;
2710
+ const { messageId } = message;
2711
+ console.log(`[iframe] SDK_AUTH: projectId=${projectId}`);
2712
+ if (!origin.startsWith("https://") && !origin.startsWith("http://localhost")) {
2713
+ throw new Error("Only HTTPS origins are allowed (or localhost for dev)");
2714
+ }
2715
+ const sessionToken = this.sessionManager.createSession(projectId, origin);
2716
+ this.messenger.setSessionToken(sessionToken);
2717
+ this.messenger.addAllowedOrigin(origin);
2718
+ this.messenger.sendResponse(
2719
+ messageId,
2720
+ {
2721
+ type: "SDK_AUTH_SUCCESS",
2722
+ sessionToken
2723
+ },
2724
+ origin
2725
+ );
2726
+ console.log(`[iframe] \u2705 SDK authenticated for origin: ${origin.substring(0, 40)}...`);
2727
+ }
2728
+ async handleAuthenticate(message, origin) {
2729
+ const { sessionToken, projectId, userId } = message.data;
2730
+ const { messageId } = message;
2731
+ if (!this.sessionManager.validateSession(sessionToken, origin)) {
2732
+ throw new Error("Invalid session");
2733
+ }
2734
+ console.log(`[iframe] AUTHENTICATE: userId=${userId}, projectId=${projectId}`);
2735
+ const isAuthorized = await this.authManager.checkAuthorization(userId, projectId);
2736
+ if (!isAuthorized) {
2737
+ console.log(`[iframe] Authorization needed for project: ${projectId}`);
2738
+ const projectInfo = {
2739
+ id: projectId,
2740
+ name: "Application",
2741
+ logoUrl: "",
2742
+ website: origin,
2743
+ domains: [origin]
2744
+ };
2745
+ const consent = await this.authManager.requestAuthorization(projectInfo, origin);
2746
+ if (!consent) {
2747
+ throw new Error("User denied authorization");
2748
+ }
2749
+ await this.authManager.storeAuthorization(userId, projectId, origin);
2750
+ console.log(`[iframe] \u2705 Authorization granted: ${userId} -> ${projectId}`);
2751
+ }
2752
+ const address = this.storage.getOwnerAddress(userId);
2753
+ this.messenger.sendResponse(
2754
+ messageId,
2755
+ {
2756
+ type: "AUTH_SUCCESS",
2757
+ userId,
2758
+ address
2759
+ },
2760
+ origin
2761
+ );
2762
+ console.log(`[iframe] \u2705 User authenticated: ${userId}`);
2763
+ }
2764
+ async handleStartDKG(message, origin) {
2765
+ const { sessionToken, userId, projectId, accessToken } = message.data;
2766
+ const { messageId } = message;
2767
+ if (!this.sessionManager.validateSession(sessionToken, origin)) {
2768
+ throw new Error("Invalid session");
2769
+ }
2770
+ const isAuthorized = await this.authManager.checkAuthorization(userId, projectId);
2771
+ if (!isAuthorized) {
2772
+ throw new Error("User has not authorized this application");
2773
+ }
2774
+ console.log(`[iframe] START_DKG: userId=${userId}, projectId=${projectId}, hasToken=${!!accessToken}`);
2775
+ this.displayLoadingIndicator("Generating secure keys...");
2776
+ try {
2777
+ const result = await this.dkgManager.performDKG(userId, projectId, accessToken);
2778
+ this.storage.saveKeyshare(userId, {
2779
+ keyshare_b64: result.keyshare.keyshare_b64,
2780
+ ownerAddress: result.ownerAddress,
2781
+ sessionId: result.sessionId
2782
+ });
2783
+ this.hideLoadingIndicator();
2784
+ this.messenger.sendResponse(
2785
+ messageId,
2786
+ {
2787
+ type: "DKG_SUCCESS",
2788
+ ownerAddress: result.ownerAddress
2789
+ },
2790
+ origin
2791
+ );
2792
+ console.log(`[iframe] \u2705 DKG completed: ${result.ownerAddress}`);
2793
+ } catch (error) {
2794
+ this.hideLoadingIndicator();
2795
+ throw error;
2796
+ }
2797
+ }
2798
+ async handleSignTransaction(message, origin) {
2799
+ const { sessionToken, userId, projectId, transaction, accessToken } = message.data;
2800
+ const { messageId } = message;
2801
+ if (!this.sessionManager.validateSession(sessionToken, origin)) {
2802
+ throw new Error("Invalid session");
2803
+ }
2804
+ const isAuthorized = await this.authManager.checkAuthorization(userId, projectId);
2805
+ if (!isAuthorized) {
2806
+ throw new Error("User has not authorized this application");
2807
+ }
2808
+ console.log(`[iframe] SIGN_TRANSACTION: userId=${userId}, hasAccessToken=${!!accessToken}`);
2809
+ try {
2810
+ const signature = await this.signingManager.signTransaction(
2811
+ userId,
2812
+ projectId,
2813
+ origin,
2814
+ transaction,
2815
+ accessToken
2816
+ );
2817
+ this.messenger.sendResponse(
2818
+ messageId,
2819
+ {
2820
+ type: "SIGNATURE",
2821
+ signature
2822
+ },
2823
+ origin
2824
+ );
2825
+ console.log(`[iframe] \u2705 Transaction signed`);
2826
+ } catch (error) {
2827
+ console.error("[iframe] Signing failed:", error);
2828
+ throw error;
2829
+ }
2830
+ }
2831
+ async handleGetAddress(message, origin) {
2832
+ const { sessionToken, userId } = message.data;
2833
+ const { messageId } = message;
2834
+ if (!this.sessionManager.validateSession(sessionToken, origin)) {
2835
+ throw new Error("Invalid session");
2836
+ }
2837
+ const address = this.storage.getOwnerAddress(userId);
2838
+ this.messenger.sendResponse(
2839
+ messageId,
2840
+ {
2841
+ type: "ADDRESS",
2842
+ address
2843
+ },
2844
+ origin
2845
+ );
2846
+ }
2847
+ async handleCheckKeyshare(message, origin) {
2848
+ const { sessionToken, userId } = message.data;
2849
+ const { messageId } = message;
2850
+ if (!this.sessionManager.validateSession(sessionToken, origin)) {
2851
+ throw new Error("Invalid session");
2852
+ }
2853
+ const hasKeyshare = this.storage.hasKeyshare(userId);
2854
+ const address = hasKeyshare ? this.storage.getOwnerAddress(userId) : void 0;
2855
+ this.messenger.sendResponse(
2856
+ messageId,
2857
+ {
2858
+ type: "KEYSHARE_STATUS",
2859
+ hasKeyshare,
2860
+ address
2861
+ },
2862
+ origin
2863
+ );
2864
+ }
2865
+ async handleGetTrustedApps(message, origin) {
2866
+ const { sessionToken, userId } = message.data;
2867
+ const { messageId } = message;
2868
+ console.log(`[iframe] GET_TRUSTED_APPS: userId=${userId}, sessionToken=${sessionToken ? "present" : "missing"}`);
2869
+ if (!this.sessionManager.validateSession(sessionToken, origin)) {
2870
+ console.error("[iframe] GET_TRUSTED_APPS: Session validation failed");
2871
+ throw new Error("Invalid session");
2872
+ }
2873
+ console.log("[iframe] GET_TRUSTED_APPS: Session validated, fetching apps...");
2874
+ const trustedApps = this.trustedApps.getTrustedAppsForUser(userId);
2875
+ console.log(`[iframe] GET_TRUSTED_APPS: Found ${trustedApps.length} trusted apps`);
2876
+ this.messenger.sendResponse(
2877
+ messageId,
2878
+ {
2879
+ type: "TRUSTED_APPS_LIST",
2880
+ apps: trustedApps
2881
+ },
2882
+ origin
2883
+ );
2884
+ console.log(`[iframe] \u2705 GET_TRUSTED_APPS: Response sent with ${trustedApps.length} apps`);
2885
+ }
2886
+ async handleRemoveTrustedApp(message, origin) {
2887
+ const { sessionToken, userId, projectId, appOrigin } = message.data;
2888
+ const { messageId } = message;
2889
+ console.log(`[iframe] REMOVE_TRUSTED_APP: userId=${userId}, projectId=${projectId}, origin=${appOrigin}`);
2890
+ if (!this.sessionManager.validateSession(sessionToken, origin)) {
2891
+ console.error("[iframe] REMOVE_TRUSTED_APP: Session validation failed");
2892
+ throw new Error("Invalid session");
2893
+ }
2894
+ console.log("[iframe] REMOVE_TRUSTED_APP: Session validated, removing app...");
2895
+ this.trustedApps.removeTrustedApp(userId, projectId, appOrigin);
2896
+ this.messenger.sendResponse(
2897
+ messageId,
2898
+ {
2899
+ type: "TRUSTED_APP_REMOVED",
2900
+ success: true
2901
+ },
2902
+ origin
2903
+ );
2904
+ console.log(`[iframe] \u2705 REMOVE_TRUSTED_APP: App removed`);
2905
+ }
2906
+ displayReadyIndicator() {
2907
+ const app = document.getElementById("app");
2908
+ if (!app) return;
2909
+ app.innerHTML = `
2910
+ <div class="ready-indicator">
2911
+ <div class="status-icon">\u{1F512}</div>
2912
+ <h2>Secure Wallet Ready</h2>
2913
+ <p>Lumia Passport is ready for secure operations</p>
2914
+ <div class="info">
2915
+ <div class="info-row">
2916
+ <strong>Origin:</strong>
2917
+ <span>${window.location.origin}</span>
2918
+ </div>
2919
+ <div class="info-row">
2920
+ <strong>Status:</strong>
2921
+ <span class="status-active">Active</span>
2922
+ </div>
2923
+ </div>
2924
+ </div>
2925
+ `;
2926
+ }
2927
+ displayLoadingIndicator(message) {
2928
+ const app = document.getElementById("app");
2929
+ if (!app) return;
2930
+ app.innerHTML = `
2931
+ <div class="loading-indicator">
2932
+ <div class="spinner"></div>
2933
+ <p>${message}</p>
2934
+ </div>
2935
+ `;
2936
+ }
2937
+ hideLoadingIndicator() {
2938
+ this.displayReadyIndicator();
2939
+ }
2940
+ };
2941
+ function initWallet() {
2942
+ const wallet = new IframeWallet();
2943
+ wallet.initialize().catch((error) => {
2944
+ console.error("[iframe] \u274C Failed to initialize:", error);
2945
+ const app = document.getElementById("app");
2946
+ if (app) {
2947
+ app.innerHTML = `
2948
+ <div class="error-indicator">
2949
+ <div class="error-icon">\u274C</div>
2950
+ <h2>Initialization Failed</h2>
2951
+ <p>${error instanceof Error ? error.message : "Unknown error"}</p>
2952
+ </div>
2953
+ `;
2954
+ }
2955
+ });
2956
+ }
2957
+ if (document.readyState === "loading") {
2958
+ document.addEventListener("DOMContentLoaded", initWallet);
2959
+ } else {
2960
+ initWallet();
2961
+ }
2962
+ /*! Bundled license information:
2963
+
2964
+ @noble/hashes/esm/utils.js:
2965
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2966
+ */
2967
+ //# sourceMappingURL=main.js.map