eocene-auth-sdk 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/LICENSE +21 -0
- package/README.md +71 -0
- package/dist/index.d.ts +437 -0
- package/dist/index.js +4187 -0
- package/dist/index.js.map +1 -0
- package/dist/styles.css +534 -0
- package/package.json +69 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4187 @@
|
|
|
1
|
+
import { createContext, useState, useEffect, useMemo, useRef, useCallback, useContext } from 'react';
|
|
2
|
+
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
|
|
3
|
+
import './styles.css';
|
|
4
|
+
|
|
5
|
+
// src/config.ts
|
|
6
|
+
var DEFAULT_CONTROL_BASE_URL = "https://api.eocene.io";
|
|
7
|
+
var DEFAULT_STORAGE_KEY = "eocene:device-state";
|
|
8
|
+
var DEFAULT_OAUTH_PENDING_KEY = "eocene:oauth-pending";
|
|
9
|
+
function resolveControlAbsoluteUrl(controlBaseUrl) {
|
|
10
|
+
const base = controlBaseUrl.replace(/\/$/, "");
|
|
11
|
+
if (base.startsWith("http://") || base.startsWith("https://")) return base;
|
|
12
|
+
if (typeof window === "undefined") return base;
|
|
13
|
+
const path = base.startsWith("/") ? base : `/${base}`;
|
|
14
|
+
return `${window.location.origin}${path}`.replace(/\/$/, "");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// ../eocene-worker/node_modules/@noble/hashes/esm/crypto.js
|
|
18
|
+
var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
|
|
19
|
+
|
|
20
|
+
// ../eocene-worker/node_modules/@noble/hashes/esm/utils.js
|
|
21
|
+
function isBytes(a) {
|
|
22
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
23
|
+
}
|
|
24
|
+
function anumber(n) {
|
|
25
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
26
|
+
throw new Error("positive integer expected, got " + n);
|
|
27
|
+
}
|
|
28
|
+
function abytes(b, ...lengths) {
|
|
29
|
+
if (!isBytes(b))
|
|
30
|
+
throw new Error("Uint8Array expected");
|
|
31
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
32
|
+
throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
|
|
33
|
+
}
|
|
34
|
+
function ahash(h) {
|
|
35
|
+
if (typeof h !== "function" || typeof h.create !== "function")
|
|
36
|
+
throw new Error("Hash should be wrapped by utils.createHasher");
|
|
37
|
+
anumber(h.outputLen);
|
|
38
|
+
anumber(h.blockLen);
|
|
39
|
+
}
|
|
40
|
+
function aexists(instance, checkFinished = true) {
|
|
41
|
+
if (instance.destroyed)
|
|
42
|
+
throw new Error("Hash instance has been destroyed");
|
|
43
|
+
if (checkFinished && instance.finished)
|
|
44
|
+
throw new Error("Hash#digest() has already been called");
|
|
45
|
+
}
|
|
46
|
+
function aoutput(out, instance) {
|
|
47
|
+
abytes(out);
|
|
48
|
+
const min = instance.outputLen;
|
|
49
|
+
if (out.length < min) {
|
|
50
|
+
throw new Error("digestInto() expects output buffer of length at least " + min);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function u32(arr) {
|
|
54
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
55
|
+
}
|
|
56
|
+
function clean(...arrays) {
|
|
57
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
58
|
+
arrays[i].fill(0);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function createView(arr) {
|
|
62
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
63
|
+
}
|
|
64
|
+
function rotr(word, shift) {
|
|
65
|
+
return word << 32 - shift | word >>> shift;
|
|
66
|
+
}
|
|
67
|
+
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
|
68
|
+
function byteSwap(word) {
|
|
69
|
+
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
|
|
70
|
+
}
|
|
71
|
+
function byteSwap32(arr) {
|
|
72
|
+
for (let i = 0; i < arr.length; i++) {
|
|
73
|
+
arr[i] = byteSwap(arr[i]);
|
|
74
|
+
}
|
|
75
|
+
return arr;
|
|
76
|
+
}
|
|
77
|
+
var swap32IfBE = isLE ? (u) => u : byteSwap32;
|
|
78
|
+
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
79
|
+
// @ts-ignore
|
|
80
|
+
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
81
|
+
))();
|
|
82
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
83
|
+
function bytesToHex(bytes) {
|
|
84
|
+
abytes(bytes);
|
|
85
|
+
if (hasHexBuiltin)
|
|
86
|
+
return bytes.toHex();
|
|
87
|
+
let hex = "";
|
|
88
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
89
|
+
hex += hexes[bytes[i]];
|
|
90
|
+
}
|
|
91
|
+
return hex;
|
|
92
|
+
}
|
|
93
|
+
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
94
|
+
function asciiToBase16(ch) {
|
|
95
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
96
|
+
return ch - asciis._0;
|
|
97
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
98
|
+
return ch - (asciis.A - 10);
|
|
99
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
100
|
+
return ch - (asciis.a - 10);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
function hexToBytes(hex) {
|
|
104
|
+
if (typeof hex !== "string")
|
|
105
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
106
|
+
if (hasHexBuiltin)
|
|
107
|
+
return Uint8Array.fromHex(hex);
|
|
108
|
+
const hl = hex.length;
|
|
109
|
+
const al = hl / 2;
|
|
110
|
+
if (hl % 2)
|
|
111
|
+
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
112
|
+
const array = new Uint8Array(al);
|
|
113
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
114
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
115
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
116
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
117
|
+
const char = hex[hi] + hex[hi + 1];
|
|
118
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
119
|
+
}
|
|
120
|
+
array[ai] = n1 * 16 + n2;
|
|
121
|
+
}
|
|
122
|
+
return array;
|
|
123
|
+
}
|
|
124
|
+
function utf8ToBytes(str) {
|
|
125
|
+
if (typeof str !== "string")
|
|
126
|
+
throw new Error("string expected");
|
|
127
|
+
return new Uint8Array(new TextEncoder().encode(str));
|
|
128
|
+
}
|
|
129
|
+
function toBytes(data) {
|
|
130
|
+
if (typeof data === "string")
|
|
131
|
+
data = utf8ToBytes(data);
|
|
132
|
+
abytes(data);
|
|
133
|
+
return data;
|
|
134
|
+
}
|
|
135
|
+
function concatBytes(...arrays) {
|
|
136
|
+
let sum = 0;
|
|
137
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
138
|
+
const a = arrays[i];
|
|
139
|
+
abytes(a);
|
|
140
|
+
sum += a.length;
|
|
141
|
+
}
|
|
142
|
+
const res = new Uint8Array(sum);
|
|
143
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
144
|
+
const a = arrays[i];
|
|
145
|
+
res.set(a, pad);
|
|
146
|
+
pad += a.length;
|
|
147
|
+
}
|
|
148
|
+
return res;
|
|
149
|
+
}
|
|
150
|
+
var Hash = class {
|
|
151
|
+
};
|
|
152
|
+
function createHasher(hashCons) {
|
|
153
|
+
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
|
|
154
|
+
const tmp = hashCons();
|
|
155
|
+
hashC.outputLen = tmp.outputLen;
|
|
156
|
+
hashC.blockLen = tmp.blockLen;
|
|
157
|
+
hashC.create = () => hashCons();
|
|
158
|
+
return hashC;
|
|
159
|
+
}
|
|
160
|
+
function randomBytes(bytesLength = 32) {
|
|
161
|
+
if (crypto && typeof crypto.getRandomValues === "function") {
|
|
162
|
+
return crypto.getRandomValues(new Uint8Array(bytesLength));
|
|
163
|
+
}
|
|
164
|
+
if (crypto && typeof crypto.randomBytes === "function") {
|
|
165
|
+
return Uint8Array.from(crypto.randomBytes(bytesLength));
|
|
166
|
+
}
|
|
167
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ../eocene-worker/node_modules/@noble/hashes/esm/hmac.js
|
|
171
|
+
var HMAC = class extends Hash {
|
|
172
|
+
constructor(hash, _key) {
|
|
173
|
+
super();
|
|
174
|
+
this.finished = false;
|
|
175
|
+
this.destroyed = false;
|
|
176
|
+
ahash(hash);
|
|
177
|
+
const key = toBytes(_key);
|
|
178
|
+
this.iHash = hash.create();
|
|
179
|
+
if (typeof this.iHash.update !== "function")
|
|
180
|
+
throw new Error("Expected instance of class which extends utils.Hash");
|
|
181
|
+
this.blockLen = this.iHash.blockLen;
|
|
182
|
+
this.outputLen = this.iHash.outputLen;
|
|
183
|
+
const blockLen = this.blockLen;
|
|
184
|
+
const pad = new Uint8Array(blockLen);
|
|
185
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
186
|
+
for (let i = 0; i < pad.length; i++)
|
|
187
|
+
pad[i] ^= 54;
|
|
188
|
+
this.iHash.update(pad);
|
|
189
|
+
this.oHash = hash.create();
|
|
190
|
+
for (let i = 0; i < pad.length; i++)
|
|
191
|
+
pad[i] ^= 54 ^ 92;
|
|
192
|
+
this.oHash.update(pad);
|
|
193
|
+
clean(pad);
|
|
194
|
+
}
|
|
195
|
+
update(buf) {
|
|
196
|
+
aexists(this);
|
|
197
|
+
this.iHash.update(buf);
|
|
198
|
+
return this;
|
|
199
|
+
}
|
|
200
|
+
digestInto(out) {
|
|
201
|
+
aexists(this);
|
|
202
|
+
abytes(out, this.outputLen);
|
|
203
|
+
this.finished = true;
|
|
204
|
+
this.iHash.digestInto(out);
|
|
205
|
+
this.oHash.update(out);
|
|
206
|
+
this.oHash.digestInto(out);
|
|
207
|
+
this.destroy();
|
|
208
|
+
}
|
|
209
|
+
digest() {
|
|
210
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
211
|
+
this.digestInto(out);
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
_cloneInto(to) {
|
|
215
|
+
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
|
216
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
217
|
+
to = to;
|
|
218
|
+
to.finished = finished;
|
|
219
|
+
to.destroyed = destroyed;
|
|
220
|
+
to.blockLen = blockLen;
|
|
221
|
+
to.outputLen = outputLen;
|
|
222
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
223
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
224
|
+
return to;
|
|
225
|
+
}
|
|
226
|
+
clone() {
|
|
227
|
+
return this._cloneInto();
|
|
228
|
+
}
|
|
229
|
+
destroy() {
|
|
230
|
+
this.destroyed = true;
|
|
231
|
+
this.oHash.destroy();
|
|
232
|
+
this.iHash.destroy();
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
|
236
|
+
hmac.create = (hash, key) => new HMAC(hash, key);
|
|
237
|
+
|
|
238
|
+
// ../eocene-worker/node_modules/@noble/hashes/esm/_md.js
|
|
239
|
+
function setBigUint64(view, byteOffset, value, isLE2) {
|
|
240
|
+
if (typeof view.setBigUint64 === "function")
|
|
241
|
+
return view.setBigUint64(byteOffset, value, isLE2);
|
|
242
|
+
const _32n2 = BigInt(32);
|
|
243
|
+
const _u32_max = BigInt(4294967295);
|
|
244
|
+
const wh = Number(value >> _32n2 & _u32_max);
|
|
245
|
+
const wl = Number(value & _u32_max);
|
|
246
|
+
const h = isLE2 ? 4 : 0;
|
|
247
|
+
const l = isLE2 ? 0 : 4;
|
|
248
|
+
view.setUint32(byteOffset + h, wh, isLE2);
|
|
249
|
+
view.setUint32(byteOffset + l, wl, isLE2);
|
|
250
|
+
}
|
|
251
|
+
function Chi(a, b, c) {
|
|
252
|
+
return a & b ^ ~a & c;
|
|
253
|
+
}
|
|
254
|
+
function Maj(a, b, c) {
|
|
255
|
+
return a & b ^ a & c ^ b & c;
|
|
256
|
+
}
|
|
257
|
+
var HashMD = class extends Hash {
|
|
258
|
+
constructor(blockLen, outputLen, padOffset, isLE2) {
|
|
259
|
+
super();
|
|
260
|
+
this.finished = false;
|
|
261
|
+
this.length = 0;
|
|
262
|
+
this.pos = 0;
|
|
263
|
+
this.destroyed = false;
|
|
264
|
+
this.blockLen = blockLen;
|
|
265
|
+
this.outputLen = outputLen;
|
|
266
|
+
this.padOffset = padOffset;
|
|
267
|
+
this.isLE = isLE2;
|
|
268
|
+
this.buffer = new Uint8Array(blockLen);
|
|
269
|
+
this.view = createView(this.buffer);
|
|
270
|
+
}
|
|
271
|
+
update(data) {
|
|
272
|
+
aexists(this);
|
|
273
|
+
data = toBytes(data);
|
|
274
|
+
abytes(data);
|
|
275
|
+
const { view, buffer, blockLen } = this;
|
|
276
|
+
const len = data.length;
|
|
277
|
+
for (let pos = 0; pos < len; ) {
|
|
278
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
279
|
+
if (take === blockLen) {
|
|
280
|
+
const dataView = createView(data);
|
|
281
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
282
|
+
this.process(dataView, pos);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
286
|
+
this.pos += take;
|
|
287
|
+
pos += take;
|
|
288
|
+
if (this.pos === blockLen) {
|
|
289
|
+
this.process(view, 0);
|
|
290
|
+
this.pos = 0;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
this.length += data.length;
|
|
294
|
+
this.roundClean();
|
|
295
|
+
return this;
|
|
296
|
+
}
|
|
297
|
+
digestInto(out) {
|
|
298
|
+
aexists(this);
|
|
299
|
+
aoutput(out, this);
|
|
300
|
+
this.finished = true;
|
|
301
|
+
const { buffer, view, blockLen, isLE: isLE2 } = this;
|
|
302
|
+
let { pos } = this;
|
|
303
|
+
buffer[pos++] = 128;
|
|
304
|
+
clean(this.buffer.subarray(pos));
|
|
305
|
+
if (this.padOffset > blockLen - pos) {
|
|
306
|
+
this.process(view, 0);
|
|
307
|
+
pos = 0;
|
|
308
|
+
}
|
|
309
|
+
for (let i = pos; i < blockLen; i++)
|
|
310
|
+
buffer[i] = 0;
|
|
311
|
+
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
|
|
312
|
+
this.process(view, 0);
|
|
313
|
+
const oview = createView(out);
|
|
314
|
+
const len = this.outputLen;
|
|
315
|
+
if (len % 4)
|
|
316
|
+
throw new Error("_sha2: outputLen should be aligned to 32bit");
|
|
317
|
+
const outLen = len / 4;
|
|
318
|
+
const state = this.get();
|
|
319
|
+
if (outLen > state.length)
|
|
320
|
+
throw new Error("_sha2: outputLen bigger than state");
|
|
321
|
+
for (let i = 0; i < outLen; i++)
|
|
322
|
+
oview.setUint32(4 * i, state[i], isLE2);
|
|
323
|
+
}
|
|
324
|
+
digest() {
|
|
325
|
+
const { buffer, outputLen } = this;
|
|
326
|
+
this.digestInto(buffer);
|
|
327
|
+
const res = buffer.slice(0, outputLen);
|
|
328
|
+
this.destroy();
|
|
329
|
+
return res;
|
|
330
|
+
}
|
|
331
|
+
_cloneInto(to) {
|
|
332
|
+
to || (to = new this.constructor());
|
|
333
|
+
to.set(...this.get());
|
|
334
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
335
|
+
to.destroyed = destroyed;
|
|
336
|
+
to.finished = finished;
|
|
337
|
+
to.length = length;
|
|
338
|
+
to.pos = pos;
|
|
339
|
+
if (length % blockLen)
|
|
340
|
+
to.buffer.set(buffer);
|
|
341
|
+
return to;
|
|
342
|
+
}
|
|
343
|
+
clone() {
|
|
344
|
+
return this._cloneInto();
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
348
|
+
1779033703,
|
|
349
|
+
3144134277,
|
|
350
|
+
1013904242,
|
|
351
|
+
2773480762,
|
|
352
|
+
1359893119,
|
|
353
|
+
2600822924,
|
|
354
|
+
528734635,
|
|
355
|
+
1541459225
|
|
356
|
+
]);
|
|
357
|
+
|
|
358
|
+
// ../eocene-worker/node_modules/@noble/hashes/esm/_u64.js
|
|
359
|
+
var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
|
360
|
+
var _32n = /* @__PURE__ */ BigInt(32);
|
|
361
|
+
function fromBig(n, le = false) {
|
|
362
|
+
if (le)
|
|
363
|
+
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
|
|
364
|
+
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
365
|
+
}
|
|
366
|
+
function split(lst, le = false) {
|
|
367
|
+
const len = lst.length;
|
|
368
|
+
let Ah = new Uint32Array(len);
|
|
369
|
+
let Al = new Uint32Array(len);
|
|
370
|
+
for (let i = 0; i < len; i++) {
|
|
371
|
+
const { h, l } = fromBig(lst[i], le);
|
|
372
|
+
[Ah[i], Al[i]] = [h, l];
|
|
373
|
+
}
|
|
374
|
+
return [Ah, Al];
|
|
375
|
+
}
|
|
376
|
+
var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
|
|
377
|
+
var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
|
|
378
|
+
var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
|
|
379
|
+
var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
|
|
380
|
+
|
|
381
|
+
// ../eocene-worker/node_modules/@noble/hashes/esm/sha2.js
|
|
382
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
383
|
+
1116352408,
|
|
384
|
+
1899447441,
|
|
385
|
+
3049323471,
|
|
386
|
+
3921009573,
|
|
387
|
+
961987163,
|
|
388
|
+
1508970993,
|
|
389
|
+
2453635748,
|
|
390
|
+
2870763221,
|
|
391
|
+
3624381080,
|
|
392
|
+
310598401,
|
|
393
|
+
607225278,
|
|
394
|
+
1426881987,
|
|
395
|
+
1925078388,
|
|
396
|
+
2162078206,
|
|
397
|
+
2614888103,
|
|
398
|
+
3248222580,
|
|
399
|
+
3835390401,
|
|
400
|
+
4022224774,
|
|
401
|
+
264347078,
|
|
402
|
+
604807628,
|
|
403
|
+
770255983,
|
|
404
|
+
1249150122,
|
|
405
|
+
1555081692,
|
|
406
|
+
1996064986,
|
|
407
|
+
2554220882,
|
|
408
|
+
2821834349,
|
|
409
|
+
2952996808,
|
|
410
|
+
3210313671,
|
|
411
|
+
3336571891,
|
|
412
|
+
3584528711,
|
|
413
|
+
113926993,
|
|
414
|
+
338241895,
|
|
415
|
+
666307205,
|
|
416
|
+
773529912,
|
|
417
|
+
1294757372,
|
|
418
|
+
1396182291,
|
|
419
|
+
1695183700,
|
|
420
|
+
1986661051,
|
|
421
|
+
2177026350,
|
|
422
|
+
2456956037,
|
|
423
|
+
2730485921,
|
|
424
|
+
2820302411,
|
|
425
|
+
3259730800,
|
|
426
|
+
3345764771,
|
|
427
|
+
3516065817,
|
|
428
|
+
3600352804,
|
|
429
|
+
4094571909,
|
|
430
|
+
275423344,
|
|
431
|
+
430227734,
|
|
432
|
+
506948616,
|
|
433
|
+
659060556,
|
|
434
|
+
883997877,
|
|
435
|
+
958139571,
|
|
436
|
+
1322822218,
|
|
437
|
+
1537002063,
|
|
438
|
+
1747873779,
|
|
439
|
+
1955562222,
|
|
440
|
+
2024104815,
|
|
441
|
+
2227730452,
|
|
442
|
+
2361852424,
|
|
443
|
+
2428436474,
|
|
444
|
+
2756734187,
|
|
445
|
+
3204031479,
|
|
446
|
+
3329325298
|
|
447
|
+
]);
|
|
448
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
449
|
+
var SHA256 = class extends HashMD {
|
|
450
|
+
constructor(outputLen = 32) {
|
|
451
|
+
super(64, outputLen, 8, false);
|
|
452
|
+
this.A = SHA256_IV[0] | 0;
|
|
453
|
+
this.B = SHA256_IV[1] | 0;
|
|
454
|
+
this.C = SHA256_IV[2] | 0;
|
|
455
|
+
this.D = SHA256_IV[3] | 0;
|
|
456
|
+
this.E = SHA256_IV[4] | 0;
|
|
457
|
+
this.F = SHA256_IV[5] | 0;
|
|
458
|
+
this.G = SHA256_IV[6] | 0;
|
|
459
|
+
this.H = SHA256_IV[7] | 0;
|
|
460
|
+
}
|
|
461
|
+
get() {
|
|
462
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
463
|
+
return [A, B, C, D, E, F, G, H];
|
|
464
|
+
}
|
|
465
|
+
// prettier-ignore
|
|
466
|
+
set(A, B, C, D, E, F, G, H) {
|
|
467
|
+
this.A = A | 0;
|
|
468
|
+
this.B = B | 0;
|
|
469
|
+
this.C = C | 0;
|
|
470
|
+
this.D = D | 0;
|
|
471
|
+
this.E = E | 0;
|
|
472
|
+
this.F = F | 0;
|
|
473
|
+
this.G = G | 0;
|
|
474
|
+
this.H = H | 0;
|
|
475
|
+
}
|
|
476
|
+
process(view, offset) {
|
|
477
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
478
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
479
|
+
for (let i = 16; i < 64; i++) {
|
|
480
|
+
const W15 = SHA256_W[i - 15];
|
|
481
|
+
const W2 = SHA256_W[i - 2];
|
|
482
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
483
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
484
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
485
|
+
}
|
|
486
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
487
|
+
for (let i = 0; i < 64; i++) {
|
|
488
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
489
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
490
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
491
|
+
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
492
|
+
H = G;
|
|
493
|
+
G = F;
|
|
494
|
+
F = E;
|
|
495
|
+
E = D + T1 | 0;
|
|
496
|
+
D = C;
|
|
497
|
+
C = B;
|
|
498
|
+
B = A;
|
|
499
|
+
A = T1 + T2 | 0;
|
|
500
|
+
}
|
|
501
|
+
A = A + this.A | 0;
|
|
502
|
+
B = B + this.B | 0;
|
|
503
|
+
C = C + this.C | 0;
|
|
504
|
+
D = D + this.D | 0;
|
|
505
|
+
E = E + this.E | 0;
|
|
506
|
+
F = F + this.F | 0;
|
|
507
|
+
G = G + this.G | 0;
|
|
508
|
+
H = H + this.H | 0;
|
|
509
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
510
|
+
}
|
|
511
|
+
roundClean() {
|
|
512
|
+
clean(SHA256_W);
|
|
513
|
+
}
|
|
514
|
+
destroy() {
|
|
515
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
516
|
+
clean(this.buffer);
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
|
|
520
|
+
|
|
521
|
+
// ../eocene-worker/node_modules/@noble/curves/esm/utils.js
|
|
522
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
523
|
+
var _1n = /* @__PURE__ */ BigInt(1);
|
|
524
|
+
function _abool2(value, title = "") {
|
|
525
|
+
if (typeof value !== "boolean") {
|
|
526
|
+
const prefix = title && `"${title}"`;
|
|
527
|
+
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
528
|
+
}
|
|
529
|
+
return value;
|
|
530
|
+
}
|
|
531
|
+
function _abytes2(value, length, title = "") {
|
|
532
|
+
const bytes = isBytes(value);
|
|
533
|
+
const len = value?.length;
|
|
534
|
+
const needsLen = length !== void 0;
|
|
535
|
+
if (!bytes || needsLen && len !== length) {
|
|
536
|
+
const prefix = title && `"${title}" `;
|
|
537
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
538
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
539
|
+
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
540
|
+
}
|
|
541
|
+
return value;
|
|
542
|
+
}
|
|
543
|
+
function numberToHexUnpadded(num) {
|
|
544
|
+
const hex = num.toString(16);
|
|
545
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
546
|
+
}
|
|
547
|
+
function hexToNumber(hex) {
|
|
548
|
+
if (typeof hex !== "string")
|
|
549
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
550
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
551
|
+
}
|
|
552
|
+
function bytesToNumberBE(bytes) {
|
|
553
|
+
return hexToNumber(bytesToHex(bytes));
|
|
554
|
+
}
|
|
555
|
+
function bytesToNumberLE(bytes) {
|
|
556
|
+
abytes(bytes);
|
|
557
|
+
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
|
558
|
+
}
|
|
559
|
+
function numberToBytesBE(n, len) {
|
|
560
|
+
return hexToBytes(n.toString(16).padStart(len * 2, "0"));
|
|
561
|
+
}
|
|
562
|
+
function numberToBytesLE(n, len) {
|
|
563
|
+
return numberToBytesBE(n, len).reverse();
|
|
564
|
+
}
|
|
565
|
+
function ensureBytes(title, hex, expectedLength) {
|
|
566
|
+
let res;
|
|
567
|
+
if (typeof hex === "string") {
|
|
568
|
+
try {
|
|
569
|
+
res = hexToBytes(hex);
|
|
570
|
+
} catch (e) {
|
|
571
|
+
throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
|
|
572
|
+
}
|
|
573
|
+
} else if (isBytes(hex)) {
|
|
574
|
+
res = Uint8Array.from(hex);
|
|
575
|
+
} else {
|
|
576
|
+
throw new Error(title + " must be hex string or Uint8Array");
|
|
577
|
+
}
|
|
578
|
+
res.length;
|
|
579
|
+
return res;
|
|
580
|
+
}
|
|
581
|
+
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
582
|
+
function inRange(n, min, max) {
|
|
583
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
584
|
+
}
|
|
585
|
+
function aInRange(title, n, min, max) {
|
|
586
|
+
if (!inRange(n, min, max))
|
|
587
|
+
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
588
|
+
}
|
|
589
|
+
function bitLen(n) {
|
|
590
|
+
let len;
|
|
591
|
+
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
592
|
+
;
|
|
593
|
+
return len;
|
|
594
|
+
}
|
|
595
|
+
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
596
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
597
|
+
if (typeof hashLen !== "number" || hashLen < 2)
|
|
598
|
+
throw new Error("hashLen must be a number");
|
|
599
|
+
if (typeof qByteLen !== "number" || qByteLen < 2)
|
|
600
|
+
throw new Error("qByteLen must be a number");
|
|
601
|
+
if (typeof hmacFn !== "function")
|
|
602
|
+
throw new Error("hmacFn must be a function");
|
|
603
|
+
const u8n = (len) => new Uint8Array(len);
|
|
604
|
+
const u8of = (byte) => Uint8Array.of(byte);
|
|
605
|
+
let v = u8n(hashLen);
|
|
606
|
+
let k = u8n(hashLen);
|
|
607
|
+
let i = 0;
|
|
608
|
+
const reset = () => {
|
|
609
|
+
v.fill(1);
|
|
610
|
+
k.fill(0);
|
|
611
|
+
i = 0;
|
|
612
|
+
};
|
|
613
|
+
const h = (...b) => hmacFn(k, v, ...b);
|
|
614
|
+
const reseed = (seed = u8n(0)) => {
|
|
615
|
+
k = h(u8of(0), seed);
|
|
616
|
+
v = h();
|
|
617
|
+
if (seed.length === 0)
|
|
618
|
+
return;
|
|
619
|
+
k = h(u8of(1), seed);
|
|
620
|
+
v = h();
|
|
621
|
+
};
|
|
622
|
+
const gen2 = () => {
|
|
623
|
+
if (i++ >= 1e3)
|
|
624
|
+
throw new Error("drbg: tried 1000 values");
|
|
625
|
+
let len = 0;
|
|
626
|
+
const out = [];
|
|
627
|
+
while (len < qByteLen) {
|
|
628
|
+
v = h();
|
|
629
|
+
const sl = v.slice();
|
|
630
|
+
out.push(sl);
|
|
631
|
+
len += v.length;
|
|
632
|
+
}
|
|
633
|
+
return concatBytes(...out);
|
|
634
|
+
};
|
|
635
|
+
const genUntil = (seed, pred) => {
|
|
636
|
+
reset();
|
|
637
|
+
reseed(seed);
|
|
638
|
+
let res = void 0;
|
|
639
|
+
while (!(res = pred(gen2())))
|
|
640
|
+
reseed();
|
|
641
|
+
reset();
|
|
642
|
+
return res;
|
|
643
|
+
};
|
|
644
|
+
return genUntil;
|
|
645
|
+
}
|
|
646
|
+
function _validateObject(object, fields, optFields = {}) {
|
|
647
|
+
if (!object || typeof object !== "object")
|
|
648
|
+
throw new Error("expected valid options object");
|
|
649
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
650
|
+
const val = object[fieldName];
|
|
651
|
+
if (isOpt && val === void 0)
|
|
652
|
+
return;
|
|
653
|
+
const current = typeof val;
|
|
654
|
+
if (current !== expectedType || val === null)
|
|
655
|
+
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
656
|
+
}
|
|
657
|
+
Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
|
|
658
|
+
Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
|
|
659
|
+
}
|
|
660
|
+
function memoized(fn) {
|
|
661
|
+
const map = /* @__PURE__ */ new WeakMap();
|
|
662
|
+
return (arg, ...args) => {
|
|
663
|
+
const val = map.get(arg);
|
|
664
|
+
if (val !== void 0)
|
|
665
|
+
return val;
|
|
666
|
+
const computed = fn(arg, ...args);
|
|
667
|
+
map.set(arg, computed);
|
|
668
|
+
return computed;
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// ../eocene-worker/node_modules/@noble/curves/esm/abstract/modular.js
|
|
673
|
+
var _0n2 = BigInt(0);
|
|
674
|
+
var _1n2 = BigInt(1);
|
|
675
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
676
|
+
var _3n = /* @__PURE__ */ BigInt(3);
|
|
677
|
+
var _4n = /* @__PURE__ */ BigInt(4);
|
|
678
|
+
var _5n = /* @__PURE__ */ BigInt(5);
|
|
679
|
+
var _7n = /* @__PURE__ */ BigInt(7);
|
|
680
|
+
var _8n = /* @__PURE__ */ BigInt(8);
|
|
681
|
+
var _9n = /* @__PURE__ */ BigInt(9);
|
|
682
|
+
var _16n = /* @__PURE__ */ BigInt(16);
|
|
683
|
+
function mod(a, b) {
|
|
684
|
+
const result = a % b;
|
|
685
|
+
return result >= _0n2 ? result : b + result;
|
|
686
|
+
}
|
|
687
|
+
function pow2(x, power, modulo) {
|
|
688
|
+
let res = x;
|
|
689
|
+
while (power-- > _0n2) {
|
|
690
|
+
res *= res;
|
|
691
|
+
res %= modulo;
|
|
692
|
+
}
|
|
693
|
+
return res;
|
|
694
|
+
}
|
|
695
|
+
function invert(number, modulo) {
|
|
696
|
+
if (number === _0n2)
|
|
697
|
+
throw new Error("invert: expected non-zero number");
|
|
698
|
+
if (modulo <= _0n2)
|
|
699
|
+
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
700
|
+
let a = mod(number, modulo);
|
|
701
|
+
let b = modulo;
|
|
702
|
+
let x = _0n2, u = _1n2;
|
|
703
|
+
while (a !== _0n2) {
|
|
704
|
+
const q = b / a;
|
|
705
|
+
const r = b % a;
|
|
706
|
+
const m = x - u * q;
|
|
707
|
+
b = a, a = r, x = u, u = m;
|
|
708
|
+
}
|
|
709
|
+
const gcd = b;
|
|
710
|
+
if (gcd !== _1n2)
|
|
711
|
+
throw new Error("invert: does not exist");
|
|
712
|
+
return mod(x, modulo);
|
|
713
|
+
}
|
|
714
|
+
function assertIsSquare(Fp, root, n) {
|
|
715
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
716
|
+
throw new Error("Cannot find square root");
|
|
717
|
+
}
|
|
718
|
+
function sqrt3mod4(Fp, n) {
|
|
719
|
+
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
720
|
+
const root = Fp.pow(n, p1div4);
|
|
721
|
+
assertIsSquare(Fp, root, n);
|
|
722
|
+
return root;
|
|
723
|
+
}
|
|
724
|
+
function sqrt5mod8(Fp, n) {
|
|
725
|
+
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
726
|
+
const n2 = Fp.mul(n, _2n);
|
|
727
|
+
const v = Fp.pow(n2, p5div8);
|
|
728
|
+
const nv = Fp.mul(n, v);
|
|
729
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
730
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
731
|
+
assertIsSquare(Fp, root, n);
|
|
732
|
+
return root;
|
|
733
|
+
}
|
|
734
|
+
function sqrt9mod16(P) {
|
|
735
|
+
const Fp_ = Field(P);
|
|
736
|
+
const tn = tonelliShanks(P);
|
|
737
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
738
|
+
const c2 = tn(Fp_, c1);
|
|
739
|
+
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
740
|
+
const c4 = (P + _7n) / _16n;
|
|
741
|
+
return (Fp, n) => {
|
|
742
|
+
let tv1 = Fp.pow(n, c4);
|
|
743
|
+
let tv2 = Fp.mul(tv1, c1);
|
|
744
|
+
const tv3 = Fp.mul(tv1, c2);
|
|
745
|
+
const tv4 = Fp.mul(tv1, c3);
|
|
746
|
+
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
747
|
+
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
748
|
+
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
749
|
+
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
750
|
+
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
751
|
+
const root = Fp.cmov(tv1, tv2, e3);
|
|
752
|
+
assertIsSquare(Fp, root, n);
|
|
753
|
+
return root;
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
function tonelliShanks(P) {
|
|
757
|
+
if (P < _3n)
|
|
758
|
+
throw new Error("sqrt is not defined for small field");
|
|
759
|
+
let Q = P - _1n2;
|
|
760
|
+
let S = 0;
|
|
761
|
+
while (Q % _2n === _0n2) {
|
|
762
|
+
Q /= _2n;
|
|
763
|
+
S++;
|
|
764
|
+
}
|
|
765
|
+
let Z = _2n;
|
|
766
|
+
const _Fp = Field(P);
|
|
767
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
768
|
+
if (Z++ > 1e3)
|
|
769
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
770
|
+
}
|
|
771
|
+
if (S === 1)
|
|
772
|
+
return sqrt3mod4;
|
|
773
|
+
let cc = _Fp.pow(Z, Q);
|
|
774
|
+
const Q1div2 = (Q + _1n2) / _2n;
|
|
775
|
+
return function tonelliSlow(Fp, n) {
|
|
776
|
+
if (Fp.is0(n))
|
|
777
|
+
return n;
|
|
778
|
+
if (FpLegendre(Fp, n) !== 1)
|
|
779
|
+
throw new Error("Cannot find square root");
|
|
780
|
+
let M = S;
|
|
781
|
+
let c = Fp.mul(Fp.ONE, cc);
|
|
782
|
+
let t = Fp.pow(n, Q);
|
|
783
|
+
let R = Fp.pow(n, Q1div2);
|
|
784
|
+
while (!Fp.eql(t, Fp.ONE)) {
|
|
785
|
+
if (Fp.is0(t))
|
|
786
|
+
return Fp.ZERO;
|
|
787
|
+
let i = 1;
|
|
788
|
+
let t_tmp = Fp.sqr(t);
|
|
789
|
+
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
790
|
+
i++;
|
|
791
|
+
t_tmp = Fp.sqr(t_tmp);
|
|
792
|
+
if (i === M)
|
|
793
|
+
throw new Error("Cannot find square root");
|
|
794
|
+
}
|
|
795
|
+
const exponent = _1n2 << BigInt(M - i - 1);
|
|
796
|
+
const b = Fp.pow(c, exponent);
|
|
797
|
+
M = i;
|
|
798
|
+
c = Fp.sqr(b);
|
|
799
|
+
t = Fp.mul(t, c);
|
|
800
|
+
R = Fp.mul(R, b);
|
|
801
|
+
}
|
|
802
|
+
return R;
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
function FpSqrt(P) {
|
|
806
|
+
if (P % _4n === _3n)
|
|
807
|
+
return sqrt3mod4;
|
|
808
|
+
if (P % _8n === _5n)
|
|
809
|
+
return sqrt5mod8;
|
|
810
|
+
if (P % _16n === _9n)
|
|
811
|
+
return sqrt9mod16(P);
|
|
812
|
+
return tonelliShanks(P);
|
|
813
|
+
}
|
|
814
|
+
var FIELD_FIELDS = [
|
|
815
|
+
"create",
|
|
816
|
+
"isValid",
|
|
817
|
+
"is0",
|
|
818
|
+
"neg",
|
|
819
|
+
"inv",
|
|
820
|
+
"sqrt",
|
|
821
|
+
"sqr",
|
|
822
|
+
"eql",
|
|
823
|
+
"add",
|
|
824
|
+
"sub",
|
|
825
|
+
"mul",
|
|
826
|
+
"pow",
|
|
827
|
+
"div",
|
|
828
|
+
"addN",
|
|
829
|
+
"subN",
|
|
830
|
+
"mulN",
|
|
831
|
+
"sqrN"
|
|
832
|
+
];
|
|
833
|
+
function validateField(field) {
|
|
834
|
+
const initial = {
|
|
835
|
+
ORDER: "bigint",
|
|
836
|
+
MASK: "bigint",
|
|
837
|
+
BYTES: "number",
|
|
838
|
+
BITS: "number"
|
|
839
|
+
};
|
|
840
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
841
|
+
map[val] = "function";
|
|
842
|
+
return map;
|
|
843
|
+
}, initial);
|
|
844
|
+
_validateObject(field, opts);
|
|
845
|
+
return field;
|
|
846
|
+
}
|
|
847
|
+
function FpPow(Fp, num, power) {
|
|
848
|
+
if (power < _0n2)
|
|
849
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
850
|
+
if (power === _0n2)
|
|
851
|
+
return Fp.ONE;
|
|
852
|
+
if (power === _1n2)
|
|
853
|
+
return num;
|
|
854
|
+
let p = Fp.ONE;
|
|
855
|
+
let d = num;
|
|
856
|
+
while (power > _0n2) {
|
|
857
|
+
if (power & _1n2)
|
|
858
|
+
p = Fp.mul(p, d);
|
|
859
|
+
d = Fp.sqr(d);
|
|
860
|
+
power >>= _1n2;
|
|
861
|
+
}
|
|
862
|
+
return p;
|
|
863
|
+
}
|
|
864
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
865
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
866
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
867
|
+
if (Fp.is0(num))
|
|
868
|
+
return acc;
|
|
869
|
+
inverted[i] = acc;
|
|
870
|
+
return Fp.mul(acc, num);
|
|
871
|
+
}, Fp.ONE);
|
|
872
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
873
|
+
nums.reduceRight((acc, num, i) => {
|
|
874
|
+
if (Fp.is0(num))
|
|
875
|
+
return acc;
|
|
876
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
877
|
+
return Fp.mul(acc, num);
|
|
878
|
+
}, invertedAcc);
|
|
879
|
+
return inverted;
|
|
880
|
+
}
|
|
881
|
+
function FpLegendre(Fp, n) {
|
|
882
|
+
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
883
|
+
const powered = Fp.pow(n, p1mod2);
|
|
884
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
885
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
886
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
887
|
+
if (!yes && !zero && !no)
|
|
888
|
+
throw new Error("invalid Legendre symbol result");
|
|
889
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
890
|
+
}
|
|
891
|
+
function nLength(n, nBitLength) {
|
|
892
|
+
if (nBitLength !== void 0)
|
|
893
|
+
anumber(nBitLength);
|
|
894
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
895
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
896
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
897
|
+
}
|
|
898
|
+
function Field(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
|
|
899
|
+
if (ORDER <= _0n2)
|
|
900
|
+
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
901
|
+
let _nbitLength = void 0;
|
|
902
|
+
let _sqrt = void 0;
|
|
903
|
+
let modFromBytes = false;
|
|
904
|
+
let allowedLengths = void 0;
|
|
905
|
+
if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
|
|
906
|
+
if (opts.sqrt || isLE2)
|
|
907
|
+
throw new Error("cannot specify opts in two arguments");
|
|
908
|
+
const _opts = bitLenOrOpts;
|
|
909
|
+
if (_opts.BITS)
|
|
910
|
+
_nbitLength = _opts.BITS;
|
|
911
|
+
if (_opts.sqrt)
|
|
912
|
+
_sqrt = _opts.sqrt;
|
|
913
|
+
if (typeof _opts.isLE === "boolean")
|
|
914
|
+
isLE2 = _opts.isLE;
|
|
915
|
+
if (typeof _opts.modFromBytes === "boolean")
|
|
916
|
+
modFromBytes = _opts.modFromBytes;
|
|
917
|
+
allowedLengths = _opts.allowedLengths;
|
|
918
|
+
} else {
|
|
919
|
+
if (typeof bitLenOrOpts === "number")
|
|
920
|
+
_nbitLength = bitLenOrOpts;
|
|
921
|
+
if (opts.sqrt)
|
|
922
|
+
_sqrt = opts.sqrt;
|
|
923
|
+
}
|
|
924
|
+
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
|
|
925
|
+
if (BYTES > 2048)
|
|
926
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
927
|
+
let sqrtP;
|
|
928
|
+
const f = Object.freeze({
|
|
929
|
+
ORDER,
|
|
930
|
+
isLE: isLE2,
|
|
931
|
+
BITS,
|
|
932
|
+
BYTES,
|
|
933
|
+
MASK: bitMask(BITS),
|
|
934
|
+
ZERO: _0n2,
|
|
935
|
+
ONE: _1n2,
|
|
936
|
+
allowedLengths,
|
|
937
|
+
create: (num) => mod(num, ORDER),
|
|
938
|
+
isValid: (num) => {
|
|
939
|
+
if (typeof num !== "bigint")
|
|
940
|
+
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
941
|
+
return _0n2 <= num && num < ORDER;
|
|
942
|
+
},
|
|
943
|
+
is0: (num) => num === _0n2,
|
|
944
|
+
// is valid and invertible
|
|
945
|
+
isValidNot0: (num) => !f.is0(num) && f.isValid(num),
|
|
946
|
+
isOdd: (num) => (num & _1n2) === _1n2,
|
|
947
|
+
neg: (num) => mod(-num, ORDER),
|
|
948
|
+
eql: (lhs, rhs) => lhs === rhs,
|
|
949
|
+
sqr: (num) => mod(num * num, ORDER),
|
|
950
|
+
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
|
|
951
|
+
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
|
|
952
|
+
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
|
|
953
|
+
pow: (num, power) => FpPow(f, num, power),
|
|
954
|
+
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
|
|
955
|
+
// Same as above, but doesn't normalize
|
|
956
|
+
sqrN: (num) => num * num,
|
|
957
|
+
addN: (lhs, rhs) => lhs + rhs,
|
|
958
|
+
subN: (lhs, rhs) => lhs - rhs,
|
|
959
|
+
mulN: (lhs, rhs) => lhs * rhs,
|
|
960
|
+
inv: (num) => invert(num, ORDER),
|
|
961
|
+
sqrt: _sqrt || ((n) => {
|
|
962
|
+
if (!sqrtP)
|
|
963
|
+
sqrtP = FpSqrt(ORDER);
|
|
964
|
+
return sqrtP(f, n);
|
|
965
|
+
}),
|
|
966
|
+
toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
|
|
967
|
+
fromBytes: (bytes, skipValidation = true) => {
|
|
968
|
+
if (allowedLengths) {
|
|
969
|
+
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
970
|
+
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
971
|
+
}
|
|
972
|
+
const padded = new Uint8Array(BYTES);
|
|
973
|
+
padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
|
|
974
|
+
bytes = padded;
|
|
975
|
+
}
|
|
976
|
+
if (bytes.length !== BYTES)
|
|
977
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
978
|
+
let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
979
|
+
if (modFromBytes)
|
|
980
|
+
scalar = mod(scalar, ORDER);
|
|
981
|
+
if (!skipValidation) {
|
|
982
|
+
if (!f.isValid(scalar))
|
|
983
|
+
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
984
|
+
}
|
|
985
|
+
return scalar;
|
|
986
|
+
},
|
|
987
|
+
// TODO: we don't need it here, move out to separate fn
|
|
988
|
+
invertBatch: (lst) => FpInvertBatch(f, lst),
|
|
989
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
990
|
+
// and it's unclear what to return in there.
|
|
991
|
+
cmov: (a, b, c) => c ? b : a
|
|
992
|
+
});
|
|
993
|
+
return Object.freeze(f);
|
|
994
|
+
}
|
|
995
|
+
function getFieldBytesLength(fieldOrder) {
|
|
996
|
+
if (typeof fieldOrder !== "bigint")
|
|
997
|
+
throw new Error("field order must be bigint");
|
|
998
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
999
|
+
return Math.ceil(bitLength / 8);
|
|
1000
|
+
}
|
|
1001
|
+
function getMinHashLength(fieldOrder) {
|
|
1002
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
1003
|
+
return length + Math.ceil(length / 2);
|
|
1004
|
+
}
|
|
1005
|
+
function mapHashToField(key, fieldOrder, isLE2 = false) {
|
|
1006
|
+
const len = key.length;
|
|
1007
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
1008
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
1009
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
1010
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
1011
|
+
const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
1012
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
1013
|
+
return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// ../eocene-worker/node_modules/@noble/curves/esm/abstract/curve.js
|
|
1017
|
+
var _0n3 = BigInt(0);
|
|
1018
|
+
var _1n3 = BigInt(1);
|
|
1019
|
+
function negateCt(condition, item) {
|
|
1020
|
+
const neg = item.negate();
|
|
1021
|
+
return condition ? neg : item;
|
|
1022
|
+
}
|
|
1023
|
+
function normalizeZ(c, points) {
|
|
1024
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
1025
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
1026
|
+
}
|
|
1027
|
+
function validateW(W, bits) {
|
|
1028
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
1029
|
+
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
1030
|
+
}
|
|
1031
|
+
function calcWOpts(W, scalarBits) {
|
|
1032
|
+
validateW(W, scalarBits);
|
|
1033
|
+
const windows = Math.ceil(scalarBits / W) + 1;
|
|
1034
|
+
const windowSize = 2 ** (W - 1);
|
|
1035
|
+
const maxNumber = 2 ** W;
|
|
1036
|
+
const mask = bitMask(W);
|
|
1037
|
+
const shiftBy = BigInt(W);
|
|
1038
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
1039
|
+
}
|
|
1040
|
+
function calcOffsets(n, window2, wOpts) {
|
|
1041
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
1042
|
+
let wbits = Number(n & mask);
|
|
1043
|
+
let nextN = n >> shiftBy;
|
|
1044
|
+
if (wbits > windowSize) {
|
|
1045
|
+
wbits -= maxNumber;
|
|
1046
|
+
nextN += _1n3;
|
|
1047
|
+
}
|
|
1048
|
+
const offsetStart = window2 * windowSize;
|
|
1049
|
+
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
1050
|
+
const isZero = wbits === 0;
|
|
1051
|
+
const isNeg = wbits < 0;
|
|
1052
|
+
const isNegF = window2 % 2 !== 0;
|
|
1053
|
+
const offsetF = offsetStart;
|
|
1054
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
1055
|
+
}
|
|
1056
|
+
function validateMSMPoints(points, c) {
|
|
1057
|
+
if (!Array.isArray(points))
|
|
1058
|
+
throw new Error("array expected");
|
|
1059
|
+
points.forEach((p, i) => {
|
|
1060
|
+
if (!(p instanceof c))
|
|
1061
|
+
throw new Error("invalid point at index " + i);
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
function validateMSMScalars(scalars, field) {
|
|
1065
|
+
if (!Array.isArray(scalars))
|
|
1066
|
+
throw new Error("array of scalars expected");
|
|
1067
|
+
scalars.forEach((s, i) => {
|
|
1068
|
+
if (!field.isValid(s))
|
|
1069
|
+
throw new Error("invalid scalar at index " + i);
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
1073
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
1074
|
+
function getW(P) {
|
|
1075
|
+
return pointWindowSizes.get(P) || 1;
|
|
1076
|
+
}
|
|
1077
|
+
function assert0(n) {
|
|
1078
|
+
if (n !== _0n3)
|
|
1079
|
+
throw new Error("invalid wNAF");
|
|
1080
|
+
}
|
|
1081
|
+
var wNAF = class {
|
|
1082
|
+
// Parametrized with a given Point class (not individual point)
|
|
1083
|
+
constructor(Point, bits) {
|
|
1084
|
+
this.BASE = Point.BASE;
|
|
1085
|
+
this.ZERO = Point.ZERO;
|
|
1086
|
+
this.Fn = Point.Fn;
|
|
1087
|
+
this.bits = bits;
|
|
1088
|
+
}
|
|
1089
|
+
// non-const time multiplication ladder
|
|
1090
|
+
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
1091
|
+
let d = elm;
|
|
1092
|
+
while (n > _0n3) {
|
|
1093
|
+
if (n & _1n3)
|
|
1094
|
+
p = p.add(d);
|
|
1095
|
+
d = d.double();
|
|
1096
|
+
n >>= _1n3;
|
|
1097
|
+
}
|
|
1098
|
+
return p;
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
1102
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
1103
|
+
* Number of precomputed points depends on the curve size:
|
|
1104
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
1105
|
+
* - 𝑊 is the window size
|
|
1106
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
1107
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
1108
|
+
* @param point Point instance
|
|
1109
|
+
* @param W window size
|
|
1110
|
+
* @returns precomputed point tables flattened to a single array
|
|
1111
|
+
*/
|
|
1112
|
+
precomputeWindow(point, W) {
|
|
1113
|
+
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
1114
|
+
const points = [];
|
|
1115
|
+
let p = point;
|
|
1116
|
+
let base = p;
|
|
1117
|
+
for (let window2 = 0; window2 < windows; window2++) {
|
|
1118
|
+
base = p;
|
|
1119
|
+
points.push(base);
|
|
1120
|
+
for (let i = 1; i < windowSize; i++) {
|
|
1121
|
+
base = base.add(p);
|
|
1122
|
+
points.push(base);
|
|
1123
|
+
}
|
|
1124
|
+
p = base.double();
|
|
1125
|
+
}
|
|
1126
|
+
return points;
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
1130
|
+
* More compact implementation:
|
|
1131
|
+
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
1132
|
+
* @returns real and fake (for const-time) points
|
|
1133
|
+
*/
|
|
1134
|
+
wNAF(W, precomputes, n) {
|
|
1135
|
+
if (!this.Fn.isValid(n))
|
|
1136
|
+
throw new Error("invalid scalar");
|
|
1137
|
+
let p = this.ZERO;
|
|
1138
|
+
let f = this.BASE;
|
|
1139
|
+
const wo = calcWOpts(W, this.bits);
|
|
1140
|
+
for (let window2 = 0; window2 < wo.windows; window2++) {
|
|
1141
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo);
|
|
1142
|
+
n = nextN;
|
|
1143
|
+
if (isZero) {
|
|
1144
|
+
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
1145
|
+
} else {
|
|
1146
|
+
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
assert0(n);
|
|
1150
|
+
return { p, f };
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
1154
|
+
* @param acc accumulator point to add result of multiplication
|
|
1155
|
+
* @returns point
|
|
1156
|
+
*/
|
|
1157
|
+
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
1158
|
+
const wo = calcWOpts(W, this.bits);
|
|
1159
|
+
for (let window2 = 0; window2 < wo.windows; window2++) {
|
|
1160
|
+
if (n === _0n3)
|
|
1161
|
+
break;
|
|
1162
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo);
|
|
1163
|
+
n = nextN;
|
|
1164
|
+
if (isZero) {
|
|
1165
|
+
continue;
|
|
1166
|
+
} else {
|
|
1167
|
+
const item = precomputes[offset];
|
|
1168
|
+
acc = acc.add(isNeg ? item.negate() : item);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
assert0(n);
|
|
1172
|
+
return acc;
|
|
1173
|
+
}
|
|
1174
|
+
getPrecomputes(W, point, transform) {
|
|
1175
|
+
let comp = pointPrecomputes.get(point);
|
|
1176
|
+
if (!comp) {
|
|
1177
|
+
comp = this.precomputeWindow(point, W);
|
|
1178
|
+
if (W !== 1) {
|
|
1179
|
+
if (typeof transform === "function")
|
|
1180
|
+
comp = transform(comp);
|
|
1181
|
+
pointPrecomputes.set(point, comp);
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
return comp;
|
|
1185
|
+
}
|
|
1186
|
+
cached(point, scalar, transform) {
|
|
1187
|
+
const W = getW(point);
|
|
1188
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
1189
|
+
}
|
|
1190
|
+
unsafe(point, scalar, transform, prev) {
|
|
1191
|
+
const W = getW(point);
|
|
1192
|
+
if (W === 1)
|
|
1193
|
+
return this._unsafeLadder(point, scalar, prev);
|
|
1194
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
1195
|
+
}
|
|
1196
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
1197
|
+
// using windowed method. This specifies window size and
|
|
1198
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
1199
|
+
createCache(P, W) {
|
|
1200
|
+
validateW(W, this.bits);
|
|
1201
|
+
pointWindowSizes.set(P, W);
|
|
1202
|
+
pointPrecomputes.delete(P);
|
|
1203
|
+
}
|
|
1204
|
+
hasCache(elm) {
|
|
1205
|
+
return getW(elm) !== 1;
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
1209
|
+
let acc = point;
|
|
1210
|
+
let p1 = Point.ZERO;
|
|
1211
|
+
let p2 = Point.ZERO;
|
|
1212
|
+
while (k1 > _0n3 || k2 > _0n3) {
|
|
1213
|
+
if (k1 & _1n3)
|
|
1214
|
+
p1 = p1.add(acc);
|
|
1215
|
+
if (k2 & _1n3)
|
|
1216
|
+
p2 = p2.add(acc);
|
|
1217
|
+
acc = acc.double();
|
|
1218
|
+
k1 >>= _1n3;
|
|
1219
|
+
k2 >>= _1n3;
|
|
1220
|
+
}
|
|
1221
|
+
return { p1, p2 };
|
|
1222
|
+
}
|
|
1223
|
+
function pippenger(c, fieldN, points, scalars) {
|
|
1224
|
+
validateMSMPoints(points, c);
|
|
1225
|
+
validateMSMScalars(scalars, fieldN);
|
|
1226
|
+
const plength = points.length;
|
|
1227
|
+
const slength = scalars.length;
|
|
1228
|
+
if (plength !== slength)
|
|
1229
|
+
throw new Error("arrays of points and scalars must have equal length");
|
|
1230
|
+
const zero = c.ZERO;
|
|
1231
|
+
const wbits = bitLen(BigInt(plength));
|
|
1232
|
+
let windowSize = 1;
|
|
1233
|
+
if (wbits > 12)
|
|
1234
|
+
windowSize = wbits - 3;
|
|
1235
|
+
else if (wbits > 4)
|
|
1236
|
+
windowSize = wbits - 2;
|
|
1237
|
+
else if (wbits > 0)
|
|
1238
|
+
windowSize = 2;
|
|
1239
|
+
const MASK = bitMask(windowSize);
|
|
1240
|
+
const buckets = new Array(Number(MASK) + 1).fill(zero);
|
|
1241
|
+
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
|
1242
|
+
let sum = zero;
|
|
1243
|
+
for (let i = lastBits; i >= 0; i -= windowSize) {
|
|
1244
|
+
buckets.fill(zero);
|
|
1245
|
+
for (let j = 0; j < slength; j++) {
|
|
1246
|
+
const scalar = scalars[j];
|
|
1247
|
+
const wbits2 = Number(scalar >> BigInt(i) & MASK);
|
|
1248
|
+
buckets[wbits2] = buckets[wbits2].add(points[j]);
|
|
1249
|
+
}
|
|
1250
|
+
let resI = zero;
|
|
1251
|
+
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
|
1252
|
+
sumI = sumI.add(buckets[j]);
|
|
1253
|
+
resI = resI.add(sumI);
|
|
1254
|
+
}
|
|
1255
|
+
sum = sum.add(resI);
|
|
1256
|
+
if (i !== 0)
|
|
1257
|
+
for (let j = 0; j < windowSize; j++)
|
|
1258
|
+
sum = sum.double();
|
|
1259
|
+
}
|
|
1260
|
+
return sum;
|
|
1261
|
+
}
|
|
1262
|
+
function createField(order, field, isLE2) {
|
|
1263
|
+
if (field) {
|
|
1264
|
+
if (field.ORDER !== order)
|
|
1265
|
+
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
1266
|
+
validateField(field);
|
|
1267
|
+
return field;
|
|
1268
|
+
} else {
|
|
1269
|
+
return Field(order, { isLE: isLE2 });
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
1273
|
+
if (FpFnLE === void 0)
|
|
1274
|
+
FpFnLE = type === "edwards";
|
|
1275
|
+
if (!CURVE || typeof CURVE !== "object")
|
|
1276
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
1277
|
+
for (const p of ["p", "n", "h"]) {
|
|
1278
|
+
const val = CURVE[p];
|
|
1279
|
+
if (!(typeof val === "bigint" && val > _0n3))
|
|
1280
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
1281
|
+
}
|
|
1282
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
1283
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
1284
|
+
const _b = "b" ;
|
|
1285
|
+
const params = ["Gx", "Gy", "a", _b];
|
|
1286
|
+
for (const p of params) {
|
|
1287
|
+
if (!Fp.isValid(CURVE[p]))
|
|
1288
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
1289
|
+
}
|
|
1290
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
1291
|
+
return { CURVE, Fp, Fn };
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
// ../eocene-worker/node_modules/@noble/curves/esm/abstract/weierstrass.js
|
|
1295
|
+
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
1296
|
+
function _splitEndoScalar(k, basis, n) {
|
|
1297
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
1298
|
+
const c1 = divNearest(b2 * k, n);
|
|
1299
|
+
const c2 = divNearest(-b1 * k, n);
|
|
1300
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
1301
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
1302
|
+
const k1neg = k1 < _0n4;
|
|
1303
|
+
const k2neg = k2 < _0n4;
|
|
1304
|
+
if (k1neg)
|
|
1305
|
+
k1 = -k1;
|
|
1306
|
+
if (k2neg)
|
|
1307
|
+
k2 = -k2;
|
|
1308
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
1309
|
+
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
1310
|
+
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
1311
|
+
}
|
|
1312
|
+
return { k1neg, k1, k2neg, k2 };
|
|
1313
|
+
}
|
|
1314
|
+
function validateSigFormat(format) {
|
|
1315
|
+
if (!["compact", "recovered", "der"].includes(format))
|
|
1316
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
1317
|
+
return format;
|
|
1318
|
+
}
|
|
1319
|
+
function validateSigOpts(opts, def) {
|
|
1320
|
+
const optsn = {};
|
|
1321
|
+
for (let optName of Object.keys(def)) {
|
|
1322
|
+
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
1323
|
+
}
|
|
1324
|
+
_abool2(optsn.lowS, "lowS");
|
|
1325
|
+
_abool2(optsn.prehash, "prehash");
|
|
1326
|
+
if (optsn.format !== void 0)
|
|
1327
|
+
validateSigFormat(optsn.format);
|
|
1328
|
+
return optsn;
|
|
1329
|
+
}
|
|
1330
|
+
var DERErr = class extends Error {
|
|
1331
|
+
constructor(m = "") {
|
|
1332
|
+
super(m);
|
|
1333
|
+
}
|
|
1334
|
+
};
|
|
1335
|
+
var DER = {
|
|
1336
|
+
// asn.1 DER encoding utils
|
|
1337
|
+
Err: DERErr,
|
|
1338
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
1339
|
+
_tlv: {
|
|
1340
|
+
encode: (tag, data) => {
|
|
1341
|
+
const { Err: E } = DER;
|
|
1342
|
+
if (tag < 0 || tag > 256)
|
|
1343
|
+
throw new E("tlv.encode: wrong tag");
|
|
1344
|
+
if (data.length & 1)
|
|
1345
|
+
throw new E("tlv.encode: unpadded data");
|
|
1346
|
+
const dataLen = data.length / 2;
|
|
1347
|
+
const len = numberToHexUnpadded(dataLen);
|
|
1348
|
+
if (len.length / 2 & 128)
|
|
1349
|
+
throw new E("tlv.encode: long form length too big");
|
|
1350
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
1351
|
+
const t = numberToHexUnpadded(tag);
|
|
1352
|
+
return t + lenLen + len + data;
|
|
1353
|
+
},
|
|
1354
|
+
// v - value, l - left bytes (unparsed)
|
|
1355
|
+
decode(tag, data) {
|
|
1356
|
+
const { Err: E } = DER;
|
|
1357
|
+
let pos = 0;
|
|
1358
|
+
if (tag < 0 || tag > 256)
|
|
1359
|
+
throw new E("tlv.encode: wrong tag");
|
|
1360
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
1361
|
+
throw new E("tlv.decode: wrong tlv");
|
|
1362
|
+
const first = data[pos++];
|
|
1363
|
+
const isLong = !!(first & 128);
|
|
1364
|
+
let length = 0;
|
|
1365
|
+
if (!isLong)
|
|
1366
|
+
length = first;
|
|
1367
|
+
else {
|
|
1368
|
+
const lenLen = first & 127;
|
|
1369
|
+
if (!lenLen)
|
|
1370
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
1371
|
+
if (lenLen > 4)
|
|
1372
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
1373
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
1374
|
+
if (lengthBytes.length !== lenLen)
|
|
1375
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
1376
|
+
if (lengthBytes[0] === 0)
|
|
1377
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
1378
|
+
for (const b of lengthBytes)
|
|
1379
|
+
length = length << 8 | b;
|
|
1380
|
+
pos += lenLen;
|
|
1381
|
+
if (length < 128)
|
|
1382
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
1383
|
+
}
|
|
1384
|
+
const v = data.subarray(pos, pos + length);
|
|
1385
|
+
if (v.length !== length)
|
|
1386
|
+
throw new E("tlv.decode: wrong value length");
|
|
1387
|
+
return { v, l: data.subarray(pos + length) };
|
|
1388
|
+
}
|
|
1389
|
+
},
|
|
1390
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
1391
|
+
// since we always use positive integers here. It must always be empty:
|
|
1392
|
+
// - add zero byte if exists
|
|
1393
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
1394
|
+
_int: {
|
|
1395
|
+
encode(num) {
|
|
1396
|
+
const { Err: E } = DER;
|
|
1397
|
+
if (num < _0n4)
|
|
1398
|
+
throw new E("integer: negative integers are not allowed");
|
|
1399
|
+
let hex = numberToHexUnpadded(num);
|
|
1400
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
1401
|
+
hex = "00" + hex;
|
|
1402
|
+
if (hex.length & 1)
|
|
1403
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
1404
|
+
return hex;
|
|
1405
|
+
},
|
|
1406
|
+
decode(data) {
|
|
1407
|
+
const { Err: E } = DER;
|
|
1408
|
+
if (data[0] & 128)
|
|
1409
|
+
throw new E("invalid signature integer: negative");
|
|
1410
|
+
if (data[0] === 0 && !(data[1] & 128))
|
|
1411
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
1412
|
+
return bytesToNumberBE(data);
|
|
1413
|
+
}
|
|
1414
|
+
},
|
|
1415
|
+
toSig(hex) {
|
|
1416
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
1417
|
+
const data = ensureBytes("signature", hex);
|
|
1418
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
1419
|
+
if (seqLeftBytes.length)
|
|
1420
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
1421
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
1422
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
1423
|
+
if (sLeftBytes.length)
|
|
1424
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
1425
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
1426
|
+
},
|
|
1427
|
+
hexFromSig(sig) {
|
|
1428
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
1429
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
1430
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
1431
|
+
const seq = rs + ss;
|
|
1432
|
+
return tlv.encode(48, seq);
|
|
1433
|
+
}
|
|
1434
|
+
};
|
|
1435
|
+
var _0n4 = BigInt(0);
|
|
1436
|
+
var _1n4 = BigInt(1);
|
|
1437
|
+
var _2n2 = BigInt(2);
|
|
1438
|
+
var _3n2 = BigInt(3);
|
|
1439
|
+
var _4n2 = BigInt(4);
|
|
1440
|
+
function _normFnElement(Fn, key) {
|
|
1441
|
+
const { BYTES: expected } = Fn;
|
|
1442
|
+
let num;
|
|
1443
|
+
if (typeof key === "bigint") {
|
|
1444
|
+
num = key;
|
|
1445
|
+
} else {
|
|
1446
|
+
let bytes = ensureBytes("private key", key);
|
|
1447
|
+
try {
|
|
1448
|
+
num = Fn.fromBytes(bytes);
|
|
1449
|
+
} catch (error) {
|
|
1450
|
+
throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
if (!Fn.isValidNot0(num))
|
|
1454
|
+
throw new Error("invalid private key: out of range [1..N-1]");
|
|
1455
|
+
return num;
|
|
1456
|
+
}
|
|
1457
|
+
function weierstrassN(params, extraOpts = {}) {
|
|
1458
|
+
const validated = _createCurveFields("weierstrass", params, extraOpts);
|
|
1459
|
+
const { Fp, Fn } = validated;
|
|
1460
|
+
let CURVE = validated.CURVE;
|
|
1461
|
+
const { h: cofactor, n: CURVE_ORDER } = CURVE;
|
|
1462
|
+
_validateObject(extraOpts, {}, {
|
|
1463
|
+
allowInfinityPoint: "boolean",
|
|
1464
|
+
clearCofactor: "function",
|
|
1465
|
+
isTorsionFree: "function",
|
|
1466
|
+
fromBytes: "function",
|
|
1467
|
+
toBytes: "function",
|
|
1468
|
+
endo: "object",
|
|
1469
|
+
wrapPrivateKey: "boolean"
|
|
1470
|
+
});
|
|
1471
|
+
const { endo } = extraOpts;
|
|
1472
|
+
if (endo) {
|
|
1473
|
+
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
1474
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
const lengths = getWLengths(Fp, Fn);
|
|
1478
|
+
function assertCompressionIsSupported() {
|
|
1479
|
+
if (!Fp.isOdd)
|
|
1480
|
+
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
1481
|
+
}
|
|
1482
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
1483
|
+
const { x, y } = point.toAffine();
|
|
1484
|
+
const bx = Fp.toBytes(x);
|
|
1485
|
+
_abool2(isCompressed, "isCompressed");
|
|
1486
|
+
if (isCompressed) {
|
|
1487
|
+
assertCompressionIsSupported();
|
|
1488
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
1489
|
+
return concatBytes(pprefix(hasEvenY), bx);
|
|
1490
|
+
} else {
|
|
1491
|
+
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
function pointFromBytes(bytes) {
|
|
1495
|
+
_abytes2(bytes, void 0, "Point");
|
|
1496
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
1497
|
+
const length = bytes.length;
|
|
1498
|
+
const head = bytes[0];
|
|
1499
|
+
const tail = bytes.subarray(1);
|
|
1500
|
+
if (length === comp && (head === 2 || head === 3)) {
|
|
1501
|
+
const x = Fp.fromBytes(tail);
|
|
1502
|
+
if (!Fp.isValid(x))
|
|
1503
|
+
throw new Error("bad point: is not on curve, wrong x");
|
|
1504
|
+
const y2 = weierstrassEquation(x);
|
|
1505
|
+
let y;
|
|
1506
|
+
try {
|
|
1507
|
+
y = Fp.sqrt(y2);
|
|
1508
|
+
} catch (sqrtError) {
|
|
1509
|
+
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
1510
|
+
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
1511
|
+
}
|
|
1512
|
+
assertCompressionIsSupported();
|
|
1513
|
+
const isYOdd = Fp.isOdd(y);
|
|
1514
|
+
const isHeadOdd = (head & 1) === 1;
|
|
1515
|
+
if (isHeadOdd !== isYOdd)
|
|
1516
|
+
y = Fp.neg(y);
|
|
1517
|
+
return { x, y };
|
|
1518
|
+
} else if (length === uncomp && head === 4) {
|
|
1519
|
+
const L = Fp.BYTES;
|
|
1520
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
1521
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
1522
|
+
if (!isValidXY(x, y))
|
|
1523
|
+
throw new Error("bad point: is not on curve");
|
|
1524
|
+
return { x, y };
|
|
1525
|
+
} else {
|
|
1526
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
1530
|
+
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
1531
|
+
function weierstrassEquation(x) {
|
|
1532
|
+
const x2 = Fp.sqr(x);
|
|
1533
|
+
const x3 = Fp.mul(x2, x);
|
|
1534
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
1535
|
+
}
|
|
1536
|
+
function isValidXY(x, y) {
|
|
1537
|
+
const left = Fp.sqr(y);
|
|
1538
|
+
const right = weierstrassEquation(x);
|
|
1539
|
+
return Fp.eql(left, right);
|
|
1540
|
+
}
|
|
1541
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
1542
|
+
throw new Error("bad curve params: generator point");
|
|
1543
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
1544
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
1545
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
1546
|
+
throw new Error("bad curve params: a or b");
|
|
1547
|
+
function acoord(title, n, banZero = false) {
|
|
1548
|
+
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
1549
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
1550
|
+
return n;
|
|
1551
|
+
}
|
|
1552
|
+
function aprjpoint(other) {
|
|
1553
|
+
if (!(other instanceof Point))
|
|
1554
|
+
throw new Error("ProjectivePoint expected");
|
|
1555
|
+
}
|
|
1556
|
+
function splitEndoScalarN(k) {
|
|
1557
|
+
if (!endo || !endo.basises)
|
|
1558
|
+
throw new Error("no endo");
|
|
1559
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
1560
|
+
}
|
|
1561
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
1562
|
+
const { X, Y, Z } = p;
|
|
1563
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
1564
|
+
return { x: X, y: Y };
|
|
1565
|
+
const is0 = p.is0();
|
|
1566
|
+
if (iz == null)
|
|
1567
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
1568
|
+
const x = Fp.mul(X, iz);
|
|
1569
|
+
const y = Fp.mul(Y, iz);
|
|
1570
|
+
const zz = Fp.mul(Z, iz);
|
|
1571
|
+
if (is0)
|
|
1572
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
1573
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
1574
|
+
throw new Error("invZ was invalid");
|
|
1575
|
+
return { x, y };
|
|
1576
|
+
});
|
|
1577
|
+
const assertValidMemo = memoized((p) => {
|
|
1578
|
+
if (p.is0()) {
|
|
1579
|
+
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
1580
|
+
return;
|
|
1581
|
+
throw new Error("bad point: ZERO");
|
|
1582
|
+
}
|
|
1583
|
+
const { x, y } = p.toAffine();
|
|
1584
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
1585
|
+
throw new Error("bad point: x or y not field elements");
|
|
1586
|
+
if (!isValidXY(x, y))
|
|
1587
|
+
throw new Error("bad point: equation left != right");
|
|
1588
|
+
if (!p.isTorsionFree())
|
|
1589
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
1590
|
+
return true;
|
|
1591
|
+
});
|
|
1592
|
+
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
1593
|
+
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
1594
|
+
k1p = negateCt(k1neg, k1p);
|
|
1595
|
+
k2p = negateCt(k2neg, k2p);
|
|
1596
|
+
return k1p.add(k2p);
|
|
1597
|
+
}
|
|
1598
|
+
class Point {
|
|
1599
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
1600
|
+
constructor(X, Y, Z) {
|
|
1601
|
+
this.X = acoord("x", X);
|
|
1602
|
+
this.Y = acoord("y", Y, true);
|
|
1603
|
+
this.Z = acoord("z", Z);
|
|
1604
|
+
Object.freeze(this);
|
|
1605
|
+
}
|
|
1606
|
+
static CURVE() {
|
|
1607
|
+
return CURVE;
|
|
1608
|
+
}
|
|
1609
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
1610
|
+
static fromAffine(p) {
|
|
1611
|
+
const { x, y } = p || {};
|
|
1612
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
1613
|
+
throw new Error("invalid affine point");
|
|
1614
|
+
if (p instanceof Point)
|
|
1615
|
+
throw new Error("projective point not allowed");
|
|
1616
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
1617
|
+
return Point.ZERO;
|
|
1618
|
+
return new Point(x, y, Fp.ONE);
|
|
1619
|
+
}
|
|
1620
|
+
static fromBytes(bytes) {
|
|
1621
|
+
const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
|
|
1622
|
+
P.assertValidity();
|
|
1623
|
+
return P;
|
|
1624
|
+
}
|
|
1625
|
+
static fromHex(hex) {
|
|
1626
|
+
return Point.fromBytes(ensureBytes("pointHex", hex));
|
|
1627
|
+
}
|
|
1628
|
+
get x() {
|
|
1629
|
+
return this.toAffine().x;
|
|
1630
|
+
}
|
|
1631
|
+
get y() {
|
|
1632
|
+
return this.toAffine().y;
|
|
1633
|
+
}
|
|
1634
|
+
/**
|
|
1635
|
+
*
|
|
1636
|
+
* @param windowSize
|
|
1637
|
+
* @param isLazy true will defer table computation until the first multiplication
|
|
1638
|
+
* @returns
|
|
1639
|
+
*/
|
|
1640
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
1641
|
+
wnaf.createCache(this, windowSize);
|
|
1642
|
+
if (!isLazy)
|
|
1643
|
+
this.multiply(_3n2);
|
|
1644
|
+
return this;
|
|
1645
|
+
}
|
|
1646
|
+
// TODO: return `this`
|
|
1647
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
1648
|
+
assertValidity() {
|
|
1649
|
+
assertValidMemo(this);
|
|
1650
|
+
}
|
|
1651
|
+
hasEvenY() {
|
|
1652
|
+
const { y } = this.toAffine();
|
|
1653
|
+
if (!Fp.isOdd)
|
|
1654
|
+
throw new Error("Field doesn't support isOdd");
|
|
1655
|
+
return !Fp.isOdd(y);
|
|
1656
|
+
}
|
|
1657
|
+
/** Compare one point to another. */
|
|
1658
|
+
equals(other) {
|
|
1659
|
+
aprjpoint(other);
|
|
1660
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
1661
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
1662
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
1663
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
1664
|
+
return U1 && U2;
|
|
1665
|
+
}
|
|
1666
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
1667
|
+
negate() {
|
|
1668
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
1669
|
+
}
|
|
1670
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
1671
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
1672
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
1673
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
1674
|
+
double() {
|
|
1675
|
+
const { a, b } = CURVE;
|
|
1676
|
+
const b3 = Fp.mul(b, _3n2);
|
|
1677
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
1678
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
1679
|
+
let t0 = Fp.mul(X1, X1);
|
|
1680
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
1681
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
1682
|
+
let t3 = Fp.mul(X1, Y1);
|
|
1683
|
+
t3 = Fp.add(t3, t3);
|
|
1684
|
+
Z3 = Fp.mul(X1, Z1);
|
|
1685
|
+
Z3 = Fp.add(Z3, Z3);
|
|
1686
|
+
X3 = Fp.mul(a, Z3);
|
|
1687
|
+
Y3 = Fp.mul(b3, t2);
|
|
1688
|
+
Y3 = Fp.add(X3, Y3);
|
|
1689
|
+
X3 = Fp.sub(t1, Y3);
|
|
1690
|
+
Y3 = Fp.add(t1, Y3);
|
|
1691
|
+
Y3 = Fp.mul(X3, Y3);
|
|
1692
|
+
X3 = Fp.mul(t3, X3);
|
|
1693
|
+
Z3 = Fp.mul(b3, Z3);
|
|
1694
|
+
t2 = Fp.mul(a, t2);
|
|
1695
|
+
t3 = Fp.sub(t0, t2);
|
|
1696
|
+
t3 = Fp.mul(a, t3);
|
|
1697
|
+
t3 = Fp.add(t3, Z3);
|
|
1698
|
+
Z3 = Fp.add(t0, t0);
|
|
1699
|
+
t0 = Fp.add(Z3, t0);
|
|
1700
|
+
t0 = Fp.add(t0, t2);
|
|
1701
|
+
t0 = Fp.mul(t0, t3);
|
|
1702
|
+
Y3 = Fp.add(Y3, t0);
|
|
1703
|
+
t2 = Fp.mul(Y1, Z1);
|
|
1704
|
+
t2 = Fp.add(t2, t2);
|
|
1705
|
+
t0 = Fp.mul(t2, t3);
|
|
1706
|
+
X3 = Fp.sub(X3, t0);
|
|
1707
|
+
Z3 = Fp.mul(t2, t1);
|
|
1708
|
+
Z3 = Fp.add(Z3, Z3);
|
|
1709
|
+
Z3 = Fp.add(Z3, Z3);
|
|
1710
|
+
return new Point(X3, Y3, Z3);
|
|
1711
|
+
}
|
|
1712
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
1713
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
1714
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
1715
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
1716
|
+
add(other) {
|
|
1717
|
+
aprjpoint(other);
|
|
1718
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
1719
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
1720
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
1721
|
+
const a = CURVE.a;
|
|
1722
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
1723
|
+
let t0 = Fp.mul(X1, X2);
|
|
1724
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
1725
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
1726
|
+
let t3 = Fp.add(X1, Y1);
|
|
1727
|
+
let t4 = Fp.add(X2, Y2);
|
|
1728
|
+
t3 = Fp.mul(t3, t4);
|
|
1729
|
+
t4 = Fp.add(t0, t1);
|
|
1730
|
+
t3 = Fp.sub(t3, t4);
|
|
1731
|
+
t4 = Fp.add(X1, Z1);
|
|
1732
|
+
let t5 = Fp.add(X2, Z2);
|
|
1733
|
+
t4 = Fp.mul(t4, t5);
|
|
1734
|
+
t5 = Fp.add(t0, t2);
|
|
1735
|
+
t4 = Fp.sub(t4, t5);
|
|
1736
|
+
t5 = Fp.add(Y1, Z1);
|
|
1737
|
+
X3 = Fp.add(Y2, Z2);
|
|
1738
|
+
t5 = Fp.mul(t5, X3);
|
|
1739
|
+
X3 = Fp.add(t1, t2);
|
|
1740
|
+
t5 = Fp.sub(t5, X3);
|
|
1741
|
+
Z3 = Fp.mul(a, t4);
|
|
1742
|
+
X3 = Fp.mul(b3, t2);
|
|
1743
|
+
Z3 = Fp.add(X3, Z3);
|
|
1744
|
+
X3 = Fp.sub(t1, Z3);
|
|
1745
|
+
Z3 = Fp.add(t1, Z3);
|
|
1746
|
+
Y3 = Fp.mul(X3, Z3);
|
|
1747
|
+
t1 = Fp.add(t0, t0);
|
|
1748
|
+
t1 = Fp.add(t1, t0);
|
|
1749
|
+
t2 = Fp.mul(a, t2);
|
|
1750
|
+
t4 = Fp.mul(b3, t4);
|
|
1751
|
+
t1 = Fp.add(t1, t2);
|
|
1752
|
+
t2 = Fp.sub(t0, t2);
|
|
1753
|
+
t2 = Fp.mul(a, t2);
|
|
1754
|
+
t4 = Fp.add(t4, t2);
|
|
1755
|
+
t0 = Fp.mul(t1, t4);
|
|
1756
|
+
Y3 = Fp.add(Y3, t0);
|
|
1757
|
+
t0 = Fp.mul(t5, t4);
|
|
1758
|
+
X3 = Fp.mul(t3, X3);
|
|
1759
|
+
X3 = Fp.sub(X3, t0);
|
|
1760
|
+
t0 = Fp.mul(t3, t1);
|
|
1761
|
+
Z3 = Fp.mul(t5, Z3);
|
|
1762
|
+
Z3 = Fp.add(Z3, t0);
|
|
1763
|
+
return new Point(X3, Y3, Z3);
|
|
1764
|
+
}
|
|
1765
|
+
subtract(other) {
|
|
1766
|
+
return this.add(other.negate());
|
|
1767
|
+
}
|
|
1768
|
+
is0() {
|
|
1769
|
+
return this.equals(Point.ZERO);
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Constant time multiplication.
|
|
1773
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
1774
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
1775
|
+
* Uses precomputes when available.
|
|
1776
|
+
* Uses endomorphism for Koblitz curves.
|
|
1777
|
+
* @param scalar by which the point would be multiplied
|
|
1778
|
+
* @returns New point
|
|
1779
|
+
*/
|
|
1780
|
+
multiply(scalar) {
|
|
1781
|
+
const { endo: endo2 } = extraOpts;
|
|
1782
|
+
if (!Fn.isValidNot0(scalar))
|
|
1783
|
+
throw new Error("invalid scalar: out of range");
|
|
1784
|
+
let point, fake;
|
|
1785
|
+
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
1786
|
+
if (endo2) {
|
|
1787
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
1788
|
+
const { p: k1p, f: k1f } = mul(k1);
|
|
1789
|
+
const { p: k2p, f: k2f } = mul(k2);
|
|
1790
|
+
fake = k1f.add(k2f);
|
|
1791
|
+
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
1792
|
+
} else {
|
|
1793
|
+
const { p, f } = mul(scalar);
|
|
1794
|
+
point = p;
|
|
1795
|
+
fake = f;
|
|
1796
|
+
}
|
|
1797
|
+
return normalizeZ(Point, [point, fake])[0];
|
|
1798
|
+
}
|
|
1799
|
+
/**
|
|
1800
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
1801
|
+
* It's faster, but should only be used when you don't care about
|
|
1802
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
1803
|
+
*/
|
|
1804
|
+
multiplyUnsafe(sc) {
|
|
1805
|
+
const { endo: endo2 } = extraOpts;
|
|
1806
|
+
const p = this;
|
|
1807
|
+
if (!Fn.isValid(sc))
|
|
1808
|
+
throw new Error("invalid scalar: out of range");
|
|
1809
|
+
if (sc === _0n4 || p.is0())
|
|
1810
|
+
return Point.ZERO;
|
|
1811
|
+
if (sc === _1n4)
|
|
1812
|
+
return p;
|
|
1813
|
+
if (wnaf.hasCache(this))
|
|
1814
|
+
return this.multiply(sc);
|
|
1815
|
+
if (endo2) {
|
|
1816
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
1817
|
+
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
1818
|
+
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
1819
|
+
} else {
|
|
1820
|
+
return wnaf.unsafe(p, sc);
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
multiplyAndAddUnsafe(Q, a, b) {
|
|
1824
|
+
const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
|
|
1825
|
+
return sum.is0() ? void 0 : sum;
|
|
1826
|
+
}
|
|
1827
|
+
/**
|
|
1828
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
1829
|
+
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
1830
|
+
*/
|
|
1831
|
+
toAffine(invertedZ) {
|
|
1832
|
+
return toAffineMemo(this, invertedZ);
|
|
1833
|
+
}
|
|
1834
|
+
/**
|
|
1835
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
1836
|
+
* Always torsion-free for cofactor=1 curves.
|
|
1837
|
+
*/
|
|
1838
|
+
isTorsionFree() {
|
|
1839
|
+
const { isTorsionFree } = extraOpts;
|
|
1840
|
+
if (cofactor === _1n4)
|
|
1841
|
+
return true;
|
|
1842
|
+
if (isTorsionFree)
|
|
1843
|
+
return isTorsionFree(Point, this);
|
|
1844
|
+
return wnaf.unsafe(this, CURVE_ORDER).is0();
|
|
1845
|
+
}
|
|
1846
|
+
clearCofactor() {
|
|
1847
|
+
const { clearCofactor } = extraOpts;
|
|
1848
|
+
if (cofactor === _1n4)
|
|
1849
|
+
return this;
|
|
1850
|
+
if (clearCofactor)
|
|
1851
|
+
return clearCofactor(Point, this);
|
|
1852
|
+
return this.multiplyUnsafe(cofactor);
|
|
1853
|
+
}
|
|
1854
|
+
isSmallOrder() {
|
|
1855
|
+
return this.multiplyUnsafe(cofactor).is0();
|
|
1856
|
+
}
|
|
1857
|
+
toBytes(isCompressed = true) {
|
|
1858
|
+
_abool2(isCompressed, "isCompressed");
|
|
1859
|
+
this.assertValidity();
|
|
1860
|
+
return encodePoint(Point, this, isCompressed);
|
|
1861
|
+
}
|
|
1862
|
+
toHex(isCompressed = true) {
|
|
1863
|
+
return bytesToHex(this.toBytes(isCompressed));
|
|
1864
|
+
}
|
|
1865
|
+
toString() {
|
|
1866
|
+
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
1867
|
+
}
|
|
1868
|
+
// TODO: remove
|
|
1869
|
+
get px() {
|
|
1870
|
+
return this.X;
|
|
1871
|
+
}
|
|
1872
|
+
get py() {
|
|
1873
|
+
return this.X;
|
|
1874
|
+
}
|
|
1875
|
+
get pz() {
|
|
1876
|
+
return this.Z;
|
|
1877
|
+
}
|
|
1878
|
+
toRawBytes(isCompressed = true) {
|
|
1879
|
+
return this.toBytes(isCompressed);
|
|
1880
|
+
}
|
|
1881
|
+
_setWindowSize(windowSize) {
|
|
1882
|
+
this.precompute(windowSize);
|
|
1883
|
+
}
|
|
1884
|
+
static normalizeZ(points) {
|
|
1885
|
+
return normalizeZ(Point, points);
|
|
1886
|
+
}
|
|
1887
|
+
static msm(points, scalars) {
|
|
1888
|
+
return pippenger(Point, Fn, points, scalars);
|
|
1889
|
+
}
|
|
1890
|
+
static fromPrivateKey(privateKey) {
|
|
1891
|
+
return Point.BASE.multiply(_normFnElement(Fn, privateKey));
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
1895
|
+
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
1896
|
+
Point.Fp = Fp;
|
|
1897
|
+
Point.Fn = Fn;
|
|
1898
|
+
const bits = Fn.BITS;
|
|
1899
|
+
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
1900
|
+
Point.BASE.precompute(8);
|
|
1901
|
+
return Point;
|
|
1902
|
+
}
|
|
1903
|
+
function pprefix(hasEvenY) {
|
|
1904
|
+
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
1905
|
+
}
|
|
1906
|
+
function getWLengths(Fp, Fn) {
|
|
1907
|
+
return {
|
|
1908
|
+
secretKey: Fn.BYTES,
|
|
1909
|
+
publicKey: 1 + Fp.BYTES,
|
|
1910
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
1911
|
+
publicKeyHasPrefix: true,
|
|
1912
|
+
signature: 2 * Fn.BYTES
|
|
1913
|
+
};
|
|
1914
|
+
}
|
|
1915
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
1916
|
+
const { Fn } = Point;
|
|
1917
|
+
const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
|
|
1918
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
1919
|
+
function isValidSecretKey(secretKey) {
|
|
1920
|
+
try {
|
|
1921
|
+
return !!_normFnElement(Fn, secretKey);
|
|
1922
|
+
} catch (error) {
|
|
1923
|
+
return false;
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
1927
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
1928
|
+
try {
|
|
1929
|
+
const l = publicKey.length;
|
|
1930
|
+
if (isCompressed === true && l !== comp)
|
|
1931
|
+
return false;
|
|
1932
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
1933
|
+
return false;
|
|
1934
|
+
return !!Point.fromBytes(publicKey);
|
|
1935
|
+
} catch (error) {
|
|
1936
|
+
return false;
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
1940
|
+
return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
1941
|
+
}
|
|
1942
|
+
function getPublicKey(secretKey, isCompressed = true) {
|
|
1943
|
+
return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
|
|
1944
|
+
}
|
|
1945
|
+
function keygen(seed) {
|
|
1946
|
+
const secretKey = randomSecretKey(seed);
|
|
1947
|
+
return { secretKey, publicKey: getPublicKey(secretKey) };
|
|
1948
|
+
}
|
|
1949
|
+
function isProbPub(item) {
|
|
1950
|
+
if (typeof item === "bigint")
|
|
1951
|
+
return false;
|
|
1952
|
+
if (item instanceof Point)
|
|
1953
|
+
return true;
|
|
1954
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
1955
|
+
if (Fn.allowedLengths || secretKey === publicKey)
|
|
1956
|
+
return void 0;
|
|
1957
|
+
const l = ensureBytes("key", item).length;
|
|
1958
|
+
return l === publicKey || l === publicKeyUncompressed;
|
|
1959
|
+
}
|
|
1960
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
1961
|
+
if (isProbPub(secretKeyA) === true)
|
|
1962
|
+
throw new Error("first arg must be private key");
|
|
1963
|
+
if (isProbPub(publicKeyB) === false)
|
|
1964
|
+
throw new Error("second arg must be public key");
|
|
1965
|
+
const s = _normFnElement(Fn, secretKeyA);
|
|
1966
|
+
const b = Point.fromHex(publicKeyB);
|
|
1967
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
1968
|
+
}
|
|
1969
|
+
const utils = {
|
|
1970
|
+
isValidSecretKey,
|
|
1971
|
+
isValidPublicKey,
|
|
1972
|
+
randomSecretKey,
|
|
1973
|
+
// TODO: remove
|
|
1974
|
+
isValidPrivateKey: isValidSecretKey,
|
|
1975
|
+
randomPrivateKey: randomSecretKey,
|
|
1976
|
+
normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
|
|
1977
|
+
precompute(windowSize = 8, point = Point.BASE) {
|
|
1978
|
+
return point.precompute(windowSize, false);
|
|
1979
|
+
}
|
|
1980
|
+
};
|
|
1981
|
+
return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
|
|
1982
|
+
}
|
|
1983
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
1984
|
+
ahash(hash);
|
|
1985
|
+
_validateObject(ecdsaOpts, {}, {
|
|
1986
|
+
hmac: "function",
|
|
1987
|
+
lowS: "boolean",
|
|
1988
|
+
randomBytes: "function",
|
|
1989
|
+
bits2int: "function",
|
|
1990
|
+
bits2int_modN: "function"
|
|
1991
|
+
});
|
|
1992
|
+
const randomBytes2 = ecdsaOpts.randomBytes || randomBytes;
|
|
1993
|
+
const hmac2 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
|
|
1994
|
+
const { Fp, Fn } = Point;
|
|
1995
|
+
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
|
|
1996
|
+
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
1997
|
+
const defaultSigOpts = {
|
|
1998
|
+
prehash: false,
|
|
1999
|
+
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
|
|
2000
|
+
format: void 0,
|
|
2001
|
+
//'compact' as ECDSASigFormat,
|
|
2002
|
+
extraEntropy: false
|
|
2003
|
+
};
|
|
2004
|
+
const defaultSigOpts_format = "compact";
|
|
2005
|
+
function isBiggerThanHalfOrder(number) {
|
|
2006
|
+
const HALF = CURVE_ORDER >> _1n4;
|
|
2007
|
+
return number > HALF;
|
|
2008
|
+
}
|
|
2009
|
+
function validateRS(title, num) {
|
|
2010
|
+
if (!Fn.isValidNot0(num))
|
|
2011
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
2012
|
+
return num;
|
|
2013
|
+
}
|
|
2014
|
+
function validateSigLength(bytes, format) {
|
|
2015
|
+
validateSigFormat(format);
|
|
2016
|
+
const size = lengths.signature;
|
|
2017
|
+
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
2018
|
+
return _abytes2(bytes, sizer, `${format} signature`);
|
|
2019
|
+
}
|
|
2020
|
+
class Signature {
|
|
2021
|
+
constructor(r, s, recovery) {
|
|
2022
|
+
this.r = validateRS("r", r);
|
|
2023
|
+
this.s = validateRS("s", s);
|
|
2024
|
+
if (recovery != null)
|
|
2025
|
+
this.recovery = recovery;
|
|
2026
|
+
Object.freeze(this);
|
|
2027
|
+
}
|
|
2028
|
+
static fromBytes(bytes, format = defaultSigOpts_format) {
|
|
2029
|
+
validateSigLength(bytes, format);
|
|
2030
|
+
let recid;
|
|
2031
|
+
if (format === "der") {
|
|
2032
|
+
const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes));
|
|
2033
|
+
return new Signature(r2, s2);
|
|
2034
|
+
}
|
|
2035
|
+
if (format === "recovered") {
|
|
2036
|
+
recid = bytes[0];
|
|
2037
|
+
format = "compact";
|
|
2038
|
+
bytes = bytes.subarray(1);
|
|
2039
|
+
}
|
|
2040
|
+
const L = Fn.BYTES;
|
|
2041
|
+
const r = bytes.subarray(0, L);
|
|
2042
|
+
const s = bytes.subarray(L, L * 2);
|
|
2043
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
2044
|
+
}
|
|
2045
|
+
static fromHex(hex, format) {
|
|
2046
|
+
return this.fromBytes(hexToBytes(hex), format);
|
|
2047
|
+
}
|
|
2048
|
+
addRecoveryBit(recovery) {
|
|
2049
|
+
return new Signature(this.r, this.s, recovery);
|
|
2050
|
+
}
|
|
2051
|
+
recoverPublicKey(messageHash) {
|
|
2052
|
+
const FIELD_ORDER = Fp.ORDER;
|
|
2053
|
+
const { r, s, recovery: rec } = this;
|
|
2054
|
+
if (rec == null || ![0, 1, 2, 3].includes(rec))
|
|
2055
|
+
throw new Error("recovery id invalid");
|
|
2056
|
+
const hasCofactor = CURVE_ORDER * _2n2 < FIELD_ORDER;
|
|
2057
|
+
if (hasCofactor && rec > 1)
|
|
2058
|
+
throw new Error("recovery id is ambiguous for h>1 curve");
|
|
2059
|
+
const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
|
|
2060
|
+
if (!Fp.isValid(radj))
|
|
2061
|
+
throw new Error("recovery id 2 or 3 invalid");
|
|
2062
|
+
const x = Fp.toBytes(radj);
|
|
2063
|
+
const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
|
|
2064
|
+
const ir = Fn.inv(radj);
|
|
2065
|
+
const h = bits2int_modN(ensureBytes("msgHash", messageHash));
|
|
2066
|
+
const u1 = Fn.create(-h * ir);
|
|
2067
|
+
const u2 = Fn.create(s * ir);
|
|
2068
|
+
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
2069
|
+
if (Q.is0())
|
|
2070
|
+
throw new Error("point at infinify");
|
|
2071
|
+
Q.assertValidity();
|
|
2072
|
+
return Q;
|
|
2073
|
+
}
|
|
2074
|
+
// Signatures should be low-s, to prevent malleability.
|
|
2075
|
+
hasHighS() {
|
|
2076
|
+
return isBiggerThanHalfOrder(this.s);
|
|
2077
|
+
}
|
|
2078
|
+
toBytes(format = defaultSigOpts_format) {
|
|
2079
|
+
validateSigFormat(format);
|
|
2080
|
+
if (format === "der")
|
|
2081
|
+
return hexToBytes(DER.hexFromSig(this));
|
|
2082
|
+
const r = Fn.toBytes(this.r);
|
|
2083
|
+
const s = Fn.toBytes(this.s);
|
|
2084
|
+
if (format === "recovered") {
|
|
2085
|
+
if (this.recovery == null)
|
|
2086
|
+
throw new Error("recovery bit must be present");
|
|
2087
|
+
return concatBytes(Uint8Array.of(this.recovery), r, s);
|
|
2088
|
+
}
|
|
2089
|
+
return concatBytes(r, s);
|
|
2090
|
+
}
|
|
2091
|
+
toHex(format) {
|
|
2092
|
+
return bytesToHex(this.toBytes(format));
|
|
2093
|
+
}
|
|
2094
|
+
// TODO: remove
|
|
2095
|
+
assertValidity() {
|
|
2096
|
+
}
|
|
2097
|
+
static fromCompact(hex) {
|
|
2098
|
+
return Signature.fromBytes(ensureBytes("sig", hex), "compact");
|
|
2099
|
+
}
|
|
2100
|
+
static fromDER(hex) {
|
|
2101
|
+
return Signature.fromBytes(ensureBytes("sig", hex), "der");
|
|
2102
|
+
}
|
|
2103
|
+
normalizeS() {
|
|
2104
|
+
return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
|
|
2105
|
+
}
|
|
2106
|
+
toDERRawBytes() {
|
|
2107
|
+
return this.toBytes("der");
|
|
2108
|
+
}
|
|
2109
|
+
toDERHex() {
|
|
2110
|
+
return bytesToHex(this.toBytes("der"));
|
|
2111
|
+
}
|
|
2112
|
+
toCompactRawBytes() {
|
|
2113
|
+
return this.toBytes("compact");
|
|
2114
|
+
}
|
|
2115
|
+
toCompactHex() {
|
|
2116
|
+
return bytesToHex(this.toBytes("compact"));
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
2120
|
+
if (bytes.length > 8192)
|
|
2121
|
+
throw new Error("input is too large");
|
|
2122
|
+
const num = bytesToNumberBE(bytes);
|
|
2123
|
+
const delta = bytes.length * 8 - fnBits;
|
|
2124
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
2125
|
+
};
|
|
2126
|
+
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
2127
|
+
return Fn.create(bits2int(bytes));
|
|
2128
|
+
};
|
|
2129
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
2130
|
+
function int2octets(num) {
|
|
2131
|
+
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
2132
|
+
return Fn.toBytes(num);
|
|
2133
|
+
}
|
|
2134
|
+
function validateMsgAndHash(message, prehash) {
|
|
2135
|
+
_abytes2(message, void 0, "message");
|
|
2136
|
+
return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
|
|
2137
|
+
}
|
|
2138
|
+
function prepSig(message, privateKey, opts) {
|
|
2139
|
+
if (["recovered", "canonical"].some((k) => k in opts))
|
|
2140
|
+
throw new Error("sign() legacy options not supported");
|
|
2141
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
2142
|
+
message = validateMsgAndHash(message, prehash);
|
|
2143
|
+
const h1int = bits2int_modN(message);
|
|
2144
|
+
const d = _normFnElement(Fn, privateKey);
|
|
2145
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
2146
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
2147
|
+
const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy;
|
|
2148
|
+
seedArgs.push(ensureBytes("extraEntropy", e));
|
|
2149
|
+
}
|
|
2150
|
+
const seed = concatBytes(...seedArgs);
|
|
2151
|
+
const m = h1int;
|
|
2152
|
+
function k2sig(kBytes) {
|
|
2153
|
+
const k = bits2int(kBytes);
|
|
2154
|
+
if (!Fn.isValidNot0(k))
|
|
2155
|
+
return;
|
|
2156
|
+
const ik = Fn.inv(k);
|
|
2157
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
2158
|
+
const r = Fn.create(q.x);
|
|
2159
|
+
if (r === _0n4)
|
|
2160
|
+
return;
|
|
2161
|
+
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
2162
|
+
if (s === _0n4)
|
|
2163
|
+
return;
|
|
2164
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
2165
|
+
let normS = s;
|
|
2166
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
2167
|
+
normS = Fn.neg(s);
|
|
2168
|
+
recovery ^= 1;
|
|
2169
|
+
}
|
|
2170
|
+
return new Signature(r, normS, recovery);
|
|
2171
|
+
}
|
|
2172
|
+
return { seed, k2sig };
|
|
2173
|
+
}
|
|
2174
|
+
function sign(message, secretKey, opts = {}) {
|
|
2175
|
+
message = ensureBytes("message", message);
|
|
2176
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
2177
|
+
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
2178
|
+
const sig = drbg(seed, k2sig);
|
|
2179
|
+
return sig;
|
|
2180
|
+
}
|
|
2181
|
+
function tryParsingSig(sg) {
|
|
2182
|
+
let sig = void 0;
|
|
2183
|
+
const isHex = typeof sg === "string" || isBytes(sg);
|
|
2184
|
+
const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
|
|
2185
|
+
if (!isHex && !isObj)
|
|
2186
|
+
throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
|
|
2187
|
+
if (isObj) {
|
|
2188
|
+
sig = new Signature(sg.r, sg.s);
|
|
2189
|
+
} else if (isHex) {
|
|
2190
|
+
try {
|
|
2191
|
+
sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
|
|
2192
|
+
} catch (derError) {
|
|
2193
|
+
if (!(derError instanceof DER.Err))
|
|
2194
|
+
throw derError;
|
|
2195
|
+
}
|
|
2196
|
+
if (!sig) {
|
|
2197
|
+
try {
|
|
2198
|
+
sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
|
|
2199
|
+
} catch (error) {
|
|
2200
|
+
return false;
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
if (!sig)
|
|
2205
|
+
return false;
|
|
2206
|
+
return sig;
|
|
2207
|
+
}
|
|
2208
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
2209
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
2210
|
+
publicKey = ensureBytes("publicKey", publicKey);
|
|
2211
|
+
message = validateMsgAndHash(ensureBytes("message", message), prehash);
|
|
2212
|
+
if ("strict" in opts)
|
|
2213
|
+
throw new Error("options.strict was renamed to lowS");
|
|
2214
|
+
const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
|
|
2215
|
+
if (sig === false)
|
|
2216
|
+
return false;
|
|
2217
|
+
try {
|
|
2218
|
+
const P = Point.fromBytes(publicKey);
|
|
2219
|
+
if (lowS && sig.hasHighS())
|
|
2220
|
+
return false;
|
|
2221
|
+
const { r, s } = sig;
|
|
2222
|
+
const h = bits2int_modN(message);
|
|
2223
|
+
const is = Fn.inv(s);
|
|
2224
|
+
const u1 = Fn.create(h * is);
|
|
2225
|
+
const u2 = Fn.create(r * is);
|
|
2226
|
+
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
2227
|
+
if (R.is0())
|
|
2228
|
+
return false;
|
|
2229
|
+
const v = Fn.create(R.x);
|
|
2230
|
+
return v === r;
|
|
2231
|
+
} catch (e) {
|
|
2232
|
+
return false;
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
2236
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
2237
|
+
message = validateMsgAndHash(message, prehash);
|
|
2238
|
+
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
2239
|
+
}
|
|
2240
|
+
return Object.freeze({
|
|
2241
|
+
keygen,
|
|
2242
|
+
getPublicKey,
|
|
2243
|
+
getSharedSecret,
|
|
2244
|
+
utils,
|
|
2245
|
+
lengths,
|
|
2246
|
+
Point,
|
|
2247
|
+
sign,
|
|
2248
|
+
verify,
|
|
2249
|
+
recoverPublicKey,
|
|
2250
|
+
Signature,
|
|
2251
|
+
hash
|
|
2252
|
+
});
|
|
2253
|
+
}
|
|
2254
|
+
function _weierstrass_legacy_opts_to_new(c) {
|
|
2255
|
+
const CURVE = {
|
|
2256
|
+
a: c.a,
|
|
2257
|
+
b: c.b,
|
|
2258
|
+
p: c.Fp.ORDER,
|
|
2259
|
+
n: c.n,
|
|
2260
|
+
h: c.h,
|
|
2261
|
+
Gx: c.Gx,
|
|
2262
|
+
Gy: c.Gy
|
|
2263
|
+
};
|
|
2264
|
+
const Fp = c.Fp;
|
|
2265
|
+
let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
|
|
2266
|
+
const Fn = Field(CURVE.n, {
|
|
2267
|
+
BITS: c.nBitLength,
|
|
2268
|
+
allowedLengths,
|
|
2269
|
+
modFromBytes: c.wrapPrivateKey
|
|
2270
|
+
});
|
|
2271
|
+
const curveOpts = {
|
|
2272
|
+
Fp,
|
|
2273
|
+
Fn,
|
|
2274
|
+
allowInfinityPoint: c.allowInfinityPoint,
|
|
2275
|
+
endo: c.endo,
|
|
2276
|
+
isTorsionFree: c.isTorsionFree,
|
|
2277
|
+
clearCofactor: c.clearCofactor,
|
|
2278
|
+
fromBytes: c.fromBytes,
|
|
2279
|
+
toBytes: c.toBytes
|
|
2280
|
+
};
|
|
2281
|
+
return { CURVE, curveOpts };
|
|
2282
|
+
}
|
|
2283
|
+
function _ecdsa_legacy_opts_to_new(c) {
|
|
2284
|
+
const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
|
|
2285
|
+
const ecdsaOpts = {
|
|
2286
|
+
hmac: c.hmac,
|
|
2287
|
+
randomBytes: c.randomBytes,
|
|
2288
|
+
lowS: c.lowS,
|
|
2289
|
+
bits2int: c.bits2int,
|
|
2290
|
+
bits2int_modN: c.bits2int_modN
|
|
2291
|
+
};
|
|
2292
|
+
return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
|
|
2293
|
+
}
|
|
2294
|
+
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
|
|
2295
|
+
const Point = _ecdsa.Point;
|
|
2296
|
+
return Object.assign({}, _ecdsa, {
|
|
2297
|
+
ProjectivePoint: Point,
|
|
2298
|
+
CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
|
|
2299
|
+
});
|
|
2300
|
+
}
|
|
2301
|
+
function weierstrass(c) {
|
|
2302
|
+
const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
|
|
2303
|
+
const Point = weierstrassN(CURVE, curveOpts);
|
|
2304
|
+
const signs = ecdsa(Point, hash, ecdsaOpts);
|
|
2305
|
+
return _ecdsa_new_output_to_legacy(c, signs);
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2308
|
+
// ../eocene-worker/node_modules/@noble/curves/esm/_shortw_utils.js
|
|
2309
|
+
function createCurve(curveDef, defHash) {
|
|
2310
|
+
const create = (hash) => weierstrass({ ...curveDef, hash });
|
|
2311
|
+
return { ...create(defHash), create };
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
// ../eocene-worker/node_modules/@noble/curves/esm/secp256k1.js
|
|
2315
|
+
var secp256k1_CURVE = {
|
|
2316
|
+
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
2317
|
+
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
2318
|
+
h: BigInt(1),
|
|
2319
|
+
a: BigInt(0),
|
|
2320
|
+
b: BigInt(7),
|
|
2321
|
+
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
2322
|
+
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
2323
|
+
};
|
|
2324
|
+
var secp256k1_ENDO = {
|
|
2325
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
2326
|
+
basises: [
|
|
2327
|
+
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
2328
|
+
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
2329
|
+
]
|
|
2330
|
+
};
|
|
2331
|
+
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
2332
|
+
function sqrtMod(y) {
|
|
2333
|
+
const P = secp256k1_CURVE.p;
|
|
2334
|
+
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
2335
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
2336
|
+
const b2 = y * y * y % P;
|
|
2337
|
+
const b3 = b2 * b2 * y % P;
|
|
2338
|
+
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
2339
|
+
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
2340
|
+
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
2341
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
2342
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
2343
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
2344
|
+
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
2345
|
+
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
2346
|
+
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
2347
|
+
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
2348
|
+
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
2349
|
+
const root = pow2(t2, _2n3, P);
|
|
2350
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
2351
|
+
throw new Error("Cannot find square root");
|
|
2352
|
+
return root;
|
|
2353
|
+
}
|
|
2354
|
+
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
2355
|
+
var secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
|
|
2356
|
+
|
|
2357
|
+
// ../eocene-worker/node_modules/@noble/hashes/esm/sha3.js
|
|
2358
|
+
var _0n5 = BigInt(0);
|
|
2359
|
+
var _1n5 = BigInt(1);
|
|
2360
|
+
var _2n4 = BigInt(2);
|
|
2361
|
+
var _7n2 = BigInt(7);
|
|
2362
|
+
var _256n = BigInt(256);
|
|
2363
|
+
var _0x71n = BigInt(113);
|
|
2364
|
+
var SHA3_PI = [];
|
|
2365
|
+
var SHA3_ROTL = [];
|
|
2366
|
+
var _SHA3_IOTA = [];
|
|
2367
|
+
for (let round = 0, R = _1n5, x = 1, y = 0; round < 24; round++) {
|
|
2368
|
+
[x, y] = [y, (2 * x + 3 * y) % 5];
|
|
2369
|
+
SHA3_PI.push(2 * (5 * y + x));
|
|
2370
|
+
SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
|
|
2371
|
+
let t = _0n5;
|
|
2372
|
+
for (let j = 0; j < 7; j++) {
|
|
2373
|
+
R = (R << _1n5 ^ (R >> _7n2) * _0x71n) % _256n;
|
|
2374
|
+
if (R & _2n4)
|
|
2375
|
+
t ^= _1n5 << (_1n5 << /* @__PURE__ */ BigInt(j)) - _1n5;
|
|
2376
|
+
}
|
|
2377
|
+
_SHA3_IOTA.push(t);
|
|
2378
|
+
}
|
|
2379
|
+
var IOTAS = split(_SHA3_IOTA, true);
|
|
2380
|
+
var SHA3_IOTA_H = IOTAS[0];
|
|
2381
|
+
var SHA3_IOTA_L = IOTAS[1];
|
|
2382
|
+
var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
|
|
2383
|
+
var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
|
|
2384
|
+
function keccakP(s, rounds = 24) {
|
|
2385
|
+
const B = new Uint32Array(5 * 2);
|
|
2386
|
+
for (let round = 24 - rounds; round < 24; round++) {
|
|
2387
|
+
for (let x = 0; x < 10; x++)
|
|
2388
|
+
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
|
|
2389
|
+
for (let x = 0; x < 10; x += 2) {
|
|
2390
|
+
const idx1 = (x + 8) % 10;
|
|
2391
|
+
const idx0 = (x + 2) % 10;
|
|
2392
|
+
const B0 = B[idx0];
|
|
2393
|
+
const B1 = B[idx0 + 1];
|
|
2394
|
+
const Th = rotlH(B0, B1, 1) ^ B[idx1];
|
|
2395
|
+
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
|
|
2396
|
+
for (let y = 0; y < 50; y += 10) {
|
|
2397
|
+
s[x + y] ^= Th;
|
|
2398
|
+
s[x + y + 1] ^= Tl;
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
let curH = s[2];
|
|
2402
|
+
let curL = s[3];
|
|
2403
|
+
for (let t = 0; t < 24; t++) {
|
|
2404
|
+
const shift = SHA3_ROTL[t];
|
|
2405
|
+
const Th = rotlH(curH, curL, shift);
|
|
2406
|
+
const Tl = rotlL(curH, curL, shift);
|
|
2407
|
+
const PI = SHA3_PI[t];
|
|
2408
|
+
curH = s[PI];
|
|
2409
|
+
curL = s[PI + 1];
|
|
2410
|
+
s[PI] = Th;
|
|
2411
|
+
s[PI + 1] = Tl;
|
|
2412
|
+
}
|
|
2413
|
+
for (let y = 0; y < 50; y += 10) {
|
|
2414
|
+
for (let x = 0; x < 10; x++)
|
|
2415
|
+
B[x] = s[y + x];
|
|
2416
|
+
for (let x = 0; x < 10; x++)
|
|
2417
|
+
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
|
|
2418
|
+
}
|
|
2419
|
+
s[0] ^= SHA3_IOTA_H[round];
|
|
2420
|
+
s[1] ^= SHA3_IOTA_L[round];
|
|
2421
|
+
}
|
|
2422
|
+
clean(B);
|
|
2423
|
+
}
|
|
2424
|
+
var Keccak = class _Keccak extends Hash {
|
|
2425
|
+
// NOTE: we accept arguments in bytes instead of bits here.
|
|
2426
|
+
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
|
|
2427
|
+
super();
|
|
2428
|
+
this.pos = 0;
|
|
2429
|
+
this.posOut = 0;
|
|
2430
|
+
this.finished = false;
|
|
2431
|
+
this.destroyed = false;
|
|
2432
|
+
this.enableXOF = false;
|
|
2433
|
+
this.blockLen = blockLen;
|
|
2434
|
+
this.suffix = suffix;
|
|
2435
|
+
this.outputLen = outputLen;
|
|
2436
|
+
this.enableXOF = enableXOF;
|
|
2437
|
+
this.rounds = rounds;
|
|
2438
|
+
anumber(outputLen);
|
|
2439
|
+
if (!(0 < blockLen && blockLen < 200))
|
|
2440
|
+
throw new Error("only keccak-f1600 function is supported");
|
|
2441
|
+
this.state = new Uint8Array(200);
|
|
2442
|
+
this.state32 = u32(this.state);
|
|
2443
|
+
}
|
|
2444
|
+
clone() {
|
|
2445
|
+
return this._cloneInto();
|
|
2446
|
+
}
|
|
2447
|
+
keccak() {
|
|
2448
|
+
swap32IfBE(this.state32);
|
|
2449
|
+
keccakP(this.state32, this.rounds);
|
|
2450
|
+
swap32IfBE(this.state32);
|
|
2451
|
+
this.posOut = 0;
|
|
2452
|
+
this.pos = 0;
|
|
2453
|
+
}
|
|
2454
|
+
update(data) {
|
|
2455
|
+
aexists(this);
|
|
2456
|
+
data = toBytes(data);
|
|
2457
|
+
abytes(data);
|
|
2458
|
+
const { blockLen, state } = this;
|
|
2459
|
+
const len = data.length;
|
|
2460
|
+
for (let pos = 0; pos < len; ) {
|
|
2461
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
2462
|
+
for (let i = 0; i < take; i++)
|
|
2463
|
+
state[this.pos++] ^= data[pos++];
|
|
2464
|
+
if (this.pos === blockLen)
|
|
2465
|
+
this.keccak();
|
|
2466
|
+
}
|
|
2467
|
+
return this;
|
|
2468
|
+
}
|
|
2469
|
+
finish() {
|
|
2470
|
+
if (this.finished)
|
|
2471
|
+
return;
|
|
2472
|
+
this.finished = true;
|
|
2473
|
+
const { state, suffix, pos, blockLen } = this;
|
|
2474
|
+
state[pos] ^= suffix;
|
|
2475
|
+
if ((suffix & 128) !== 0 && pos === blockLen - 1)
|
|
2476
|
+
this.keccak();
|
|
2477
|
+
state[blockLen - 1] ^= 128;
|
|
2478
|
+
this.keccak();
|
|
2479
|
+
}
|
|
2480
|
+
writeInto(out) {
|
|
2481
|
+
aexists(this, false);
|
|
2482
|
+
abytes(out);
|
|
2483
|
+
this.finish();
|
|
2484
|
+
const bufferOut = this.state;
|
|
2485
|
+
const { blockLen } = this;
|
|
2486
|
+
for (let pos = 0, len = out.length; pos < len; ) {
|
|
2487
|
+
if (this.posOut >= blockLen)
|
|
2488
|
+
this.keccak();
|
|
2489
|
+
const take = Math.min(blockLen - this.posOut, len - pos);
|
|
2490
|
+
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
|
|
2491
|
+
this.posOut += take;
|
|
2492
|
+
pos += take;
|
|
2493
|
+
}
|
|
2494
|
+
return out;
|
|
2495
|
+
}
|
|
2496
|
+
xofInto(out) {
|
|
2497
|
+
if (!this.enableXOF)
|
|
2498
|
+
throw new Error("XOF is not possible for this instance");
|
|
2499
|
+
return this.writeInto(out);
|
|
2500
|
+
}
|
|
2501
|
+
xof(bytes) {
|
|
2502
|
+
anumber(bytes);
|
|
2503
|
+
return this.xofInto(new Uint8Array(bytes));
|
|
2504
|
+
}
|
|
2505
|
+
digestInto(out) {
|
|
2506
|
+
aoutput(out, this);
|
|
2507
|
+
if (this.finished)
|
|
2508
|
+
throw new Error("digest() was already called");
|
|
2509
|
+
this.writeInto(out);
|
|
2510
|
+
this.destroy();
|
|
2511
|
+
return out;
|
|
2512
|
+
}
|
|
2513
|
+
digest() {
|
|
2514
|
+
return this.digestInto(new Uint8Array(this.outputLen));
|
|
2515
|
+
}
|
|
2516
|
+
destroy() {
|
|
2517
|
+
this.destroyed = true;
|
|
2518
|
+
clean(this.state);
|
|
2519
|
+
}
|
|
2520
|
+
_cloneInto(to) {
|
|
2521
|
+
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
|
|
2522
|
+
to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
|
|
2523
|
+
to.state32.set(this.state32);
|
|
2524
|
+
to.pos = this.pos;
|
|
2525
|
+
to.posOut = this.posOut;
|
|
2526
|
+
to.finished = this.finished;
|
|
2527
|
+
to.rounds = rounds;
|
|
2528
|
+
to.suffix = suffix;
|
|
2529
|
+
to.outputLen = outputLen;
|
|
2530
|
+
to.enableXOF = enableXOF;
|
|
2531
|
+
to.destroyed = this.destroyed;
|
|
2532
|
+
return to;
|
|
2533
|
+
}
|
|
2534
|
+
};
|
|
2535
|
+
var gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
|
|
2536
|
+
var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
|
|
2537
|
+
|
|
2538
|
+
// ../eocene-worker/packages/core/src/secp.ts
|
|
2539
|
+
function normalizeAddress(address) {
|
|
2540
|
+
return address.trim().toLowerCase();
|
|
2541
|
+
}
|
|
2542
|
+
function hashPersonalMessage(message) {
|
|
2543
|
+
const msg = typeof message === "string" ? new TextEncoder().encode(message) : message;
|
|
2544
|
+
const prefix = new TextEncoder().encode(`Ethereum Signed Message:
|
|
2545
|
+
${msg.length}`);
|
|
2546
|
+
const body = new Uint8Array(prefix.length + msg.length);
|
|
2547
|
+
body.set(prefix, 0);
|
|
2548
|
+
body.set(msg, prefix.length);
|
|
2549
|
+
return keccak_256(body);
|
|
2550
|
+
}
|
|
2551
|
+
function recoverAddressFromDigest(digest, signature) {
|
|
2552
|
+
const raw = hexToBytes(strip0x(signature));
|
|
2553
|
+
if (raw.length !== 65) throw new Error("signature must be 65 bytes");
|
|
2554
|
+
const v = raw[64];
|
|
2555
|
+
const recovery = v >= 27 ? v - 27 : v;
|
|
2556
|
+
const point = secp256k1.Signature.fromCompact(raw.slice(0, 64)).addRecoveryBit(recovery).recoverPublicKey(digest);
|
|
2557
|
+
const pub = point.toRawBytes(false).slice(1);
|
|
2558
|
+
const hash = keccak_256(pub);
|
|
2559
|
+
return `0x${bytesToHex(hash.slice(-20))}`;
|
|
2560
|
+
}
|
|
2561
|
+
function shareFromHex(hex) {
|
|
2562
|
+
return hexToBytes(strip0x(hex));
|
|
2563
|
+
}
|
|
2564
|
+
function strip0x(hex) {
|
|
2565
|
+
return hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
// ../eocene-worker/packages/sdk/src/errors.ts
|
|
2569
|
+
var WaasHttpError = class extends Error {
|
|
2570
|
+
status;
|
|
2571
|
+
code;
|
|
2572
|
+
body;
|
|
2573
|
+
attemptsRemaining;
|
|
2574
|
+
lockedUntil;
|
|
2575
|
+
retryAfterSec;
|
|
2576
|
+
constructor(status, url, body) {
|
|
2577
|
+
const code = normalizeErrorCode(body, status);
|
|
2578
|
+
const msg = typeof body.message === "string" ? body.message : typeof body.error === "string" ? body.error : `${status} ${url}`;
|
|
2579
|
+
super(msg);
|
|
2580
|
+
this.name = "WaasHttpError";
|
|
2581
|
+
this.status = status;
|
|
2582
|
+
this.code = code;
|
|
2583
|
+
this.body = body;
|
|
2584
|
+
if (typeof body.attemptsRemaining === "number") this.attemptsRemaining = body.attemptsRemaining;
|
|
2585
|
+
if (typeof body.lockedUntil === "string") this.lockedUntil = body.lockedUntil;
|
|
2586
|
+
if (typeof body.retryAfterSec === "number") this.retryAfterSec = body.retryAfterSec;
|
|
2587
|
+
}
|
|
2588
|
+
get isPasswordError() {
|
|
2589
|
+
return this.code === "password_invalid" || this.code === "password_locked" || this.code === "password_required";
|
|
2590
|
+
}
|
|
2591
|
+
/** The session is gone — the caller has to log in again; retrying will not help. */
|
|
2592
|
+
get isSessionError() {
|
|
2593
|
+
return this.code === "session_expired";
|
|
2594
|
+
}
|
|
2595
|
+
};
|
|
2596
|
+
function normalizeErrorCode(body, status) {
|
|
2597
|
+
if (status === 401) return "session_expired";
|
|
2598
|
+
if (status === 429 && String(body.code ?? "") === "RATE_LIMITED") return "rate_limited";
|
|
2599
|
+
const raw = String(body.code ?? body.error ?? "");
|
|
2600
|
+
if (raw === "PLAN_USER_LIMIT" || raw === "plan_user_limit") return "plan_user_limit";
|
|
2601
|
+
if (raw === "PLAN_PROJECT_LIMIT" || raw === "plan_project_limit") return "plan_project_limit";
|
|
2602
|
+
if (raw === "RATE_LIMITED" || raw === "rate_limited") return "rate_limited";
|
|
2603
|
+
if (raw === "password_locked" || raw.includes("password_locked")) return "password_locked";
|
|
2604
|
+
if (raw === "password_invalid") return "password_invalid";
|
|
2605
|
+
if (raw.includes("at least 6")) return "password_too_short";
|
|
2606
|
+
if (raw.includes("Incorrect") || raw.includes("invalid")) return "password_invalid";
|
|
2607
|
+
if (raw.includes("password")) return "password_invalid";
|
|
2608
|
+
return "unknown";
|
|
2609
|
+
}
|
|
2610
|
+
function isWaasHttpError(e) {
|
|
2611
|
+
return e instanceof WaasHttpError || Boolean(e) && typeof e === "object" && e.name === "WaasHttpError";
|
|
2612
|
+
}
|
|
2613
|
+
|
|
2614
|
+
// ../eocene-worker/packages/sdk/src/eip1193.ts
|
|
2615
|
+
function asParamList(params) {
|
|
2616
|
+
if (!params) return [];
|
|
2617
|
+
return Array.isArray(params) ? params : Object.values(params);
|
|
2618
|
+
}
|
|
2619
|
+
function decodePersonalSignMessage(raw) {
|
|
2620
|
+
if (typeof raw !== "string") throw new Error("personal_sign message must be string");
|
|
2621
|
+
if (!raw.startsWith("0x") && !raw.startsWith("0X")) return raw;
|
|
2622
|
+
const hex = raw.slice(2);
|
|
2623
|
+
if (hex.length % 2 !== 0) throw new Error("bad hex message");
|
|
2624
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
2625
|
+
for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
2626
|
+
return new TextDecoder().decode(bytes);
|
|
2627
|
+
}
|
|
2628
|
+
function userRejectedError(method) {
|
|
2629
|
+
const err = new Error(`User rejected the request. (${method})`);
|
|
2630
|
+
err.code = 4001;
|
|
2631
|
+
return err;
|
|
2632
|
+
}
|
|
2633
|
+
function normalizeApproval(result) {
|
|
2634
|
+
if (result === void 0) return { approved: false };
|
|
2635
|
+
if (typeof result === "boolean") return { approved: result };
|
|
2636
|
+
return { approved: result.approved, password: result.password };
|
|
2637
|
+
}
|
|
2638
|
+
function missingApprovalError() {
|
|
2639
|
+
const err = new Error(
|
|
2640
|
+
"waas provider refuses to sign without an approval handler. Pass `requestApproval` to createWaasEip1193Provider / AuthClient, or use <AuthProvider> which supplies the built-in confirmation modal."
|
|
2641
|
+
);
|
|
2642
|
+
err.code = 4100;
|
|
2643
|
+
return err;
|
|
2644
|
+
}
|
|
2645
|
+
async function assertApproved(options, req) {
|
|
2646
|
+
if (!options?.requestApproval) throw missingApprovalError();
|
|
2647
|
+
const { approved, password } = normalizeApproval(await options.requestApproval(req));
|
|
2648
|
+
if (!approved) throw userRejectedError(req.method);
|
|
2649
|
+
return password;
|
|
2650
|
+
}
|
|
2651
|
+
function toAuthError(e) {
|
|
2652
|
+
return {
|
|
2653
|
+
code: e.code,
|
|
2654
|
+
message: e.message,
|
|
2655
|
+
attemptsRemaining: e.attemptsRemaining,
|
|
2656
|
+
lockedUntil: e.lockedUntil,
|
|
2657
|
+
retryAfterSec: e.retryAfterSec
|
|
2658
|
+
};
|
|
2659
|
+
}
|
|
2660
|
+
async function signWithPasswordRetry(options, baseReq, run) {
|
|
2661
|
+
let authError;
|
|
2662
|
+
for (let i = 0; i < 20; i++) {
|
|
2663
|
+
const password = await assertApproved(options, { ...baseReq, authError });
|
|
2664
|
+
try {
|
|
2665
|
+
return await run(password);
|
|
2666
|
+
} catch (e) {
|
|
2667
|
+
if (isWaasHttpError(e) && e.isPasswordError) {
|
|
2668
|
+
authError = toAuthError(e);
|
|
2669
|
+
baseReq = { ...baseReq, passwordEnabled: true };
|
|
2670
|
+
continue;
|
|
2671
|
+
}
|
|
2672
|
+
throw e;
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
throw new Error("password retry limit exceeded");
|
|
2676
|
+
}
|
|
2677
|
+
function createWaasEip1193Provider(client, options) {
|
|
2678
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
2679
|
+
let chainId = options?.chainId ?? 1;
|
|
2680
|
+
function emit(event, ...args) {
|
|
2681
|
+
for (const handler of listeners.get(event) ?? []) {
|
|
2682
|
+
try {
|
|
2683
|
+
handler(...args);
|
|
2684
|
+
} catch {
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
const provider = {
|
|
2689
|
+
request: async ({ method, params }) => {
|
|
2690
|
+
const list = asParamList(params);
|
|
2691
|
+
const address = client.getState()?.address;
|
|
2692
|
+
if (!address && method !== "eth_accounts") {
|
|
2693
|
+
throw new Error("waas wallet not ready");
|
|
2694
|
+
}
|
|
2695
|
+
switch (method) {
|
|
2696
|
+
case "eth_requestAccounts":
|
|
2697
|
+
case "eth_accounts":
|
|
2698
|
+
return address ? [address] : [];
|
|
2699
|
+
case "eth_chainId":
|
|
2700
|
+
return `0x${chainId.toString(16)}`;
|
|
2701
|
+
case "net_version":
|
|
2702
|
+
return String(chainId);
|
|
2703
|
+
case "wallet_switchEthereumChain": {
|
|
2704
|
+
const target = list[0] ?? {};
|
|
2705
|
+
const next = Number.parseInt(String(target.chainId ?? ""), 16);
|
|
2706
|
+
if (!Number.isFinite(next) || next <= 0) {
|
|
2707
|
+
throw new Error("wallet_switchEthereumChain requires a hex chainId");
|
|
2708
|
+
}
|
|
2709
|
+
if (next !== chainId) {
|
|
2710
|
+
chainId = next;
|
|
2711
|
+
options?.onChainChanged?.(next);
|
|
2712
|
+
emit("chainChanged", `0x${next.toString(16)}`);
|
|
2713
|
+
}
|
|
2714
|
+
return null;
|
|
2715
|
+
}
|
|
2716
|
+
case "personal_sign": {
|
|
2717
|
+
const message = decodePersonalSignMessage(list[0]);
|
|
2718
|
+
return signWithPasswordRetry(
|
|
2719
|
+
options,
|
|
2720
|
+
{
|
|
2721
|
+
method: "personal_sign",
|
|
2722
|
+
address,
|
|
2723
|
+
message,
|
|
2724
|
+
passwordEnabled: Boolean(client.getState()?.passwordEnabled)
|
|
2725
|
+
},
|
|
2726
|
+
async (password) => {
|
|
2727
|
+
const out = await client.signMessage(message, { password });
|
|
2728
|
+
return out.signature;
|
|
2729
|
+
}
|
|
2730
|
+
);
|
|
2731
|
+
}
|
|
2732
|
+
case "eth_signTypedData_v4": {
|
|
2733
|
+
const payloadRaw = list[1];
|
|
2734
|
+
const payload = typeof payloadRaw === "string" ? JSON.parse(payloadRaw) : payloadRaw;
|
|
2735
|
+
const message = JSON.stringify(payload, null, 2);
|
|
2736
|
+
return signWithPasswordRetry(
|
|
2737
|
+
options,
|
|
2738
|
+
{
|
|
2739
|
+
method: "eth_signTypedData_v4",
|
|
2740
|
+
address,
|
|
2741
|
+
message,
|
|
2742
|
+
passwordEnabled: Boolean(client.getState()?.passwordEnabled)
|
|
2743
|
+
},
|
|
2744
|
+
async (password) => {
|
|
2745
|
+
const out = await client.signTypedData(
|
|
2746
|
+
{
|
|
2747
|
+
domain: payload.domain ?? {},
|
|
2748
|
+
types: payload.types ?? {},
|
|
2749
|
+
primaryType: payload.primaryType,
|
|
2750
|
+
message: payload.message ?? {}
|
|
2751
|
+
},
|
|
2752
|
+
{ password }
|
|
2753
|
+
);
|
|
2754
|
+
return out.signature;
|
|
2755
|
+
}
|
|
2756
|
+
);
|
|
2757
|
+
}
|
|
2758
|
+
case "eth_sendTransaction": {
|
|
2759
|
+
const tx = list[0] ?? {};
|
|
2760
|
+
if (!tx.to) throw new Error("eth_sendTransaction requires to");
|
|
2761
|
+
let token = "native";
|
|
2762
|
+
let to = tx.to;
|
|
2763
|
+
let amountRaw = tx.value ? BigInt(tx.value).toString() : "0";
|
|
2764
|
+
const data = (tx.data ?? "").trim();
|
|
2765
|
+
const hasCalldata = data !== "" && data !== "0x";
|
|
2766
|
+
const isErc20Transfer = data.toLowerCase().startsWith("0xa9059cbb") && data.length >= 138;
|
|
2767
|
+
if (isErc20Transfer) {
|
|
2768
|
+
token = tx.to;
|
|
2769
|
+
to = `0x${data.slice(34, 74)}`;
|
|
2770
|
+
amountRaw = BigInt(`0x${data.slice(74, 138)}`).toString();
|
|
2771
|
+
} else if (hasCalldata) {
|
|
2772
|
+
const selector = data.slice(0, 10);
|
|
2773
|
+
const err = new Error(
|
|
2774
|
+
`waas provider cannot send contract calls yet (data ${selector}\u2026). Only native transfers and ERC-20 transfer() are supported.`
|
|
2775
|
+
);
|
|
2776
|
+
err.code = 4200;
|
|
2777
|
+
throw err;
|
|
2778
|
+
}
|
|
2779
|
+
const summary = `Send ${amountRaw} units (${token === "native" ? "ETH" : token}) to ${to}`;
|
|
2780
|
+
return signWithPasswordRetry(
|
|
2781
|
+
options,
|
|
2782
|
+
{
|
|
2783
|
+
method: "eth_sendTransaction",
|
|
2784
|
+
address,
|
|
2785
|
+
message: summary,
|
|
2786
|
+
passwordEnabled: Boolean(client.getState()?.passwordEnabled)
|
|
2787
|
+
},
|
|
2788
|
+
async (password) => {
|
|
2789
|
+
const out = await client.transfer({
|
|
2790
|
+
to,
|
|
2791
|
+
amountRaw,
|
|
2792
|
+
token,
|
|
2793
|
+
chainId,
|
|
2794
|
+
password
|
|
2795
|
+
});
|
|
2796
|
+
return out.txHash;
|
|
2797
|
+
}
|
|
2798
|
+
);
|
|
2799
|
+
}
|
|
2800
|
+
default:
|
|
2801
|
+
throw new Error(`waas provider unsupported method: ${method}`);
|
|
2802
|
+
}
|
|
2803
|
+
},
|
|
2804
|
+
on(event, handler) {
|
|
2805
|
+
if (!listeners.has(event)) listeners.set(event, /* @__PURE__ */ new Set());
|
|
2806
|
+
listeners.get(event).add(handler);
|
|
2807
|
+
},
|
|
2808
|
+
removeListener(event, handler) {
|
|
2809
|
+
listeners.get(event)?.delete(handler);
|
|
2810
|
+
}
|
|
2811
|
+
};
|
|
2812
|
+
return provider;
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
// ../eocene-worker/packages/sdk/src/index.ts
|
|
2816
|
+
async function http(url, init) {
|
|
2817
|
+
const res = await fetch(url, init);
|
|
2818
|
+
const body = await res.json().catch(() => ({}));
|
|
2819
|
+
if (!res.ok) {
|
|
2820
|
+
throw new WaasHttpError(res.status, url, body);
|
|
2821
|
+
}
|
|
2822
|
+
return body;
|
|
2823
|
+
}
|
|
2824
|
+
function digestToHex(digest) {
|
|
2825
|
+
return `0x${Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
2826
|
+
}
|
|
2827
|
+
var WaasClient = class {
|
|
2828
|
+
controlBaseUrl;
|
|
2829
|
+
state = null;
|
|
2830
|
+
onSessionExpired;
|
|
2831
|
+
constructor(opts) {
|
|
2832
|
+
this.controlBaseUrl = opts.controlBaseUrl.replace(/\/$/, "");
|
|
2833
|
+
this.onSessionExpired = opts.onSessionExpired;
|
|
2834
|
+
}
|
|
2835
|
+
setOnSessionExpired(fn) {
|
|
2836
|
+
this.onSessionExpired = fn;
|
|
2837
|
+
}
|
|
2838
|
+
/**
|
|
2839
|
+
* Authenticated request. A 401 means the session is unusable, so the local
|
|
2840
|
+
* state is dropped immediately rather than left to fail every later call.
|
|
2841
|
+
*/
|
|
2842
|
+
async authed(url, init) {
|
|
2843
|
+
try {
|
|
2844
|
+
return await http(url, init);
|
|
2845
|
+
} catch (e) {
|
|
2846
|
+
if (isWaasHttpError(e) && e.isSessionError) {
|
|
2847
|
+
this.state = null;
|
|
2848
|
+
this.onSessionExpired?.();
|
|
2849
|
+
}
|
|
2850
|
+
throw e;
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
getState() {
|
|
2854
|
+
return this.state ? { ...this.state } : null;
|
|
2855
|
+
}
|
|
2856
|
+
clearAll() {
|
|
2857
|
+
this.state = null;
|
|
2858
|
+
}
|
|
2859
|
+
hydrate(state) {
|
|
2860
|
+
this.state = { ...state };
|
|
2861
|
+
}
|
|
2862
|
+
async loginDev(email, provider = "dev", opts) {
|
|
2863
|
+
const out = await http(`${this.controlBaseUrl}/auth/dev-login`, {
|
|
2864
|
+
method: "POST",
|
|
2865
|
+
headers: { "content-type": "application/json" },
|
|
2866
|
+
body: JSON.stringify({
|
|
2867
|
+
email,
|
|
2868
|
+
provider,
|
|
2869
|
+
projectId: opts?.projectId,
|
|
2870
|
+
asDeveloper: opts?.asDeveloper
|
|
2871
|
+
})
|
|
2872
|
+
});
|
|
2873
|
+
this.state = {
|
|
2874
|
+
sessionToken: out.sessionToken,
|
|
2875
|
+
principalId: out.principalId,
|
|
2876
|
+
email: out.email
|
|
2877
|
+
};
|
|
2878
|
+
return this.getState();
|
|
2879
|
+
}
|
|
2880
|
+
async loginWithSessionToken(sessionToken) {
|
|
2881
|
+
this.state = { sessionToken, principalId: "" };
|
|
2882
|
+
const me = await this.fetchMe();
|
|
2883
|
+
this.state = {
|
|
2884
|
+
sessionToken,
|
|
2885
|
+
principalId: me.principalId,
|
|
2886
|
+
email: me.email,
|
|
2887
|
+
walletId: me.wallet?.walletId,
|
|
2888
|
+
address: me.wallet?.address,
|
|
2889
|
+
epoch: me.wallet?.epoch,
|
|
2890
|
+
passwordEnabled: me.wallet?.passwordEnabled ?? false
|
|
2891
|
+
};
|
|
2892
|
+
return this.getState();
|
|
2893
|
+
}
|
|
2894
|
+
async fetchMe() {
|
|
2895
|
+
this.requireSession();
|
|
2896
|
+
return this.authed(`${this.controlBaseUrl}/wallet/me`, {
|
|
2897
|
+
headers: this.authHeaders()
|
|
2898
|
+
});
|
|
2899
|
+
}
|
|
2900
|
+
async ensureWallet() {
|
|
2901
|
+
this.requireSession();
|
|
2902
|
+
const out = await this.authed(`${this.controlBaseUrl}/wallet/ensure`, {
|
|
2903
|
+
method: "POST",
|
|
2904
|
+
headers: this.authHeaders()
|
|
2905
|
+
});
|
|
2906
|
+
this.state = {
|
|
2907
|
+
...this.state,
|
|
2908
|
+
walletId: out.walletId,
|
|
2909
|
+
address: out.address,
|
|
2910
|
+
epoch: out.epoch,
|
|
2911
|
+
passwordEnabled: out.passwordEnabled
|
|
2912
|
+
};
|
|
2913
|
+
return { walletId: out.walletId, address: out.address, passwordEnabled: out.passwordEnabled };
|
|
2914
|
+
}
|
|
2915
|
+
async setPassword(password, currentPassword) {
|
|
2916
|
+
this.requireSession();
|
|
2917
|
+
await this.authed(`${this.controlBaseUrl}/wallet/password/set`, {
|
|
2918
|
+
method: "POST",
|
|
2919
|
+
headers: { ...this.authHeaders(), "content-type": "application/json" },
|
|
2920
|
+
body: JSON.stringify({ password, currentPassword })
|
|
2921
|
+
});
|
|
2922
|
+
if (this.state) this.state.passwordEnabled = true;
|
|
2923
|
+
}
|
|
2924
|
+
async clearPassword(password) {
|
|
2925
|
+
this.requireSession();
|
|
2926
|
+
await this.authed(`${this.controlBaseUrl}/wallet/password/clear`, {
|
|
2927
|
+
method: "POST",
|
|
2928
|
+
headers: { ...this.authHeaders(), "content-type": "application/json" },
|
|
2929
|
+
body: JSON.stringify({ password })
|
|
2930
|
+
});
|
|
2931
|
+
if (this.state) this.state.passwordEnabled = false;
|
|
2932
|
+
}
|
|
2933
|
+
async signMessage(message, opts) {
|
|
2934
|
+
const digest = hashPersonalMessage(message);
|
|
2935
|
+
return this.signDigestHex(digestToHex(digest), opts);
|
|
2936
|
+
}
|
|
2937
|
+
async signDigestHex(digestHex, opts) {
|
|
2938
|
+
this.requireSession();
|
|
2939
|
+
const normalized = digestHex.startsWith("0x") ? digestHex : `0x${digestHex}`;
|
|
2940
|
+
const out = await this.authed(
|
|
2941
|
+
`${this.controlBaseUrl}/wallet/sign`,
|
|
2942
|
+
{
|
|
2943
|
+
method: "POST",
|
|
2944
|
+
headers: { ...this.authHeaders(), "content-type": "application/json" },
|
|
2945
|
+
body: JSON.stringify({ digestHex: normalized, password: opts?.password })
|
|
2946
|
+
}
|
|
2947
|
+
);
|
|
2948
|
+
const recovered = recoverAddressFromDigest(shareFromHex(normalized), out.signature);
|
|
2949
|
+
if (normalizeAddress(recovered) !== normalizeAddress(out.address)) {
|
|
2950
|
+
throw new Error("signature recovery mismatch");
|
|
2951
|
+
}
|
|
2952
|
+
return out;
|
|
2953
|
+
}
|
|
2954
|
+
async signTypedData(payload, opts) {
|
|
2955
|
+
const { TypedDataEncoder } = await import('ethers');
|
|
2956
|
+
const types = { ...payload.types };
|
|
2957
|
+
delete types.EIP712Domain;
|
|
2958
|
+
const digestHex = TypedDataEncoder.hash(
|
|
2959
|
+
payload.domain,
|
|
2960
|
+
types,
|
|
2961
|
+
payload.message
|
|
2962
|
+
);
|
|
2963
|
+
return this.signDigestHex(digestHex, opts);
|
|
2964
|
+
}
|
|
2965
|
+
async transfer(params) {
|
|
2966
|
+
this.requireSession();
|
|
2967
|
+
return this.authed(`${this.controlBaseUrl}/wallet/transfer`, {
|
|
2968
|
+
method: "POST",
|
|
2969
|
+
headers: { ...this.authHeaders(), "content-type": "application/json" },
|
|
2970
|
+
body: JSON.stringify({
|
|
2971
|
+
to: params.to,
|
|
2972
|
+
amount: params.amount,
|
|
2973
|
+
amountRaw: params.amountRaw,
|
|
2974
|
+
token: params.token ?? "native",
|
|
2975
|
+
chainId: params.chainId ?? 1,
|
|
2976
|
+
password: params.password
|
|
2977
|
+
})
|
|
2978
|
+
});
|
|
2979
|
+
}
|
|
2980
|
+
async getBalance(token = "native", chainId) {
|
|
2981
|
+
this.requireSession();
|
|
2982
|
+
const params = new URLSearchParams({ token });
|
|
2983
|
+
if (chainId) params.set("chainId", String(chainId));
|
|
2984
|
+
return this.authed(`${this.controlBaseUrl}/wallet/balance?${params}`, {
|
|
2985
|
+
headers: this.authHeaders()
|
|
2986
|
+
});
|
|
2987
|
+
}
|
|
2988
|
+
requireSession() {
|
|
2989
|
+
if (!this.state?.sessionToken) throw new Error("not logged in");
|
|
2990
|
+
}
|
|
2991
|
+
authHeaders() {
|
|
2992
|
+
if (!this.state?.sessionToken) throw new Error("not logged in");
|
|
2993
|
+
return { authorization: `Bearer ${this.state.sessionToken}` };
|
|
2994
|
+
}
|
|
2995
|
+
};
|
|
2996
|
+
|
|
2997
|
+
// src/client/storage.ts
|
|
2998
|
+
function loadPersistedState(storageKey = DEFAULT_STORAGE_KEY) {
|
|
2999
|
+
if (typeof sessionStorage === "undefined") return null;
|
|
3000
|
+
try {
|
|
3001
|
+
const raw = sessionStorage.getItem(storageKey);
|
|
3002
|
+
if (!raw) return null;
|
|
3003
|
+
return JSON.parse(raw);
|
|
3004
|
+
} catch {
|
|
3005
|
+
return null;
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
function persistDeviceState(state, storageKey = DEFAULT_STORAGE_KEY) {
|
|
3009
|
+
if (typeof sessionStorage === "undefined") return;
|
|
3010
|
+
if (!state?.sessionToken) {
|
|
3011
|
+
sessionStorage.removeItem(storageKey);
|
|
3012
|
+
return;
|
|
3013
|
+
}
|
|
3014
|
+
const payload = {
|
|
3015
|
+
sessionToken: state.sessionToken,
|
|
3016
|
+
principalId: state.principalId,
|
|
3017
|
+
email: state.email,
|
|
3018
|
+
walletId: state.walletId,
|
|
3019
|
+
address: state.address,
|
|
3020
|
+
epoch: state.epoch,
|
|
3021
|
+
passwordEnabled: state.passwordEnabled
|
|
3022
|
+
};
|
|
3023
|
+
sessionStorage.setItem(storageKey, JSON.stringify(payload));
|
|
3024
|
+
}
|
|
3025
|
+
function clearPersistedState(storageKey = DEFAULT_STORAGE_KEY) {
|
|
3026
|
+
if (typeof sessionStorage === "undefined") return;
|
|
3027
|
+
sessionStorage.removeItem(storageKey);
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
// src/client/AuthClient.ts
|
|
3031
|
+
var SOCIAL_METHODS = ["google", "twitter", "github", "apple"];
|
|
3032
|
+
var AuthClient = class {
|
|
3033
|
+
config;
|
|
3034
|
+
storageKey;
|
|
3035
|
+
oauthPendingKey;
|
|
3036
|
+
client;
|
|
3037
|
+
provider = null;
|
|
3038
|
+
chainId;
|
|
3039
|
+
active = false;
|
|
3040
|
+
requestApproval;
|
|
3041
|
+
onSessionExpired;
|
|
3042
|
+
constructor(options) {
|
|
3043
|
+
this.config = options.config;
|
|
3044
|
+
this.storageKey = options.config.storageKey ?? DEFAULT_STORAGE_KEY;
|
|
3045
|
+
this.oauthPendingKey = options.config.oauthPendingKey ?? DEFAULT_OAUTH_PENDING_KEY;
|
|
3046
|
+
this.requestApproval = options.requestApproval;
|
|
3047
|
+
this.onSessionExpired = options.onSessionExpired;
|
|
3048
|
+
this.chainId = options.chainId ?? 1;
|
|
3049
|
+
this.client = new WaasClient({
|
|
3050
|
+
controlBaseUrl: options.config.controlBaseUrl,
|
|
3051
|
+
// Drop the persisted session too, otherwise a reload would restore a
|
|
3052
|
+
// token the control-plane has already rejected.
|
|
3053
|
+
onSessionExpired: () => {
|
|
3054
|
+
this.active = false;
|
|
3055
|
+
this.provider = null;
|
|
3056
|
+
clearPersistedState(this.storageKey);
|
|
3057
|
+
this.onSessionExpired?.();
|
|
3058
|
+
}
|
|
3059
|
+
});
|
|
3060
|
+
const saved = loadPersistedState(this.storageKey);
|
|
3061
|
+
if (saved?.sessionToken) {
|
|
3062
|
+
this.client.hydrate(saved);
|
|
3063
|
+
if (saved.address) this.active = true;
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
3066
|
+
setRequestApproval(fn) {
|
|
3067
|
+
this.requestApproval = fn;
|
|
3068
|
+
this.provider = null;
|
|
3069
|
+
}
|
|
3070
|
+
setOnSessionExpired(fn) {
|
|
3071
|
+
this.onSessionExpired = fn;
|
|
3072
|
+
}
|
|
3073
|
+
isAuthenticated() {
|
|
3074
|
+
return this.active;
|
|
3075
|
+
}
|
|
3076
|
+
getUser() {
|
|
3077
|
+
const s = this.client.getState();
|
|
3078
|
+
if (!s?.sessionToken) return null;
|
|
3079
|
+
return {
|
|
3080
|
+
principalId: s.principalId,
|
|
3081
|
+
email: s.email,
|
|
3082
|
+
address: s.address,
|
|
3083
|
+
walletId: s.walletId,
|
|
3084
|
+
passwordEnabled: s.passwordEnabled
|
|
3085
|
+
};
|
|
3086
|
+
}
|
|
3087
|
+
/** Current EIP-1193 chain. Changes via wallet_switchEthereumChain. */
|
|
3088
|
+
getChainId() {
|
|
3089
|
+
return this.chainId;
|
|
3090
|
+
}
|
|
3091
|
+
getAddress() {
|
|
3092
|
+
return this.client.getState()?.address;
|
|
3093
|
+
}
|
|
3094
|
+
getWaasClient() {
|
|
3095
|
+
return this.client;
|
|
3096
|
+
}
|
|
3097
|
+
getProvider() {
|
|
3098
|
+
if (!this.provider) {
|
|
3099
|
+
this.provider = createWaasEip1193Provider(this.client, {
|
|
3100
|
+
chainId: this.chainId,
|
|
3101
|
+
onChainChanged: (id) => {
|
|
3102
|
+
this.chainId = id;
|
|
3103
|
+
},
|
|
3104
|
+
requestApproval: this.requestApproval ? (req) => this.requestApproval(req) : void 0
|
|
3105
|
+
});
|
|
3106
|
+
}
|
|
3107
|
+
return this.provider;
|
|
3108
|
+
}
|
|
3109
|
+
getConnectorShim() {
|
|
3110
|
+
return {
|
|
3111
|
+
getProvider: async () => this.getProvider()
|
|
3112
|
+
};
|
|
3113
|
+
}
|
|
3114
|
+
persist() {
|
|
3115
|
+
persistDeviceState(this.client.getState(), this.storageKey);
|
|
3116
|
+
}
|
|
3117
|
+
async fetchOAuthProviders() {
|
|
3118
|
+
const base = this.config.controlBaseUrl.replace(/\/$/, "");
|
|
3119
|
+
const url = this.config.projectId ? `${base}/auth/oauth/providers?projectId=${encodeURIComponent(this.config.projectId)}` : `${base}/auth/oauth/providers`;
|
|
3120
|
+
try {
|
|
3121
|
+
const res = await fetch(url);
|
|
3122
|
+
if (!res.ok) {
|
|
3123
|
+
throw new Error(`waas providers HTTP ${res.status}`);
|
|
3124
|
+
}
|
|
3125
|
+
return await res.json();
|
|
3126
|
+
} catch (e) {
|
|
3127
|
+
const detail = e instanceof Error ? e.message : String(e);
|
|
3128
|
+
throw new Error(
|
|
3129
|
+
`Cannot reach eocene-worker at ${base} (${detail}). Start control-plane on :18787 and ensure EOCENE_CONTROL_URL / Vite proxy (/eocene) are set.`
|
|
3130
|
+
);
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
3133
|
+
/**
|
|
3134
|
+
* Social login methods actually enabled for this project, in display order.
|
|
3135
|
+
* Used to render only the buttons that will work; falls back to all methods
|
|
3136
|
+
* if the control-plane is unreachable (login will surface a clear error).
|
|
3137
|
+
*/
|
|
3138
|
+
async listAvailableMethods() {
|
|
3139
|
+
try {
|
|
3140
|
+
const status = await this.fetchOAuthProviders();
|
|
3141
|
+
const enabled = SOCIAL_METHODS.filter(
|
|
3142
|
+
(m) => status.providers[m] || this.config.allowDevLoginFallback && status.allowDevLogin
|
|
3143
|
+
);
|
|
3144
|
+
return enabled.length ? enabled : SOCIAL_METHODS;
|
|
3145
|
+
} catch {
|
|
3146
|
+
return SOCIAL_METHODS;
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
async login(method) {
|
|
3150
|
+
const status = await this.fetchOAuthProviders();
|
|
3151
|
+
if (status.providers[method]) {
|
|
3152
|
+
if (typeof sessionStorage !== "undefined") {
|
|
3153
|
+
sessionStorage.setItem(
|
|
3154
|
+
this.oauthPendingKey,
|
|
3155
|
+
JSON.stringify({
|
|
3156
|
+
mode: method,
|
|
3157
|
+
at: Date.now(),
|
|
3158
|
+
path: typeof window !== "undefined" ? window.location.pathname + window.location.search : "/"
|
|
3159
|
+
})
|
|
3160
|
+
);
|
|
3161
|
+
}
|
|
3162
|
+
const returnTo = this.config.oauthReturnTo;
|
|
3163
|
+
const qs = new URLSearchParams({ returnTo });
|
|
3164
|
+
if (this.config.projectId) qs.set("projectId", this.config.projectId);
|
|
3165
|
+
if (this.config.asDeveloper) qs.set("asDeveloper", "1");
|
|
3166
|
+
const start = `${resolveControlAbsoluteUrl(this.config.controlBaseUrl)}/auth/oauth/${method}?${qs}`;
|
|
3167
|
+
window.location.assign(start);
|
|
3168
|
+
await new Promise(() => {
|
|
3169
|
+
});
|
|
3170
|
+
}
|
|
3171
|
+
const allowDev = this.config.allowDevLoginFallback === true;
|
|
3172
|
+
if (!allowDev || !status.allowDevLogin) {
|
|
3173
|
+
throw new Error(
|
|
3174
|
+
`${method} OAuth is not configured on eocene-worker (providers.${method}=false). Set GOOGLE_CLIENT_ID/SECRET in eocene-worker/.env and restart, or set EOCENE_OAUTH_FALLBACK_DEV=true for local mock.`
|
|
3175
|
+
);
|
|
3176
|
+
}
|
|
3177
|
+
const email = `${method}@waas.local`;
|
|
3178
|
+
await this.client.loginDev(email, method, {
|
|
3179
|
+
projectId: this.config.projectId,
|
|
3180
|
+
asDeveloper: this.config.asDeveloper
|
|
3181
|
+
});
|
|
3182
|
+
if (this.config.asDeveloper) {
|
|
3183
|
+
const ensureRes = await fetch(`${resolveControlAbsoluteUrl(this.config.controlBaseUrl)}/dev/ensure`, {
|
|
3184
|
+
method: "POST",
|
|
3185
|
+
headers: { authorization: `Bearer ${this.client.getState()?.sessionToken}` }
|
|
3186
|
+
});
|
|
3187
|
+
if (ensureRes.ok) {
|
|
3188
|
+
const body = await ensureRes.json();
|
|
3189
|
+
if (body.sessionToken) {
|
|
3190
|
+
await this.client.loginWithSessionToken(body.sessionToken);
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
const wallet = await this.client.ensureWallet();
|
|
3195
|
+
this.persist();
|
|
3196
|
+
this.active = true;
|
|
3197
|
+
this.provider = null;
|
|
3198
|
+
return wallet;
|
|
3199
|
+
}
|
|
3200
|
+
async completeOAuthFromHash(hashOrSearch) {
|
|
3201
|
+
const raw = hashOrSearch.startsWith("#") || hashOrSearch.startsWith("?") ? hashOrSearch.slice(1) : hashOrSearch;
|
|
3202
|
+
const params = new URLSearchParams(raw);
|
|
3203
|
+
const err = params.get("waas_error");
|
|
3204
|
+
if (err) throw new Error(decodeURIComponent(err));
|
|
3205
|
+
const sessionToken = params.get("waas_session");
|
|
3206
|
+
if (!sessionToken) throw new Error("missing waas_session in callback");
|
|
3207
|
+
const provider = params.get("waas_provider") ?? void 0;
|
|
3208
|
+
await this.client.loginWithSessionToken(decodeURIComponent(sessionToken));
|
|
3209
|
+
const wallet = await this.client.ensureWallet();
|
|
3210
|
+
this.persist();
|
|
3211
|
+
this.active = true;
|
|
3212
|
+
this.provider = null;
|
|
3213
|
+
if (typeof sessionStorage !== "undefined") {
|
|
3214
|
+
sessionStorage.removeItem(this.oauthPendingKey);
|
|
3215
|
+
}
|
|
3216
|
+
return {
|
|
3217
|
+
...wallet,
|
|
3218
|
+
provider: provider ? decodeURIComponent(provider) : void 0
|
|
3219
|
+
};
|
|
3220
|
+
}
|
|
3221
|
+
takeOAuthReturnPath() {
|
|
3222
|
+
if (typeof sessionStorage === "undefined") return null;
|
|
3223
|
+
try {
|
|
3224
|
+
const raw = sessionStorage.getItem(this.oauthPendingKey);
|
|
3225
|
+
if (!raw) return null;
|
|
3226
|
+
const parsed = JSON.parse(raw);
|
|
3227
|
+
return parsed.path ?? null;
|
|
3228
|
+
} catch {
|
|
3229
|
+
return null;
|
|
3230
|
+
}
|
|
3231
|
+
}
|
|
3232
|
+
markActive(on) {
|
|
3233
|
+
this.active = on;
|
|
3234
|
+
if (!on) {
|
|
3235
|
+
this.client.clearAll();
|
|
3236
|
+
clearPersistedState(this.storageKey);
|
|
3237
|
+
this.provider = null;
|
|
3238
|
+
} else {
|
|
3239
|
+
this.persist();
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
restoreIfNeeded() {
|
|
3243
|
+
const saved = loadPersistedState(this.storageKey);
|
|
3244
|
+
if (!saved?.sessionToken || !saved.address) return false;
|
|
3245
|
+
this.client.hydrate(saved);
|
|
3246
|
+
this.active = true;
|
|
3247
|
+
this.provider = null;
|
|
3248
|
+
return true;
|
|
3249
|
+
}
|
|
3250
|
+
logout() {
|
|
3251
|
+
this.markActive(false);
|
|
3252
|
+
}
|
|
3253
|
+
async setPassword(password, currentPassword) {
|
|
3254
|
+
await this.client.setPassword(password, currentPassword);
|
|
3255
|
+
this.persist();
|
|
3256
|
+
}
|
|
3257
|
+
async clearPassword(password) {
|
|
3258
|
+
await this.client.clearPassword(password);
|
|
3259
|
+
this.persist();
|
|
3260
|
+
}
|
|
3261
|
+
};
|
|
3262
|
+
|
|
3263
|
+
// src/provider/createProvider.ts
|
|
3264
|
+
function createAuthEip1193Provider(client, requestApproval) {
|
|
3265
|
+
return createWaasEip1193Provider(client, { requestApproval });
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
// src/client/formatError.ts
|
|
3269
|
+
function formatAuthError(e, labels) {
|
|
3270
|
+
if (isWaasHttpError(e)) {
|
|
3271
|
+
if (e.code === "session_expired") return labels.sessionExpired;
|
|
3272
|
+
if (e.code === "rate_limited") return labels.rateLimited;
|
|
3273
|
+
if (e.code === "plan_user_limit") {
|
|
3274
|
+
return "This app has reached its Eocene user limit. Ask the developer to upgrade their plan.";
|
|
3275
|
+
}
|
|
3276
|
+
if (e.code === "plan_project_limit") {
|
|
3277
|
+
return "Project limit reached on this Eocene account.";
|
|
3278
|
+
}
|
|
3279
|
+
return formatSignAuthError(
|
|
3280
|
+
{
|
|
3281
|
+
code: e.code,
|
|
3282
|
+
message: e.message,
|
|
3283
|
+
attemptsRemaining: e.attemptsRemaining,
|
|
3284
|
+
lockedUntil: e.lockedUntil,
|
|
3285
|
+
retryAfterSec: e.retryAfterSec
|
|
3286
|
+
},
|
|
3287
|
+
labels
|
|
3288
|
+
);
|
|
3289
|
+
}
|
|
3290
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
3291
|
+
if (/4001|User rejected/i.test(msg)) return labels.signRejected;
|
|
3292
|
+
if (/password_locked|Too many incorrect/i.test(msg)) return labels.signPasswordLocked;
|
|
3293
|
+
if (/password_invalid|Incorrect password|password required or invalid/i.test(msg)) {
|
|
3294
|
+
return labels.signPasswordIncorrect;
|
|
3295
|
+
}
|
|
3296
|
+
if (/coalesce error|UNKNOWN_ERROR|jsonrpc/i.test(msg)) {
|
|
3297
|
+
if (/password/i.test(msg)) return labels.signPasswordIncorrect;
|
|
3298
|
+
return labels.oauthFailed;
|
|
3299
|
+
}
|
|
3300
|
+
if (msg.length > 160) return labels.oauthFailed;
|
|
3301
|
+
return msg || labels.oauthFailed;
|
|
3302
|
+
}
|
|
3303
|
+
function formatSignAuthError(err, labels) {
|
|
3304
|
+
if (err.code === "password_locked") {
|
|
3305
|
+
const mins = err.retryAfterSec ? Math.max(1, Math.ceil(err.retryAfterSec / 60)) : err.lockedUntil ? Math.max(1, Math.ceil((Date.parse(err.lockedUntil) - Date.now()) / 6e4)) : 5;
|
|
3306
|
+
return labels.signPasswordLocked.replace("{minutes}", String(mins));
|
|
3307
|
+
}
|
|
3308
|
+
if (err.code === "password_invalid") {
|
|
3309
|
+
if (typeof err.attemptsRemaining === "number") {
|
|
3310
|
+
return labels.signPasswordIncorrectRemaining.replace(
|
|
3311
|
+
"{remaining}",
|
|
3312
|
+
String(err.attemptsRemaining)
|
|
3313
|
+
);
|
|
3314
|
+
}
|
|
3315
|
+
return labels.signPasswordIncorrect;
|
|
3316
|
+
}
|
|
3317
|
+
if (err.code === "password_required") return labels.signPasswordRequired;
|
|
3318
|
+
if (err.code === "password_too_short") return labels.passwordSettingsNewPlaceholder;
|
|
3319
|
+
return err.message || labels.signPasswordIncorrect;
|
|
3320
|
+
}
|
|
3321
|
+
function EoceneMark({
|
|
3322
|
+
size = 28,
|
|
3323
|
+
title = "Eocene",
|
|
3324
|
+
...props
|
|
3325
|
+
}) {
|
|
3326
|
+
return /* @__PURE__ */ jsxs(
|
|
3327
|
+
"svg",
|
|
3328
|
+
{
|
|
3329
|
+
width: size,
|
|
3330
|
+
height: size,
|
|
3331
|
+
viewBox: "0 0 48 48",
|
|
3332
|
+
fill: "none",
|
|
3333
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
3334
|
+
role: "img",
|
|
3335
|
+
"aria-label": title,
|
|
3336
|
+
...props,
|
|
3337
|
+
children: [
|
|
3338
|
+
/* @__PURE__ */ jsx("title", { children: title }),
|
|
3339
|
+
/* @__PURE__ */ jsxs("g", { fill: "#3B82D6", children: [
|
|
3340
|
+
/* @__PURE__ */ jsx("circle", { cx: "12.5", cy: "13", r: "3.6" }),
|
|
3341
|
+
/* @__PURE__ */ jsx("circle", { cx: "27", cy: "13", r: "5.6" }),
|
|
3342
|
+
/* @__PURE__ */ jsx("path", { d: "M12.5 10.1 C19.75 11.4, 19.75 11.4, 27 8.5 L27 17.5 C19.75 14.6, 19.75 14.6, 12.5 15.9 Z" })
|
|
3343
|
+
] }),
|
|
3344
|
+
/* @__PURE__ */ jsxs("g", { fill: "#2563B0", children: [
|
|
3345
|
+
/* @__PURE__ */ jsx("circle", { cx: "10.5", cy: "25", r: "7" }),
|
|
3346
|
+
/* @__PURE__ */ jsx("circle", { cx: "26.5", cy: "25", r: "5.4" }),
|
|
3347
|
+
/* @__PURE__ */ jsx("path", { d: "M10.5 19.4 C18.5 23.2, 18.5 23.2, 26.5 20.7 L26.5 29.3 C18.5 26.8, 18.5 26.8, 10.5 30.6 Z" })
|
|
3348
|
+
] }),
|
|
3349
|
+
/* @__PURE__ */ jsx("circle", { cx: "39.5", cy: "25", r: "3.9", fill: "#1D3E90" }),
|
|
3350
|
+
/* @__PURE__ */ jsxs("g", { fill: "#85CEEA", children: [
|
|
3351
|
+
/* @__PURE__ */ jsx("circle", { cx: "14", cy: "37", r: "4" }),
|
|
3352
|
+
/* @__PURE__ */ jsx("circle", { cx: "28", cy: "37", r: "5.2" }),
|
|
3353
|
+
/* @__PURE__ */ jsx("path", { d: "M14 33.8 C21 35.4, 21 35.4, 28 32.8 L28 41.2 C21 38.6, 21 38.6, 14 40.2 Z" })
|
|
3354
|
+
] })
|
|
3355
|
+
]
|
|
3356
|
+
}
|
|
3357
|
+
);
|
|
3358
|
+
}
|
|
3359
|
+
function EoceneWordmark({
|
|
3360
|
+
className,
|
|
3361
|
+
markSize = 28
|
|
3362
|
+
}) {
|
|
3363
|
+
return /* @__PURE__ */ jsxs(
|
|
3364
|
+
"span",
|
|
3365
|
+
{
|
|
3366
|
+
className,
|
|
3367
|
+
style: {
|
|
3368
|
+
display: "inline-flex",
|
|
3369
|
+
alignItems: "center",
|
|
3370
|
+
gap: 10,
|
|
3371
|
+
fontWeight: 700,
|
|
3372
|
+
letterSpacing: "-0.03em",
|
|
3373
|
+
lineHeight: 1
|
|
3374
|
+
},
|
|
3375
|
+
children: [
|
|
3376
|
+
/* @__PURE__ */ jsx(EoceneMark, { size: markSize }),
|
|
3377
|
+
/* @__PURE__ */ jsxs("span", { "aria-hidden": "true", children: [
|
|
3378
|
+
"Eo",
|
|
3379
|
+
/* @__PURE__ */ jsx("span", { style: { color: "var(--auth-sdk-accent, #2563b0)" }, children: "cene" })
|
|
3380
|
+
] })
|
|
3381
|
+
]
|
|
3382
|
+
}
|
|
3383
|
+
);
|
|
3384
|
+
}
|
|
3385
|
+
var DEFAULT_METHODS = ["google", "twitter", "github", "apple"];
|
|
3386
|
+
function methodLabel(method, labels) {
|
|
3387
|
+
switch (method) {
|
|
3388
|
+
case "google":
|
|
3389
|
+
return labels.loginGoogle;
|
|
3390
|
+
case "twitter":
|
|
3391
|
+
return labels.loginTwitter;
|
|
3392
|
+
case "github":
|
|
3393
|
+
return labels.loginGithub;
|
|
3394
|
+
case "apple":
|
|
3395
|
+
return labels.loginApple;
|
|
3396
|
+
}
|
|
3397
|
+
}
|
|
3398
|
+
function AuthLoginPanel({
|
|
3399
|
+
labels,
|
|
3400
|
+
methods = DEFAULT_METHODS,
|
|
3401
|
+
loadingMethod,
|
|
3402
|
+
loadingMethods = false,
|
|
3403
|
+
error,
|
|
3404
|
+
onLogin
|
|
3405
|
+
}) {
|
|
3406
|
+
return /* @__PURE__ */ jsxs("div", { className: "auth-sdk-root auth-sdk-login", children: [
|
|
3407
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-login-brand", children: [
|
|
3408
|
+
/* @__PURE__ */ jsx(EoceneMark, { size: 28 }),
|
|
3409
|
+
/* @__PURE__ */ jsx("p", { className: "auth-sdk-login-title", children: labels.loginTitle })
|
|
3410
|
+
] }),
|
|
3411
|
+
/* @__PURE__ */ jsx("div", { className: "auth-sdk-login-stack", children: loadingMethods ? (
|
|
3412
|
+
// Skeleton rows while the enabled-methods list loads — avoids
|
|
3413
|
+
// flashing every provider then removing the disabled ones.
|
|
3414
|
+
/* @__PURE__ */ jsxs(Fragment, { children: [
|
|
3415
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-login-skeleton", "aria-hidden": true }),
|
|
3416
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-login-skeleton", "aria-hidden": true })
|
|
3417
|
+
] })
|
|
3418
|
+
) : methods.length === 0 ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-login-empty", children: labels.loginNoMethods }) : methods.map((method) => {
|
|
3419
|
+
const busy = loadingMethod === method;
|
|
3420
|
+
return /* @__PURE__ */ jsx(
|
|
3421
|
+
"button",
|
|
3422
|
+
{
|
|
3423
|
+
type: "button",
|
|
3424
|
+
className: "auth-sdk-login-btn",
|
|
3425
|
+
disabled: loadingMethod != null,
|
|
3426
|
+
onClick: () => onLogin(method),
|
|
3427
|
+
children: busy ? labels.loginConnecting : methodLabel(method, labels)
|
|
3428
|
+
},
|
|
3429
|
+
method
|
|
3430
|
+
);
|
|
3431
|
+
}) }),
|
|
3432
|
+
error ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-login-error", children: error }) : null
|
|
3433
|
+
] });
|
|
3434
|
+
}
|
|
3435
|
+
function SetPasswordModal({
|
|
3436
|
+
open,
|
|
3437
|
+
passwordEnabled,
|
|
3438
|
+
labels,
|
|
3439
|
+
busy,
|
|
3440
|
+
error,
|
|
3441
|
+
onSubmitSet,
|
|
3442
|
+
onSubmitClear,
|
|
3443
|
+
onClose
|
|
3444
|
+
}) {
|
|
3445
|
+
const [password, setPassword] = useState("");
|
|
3446
|
+
const [confirm, setConfirm] = useState("");
|
|
3447
|
+
const [current, setCurrent] = useState("");
|
|
3448
|
+
const [mode, setMode] = useState("set");
|
|
3449
|
+
useEffect(() => {
|
|
3450
|
+
if (!open) return;
|
|
3451
|
+
setPassword("");
|
|
3452
|
+
setConfirm("");
|
|
3453
|
+
setCurrent("");
|
|
3454
|
+
setMode(passwordEnabled ? "set" : "set");
|
|
3455
|
+
}, [open, passwordEnabled]);
|
|
3456
|
+
if (!open) return null;
|
|
3457
|
+
const mismatch = password.length > 0 && confirm.length > 0 && password !== confirm;
|
|
3458
|
+
const canSet = password.length >= 6 && password === confirm && (!passwordEnabled || current.length > 0) && !busy;
|
|
3459
|
+
const canClear = passwordEnabled && current.length > 0 && !busy;
|
|
3460
|
+
return /* @__PURE__ */ jsxs("div", { className: "auth-sdk-root", role: "presentation", children: [
|
|
3461
|
+
/* @__PURE__ */ jsx("div", { className: "auth-sdk-backdrop", onClick: busy ? void 0 : onClose, "aria-hidden": true }),
|
|
3462
|
+
/* @__PURE__ */ jsxs(
|
|
3463
|
+
"div",
|
|
3464
|
+
{
|
|
3465
|
+
className: "auth-sdk-sign-panel",
|
|
3466
|
+
role: "dialog",
|
|
3467
|
+
"aria-modal": "true",
|
|
3468
|
+
"aria-labelledby": "auth-sdk-password-title",
|
|
3469
|
+
children: [
|
|
3470
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-sign-header", children: [
|
|
3471
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-app-badge", "aria-hidden": true, children: /* @__PURE__ */ jsx(EoceneMark, { size: 26 }) }),
|
|
3472
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-brand-text", children: [
|
|
3473
|
+
/* @__PURE__ */ jsx("p", { className: "auth-sdk-brand-name", children: labels.signBrandEyebrow }),
|
|
3474
|
+
/* @__PURE__ */ jsx("h2", { id: "auth-sdk-password-title", className: "auth-sdk-sign-title", children: labels.passwordSettingsTitle })
|
|
3475
|
+
] })
|
|
3476
|
+
] }),
|
|
3477
|
+
/* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-subtitle", children: passwordEnabled ? labels.passwordSettingsEnabledHint : labels.passwordSettingsDisabledHint }),
|
|
3478
|
+
passwordEnabled ? /* @__PURE__ */ jsxs("div", { className: "auth-sdk-mode-tabs", role: "tablist", children: [
|
|
3479
|
+
/* @__PURE__ */ jsx(
|
|
3480
|
+
"button",
|
|
3481
|
+
{
|
|
3482
|
+
type: "button",
|
|
3483
|
+
role: "tab",
|
|
3484
|
+
className: `auth-sdk-mode-tab${mode === "set" ? " is-active" : ""}`,
|
|
3485
|
+
"aria-selected": mode === "set",
|
|
3486
|
+
onClick: () => setMode("set"),
|
|
3487
|
+
disabled: busy,
|
|
3488
|
+
children: labels.passwordSettingsChange
|
|
3489
|
+
}
|
|
3490
|
+
),
|
|
3491
|
+
/* @__PURE__ */ jsx(
|
|
3492
|
+
"button",
|
|
3493
|
+
{
|
|
3494
|
+
type: "button",
|
|
3495
|
+
role: "tab",
|
|
3496
|
+
className: `auth-sdk-mode-tab${mode === "clear" ? " is-active" : ""}`,
|
|
3497
|
+
"aria-selected": mode === "clear",
|
|
3498
|
+
onClick: () => setMode("clear"),
|
|
3499
|
+
disabled: busy,
|
|
3500
|
+
children: labels.passwordSettingsClear
|
|
3501
|
+
}
|
|
3502
|
+
)
|
|
3503
|
+
] }) : null,
|
|
3504
|
+
mode === "set" ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
3505
|
+
passwordEnabled ? /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
|
|
3506
|
+
/* @__PURE__ */ jsx("span", { children: labels.passwordSettingsCurrentLabel }),
|
|
3507
|
+
/* @__PURE__ */ jsx(
|
|
3508
|
+
"input",
|
|
3509
|
+
{
|
|
3510
|
+
type: "password",
|
|
3511
|
+
autoComplete: "current-password",
|
|
3512
|
+
placeholder: labels.passwordSettingsCurrentPlaceholder,
|
|
3513
|
+
value: current,
|
|
3514
|
+
onChange: (e) => setCurrent(e.target.value),
|
|
3515
|
+
disabled: busy,
|
|
3516
|
+
autoFocus: true
|
|
3517
|
+
}
|
|
3518
|
+
)
|
|
3519
|
+
] }) : null,
|
|
3520
|
+
/* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
|
|
3521
|
+
/* @__PURE__ */ jsx("span", { children: labels.passwordSettingsNewLabel }),
|
|
3522
|
+
/* @__PURE__ */ jsx(
|
|
3523
|
+
"input",
|
|
3524
|
+
{
|
|
3525
|
+
type: "password",
|
|
3526
|
+
autoComplete: "new-password",
|
|
3527
|
+
placeholder: labels.passwordSettingsNewPlaceholder,
|
|
3528
|
+
value: password,
|
|
3529
|
+
onChange: (e) => setPassword(e.target.value),
|
|
3530
|
+
disabled: busy,
|
|
3531
|
+
autoFocus: !passwordEnabled
|
|
3532
|
+
}
|
|
3533
|
+
)
|
|
3534
|
+
] }),
|
|
3535
|
+
/* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
|
|
3536
|
+
/* @__PURE__ */ jsx("span", { children: labels.passwordSettingsConfirmLabel }),
|
|
3537
|
+
/* @__PURE__ */ jsx(
|
|
3538
|
+
"input",
|
|
3539
|
+
{
|
|
3540
|
+
type: "password",
|
|
3541
|
+
autoComplete: "new-password",
|
|
3542
|
+
placeholder: labels.passwordSettingsConfirmPlaceholder,
|
|
3543
|
+
value: confirm,
|
|
3544
|
+
onChange: (e) => setConfirm(e.target.value),
|
|
3545
|
+
disabled: busy
|
|
3546
|
+
}
|
|
3547
|
+
)
|
|
3548
|
+
] }),
|
|
3549
|
+
mismatch ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-error", children: labels.passwordSettingsMismatch }) : null
|
|
3550
|
+
] }) : /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
|
|
3551
|
+
/* @__PURE__ */ jsx("span", { children: labels.passwordSettingsCurrentLabel }),
|
|
3552
|
+
/* @__PURE__ */ jsx(
|
|
3553
|
+
"input",
|
|
3554
|
+
{
|
|
3555
|
+
type: "password",
|
|
3556
|
+
autoComplete: "current-password",
|
|
3557
|
+
placeholder: labels.passwordSettingsCurrentPlaceholder,
|
|
3558
|
+
value: current,
|
|
3559
|
+
onChange: (e) => setCurrent(e.target.value),
|
|
3560
|
+
disabled: busy,
|
|
3561
|
+
autoFocus: true
|
|
3562
|
+
}
|
|
3563
|
+
)
|
|
3564
|
+
] }),
|
|
3565
|
+
error ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-error", children: error }) : null,
|
|
3566
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-actions", children: [
|
|
3567
|
+
/* @__PURE__ */ jsx(
|
|
3568
|
+
"button",
|
|
3569
|
+
{
|
|
3570
|
+
type: "button",
|
|
3571
|
+
className: "auth-sdk-btn auth-sdk-btn-secondary",
|
|
3572
|
+
onClick: onClose,
|
|
3573
|
+
disabled: busy,
|
|
3574
|
+
children: labels.passwordSettingsCancel
|
|
3575
|
+
}
|
|
3576
|
+
),
|
|
3577
|
+
mode === "set" ? /* @__PURE__ */ jsx(
|
|
3578
|
+
"button",
|
|
3579
|
+
{
|
|
3580
|
+
type: "button",
|
|
3581
|
+
className: "auth-sdk-btn auth-sdk-btn-primary",
|
|
3582
|
+
disabled: !canSet,
|
|
3583
|
+
onClick: () => void onSubmitSet(password, passwordEnabled ? current : void 0),
|
|
3584
|
+
children: busy ? labels.passwordSettingsSaving : labels.passwordSettingsSave
|
|
3585
|
+
}
|
|
3586
|
+
) : /* @__PURE__ */ jsx(
|
|
3587
|
+
"button",
|
|
3588
|
+
{
|
|
3589
|
+
type: "button",
|
|
3590
|
+
className: "auth-sdk-btn auth-sdk-btn-primary",
|
|
3591
|
+
disabled: !canClear,
|
|
3592
|
+
onClick: () => void onSubmitClear(current),
|
|
3593
|
+
children: busy ? labels.passwordSettingsSaving : labels.passwordSettingsClearConfirm
|
|
3594
|
+
}
|
|
3595
|
+
)
|
|
3596
|
+
] })
|
|
3597
|
+
]
|
|
3598
|
+
}
|
|
3599
|
+
)
|
|
3600
|
+
] });
|
|
3601
|
+
}
|
|
3602
|
+
function shortenAddress(address) {
|
|
3603
|
+
if (address.length < 12) return address;
|
|
3604
|
+
return `${address.slice(0, 6)}\u2026${address.slice(-4)}`;
|
|
3605
|
+
}
|
|
3606
|
+
function truncateMessage(message, max = 800) {
|
|
3607
|
+
const trimmed = message.trim();
|
|
3608
|
+
if (trimmed.length <= max) return trimmed;
|
|
3609
|
+
return `${trimmed.slice(0, max)}\u2026`;
|
|
3610
|
+
}
|
|
3611
|
+
function addressGradient(address) {
|
|
3612
|
+
const hex = address.toLowerCase().replace(/^0x/, "").padEnd(12, "0");
|
|
3613
|
+
const h1 = Number.parseInt(hex.slice(0, 6), 16) % 360;
|
|
3614
|
+
const h2 = (Number.parseInt(hex.slice(6, 12), 16) % 360 || h1 + 40) % 360;
|
|
3615
|
+
return `linear-gradient(135deg, hsl(${h1} 72% 58%), hsl(${h2} 68% 46%))`;
|
|
3616
|
+
}
|
|
3617
|
+
function SignConfirmModal({
|
|
3618
|
+
open,
|
|
3619
|
+
request,
|
|
3620
|
+
labels,
|
|
3621
|
+
password,
|
|
3622
|
+
busy,
|
|
3623
|
+
error,
|
|
3624
|
+
locked,
|
|
3625
|
+
onPasswordChange,
|
|
3626
|
+
onApprove,
|
|
3627
|
+
onReject,
|
|
3628
|
+
onOpenSetPassword
|
|
3629
|
+
}) {
|
|
3630
|
+
if (!open || !request) return null;
|
|
3631
|
+
const isTyped = request.method === "eth_signTypedData_v4";
|
|
3632
|
+
const isTx = request.method === "eth_sendTransaction";
|
|
3633
|
+
const title = isTyped ? labels.signTypedDataTitle : labels.signMessageTitle;
|
|
3634
|
+
const payloadLabel = isTyped ? labels.signPayloadLabelTyped : isTx ? labels.signPayloadLabelTx : labels.signPayloadLabel;
|
|
3635
|
+
const needsPassword = request.passwordEnabled;
|
|
3636
|
+
const canApprove = !locked && (needsPassword ? password.length > 0 && !busy : !busy);
|
|
3637
|
+
return /* @__PURE__ */ jsxs("div", { className: "auth-sdk-root", role: "presentation", children: [
|
|
3638
|
+
/* @__PURE__ */ jsx("div", { className: "auth-sdk-backdrop", onClick: busy ? void 0 : onReject, "aria-hidden": true }),
|
|
3639
|
+
/* @__PURE__ */ jsxs(
|
|
3640
|
+
"div",
|
|
3641
|
+
{
|
|
3642
|
+
className: "auth-sdk-sign-panel",
|
|
3643
|
+
role: "dialog",
|
|
3644
|
+
"aria-modal": "true",
|
|
3645
|
+
"aria-labelledby": "auth-sdk-sign-title",
|
|
3646
|
+
children: [
|
|
3647
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-sign-header", children: [
|
|
3648
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-app-badge", "aria-hidden": true, children: /* @__PURE__ */ jsx(EoceneMark, { size: 26 }) }),
|
|
3649
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-brand-text", children: [
|
|
3650
|
+
/* @__PURE__ */ jsx("p", { className: "auth-sdk-brand-name", children: labels.signBrandEyebrow }),
|
|
3651
|
+
/* @__PURE__ */ jsx("h2", { id: "auth-sdk-sign-title", className: "auth-sdk-sign-title", children: title })
|
|
3652
|
+
] })
|
|
3653
|
+
] }),
|
|
3654
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-sign-account", children: [
|
|
3655
|
+
/* @__PURE__ */ jsx(
|
|
3656
|
+
"span",
|
|
3657
|
+
{
|
|
3658
|
+
className: "auth-sdk-account-avatar",
|
|
3659
|
+
style: { background: addressGradient(request.address) },
|
|
3660
|
+
"aria-hidden": true
|
|
3661
|
+
}
|
|
3662
|
+
),
|
|
3663
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-account-addr", children: shortenAddress(request.address) })
|
|
3664
|
+
] }),
|
|
3665
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-sign-msg-wrap", children: [
|
|
3666
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-sign-msg-label", children: payloadLabel }),
|
|
3667
|
+
/* @__PURE__ */ jsx("pre", { className: "auth-sdk-sign-body", children: truncateMessage(request.message) })
|
|
3668
|
+
] }),
|
|
3669
|
+
needsPassword ? /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
|
|
3670
|
+
/* @__PURE__ */ jsx("span", { children: labels.signPasswordLabel }),
|
|
3671
|
+
/* @__PURE__ */ jsx(
|
|
3672
|
+
"input",
|
|
3673
|
+
{
|
|
3674
|
+
type: "password",
|
|
3675
|
+
autoComplete: "current-password",
|
|
3676
|
+
placeholder: labels.signPasswordPlaceholder,
|
|
3677
|
+
value: password,
|
|
3678
|
+
onChange: (e) => onPasswordChange(e.target.value),
|
|
3679
|
+
disabled: busy || locked,
|
|
3680
|
+
autoFocus: !locked
|
|
3681
|
+
}
|
|
3682
|
+
)
|
|
3683
|
+
] }) : onOpenSetPassword ? /* @__PURE__ */ jsxs(
|
|
3684
|
+
"button",
|
|
3685
|
+
{
|
|
3686
|
+
type: "button",
|
|
3687
|
+
className: "auth-sdk-sign-optional-btn",
|
|
3688
|
+
onClick: onOpenSetPassword,
|
|
3689
|
+
disabled: busy,
|
|
3690
|
+
children: [
|
|
3691
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-sign-optional-icon", "aria-hidden": true, children: "+" }),
|
|
3692
|
+
/* @__PURE__ */ jsxs("span", { className: "auth-sdk-sign-optional-text", children: [
|
|
3693
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-sign-optional-title", children: labels.signSetPasswordButton }),
|
|
3694
|
+
/* @__PURE__ */ jsx("span", { className: "auth-sdk-sign-hint", children: labels.signSetPasswordOptional })
|
|
3695
|
+
] })
|
|
3696
|
+
]
|
|
3697
|
+
}
|
|
3698
|
+
) : null,
|
|
3699
|
+
error ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-error", role: "alert", children: error }) : null,
|
|
3700
|
+
/* @__PURE__ */ jsxs("div", { className: "auth-sdk-actions", children: [
|
|
3701
|
+
/* @__PURE__ */ jsx(
|
|
3702
|
+
"button",
|
|
3703
|
+
{
|
|
3704
|
+
type: "button",
|
|
3705
|
+
className: "auth-sdk-btn auth-sdk-btn-secondary",
|
|
3706
|
+
onClick: onReject,
|
|
3707
|
+
disabled: busy,
|
|
3708
|
+
children: labels.signReject
|
|
3709
|
+
}
|
|
3710
|
+
),
|
|
3711
|
+
/* @__PURE__ */ jsxs(
|
|
3712
|
+
"button",
|
|
3713
|
+
{
|
|
3714
|
+
type: "button",
|
|
3715
|
+
className: "auth-sdk-btn auth-sdk-btn-primary",
|
|
3716
|
+
onClick: onApprove,
|
|
3717
|
+
autoFocus: !needsPassword && !locked,
|
|
3718
|
+
disabled: !canApprove,
|
|
3719
|
+
children: [
|
|
3720
|
+
busy ? /* @__PURE__ */ jsx("span", { className: "auth-sdk-spinner", "aria-hidden": true }) : null,
|
|
3721
|
+
busy ? labels.signSigning : labels.signConfirm
|
|
3722
|
+
]
|
|
3723
|
+
}
|
|
3724
|
+
)
|
|
3725
|
+
] })
|
|
3726
|
+
]
|
|
3727
|
+
}
|
|
3728
|
+
)
|
|
3729
|
+
] });
|
|
3730
|
+
}
|
|
3731
|
+
|
|
3732
|
+
// src/ui/slots.ts
|
|
3733
|
+
var DEFAULT_LABELS = {
|
|
3734
|
+
signMessageTitle: "Confirm signature",
|
|
3735
|
+
signTypedDataTitle: "Confirm typed data signature",
|
|
3736
|
+
signBrandEyebrow: "Eocene \xB7 Secure signing",
|
|
3737
|
+
signPayloadLabel: "Message",
|
|
3738
|
+
signPayloadLabelTyped: "Typed data",
|
|
3739
|
+
signPayloadLabelTx: "Transaction",
|
|
3740
|
+
signSigning: "Signing\u2026",
|
|
3741
|
+
signConfirm: "Sign",
|
|
3742
|
+
signReject: "Reject",
|
|
3743
|
+
signPasswordLabel: "Wallet password",
|
|
3744
|
+
signPasswordPlaceholder: "Enter password",
|
|
3745
|
+
signSetPasswordOptional: "Optional \u2014 protect future signatures with a password.",
|
|
3746
|
+
signSetPasswordButton: "Set password",
|
|
3747
|
+
signPasswordIncorrect: "Incorrect password",
|
|
3748
|
+
signPasswordIncorrectRemaining: "Incorrect password. {remaining} attempts left before a 5-minute lock.",
|
|
3749
|
+
signPasswordLocked: "Too many incorrect attempts. Try again in {minutes} min.",
|
|
3750
|
+
signPasswordRequired: "Password is required",
|
|
3751
|
+
signRejected: "Signature cancelled",
|
|
3752
|
+
sessionExpired: "Your session expired. Please sign in again.",
|
|
3753
|
+
rateLimited: "Too many requests. Please wait a moment and try again.",
|
|
3754
|
+
loginTitle: "Continue with",
|
|
3755
|
+
loginGoogle: "Google",
|
|
3756
|
+
loginTwitter: "X",
|
|
3757
|
+
loginGithub: "GitHub",
|
|
3758
|
+
loginApple: "Apple",
|
|
3759
|
+
loginConnecting: "Connecting\u2026",
|
|
3760
|
+
loginError: "Sign-in failed",
|
|
3761
|
+
loginNoMethods: "No sign-in methods are enabled for this app yet.",
|
|
3762
|
+
oauthWorking: "Completing sign-in\u2026",
|
|
3763
|
+
oauthFailed: "OAuth failed",
|
|
3764
|
+
oauthBack: "Back to login",
|
|
3765
|
+
passwordSettingsTitle: "Wallet password",
|
|
3766
|
+
passwordSettingsEnabledHint: "Password is required for every signature.",
|
|
3767
|
+
passwordSettingsDisabledHint: "Optional. When set, signing will ask for this password.",
|
|
3768
|
+
passwordSettingsChange: "Change",
|
|
3769
|
+
passwordSettingsClear: "Remove",
|
|
3770
|
+
passwordSettingsCurrentLabel: "Current password",
|
|
3771
|
+
passwordSettingsCurrentPlaceholder: "Current password",
|
|
3772
|
+
passwordSettingsNewLabel: "New password",
|
|
3773
|
+
passwordSettingsNewPlaceholder: "At least 6 characters",
|
|
3774
|
+
passwordSettingsConfirmLabel: "Confirm password",
|
|
3775
|
+
passwordSettingsConfirmPlaceholder: "Re-enter password",
|
|
3776
|
+
passwordSettingsMismatch: "Passwords do not match",
|
|
3777
|
+
passwordSettingsCancel: "Cancel",
|
|
3778
|
+
passwordSettingsSave: "Save",
|
|
3779
|
+
passwordSettingsSaving: "Saving\u2026",
|
|
3780
|
+
passwordSettingsClearConfirm: "Remove password",
|
|
3781
|
+
passwordSettingsEntry: "Wallet password",
|
|
3782
|
+
passwordSettingsEntryOn: "Enabled \u2014 required on sign",
|
|
3783
|
+
passwordSettingsEntryOff: "Optional \u2014 not set"
|
|
3784
|
+
};
|
|
3785
|
+
var AuthContext = createContext(null);
|
|
3786
|
+
function AuthProvider({
|
|
3787
|
+
config,
|
|
3788
|
+
components,
|
|
3789
|
+
onRequestSignApproval,
|
|
3790
|
+
onSessionExpired,
|
|
3791
|
+
children
|
|
3792
|
+
}) {
|
|
3793
|
+
const labels = useMemo(
|
|
3794
|
+
() => ({ ...DEFAULT_LABELS, ...config.labels }),
|
|
3795
|
+
[config.labels]
|
|
3796
|
+
);
|
|
3797
|
+
const [pendingSign, setPendingSign] = useState(null);
|
|
3798
|
+
const [password, setPasswordInput] = useState("");
|
|
3799
|
+
const [signBusy, setSignBusy] = useState(false);
|
|
3800
|
+
const [signError, setSignError] = useState(null);
|
|
3801
|
+
const [passwordSettingsOpen, setPasswordSettingsOpen] = useState(false);
|
|
3802
|
+
const [passwordBusy, setPasswordBusy] = useState(false);
|
|
3803
|
+
const [passwordError, setPasswordError] = useState(null);
|
|
3804
|
+
const pendingSignRef = useRef(null);
|
|
3805
|
+
const defaultModalApproval = useCallback((req) => {
|
|
3806
|
+
return new Promise((resolve) => {
|
|
3807
|
+
const entry = { request: req, resolve };
|
|
3808
|
+
pendingSignRef.current = entry;
|
|
3809
|
+
setPasswordInput("");
|
|
3810
|
+
setSignBusy(false);
|
|
3811
|
+
if (req.authError) {
|
|
3812
|
+
setSignError(formatSignAuthError(req.authError, labels));
|
|
3813
|
+
} else {
|
|
3814
|
+
setSignError(null);
|
|
3815
|
+
}
|
|
3816
|
+
setPendingSign(entry);
|
|
3817
|
+
});
|
|
3818
|
+
}, [labels]);
|
|
3819
|
+
const approvalFn = useCallback(
|
|
3820
|
+
(req) => {
|
|
3821
|
+
if (onRequestSignApproval) return onRequestSignApproval(req);
|
|
3822
|
+
return defaultModalApproval(req);
|
|
3823
|
+
},
|
|
3824
|
+
[onRequestSignApproval, defaultModalApproval]
|
|
3825
|
+
);
|
|
3826
|
+
const [tick, setTick] = useState(0);
|
|
3827
|
+
const [ready, setReady] = useState(false);
|
|
3828
|
+
const sessionExpiredRef = useRef(void 0);
|
|
3829
|
+
sessionExpiredRef.current = onSessionExpired;
|
|
3830
|
+
const handleSessionExpired = useCallback(() => {
|
|
3831
|
+
pendingSignRef.current?.resolve(false);
|
|
3832
|
+
pendingSignRef.current = null;
|
|
3833
|
+
setPendingSign(null);
|
|
3834
|
+
setTick((n) => n + 1);
|
|
3835
|
+
sessionExpiredRef.current?.();
|
|
3836
|
+
}, []);
|
|
3837
|
+
const clientRef = useRef(null);
|
|
3838
|
+
if (!clientRef.current) {
|
|
3839
|
+
clientRef.current = new AuthClient({
|
|
3840
|
+
config,
|
|
3841
|
+
chainId: config.chainId,
|
|
3842
|
+
requestApproval: approvalFn,
|
|
3843
|
+
onSessionExpired: handleSessionExpired
|
|
3844
|
+
});
|
|
3845
|
+
}
|
|
3846
|
+
useEffect(() => {
|
|
3847
|
+
clientRef.current?.setRequestApproval(approvalFn);
|
|
3848
|
+
}, [approvalFn]);
|
|
3849
|
+
useEffect(() => {
|
|
3850
|
+
const c = clientRef.current;
|
|
3851
|
+
if (!c) return;
|
|
3852
|
+
if (c.config.controlBaseUrl !== config.controlBaseUrl || c.config.oauthReturnTo !== config.oauthReturnTo) {
|
|
3853
|
+
clientRef.current = new AuthClient({
|
|
3854
|
+
config,
|
|
3855
|
+
requestApproval: approvalFn,
|
|
3856
|
+
onSessionExpired: handleSessionExpired
|
|
3857
|
+
});
|
|
3858
|
+
setTick((n) => n + 1);
|
|
3859
|
+
}
|
|
3860
|
+
}, [config, approvalFn, handleSessionExpired]);
|
|
3861
|
+
useEffect(() => {
|
|
3862
|
+
clientRef.current?.restoreIfNeeded();
|
|
3863
|
+
setReady(true);
|
|
3864
|
+
setTick((n) => n + 1);
|
|
3865
|
+
}, []);
|
|
3866
|
+
const [availableMethods, setAvailableMethods] = useState(null);
|
|
3867
|
+
useEffect(() => {
|
|
3868
|
+
let alive = true;
|
|
3869
|
+
setAvailableMethods(null);
|
|
3870
|
+
clientRef.current?.listAvailableMethods().then((m) => {
|
|
3871
|
+
if (alive) setAvailableMethods(m);
|
|
3872
|
+
}).catch(() => {
|
|
3873
|
+
if (alive) setAvailableMethods(null);
|
|
3874
|
+
});
|
|
3875
|
+
return () => {
|
|
3876
|
+
alive = false;
|
|
3877
|
+
};
|
|
3878
|
+
}, [config.controlBaseUrl, config.projectId]);
|
|
3879
|
+
const bump = useCallback(() => setTick((n) => n + 1), []);
|
|
3880
|
+
const login = useCallback(
|
|
3881
|
+
async (args) => {
|
|
3882
|
+
const result = await clientRef.current.login(args.method);
|
|
3883
|
+
bump();
|
|
3884
|
+
return result;
|
|
3885
|
+
},
|
|
3886
|
+
[bump]
|
|
3887
|
+
);
|
|
3888
|
+
const logout = useCallback(() => {
|
|
3889
|
+
clientRef.current.logout();
|
|
3890
|
+
bump();
|
|
3891
|
+
}, [bump]);
|
|
3892
|
+
const markActive = useCallback(
|
|
3893
|
+
(on) => {
|
|
3894
|
+
clientRef.current.markActive(on);
|
|
3895
|
+
bump();
|
|
3896
|
+
},
|
|
3897
|
+
[bump]
|
|
3898
|
+
);
|
|
3899
|
+
const restoreIfNeeded = useCallback(() => {
|
|
3900
|
+
const ok = clientRef.current.restoreIfNeeded();
|
|
3901
|
+
bump();
|
|
3902
|
+
return ok;
|
|
3903
|
+
}, [bump]);
|
|
3904
|
+
const completeOAuthFromHash = useCallback(
|
|
3905
|
+
async (hashOrSearch) => {
|
|
3906
|
+
const result = await clientRef.current.completeOAuthFromHash(hashOrSearch);
|
|
3907
|
+
bump();
|
|
3908
|
+
return result;
|
|
3909
|
+
},
|
|
3910
|
+
[bump]
|
|
3911
|
+
);
|
|
3912
|
+
const takeOAuthReturnPath = useCallback(() => clientRef.current.takeOAuthReturnPath(), []);
|
|
3913
|
+
const getProvider = useCallback(() => clientRef.current.getProvider(), []);
|
|
3914
|
+
const getConnectorShim = useCallback(() => clientRef.current.getConnectorShim(), []);
|
|
3915
|
+
const setPassword = useCallback(
|
|
3916
|
+
async (pw, currentPassword) => {
|
|
3917
|
+
await clientRef.current.setPassword(pw, currentPassword);
|
|
3918
|
+
bump();
|
|
3919
|
+
},
|
|
3920
|
+
[bump]
|
|
3921
|
+
);
|
|
3922
|
+
const clearPassword = useCallback(
|
|
3923
|
+
async (pw) => {
|
|
3924
|
+
await clientRef.current.clearPassword(pw);
|
|
3925
|
+
bump();
|
|
3926
|
+
},
|
|
3927
|
+
[bump]
|
|
3928
|
+
);
|
|
3929
|
+
const openPasswordSettings = useCallback(() => {
|
|
3930
|
+
setPasswordError(null);
|
|
3931
|
+
setPasswordSettingsOpen(true);
|
|
3932
|
+
}, []);
|
|
3933
|
+
const closePasswordSettings = useCallback(() => {
|
|
3934
|
+
if (passwordBusy) return;
|
|
3935
|
+
setPasswordSettingsOpen(false);
|
|
3936
|
+
setPasswordError(null);
|
|
3937
|
+
}, [passwordBusy]);
|
|
3938
|
+
const client = clientRef.current;
|
|
3939
|
+
const authenticated = client.isAuthenticated();
|
|
3940
|
+
const user = client.getUser();
|
|
3941
|
+
const address = client.getAddress();
|
|
3942
|
+
const passwordEnabled = Boolean(user?.passwordEnabled);
|
|
3943
|
+
const LoginPanel = components?.LoginPanel ?? AuthLoginPanel;
|
|
3944
|
+
const SignApproval = components?.SignApproval ?? SignConfirmModal;
|
|
3945
|
+
const PasswordSettings = components?.PasswordSettings ?? SetPasswordModal;
|
|
3946
|
+
const resolvePending = useCallback((result) => {
|
|
3947
|
+
const entry = pendingSignRef.current;
|
|
3948
|
+
pendingSignRef.current = null;
|
|
3949
|
+
setPendingSign(null);
|
|
3950
|
+
setPasswordInput("");
|
|
3951
|
+
setSignBusy(false);
|
|
3952
|
+
setSignError(null);
|
|
3953
|
+
entry?.resolve(result);
|
|
3954
|
+
}, []);
|
|
3955
|
+
const handleSignApprove = useCallback(() => {
|
|
3956
|
+
const entry = pendingSignRef.current;
|
|
3957
|
+
if (!entry || signBusy) return;
|
|
3958
|
+
setSignError(null);
|
|
3959
|
+
if (entry.request.passwordEnabled) {
|
|
3960
|
+
if (!password) return;
|
|
3961
|
+
resolvePending({ approved: true, password });
|
|
3962
|
+
return;
|
|
3963
|
+
}
|
|
3964
|
+
resolvePending({ approved: true });
|
|
3965
|
+
}, [signBusy, password, resolvePending]);
|
|
3966
|
+
const markPendingSignNeedsPassword = useCallback(() => {
|
|
3967
|
+
const entry = pendingSignRef.current;
|
|
3968
|
+
if (!entry) return;
|
|
3969
|
+
const next = {
|
|
3970
|
+
...entry,
|
|
3971
|
+
request: { ...entry.request, passwordEnabled: true }
|
|
3972
|
+
};
|
|
3973
|
+
pendingSignRef.current = next;
|
|
3974
|
+
setPendingSign(next);
|
|
3975
|
+
setPasswordInput("");
|
|
3976
|
+
setSignError(null);
|
|
3977
|
+
}, []);
|
|
3978
|
+
const signLocked = pendingSign?.request.authError?.code === "password_locked" || (pendingSign?.request.authError?.lockedUntil ? Date.parse(pendingSign.request.authError.lockedUntil) > Date.now() : false);
|
|
3979
|
+
const signProps = {
|
|
3980
|
+
open: pendingSign != null,
|
|
3981
|
+
request: pendingSign?.request ?? null,
|
|
3982
|
+
labels,
|
|
3983
|
+
password,
|
|
3984
|
+
busy: signBusy,
|
|
3985
|
+
error: signError,
|
|
3986
|
+
locked: signLocked,
|
|
3987
|
+
onPasswordChange: setPasswordInput,
|
|
3988
|
+
onApprove: handleSignApprove,
|
|
3989
|
+
onReject: () => {
|
|
3990
|
+
if (signBusy) return;
|
|
3991
|
+
resolvePending(false);
|
|
3992
|
+
},
|
|
3993
|
+
onOpenSetPassword: openPasswordSettings
|
|
3994
|
+
};
|
|
3995
|
+
const onSubmitSet = useCallback(
|
|
3996
|
+
async (pw, currentPassword) => {
|
|
3997
|
+
setPasswordBusy(true);
|
|
3998
|
+
setPasswordError(null);
|
|
3999
|
+
try {
|
|
4000
|
+
await setPassword(pw, currentPassword);
|
|
4001
|
+
setPasswordSettingsOpen(false);
|
|
4002
|
+
if (pendingSignRef.current) markPendingSignNeedsPassword();
|
|
4003
|
+
} catch (e) {
|
|
4004
|
+
setPasswordError(formatAuthError(e, labels));
|
|
4005
|
+
} finally {
|
|
4006
|
+
setPasswordBusy(false);
|
|
4007
|
+
}
|
|
4008
|
+
},
|
|
4009
|
+
[setPassword, markPendingSignNeedsPassword, labels]
|
|
4010
|
+
);
|
|
4011
|
+
const onSubmitClear = useCallback(
|
|
4012
|
+
async (pw) => {
|
|
4013
|
+
setPasswordBusy(true);
|
|
4014
|
+
setPasswordError(null);
|
|
4015
|
+
try {
|
|
4016
|
+
await clearPassword(pw);
|
|
4017
|
+
setPasswordSettingsOpen(false);
|
|
4018
|
+
} catch (e) {
|
|
4019
|
+
setPasswordError(formatAuthError(e, labels));
|
|
4020
|
+
} finally {
|
|
4021
|
+
setPasswordBusy(false);
|
|
4022
|
+
}
|
|
4023
|
+
},
|
|
4024
|
+
[clearPassword, labels]
|
|
4025
|
+
);
|
|
4026
|
+
const passwordProps = {
|
|
4027
|
+
open: passwordSettingsOpen,
|
|
4028
|
+
passwordEnabled,
|
|
4029
|
+
labels,
|
|
4030
|
+
busy: passwordBusy,
|
|
4031
|
+
error: passwordError,
|
|
4032
|
+
onSubmitSet,
|
|
4033
|
+
onSubmitClear,
|
|
4034
|
+
onClose: closePasswordSettings
|
|
4035
|
+
};
|
|
4036
|
+
const value = useMemo(
|
|
4037
|
+
() => ({
|
|
4038
|
+
ready,
|
|
4039
|
+
authenticated,
|
|
4040
|
+
address,
|
|
4041
|
+
user,
|
|
4042
|
+
passwordEnabled,
|
|
4043
|
+
login,
|
|
4044
|
+
logout,
|
|
4045
|
+
markActive,
|
|
4046
|
+
restoreIfNeeded,
|
|
4047
|
+
completeOAuthFromHash,
|
|
4048
|
+
takeOAuthReturnPath,
|
|
4049
|
+
getProvider,
|
|
4050
|
+
getConnectorShim,
|
|
4051
|
+
setPassword,
|
|
4052
|
+
clearPassword,
|
|
4053
|
+
openPasswordSettings,
|
|
4054
|
+
closePasswordSettings,
|
|
4055
|
+
client,
|
|
4056
|
+
labels,
|
|
4057
|
+
LoginPanel,
|
|
4058
|
+
availableMethods
|
|
4059
|
+
}),
|
|
4060
|
+
[
|
|
4061
|
+
ready,
|
|
4062
|
+
authenticated,
|
|
4063
|
+
address,
|
|
4064
|
+
user,
|
|
4065
|
+
passwordEnabled,
|
|
4066
|
+
login,
|
|
4067
|
+
logout,
|
|
4068
|
+
markActive,
|
|
4069
|
+
restoreIfNeeded,
|
|
4070
|
+
completeOAuthFromHash,
|
|
4071
|
+
takeOAuthReturnPath,
|
|
4072
|
+
getProvider,
|
|
4073
|
+
getConnectorShim,
|
|
4074
|
+
setPassword,
|
|
4075
|
+
clearPassword,
|
|
4076
|
+
openPasswordSettings,
|
|
4077
|
+
closePasswordSettings,
|
|
4078
|
+
client,
|
|
4079
|
+
labels,
|
|
4080
|
+
LoginPanel,
|
|
4081
|
+
availableMethods
|
|
4082
|
+
]
|
|
4083
|
+
);
|
|
4084
|
+
return /* @__PURE__ */ jsxs(AuthContext.Provider, { value, children: [
|
|
4085
|
+
children,
|
|
4086
|
+
!onRequestSignApproval ? /* @__PURE__ */ jsx(SignApproval, { ...signProps }) : null,
|
|
4087
|
+
/* @__PURE__ */ jsx(PasswordSettings, { ...passwordProps })
|
|
4088
|
+
] });
|
|
4089
|
+
}
|
|
4090
|
+
function useAuthContext() {
|
|
4091
|
+
const ctx = useContext(AuthContext);
|
|
4092
|
+
if (!ctx) throw new Error("useAuth must be used within <AuthProvider>");
|
|
4093
|
+
return ctx;
|
|
4094
|
+
}
|
|
4095
|
+
function AuthOAuthCallback({
|
|
4096
|
+
hashOrSearch,
|
|
4097
|
+
onWalletReady,
|
|
4098
|
+
children,
|
|
4099
|
+
onBackHref = "/login"
|
|
4100
|
+
}) {
|
|
4101
|
+
const { completeOAuthFromHash, markActive, labels } = useAuthContext();
|
|
4102
|
+
const [error, setError] = useState(null);
|
|
4103
|
+
const [phase, setPhase] = useState(labels.oauthWorking);
|
|
4104
|
+
const ranRef = useRef(false);
|
|
4105
|
+
useEffect(() => {
|
|
4106
|
+
if (ranRef.current) return;
|
|
4107
|
+
ranRef.current = true;
|
|
4108
|
+
(async () => {
|
|
4109
|
+
try {
|
|
4110
|
+
setPhase(labels.oauthWorking);
|
|
4111
|
+
const raw = hashOrSearch ?? (typeof window !== "undefined" ? window.location.hash || window.location.search : "");
|
|
4112
|
+
const session = await completeOAuthFromHash(raw);
|
|
4113
|
+
if (typeof window !== "undefined") {
|
|
4114
|
+
window.history.replaceState(null, "", window.location.pathname);
|
|
4115
|
+
}
|
|
4116
|
+
markActive(true);
|
|
4117
|
+
await onWalletReady(session);
|
|
4118
|
+
} catch (e) {
|
|
4119
|
+
setError(formatAuthError(e, labels));
|
|
4120
|
+
}
|
|
4121
|
+
})();
|
|
4122
|
+
}, [completeOAuthFromHash, hashOrSearch, labels.oauthFailed, labels.oauthWorking, markActive, onWalletReady]);
|
|
4123
|
+
if (children) return /* @__PURE__ */ jsx(Fragment, { children: children({ phase, error }) });
|
|
4124
|
+
if (error) {
|
|
4125
|
+
return /* @__PURE__ */ jsxs("div", { className: "auth-sdk-root auth-sdk-oauth-page", children: [
|
|
4126
|
+
/* @__PURE__ */ jsx(EoceneMark, { size: 40 }),
|
|
4127
|
+
/* @__PURE__ */ jsx("p", { className: "auth-sdk-oauth-error", children: error }),
|
|
4128
|
+
/* @__PURE__ */ jsx("a", { className: "auth-sdk-link", href: onBackHref, children: labels.oauthBack })
|
|
4129
|
+
] });
|
|
4130
|
+
}
|
|
4131
|
+
return /* @__PURE__ */ jsxs("div", { className: "auth-sdk-root auth-sdk-oauth-page", children: [
|
|
4132
|
+
/* @__PURE__ */ jsx(EoceneMark, { size: 40 }),
|
|
4133
|
+
/* @__PURE__ */ jsx("p", { children: phase })
|
|
4134
|
+
] });
|
|
4135
|
+
}
|
|
4136
|
+
|
|
4137
|
+
// src/host/fromViteEnv.ts
|
|
4138
|
+
function read(env, key) {
|
|
4139
|
+
return String(env[key] ?? "").trim();
|
|
4140
|
+
}
|
|
4141
|
+
function readAny(env, keys) {
|
|
4142
|
+
for (const key of keys) {
|
|
4143
|
+
const v = read(env, key);
|
|
4144
|
+
if (v) return v;
|
|
4145
|
+
}
|
|
4146
|
+
return "";
|
|
4147
|
+
}
|
|
4148
|
+
function flagAny(env, keys, defaultOn = false) {
|
|
4149
|
+
for (const key of keys) {
|
|
4150
|
+
const v = read(env, key).toLowerCase();
|
|
4151
|
+
if (v) return v === "1" || v === "true" || v === "yes";
|
|
4152
|
+
}
|
|
4153
|
+
return defaultOn;
|
|
4154
|
+
}
|
|
4155
|
+
function authConfigFromViteEnv(env = {}) {
|
|
4156
|
+
const e = env;
|
|
4157
|
+
const oauthReturnTo = readAny(e, ["EOCENE_OAUTH_RETURN_TO", "WAAS_OAUTH_RETURN_TO"]);
|
|
4158
|
+
const projectId = readAny(e, ["EOCENE_PROJECT_ID", "WAAS_PROJECT_ID"]) || void 0;
|
|
4159
|
+
const chainRaw = readAny(e, ["EOCENE_CHAIN_ID", "WAAS_CHAIN_ID"]);
|
|
4160
|
+
const chainId = chainRaw && Number.isFinite(Number(chainRaw)) ? Number(chainRaw) : void 0;
|
|
4161
|
+
return {
|
|
4162
|
+
controlBaseUrl: readAny(e, ["EOCENE_CONTROL_URL", "WAAS_CONTROL_URL"]) || DEFAULT_CONTROL_BASE_URL,
|
|
4163
|
+
oauthReturnTo: oauthReturnTo || (typeof window !== "undefined" ? `${window.location.origin}/login/eocene-callback` : "http://127.0.0.1:5173/login/eocene-callback"),
|
|
4164
|
+
allowDevLoginFallback: flagAny(e, ["EOCENE_OAUTH_FALLBACK_DEV", "WAAS_OAUTH_FALLBACK_DEV"], false),
|
|
4165
|
+
projectId,
|
|
4166
|
+
chainId,
|
|
4167
|
+
storageKey: DEFAULT_STORAGE_KEY,
|
|
4168
|
+
oauthPendingKey: DEFAULT_OAUTH_PENDING_KEY
|
|
4169
|
+
};
|
|
4170
|
+
}
|
|
4171
|
+
/*! Bundled license information:
|
|
4172
|
+
|
|
4173
|
+
@noble/hashes/esm/utils.js:
|
|
4174
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
4175
|
+
|
|
4176
|
+
@noble/curves/esm/utils.js:
|
|
4177
|
+
@noble/curves/esm/abstract/modular.js:
|
|
4178
|
+
@noble/curves/esm/abstract/curve.js:
|
|
4179
|
+
@noble/curves/esm/abstract/weierstrass.js:
|
|
4180
|
+
@noble/curves/esm/_shortw_utils.js:
|
|
4181
|
+
@noble/curves/esm/secp256k1.js:
|
|
4182
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
4183
|
+
*/
|
|
4184
|
+
|
|
4185
|
+
export { AuthClient, AuthLoginPanel, AuthOAuthCallback, AuthProvider, DEFAULT_CONTROL_BASE_URL, DEFAULT_LABELS, DEFAULT_OAUTH_PENDING_KEY, DEFAULT_STORAGE_KEY, EoceneMark, EoceneWordmark, SetPasswordModal, SignConfirmModal, authConfigFromViteEnv, createAuthEip1193Provider, isWaasHttpError, resolveControlAbsoluteUrl, useAuthContext as useAuth };
|
|
4186
|
+
//# sourceMappingURL=index.js.map
|
|
4187
|
+
//# sourceMappingURL=index.js.map
|