@cavos/kit 0.0.1
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/README.md +151 -0
- package/dist/chunk-XWBX2ZIO.mjs +1061 -0
- package/dist/chunk-XWBX2ZIO.mjs.map +1 -0
- package/dist/constants-C530TZFF.d.mts +89 -0
- package/dist/constants-C530TZFF.d.ts +89 -0
- package/dist/index.d.mts +529 -0
- package/dist/index.d.ts +529 -0
- package/dist/index.js +1103 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +15 -0
- package/dist/index.mjs.map +1 -0
- package/dist/react/index.d.mts +140 -0
- package/dist/react/index.d.ts +140 -0
- package/dist/react/index.js +2055 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/index.mjs +999 -0
- package/dist/react/index.mjs.map +1 -0
- package/package.json +77 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var starknet = require('starknet');
|
|
4
|
+
var sha256 = require('@noble/hashes/sha256');
|
|
5
|
+
var p256 = require('@noble/curves/p256');
|
|
6
|
+
var hkdf = require('@noble/hashes/hkdf');
|
|
7
|
+
var pbkdf2 = require('@noble/hashes/pbkdf2');
|
|
8
|
+
var utils = require('@noble/hashes/utils');
|
|
9
|
+
|
|
10
|
+
// src/Cavos.ts
|
|
11
|
+
|
|
12
|
+
// src/crypto/encoding.ts
|
|
13
|
+
var U128_MASK = (1n << 128n) - 1n;
|
|
14
|
+
function u256ToFelts(value) {
|
|
15
|
+
return [value & U128_MASK, value >> 128n];
|
|
16
|
+
}
|
|
17
|
+
function bytesToBigInt(bytes) {
|
|
18
|
+
let out = 0n;
|
|
19
|
+
for (const b of bytes) out = out << 8n | BigInt(b);
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
function bytesToHex(bytes) {
|
|
23
|
+
let s = "0x";
|
|
24
|
+
for (const b of bytes) s += b.toString(16).padStart(2, "0");
|
|
25
|
+
return s;
|
|
26
|
+
}
|
|
27
|
+
function hexToBytes(hex) {
|
|
28
|
+
const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
|
|
29
|
+
const padded = clean.length % 2 ? "0" + clean : clean;
|
|
30
|
+
const out = new Uint8Array(padded.length / 2);
|
|
31
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16);
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
function bigIntTo32Bytes(value) {
|
|
35
|
+
const out = new Uint8Array(32);
|
|
36
|
+
let v = value;
|
|
37
|
+
for (let i = 31; i >= 0; i--) {
|
|
38
|
+
out[i] = Number(v & 0xffn);
|
|
39
|
+
v >>= 8n;
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
function signatureToFelts(sig) {
|
|
44
|
+
const [rLow, rHigh] = u256ToFelts(sig.r);
|
|
45
|
+
const [sLow, sHigh] = u256ToFelts(sig.s);
|
|
46
|
+
return [rLow, rHigh, sLow, sHigh, sig.yParity ? 1n : 0n];
|
|
47
|
+
}
|
|
48
|
+
function recoverYParity(r, s, digest, pubkey) {
|
|
49
|
+
for (const bit of [0, 1]) {
|
|
50
|
+
try {
|
|
51
|
+
const candidate = new p256.p256.Signature(r, s).addRecoveryBit(bit);
|
|
52
|
+
const point = candidate.recoverPublicKey(digest).toAffine();
|
|
53
|
+
if (point.x === pubkey.x && point.y === pubkey.y) {
|
|
54
|
+
return bit === 1;
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
throw new Error("kit/signature: could not recover parity for the given pubkey");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/signer/WebCryptoSigner.ts
|
|
63
|
+
var IDB_NAME = "cavos-kit";
|
|
64
|
+
var IDB_STORE = "device-keys";
|
|
65
|
+
var WebCryptoSigner = class _WebCryptoSigner {
|
|
66
|
+
constructor(privateKey, publicKey, keyId) {
|
|
67
|
+
this.privateKey = privateKey;
|
|
68
|
+
this.publicKey = publicKey;
|
|
69
|
+
this.keyId = keyId;
|
|
70
|
+
}
|
|
71
|
+
/** Create a fresh device key (first run on this device) and persist it. */
|
|
72
|
+
static async create(opts) {
|
|
73
|
+
assertSecureContext();
|
|
74
|
+
const pair = await crypto.subtle.generateKey(
|
|
75
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
76
|
+
false,
|
|
77
|
+
// private key is NON-extractable
|
|
78
|
+
["sign", "verify"]
|
|
79
|
+
);
|
|
80
|
+
const publicKey = await exportPublicKey(pair.publicKey);
|
|
81
|
+
await idbPut(opts.keyId, { privateKey: pair.privateKey, x: publicKey.x, y: publicKey.y });
|
|
82
|
+
return new _WebCryptoSigner(pair.privateKey, publicKey, opts.keyId);
|
|
83
|
+
}
|
|
84
|
+
/** Load an existing device key from storage, or null if none exists yet. */
|
|
85
|
+
static async load(opts) {
|
|
86
|
+
const rec = await idbGet(opts.keyId);
|
|
87
|
+
if (!rec) return null;
|
|
88
|
+
return new _WebCryptoSigner(rec.privateKey, { x: rec.x, y: rec.y }, opts.keyId);
|
|
89
|
+
}
|
|
90
|
+
/** Load the device key, creating one on first use. */
|
|
91
|
+
static async loadOrCreate(opts) {
|
|
92
|
+
return await _WebCryptoSigner.load(opts) ?? await _WebCryptoSigner.create(opts);
|
|
93
|
+
}
|
|
94
|
+
async getPublicKey() {
|
|
95
|
+
return this.publicKey;
|
|
96
|
+
}
|
|
97
|
+
async sign(txHash) {
|
|
98
|
+
const raw = new Uint8Array(
|
|
99
|
+
await crypto.subtle.sign(
|
|
100
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
101
|
+
this.privateKey,
|
|
102
|
+
txHash
|
|
103
|
+
)
|
|
104
|
+
);
|
|
105
|
+
const r = bytesToBigInt(raw.subarray(0, 32));
|
|
106
|
+
const s = bytesToBigInt(raw.subarray(32, 64));
|
|
107
|
+
const digest = sha256.sha256(txHash);
|
|
108
|
+
const yParity = recoverYParity(r, s, digest, this.publicKey);
|
|
109
|
+
return { r, s, yParity };
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
async function exportPublicKey(publicKey) {
|
|
113
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
|
|
114
|
+
return { x: bytesToBigInt(raw.subarray(1, 33)), y: bytesToBigInt(raw.subarray(33, 65)) };
|
|
115
|
+
}
|
|
116
|
+
function assertSecureContext() {
|
|
117
|
+
const ok = typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined" && (typeof window === "undefined" || window.isSecureContext);
|
|
118
|
+
if (!ok) {
|
|
119
|
+
throw new Error(
|
|
120
|
+
"Cavos: WebCrypto is unavailable. Device keys require a secure context \u2014 use HTTPS, or http://localhost. (For LAN/mobile dev testing, run `next dev --experimental-https`.)"
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function openDb() {
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
126
|
+
const req = indexedDB.open(IDB_NAME, 1);
|
|
127
|
+
req.onupgradeneeded = () => req.result.createObjectStore(IDB_STORE);
|
|
128
|
+
req.onsuccess = () => resolve(req.result);
|
|
129
|
+
req.onerror = () => reject(req.error);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
async function idbPut(keyId, value) {
|
|
133
|
+
const db = await openDb();
|
|
134
|
+
await tx(db, "readwrite", (store) => store.put(value, keyId));
|
|
135
|
+
db.close();
|
|
136
|
+
}
|
|
137
|
+
async function idbGet(keyId) {
|
|
138
|
+
const db = await openDb();
|
|
139
|
+
const result = await tx(db, "readonly", (store) => store.get(keyId));
|
|
140
|
+
db.close();
|
|
141
|
+
return result ?? null;
|
|
142
|
+
}
|
|
143
|
+
function tx(db, mode, run) {
|
|
144
|
+
return new Promise((resolve, reject) => {
|
|
145
|
+
const store = db.transaction(IDB_STORE, mode).objectStore(IDB_STORE);
|
|
146
|
+
const req = run(store);
|
|
147
|
+
req.onsuccess = () => resolve(req.result);
|
|
148
|
+
req.onerror = () => reject(req.error);
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/chains/starknet/constants.ts
|
|
153
|
+
var STARKNET_NETWORKS = {
|
|
154
|
+
sepolia: {
|
|
155
|
+
chainId: "0x534e5f5345504f4c4941",
|
|
156
|
+
// SN_SEPOLIA
|
|
157
|
+
rpcUrl: "https://api.cartridge.gg/x/starknet/sepolia"
|
|
158
|
+
},
|
|
159
|
+
mainnet: {
|
|
160
|
+
chainId: "0x534e5f4d41494e",
|
|
161
|
+
// SN_MAIN
|
|
162
|
+
rpcUrl: "https://api.cartridge.gg/x/starknet/mainnet"
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
var UDC_ADDRESS = "0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf";
|
|
166
|
+
var CAVOS_PAYMASTER_URL = {
|
|
167
|
+
sepolia: "https://sepolia-paymaster.cavos.xyz",
|
|
168
|
+
mainnet: "https://paymaster.cavos.xyz"
|
|
169
|
+
};
|
|
170
|
+
var DEVICE_ACCOUNT_CLASS_HASH = {
|
|
171
|
+
sepolia: "0x6c3c3426667b6d4adda18a0b8d8cc34c495a1ace7276c4470068ad4c324876d",
|
|
172
|
+
mainnet: ""
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// src/chains/starknet/StarknetAdapter.ts
|
|
176
|
+
var StarknetAdapter = class {
|
|
177
|
+
constructor(opts) {
|
|
178
|
+
this.opts = opts;
|
|
179
|
+
this.chain = "starknet";
|
|
180
|
+
}
|
|
181
|
+
computeAddress({ addressSeed, initialSigner, salt }) {
|
|
182
|
+
return starknet.hash.calculateContractAddressFromHash(
|
|
183
|
+
starknet.num.toHex(salt ?? addressSeed),
|
|
184
|
+
this.opts.classHash,
|
|
185
|
+
this.constructorCalldata(addressSeed, initialSigner),
|
|
186
|
+
0
|
|
187
|
+
// deployerAddress 0 => deterministic counterfactual address
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
/** Single UDC deploy; the constructor registers the first device signer, so
|
|
191
|
+
* the account is ready the moment it is deployed (fits the paymaster's
|
|
192
|
+
* deploy + execute_from_outside bundle). */
|
|
193
|
+
buildDeploy(params) {
|
|
194
|
+
const salt = params.salt ?? params.addressSeed;
|
|
195
|
+
const calldata = this.constructorCalldata(params.addressSeed, params.initialSigner);
|
|
196
|
+
return [
|
|
197
|
+
{
|
|
198
|
+
contractAddress: UDC_ADDRESS,
|
|
199
|
+
entrypoint: "deployContract",
|
|
200
|
+
calldata: [
|
|
201
|
+
this.opts.classHash,
|
|
202
|
+
starknet.num.toHex(salt),
|
|
203
|
+
"0x0",
|
|
204
|
+
// unique = false -> deployer-independent address
|
|
205
|
+
starknet.num.toHex(calldata.length),
|
|
206
|
+
...calldata
|
|
207
|
+
]
|
|
208
|
+
}
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
/** Constructor calldata: [address_seed, pub_x_low, pub_x_high, pub_y_low, pub_y_high]. */
|
|
212
|
+
constructorCalldata(addressSeed, initialSigner) {
|
|
213
|
+
return [starknet.num.toHex(addressSeed), ...pubkeyCalldata(initialSigner)];
|
|
214
|
+
}
|
|
215
|
+
buildAddSigner(accountAddress, signer) {
|
|
216
|
+
return { contractAddress: accountAddress, entrypoint: "add_signer", calldata: pubkeyCalldata(signer) };
|
|
217
|
+
}
|
|
218
|
+
buildRemoveSigner(accountAddress, signer) {
|
|
219
|
+
return { contractAddress: accountAddress, entrypoint: "remove_signer", calldata: pubkeyCalldata(signer) };
|
|
220
|
+
}
|
|
221
|
+
async isAuthorizedSigner(accountAddress, signer) {
|
|
222
|
+
if (!this.opts.provider) throw new Error("kit/starknet: provider required for reads");
|
|
223
|
+
const res = await this.opts.provider.callContract({
|
|
224
|
+
contractAddress: accountAddress,
|
|
225
|
+
entrypoint: "is_authorized_signer",
|
|
226
|
+
calldata: pubkeyCalldata(signer)
|
|
227
|
+
});
|
|
228
|
+
return BigInt(res[0] ?? 0) !== 0n;
|
|
229
|
+
}
|
|
230
|
+
async buildSignature(txHash) {
|
|
231
|
+
if (!this.opts.signer) throw new Error("kit/starknet: signer required to sign");
|
|
232
|
+
const sig = await this.opts.signer.sign(bigIntTo32Bytes(txHash));
|
|
233
|
+
return signatureToFelts(sig).map((f) => starknet.num.toHex(f));
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
function pubkeyCalldata(pk) {
|
|
237
|
+
const [xl, xh] = u256ToFelts(pk.x);
|
|
238
|
+
const [yl, yh] = u256ToFelts(pk.y);
|
|
239
|
+
return [starknet.num.toHex(xl), starknet.num.toHex(xh), starknet.num.toHex(yl), starknet.num.toHex(yh)];
|
|
240
|
+
}
|
|
241
|
+
var StarknetDeviceSigner = class extends starknet.Signer {
|
|
242
|
+
constructor(device) {
|
|
243
|
+
super("0x1");
|
|
244
|
+
this.device = device;
|
|
245
|
+
}
|
|
246
|
+
/** Device accounts are not controlled by a single Stark pubkey. */
|
|
247
|
+
async getPubKey() {
|
|
248
|
+
return "0x0";
|
|
249
|
+
}
|
|
250
|
+
/** Sign the computed tx hash silently with the device signer. */
|
|
251
|
+
async signRaw(msgHash) {
|
|
252
|
+
const sig = await this.device.sign(bigIntTo32Bytes(BigInt(msgHash)));
|
|
253
|
+
return signatureToFelts(sig).map((f) => starknet.num.toHex(f));
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// src/registry/WalletRegistry.ts
|
|
258
|
+
var InMemoryWalletRegistry = class {
|
|
259
|
+
constructor() {
|
|
260
|
+
this.wallets = /* @__PURE__ */ new Map();
|
|
261
|
+
}
|
|
262
|
+
async lookup(userId) {
|
|
263
|
+
return this.wallets.get(userId) ?? null;
|
|
264
|
+
}
|
|
265
|
+
async register(params) {
|
|
266
|
+
this.wallets.set(params.userId, { address: params.address, devices: [params.initialSigner] });
|
|
267
|
+
}
|
|
268
|
+
async addDevice(params) {
|
|
269
|
+
const w = this.wallets.get(params.userId);
|
|
270
|
+
if (w) w.devices = [...w.devices ?? [], params.signer];
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
// src/registry/HttpWalletRegistry.ts
|
|
275
|
+
function toHex(n) {
|
|
276
|
+
return "0x" + n.toString(16);
|
|
277
|
+
}
|
|
278
|
+
function fromHex(s) {
|
|
279
|
+
return BigInt(s);
|
|
280
|
+
}
|
|
281
|
+
var HttpWalletRegistry = class {
|
|
282
|
+
constructor(opts) {
|
|
283
|
+
this.opts = opts;
|
|
284
|
+
}
|
|
285
|
+
async lookup(userId) {
|
|
286
|
+
const url = new URL("/api/wallets", this.opts.baseUrl);
|
|
287
|
+
url.searchParams.set("app_id", this.opts.appId);
|
|
288
|
+
url.searchParams.set("user_social_id", userId);
|
|
289
|
+
url.searchParams.set("network", this.opts.network);
|
|
290
|
+
const res = await fetch(url, { headers: { "Content-Type": "application/json" } });
|
|
291
|
+
if (!res.ok) throw new Error(`registry lookup failed: ${res.status}`);
|
|
292
|
+
const data = await res.json();
|
|
293
|
+
if (!data.found || !data.address) return null;
|
|
294
|
+
const devices = Array.isArray(data.devices) ? data.devices.map((d) => ({
|
|
295
|
+
x: fromHex(d.pub_x),
|
|
296
|
+
y: fromHex(d.pub_y)
|
|
297
|
+
})) : void 0;
|
|
298
|
+
return { address: data.address, devices };
|
|
299
|
+
}
|
|
300
|
+
async register(params) {
|
|
301
|
+
const res = await fetch(new URL("/api/wallets", this.opts.baseUrl), {
|
|
302
|
+
method: "POST",
|
|
303
|
+
headers: { "Content-Type": "application/json" },
|
|
304
|
+
body: JSON.stringify({
|
|
305
|
+
app_id: this.opts.appId,
|
|
306
|
+
user_social_id: params.userId,
|
|
307
|
+
network: this.opts.network,
|
|
308
|
+
address: params.address,
|
|
309
|
+
// Device-signer wallets send their initial signer (no encrypted blob).
|
|
310
|
+
devices: [{ x: toHex(params.initialSigner.x), y: toHex(params.initialSigner.y) }]
|
|
311
|
+
})
|
|
312
|
+
});
|
|
313
|
+
if (!res.ok) {
|
|
314
|
+
const t = await res.text().catch(() => "");
|
|
315
|
+
throw new Error(`registry register failed: ${res.status} ${t}`);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async addDevice(params) {
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
// src/recovery/HttpRecoveryClient.ts
|
|
323
|
+
function toHex2(n) {
|
|
324
|
+
return "0x" + n.toString(16);
|
|
325
|
+
}
|
|
326
|
+
function fromHex2(s) {
|
|
327
|
+
return BigInt(s);
|
|
328
|
+
}
|
|
329
|
+
function deviceLabel() {
|
|
330
|
+
if (typeof navigator !== "undefined") {
|
|
331
|
+
return navigator.userAgent || "a new device";
|
|
332
|
+
}
|
|
333
|
+
return "a new device";
|
|
334
|
+
}
|
|
335
|
+
var HttpRecoveryClient = class {
|
|
336
|
+
constructor(opts) {
|
|
337
|
+
this.opts = opts;
|
|
338
|
+
}
|
|
339
|
+
async requestDeviceAddition(params) {
|
|
340
|
+
const res = await fetch(new URL("/api/devices/request", this.opts.baseUrl), {
|
|
341
|
+
method: "POST",
|
|
342
|
+
headers: { "Content-Type": "application/json" },
|
|
343
|
+
body: JSON.stringify({
|
|
344
|
+
app_id: this.opts.appId,
|
|
345
|
+
wallet_address: params.accountAddress,
|
|
346
|
+
new_pub_x: toHex2(params.newSigner.x),
|
|
347
|
+
new_pub_y: toHex2(params.newSigner.y),
|
|
348
|
+
device_label: params.deviceLabel ?? deviceLabel(),
|
|
349
|
+
...params.email ? { email: params.email } : {}
|
|
350
|
+
})
|
|
351
|
+
});
|
|
352
|
+
if (!res.ok) {
|
|
353
|
+
const t = await res.text().catch(() => "");
|
|
354
|
+
throw new Error(`requestDeviceAddition failed: ${res.status} ${t}`);
|
|
355
|
+
}
|
|
356
|
+
const data = await res.json();
|
|
357
|
+
return { requestId: data.request_id };
|
|
358
|
+
}
|
|
359
|
+
async getPendingRequest(requestId) {
|
|
360
|
+
const url = new URL("/api/devices/request", this.opts.baseUrl);
|
|
361
|
+
url.searchParams.set("id", requestId);
|
|
362
|
+
const res = await fetch(url, { headers: { "Content-Type": "application/json" } });
|
|
363
|
+
if (!res.ok) throw new Error(`getPendingRequest failed: ${res.status}`);
|
|
364
|
+
const data = await res.json();
|
|
365
|
+
if (!data.found) return null;
|
|
366
|
+
const status = data.status;
|
|
367
|
+
return {
|
|
368
|
+
requestId: data.request_id,
|
|
369
|
+
appId: data.app_id,
|
|
370
|
+
userId: "",
|
|
371
|
+
// the approving device already knows its own identity
|
|
372
|
+
accountAddress: data.wallet_address,
|
|
373
|
+
newSigner: { x: fromHex2(data.new_pub_x), y: fromHex2(data.new_pub_y) },
|
|
374
|
+
createdAt: data.created_at,
|
|
375
|
+
status
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
async confirmDeviceAddition(params) {
|
|
379
|
+
const res = await fetch(
|
|
380
|
+
new URL(`/api/devices/request/${params.requestId}/confirm`, this.opts.baseUrl),
|
|
381
|
+
{
|
|
382
|
+
method: "POST",
|
|
383
|
+
headers: { "Content-Type": "application/json" },
|
|
384
|
+
body: JSON.stringify({ tx_hash: params.txHash })
|
|
385
|
+
}
|
|
386
|
+
);
|
|
387
|
+
if (!res.ok) {
|
|
388
|
+
const t = await res.text().catch(() => "");
|
|
389
|
+
throw new Error(`confirmDeviceAddition failed: ${res.status} ${t}`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
var BACKUP_KDF_SALT = "cavos-recovery-v1";
|
|
394
|
+
var BACKUP_PBKDF2_ITERATIONS = 21e4;
|
|
395
|
+
var BACKUP_HKDF_INFO = "cavos-backup-signer";
|
|
396
|
+
var CODE_WORDS = 16;
|
|
397
|
+
function generateRecoveryCode() {
|
|
398
|
+
const bytes = utils.randomBytes(CODE_WORDS);
|
|
399
|
+
const words = [];
|
|
400
|
+
for (const b of bytes) words.push(WORDLIST[b]);
|
|
401
|
+
return words.join(" ");
|
|
402
|
+
}
|
|
403
|
+
function deriveBackupKey(code) {
|
|
404
|
+
const normalised = code.trim().replace(/\s+/g, " ").toLowerCase();
|
|
405
|
+
if (!normalised) throw new Error("kit: recovery code is empty");
|
|
406
|
+
const stretched = pbkdf2.pbkdf2(
|
|
407
|
+
sha256.sha256,
|
|
408
|
+
new TextEncoder().encode(normalised),
|
|
409
|
+
new TextEncoder().encode(BACKUP_KDF_SALT),
|
|
410
|
+
{ c: BACKUP_PBKDF2_ITERATIONS, dkLen: 32 }
|
|
411
|
+
);
|
|
412
|
+
const seed = hkdf.hkdf(sha256.sha256, stretched, void 0, BACKUP_HKDF_INFO, 32);
|
|
413
|
+
const d = bytesToBigInt(seed) % p256.p256.CURVE.n;
|
|
414
|
+
if (d === 0n) throw new Error("kit: derived backup key is zero (retry with a new code)");
|
|
415
|
+
const priv = bigIntTo32Bytes(d);
|
|
416
|
+
const pub = p256.p256.getPublicKey(priv, false);
|
|
417
|
+
return {
|
|
418
|
+
privateKey: priv,
|
|
419
|
+
publicKey: { x: bytesToBigInt(pub.subarray(1, 33)), y: bytesToBigInt(pub.subarray(33, 65)) }
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
var BackupSigner = class _BackupSigner {
|
|
423
|
+
constructor(privateKey, publicKey) {
|
|
424
|
+
this.privateKey = privateKey;
|
|
425
|
+
this.publicKeyValue = publicKey;
|
|
426
|
+
}
|
|
427
|
+
/** Build a signer from a recovery code (derive + wrap in one step). */
|
|
428
|
+
static fromCode(code) {
|
|
429
|
+
const { privateKey, publicKey } = deriveBackupKey(code);
|
|
430
|
+
return new _BackupSigner(privateKey, publicKey);
|
|
431
|
+
}
|
|
432
|
+
async getPublicKey() {
|
|
433
|
+
return this.publicKeyValue;
|
|
434
|
+
}
|
|
435
|
+
async sign(txHash) {
|
|
436
|
+
const digest = sha256.sha256(txHash);
|
|
437
|
+
const sig = p256.p256.sign(digest, this.privateKey);
|
|
438
|
+
const yParity = recoverYParity(sig.r, sig.s, digest, this.publicKeyValue);
|
|
439
|
+
return { r: sig.r, s: sig.s, yParity };
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
var WORDLIST = [
|
|
443
|
+
"able",
|
|
444
|
+
"acid",
|
|
445
|
+
"amber",
|
|
446
|
+
"apple",
|
|
447
|
+
"arch",
|
|
448
|
+
"arrow",
|
|
449
|
+
"ashen",
|
|
450
|
+
"atlas",
|
|
451
|
+
"axis",
|
|
452
|
+
"badge",
|
|
453
|
+
"baker",
|
|
454
|
+
"balm",
|
|
455
|
+
"banner",
|
|
456
|
+
"basin",
|
|
457
|
+
"beacon",
|
|
458
|
+
"bench",
|
|
459
|
+
"beryl",
|
|
460
|
+
"birch",
|
|
461
|
+
"blade",
|
|
462
|
+
"bloom",
|
|
463
|
+
"bluer",
|
|
464
|
+
"border",
|
|
465
|
+
"brave",
|
|
466
|
+
"brick",
|
|
467
|
+
"brook",
|
|
468
|
+
"cabin",
|
|
469
|
+
"candle",
|
|
470
|
+
"carbon",
|
|
471
|
+
"cargo",
|
|
472
|
+
"cedar",
|
|
473
|
+
"chalk",
|
|
474
|
+
"charm",
|
|
475
|
+
"chrome",
|
|
476
|
+
"cipher",
|
|
477
|
+
"clam",
|
|
478
|
+
"clasp",
|
|
479
|
+
"cliff",
|
|
480
|
+
"clock",
|
|
481
|
+
"cobia",
|
|
482
|
+
"comet",
|
|
483
|
+
"coral",
|
|
484
|
+
"cotton",
|
|
485
|
+
"coves",
|
|
486
|
+
"crane",
|
|
487
|
+
"crest",
|
|
488
|
+
"crow",
|
|
489
|
+
"crystal",
|
|
490
|
+
"curio",
|
|
491
|
+
"dawn",
|
|
492
|
+
"delta",
|
|
493
|
+
"denim",
|
|
494
|
+
"depth",
|
|
495
|
+
"dewy",
|
|
496
|
+
"digger",
|
|
497
|
+
"docks",
|
|
498
|
+
"dover",
|
|
499
|
+
"drift",
|
|
500
|
+
"dunes",
|
|
501
|
+
"eagle",
|
|
502
|
+
"ember",
|
|
503
|
+
"echo",
|
|
504
|
+
"eden",
|
|
505
|
+
"elite",
|
|
506
|
+
"ethic",
|
|
507
|
+
"fable",
|
|
508
|
+
"falcon",
|
|
509
|
+
"fawn",
|
|
510
|
+
"feather",
|
|
511
|
+
"fern",
|
|
512
|
+
"fjord",
|
|
513
|
+
"flame",
|
|
514
|
+
"flint",
|
|
515
|
+
"forest",
|
|
516
|
+
"forge",
|
|
517
|
+
"frost",
|
|
518
|
+
"garnet",
|
|
519
|
+
"gemini",
|
|
520
|
+
"glade",
|
|
521
|
+
"glider",
|
|
522
|
+
"glow",
|
|
523
|
+
"granite",
|
|
524
|
+
"grove",
|
|
525
|
+
"guppy",
|
|
526
|
+
"harbor",
|
|
527
|
+
"haven",
|
|
528
|
+
"hazel",
|
|
529
|
+
"helio",
|
|
530
|
+
"heron",
|
|
531
|
+
"hickory",
|
|
532
|
+
"honey",
|
|
533
|
+
"horizon",
|
|
534
|
+
"ivory",
|
|
535
|
+
"jade",
|
|
536
|
+
"jasper",
|
|
537
|
+
"kestrel",
|
|
538
|
+
"knot",
|
|
539
|
+
"lagoon",
|
|
540
|
+
"lattice",
|
|
541
|
+
"laurel",
|
|
542
|
+
"lavender",
|
|
543
|
+
"lemon",
|
|
544
|
+
"linden",
|
|
545
|
+
"loon",
|
|
546
|
+
"luger",
|
|
547
|
+
"lumen",
|
|
548
|
+
"lunar",
|
|
549
|
+
"mango",
|
|
550
|
+
"maple",
|
|
551
|
+
"marble",
|
|
552
|
+
"marsh",
|
|
553
|
+
"meadow",
|
|
554
|
+
"mercy",
|
|
555
|
+
"mistle",
|
|
556
|
+
"monsoon",
|
|
557
|
+
"morning",
|
|
558
|
+
"moss",
|
|
559
|
+
"nacre",
|
|
560
|
+
"nectar",
|
|
561
|
+
"needle",
|
|
562
|
+
"nimbus",
|
|
563
|
+
"nova",
|
|
564
|
+
"ocean",
|
|
565
|
+
"onyx",
|
|
566
|
+
"orbit",
|
|
567
|
+
"otter",
|
|
568
|
+
"palm",
|
|
569
|
+
"panda",
|
|
570
|
+
"pansy",
|
|
571
|
+
"papaya",
|
|
572
|
+
"passage",
|
|
573
|
+
"pebble",
|
|
574
|
+
"pelican",
|
|
575
|
+
"pepper",
|
|
576
|
+
"petal",
|
|
577
|
+
"piano",
|
|
578
|
+
"pierce",
|
|
579
|
+
"pilot",
|
|
580
|
+
"pioneer",
|
|
581
|
+
"platinum",
|
|
582
|
+
"plume",
|
|
583
|
+
"poplar",
|
|
584
|
+
"porpoise",
|
|
585
|
+
"prairie",
|
|
586
|
+
"prism",
|
|
587
|
+
"pulsar",
|
|
588
|
+
"quartz",
|
|
589
|
+
"quasar",
|
|
590
|
+
"quill",
|
|
591
|
+
"quiver",
|
|
592
|
+
"raven",
|
|
593
|
+
"reef",
|
|
594
|
+
"relic",
|
|
595
|
+
"ridge",
|
|
596
|
+
"ripple",
|
|
597
|
+
"robin",
|
|
598
|
+
"rocket",
|
|
599
|
+
"rouge",
|
|
600
|
+
"ruby",
|
|
601
|
+
"saffron",
|
|
602
|
+
"sage",
|
|
603
|
+
"sail",
|
|
604
|
+
"salmon",
|
|
605
|
+
"sapphire",
|
|
606
|
+
"scarab",
|
|
607
|
+
"shadow",
|
|
608
|
+
"shale",
|
|
609
|
+
"sienna",
|
|
610
|
+
"silica",
|
|
611
|
+
"silver",
|
|
612
|
+
"skyline",
|
|
613
|
+
"slate",
|
|
614
|
+
"sonar",
|
|
615
|
+
"spruce",
|
|
616
|
+
"starling",
|
|
617
|
+
"stone",
|
|
618
|
+
"sugar",
|
|
619
|
+
"summit",
|
|
620
|
+
"sunset",
|
|
621
|
+
"swan",
|
|
622
|
+
"tangent",
|
|
623
|
+
"tarragon",
|
|
624
|
+
"temple",
|
|
625
|
+
"thistle",
|
|
626
|
+
"thrush",
|
|
627
|
+
"tiger",
|
|
628
|
+
"topaz",
|
|
629
|
+
"tundra",
|
|
630
|
+
"turtle",
|
|
631
|
+
"umber",
|
|
632
|
+
"union",
|
|
633
|
+
"valley",
|
|
634
|
+
"vapor",
|
|
635
|
+
"vector",
|
|
636
|
+
"velvet",
|
|
637
|
+
"violet",
|
|
638
|
+
"vortex",
|
|
639
|
+
"walnut",
|
|
640
|
+
"whale",
|
|
641
|
+
"winter",
|
|
642
|
+
"wisp",
|
|
643
|
+
"wisteria",
|
|
644
|
+
"xenon",
|
|
645
|
+
"yarrow",
|
|
646
|
+
"zephyr",
|
|
647
|
+
"zinc",
|
|
648
|
+
"zodiac",
|
|
649
|
+
"anchor",
|
|
650
|
+
"basil",
|
|
651
|
+
"cider",
|
|
652
|
+
"daisy",
|
|
653
|
+
"elfin",
|
|
654
|
+
"ferry",
|
|
655
|
+
"gimlet",
|
|
656
|
+
"halcyon",
|
|
657
|
+
"indigo",
|
|
658
|
+
"juniper",
|
|
659
|
+
"kindle",
|
|
660
|
+
"lilac",
|
|
661
|
+
"mantis",
|
|
662
|
+
"nylon",
|
|
663
|
+
"oracle",
|
|
664
|
+
"parch",
|
|
665
|
+
"quokka",
|
|
666
|
+
"ramble",
|
|
667
|
+
"thatch",
|
|
668
|
+
"ultra",
|
|
669
|
+
"vivid",
|
|
670
|
+
"xylo",
|
|
671
|
+
"yodel",
|
|
672
|
+
"zesty",
|
|
673
|
+
"arbor",
|
|
674
|
+
"bliss",
|
|
675
|
+
"calyx",
|
|
676
|
+
"dwindle",
|
|
677
|
+
"folio",
|
|
678
|
+
"globe",
|
|
679
|
+
"hymn",
|
|
680
|
+
"ionic",
|
|
681
|
+
"jolly",
|
|
682
|
+
"knack",
|
|
683
|
+
"lyric",
|
|
684
|
+
"myrtle",
|
|
685
|
+
"noble",
|
|
686
|
+
"plumb",
|
|
687
|
+
"quaint",
|
|
688
|
+
"rustic",
|
|
689
|
+
"satin",
|
|
690
|
+
"timber",
|
|
691
|
+
"urge",
|
|
692
|
+
"vault",
|
|
693
|
+
"whimsy",
|
|
694
|
+
"yearn",
|
|
695
|
+
"zenith",
|
|
696
|
+
"ash",
|
|
697
|
+
"beach",
|
|
698
|
+
"dusk"
|
|
699
|
+
];
|
|
700
|
+
function deriveAddressSeed({ userId, appSalt }) {
|
|
701
|
+
const h = starknet.hash.computePoseidonHashOnElements([feltFromString(userId), feltFromString(appSalt)]);
|
|
702
|
+
return BigInt(h);
|
|
703
|
+
}
|
|
704
|
+
function feltFromString(s) {
|
|
705
|
+
const bytes = new TextEncoder().encode(s);
|
|
706
|
+
const chunks = [];
|
|
707
|
+
for (let i = 0; i < bytes.length; i += 31) {
|
|
708
|
+
let w = 0n;
|
|
709
|
+
for (const b of bytes.subarray(i, i + 31)) w = w << 8n | BigInt(b);
|
|
710
|
+
chunks.push(w);
|
|
711
|
+
}
|
|
712
|
+
if (chunks.length === 0) return 0n;
|
|
713
|
+
if (chunks.length === 1) return chunks[0];
|
|
714
|
+
return BigInt(starknet.hash.computePoseidonHashOnElements(chunks));
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// src/Cavos.ts
|
|
718
|
+
var Cavos = class _Cavos {
|
|
719
|
+
constructor(identity, address, status, account, adapter, devicePubkey) {
|
|
720
|
+
this.identity = identity;
|
|
721
|
+
this.address = address;
|
|
722
|
+
this.status = status;
|
|
723
|
+
this.account = account;
|
|
724
|
+
this.adapter = adapter;
|
|
725
|
+
this.devicePubkey = devicePubkey;
|
|
726
|
+
/** Request id of the pending device-addition, when status is needs-device-approval. */
|
|
727
|
+
this.pendingRequestId = null;
|
|
728
|
+
}
|
|
729
|
+
static async connect(opts) {
|
|
730
|
+
const identity = opts.identity ?? await opts.auth?.authenticate();
|
|
731
|
+
if (!identity) throw new Error("kit: connect requires `identity` or `auth`");
|
|
732
|
+
const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[opts.network];
|
|
733
|
+
if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${opts.network}`);
|
|
734
|
+
const provider = new starknet.RpcProvider({
|
|
735
|
+
nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[opts.network].rpcUrl
|
|
736
|
+
});
|
|
737
|
+
const paymaster = new starknet.PaymasterRpc({
|
|
738
|
+
nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[opts.network],
|
|
739
|
+
headers: { "x-paymaster-api-key": opts.paymasterApiKey }
|
|
740
|
+
});
|
|
741
|
+
const addressSeed = deriveAddressSeed({ userId: identity.userId, appSalt: opts.appSalt });
|
|
742
|
+
const signer = opts.createSigner ? await opts.createSigner(`${identity.userId}:${opts.appSalt}`) : await WebCryptoSigner.loadOrCreate({ keyId: `${identity.userId}:${opts.appSalt}` });
|
|
743
|
+
const devicePubkey = await signer.getPublicKey();
|
|
744
|
+
const adapter = new StarknetAdapter({ classHash, signer, provider });
|
|
745
|
+
const makeAccount = (address2) => new starknet.Account({
|
|
746
|
+
provider,
|
|
747
|
+
address: address2,
|
|
748
|
+
signer: new StarknetDeviceSigner(signer),
|
|
749
|
+
paymaster,
|
|
750
|
+
cairoVersion: "1"
|
|
751
|
+
});
|
|
752
|
+
const backendUrl = opts.backendUrl ?? "https://cavos.xyz";
|
|
753
|
+
const registry = opts.registry ?? (opts.appId ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network: opts.network }) : defaultRegistry);
|
|
754
|
+
const recovery = opts.recovery ?? (opts.appId ? new HttpRecoveryClient({ baseUrl: backendUrl, appId: opts.appId }) : null);
|
|
755
|
+
const existing = await registry.lookup(identity.userId);
|
|
756
|
+
if (existing) {
|
|
757
|
+
const account2 = makeAccount(existing.address);
|
|
758
|
+
const isSigner2 = await adapter.isAuthorizedSigner(existing.address, devicePubkey);
|
|
759
|
+
const cavos = new _Cavos(
|
|
760
|
+
identity,
|
|
761
|
+
existing.address,
|
|
762
|
+
isSigner2 ? "ready" : "needs-device-approval",
|
|
763
|
+
account2,
|
|
764
|
+
adapter,
|
|
765
|
+
devicePubkey
|
|
766
|
+
);
|
|
767
|
+
if (!isSigner2 && recovery) {
|
|
768
|
+
const dedup = lastDeviceRequest.get(identity.userId);
|
|
769
|
+
const fresh = dedup && Date.now() - dedup.requestedAt < DEVICE_REQUEST_DEDUP_MS;
|
|
770
|
+
try {
|
|
771
|
+
if (fresh) {
|
|
772
|
+
cavos.pendingRequestId = dedup.requestId;
|
|
773
|
+
} else {
|
|
774
|
+
const { requestId } = await recovery.requestDeviceAddition({
|
|
775
|
+
userId: identity.userId,
|
|
776
|
+
accountAddress: existing.address,
|
|
777
|
+
newSigner: devicePubkey,
|
|
778
|
+
...identity.email ? { email: identity.email } : {}
|
|
779
|
+
});
|
|
780
|
+
cavos.pendingRequestId = requestId;
|
|
781
|
+
lastDeviceRequest.set(identity.userId, { requestId, requestedAt: Date.now() });
|
|
782
|
+
}
|
|
783
|
+
} catch (e) {
|
|
784
|
+
console.warn("[Cavos] requestDeviceAddition failed:", e);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return cavos;
|
|
788
|
+
}
|
|
789
|
+
const address = adapter.computeAddress({ addressSeed, initialSigner: devicePubkey });
|
|
790
|
+
const account = makeAccount(address);
|
|
791
|
+
const alreadyDeployed = await isDeployed(provider, address);
|
|
792
|
+
if (!alreadyDeployed) {
|
|
793
|
+
const deploymentData = {
|
|
794
|
+
address,
|
|
795
|
+
class_hash: classHash,
|
|
796
|
+
salt: starknet.num.toHex(addressSeed),
|
|
797
|
+
calldata: adapter.constructorCalldata(addressSeed, devicePubkey),
|
|
798
|
+
version: 1
|
|
799
|
+
};
|
|
800
|
+
const deployRes = await account.executePaymasterTransaction([], {
|
|
801
|
+
feeMode: { mode: "sponsored" },
|
|
802
|
+
deploymentData
|
|
803
|
+
});
|
|
804
|
+
try {
|
|
805
|
+
await provider.waitForTransaction(deployRes.transaction_hash);
|
|
806
|
+
} catch (e) {
|
|
807
|
+
console.warn("[Cavos] deploy receipt wait failed:", e);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
await registry.register({ userId: identity.userId, address, initialSigner: devicePubkey });
|
|
811
|
+
let isSigner;
|
|
812
|
+
try {
|
|
813
|
+
isSigner = await adapter.isAuthorizedSigner(address, devicePubkey);
|
|
814
|
+
} catch (e) {
|
|
815
|
+
console.warn("[Cavos] isAuthorizedSigner read failed:", e);
|
|
816
|
+
isSigner = !alreadyDeployed;
|
|
817
|
+
}
|
|
818
|
+
return new _Cavos(
|
|
819
|
+
identity,
|
|
820
|
+
address,
|
|
821
|
+
isSigner ? "ready" : "needs-device-approval",
|
|
822
|
+
account,
|
|
823
|
+
adapter,
|
|
824
|
+
devicePubkey
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
/** This device's public key (e.g. to request addition to an existing wallet). */
|
|
828
|
+
get publicKey() {
|
|
829
|
+
return this.devicePubkey;
|
|
830
|
+
}
|
|
831
|
+
/** Execute a sponsored (gasless) multicall, signed silently by the device. */
|
|
832
|
+
async execute(calls) {
|
|
833
|
+
if (this.status !== "ready") {
|
|
834
|
+
throw new Error("kit: this device is not yet an authorized signer of the wallet");
|
|
835
|
+
}
|
|
836
|
+
const res = await this.account.executePaymasterTransaction(calls, {
|
|
837
|
+
feeMode: { mode: "sponsored" }
|
|
838
|
+
});
|
|
839
|
+
return { transactionHash: res.transaction_hash };
|
|
840
|
+
}
|
|
841
|
+
/** Authorize an additional device signer (sponsored). Self-submitted. */
|
|
842
|
+
async addSigner(pubkey) {
|
|
843
|
+
return this.execute([this.adapter.buildAddSigner(this.address, pubkey)]);
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Register a self-custodial backup signer derived from `code`, so the account
|
|
847
|
+
* can be recovered after the user loses every device. Idempotent: if the
|
|
848
|
+
* derived backup key is already an authorised signer, this is a no-op.
|
|
849
|
+
*
|
|
850
|
+
* The code never leaves the device — only its deterministic public key is
|
|
851
|
+
* added on-chain as an ordinary signer. Sponsor this like any other
|
|
852
|
+
* add_signer (gasless). Returns the transaction hash (or undefined when the
|
|
853
|
+
* backup was already set up).
|
|
854
|
+
*/
|
|
855
|
+
async setupRecovery(code) {
|
|
856
|
+
const { publicKey: backupPubkey } = deriveBackupKey(code);
|
|
857
|
+
const already = await this.adapter.isAuthorizedSigner(this.address, backupPubkey);
|
|
858
|
+
if (already) return void 0;
|
|
859
|
+
return this.addSigner(backupPubkey);
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Recover an account after losing every device signer. Derives the backup key
|
|
863
|
+
* from `code`, uses it (not the new device key) to sign an `add_signer` for
|
|
864
|
+
* the new device, and returns a ready Cavos bound to the new device. The
|
|
865
|
+
* account address is unchanged.
|
|
866
|
+
*
|
|
867
|
+
* Self-custodial: only someone holding the code (i.e. the rightful owner) can
|
|
868
|
+
* re-derive the backup key. The backend never sees the code.
|
|
869
|
+
*/
|
|
870
|
+
static async recover(opts) {
|
|
871
|
+
const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[opts.network];
|
|
872
|
+
if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${opts.network}`);
|
|
873
|
+
const provider = new starknet.RpcProvider({
|
|
874
|
+
nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[opts.network].rpcUrl
|
|
875
|
+
});
|
|
876
|
+
const paymaster = new starknet.PaymasterRpc({
|
|
877
|
+
nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[opts.network],
|
|
878
|
+
headers: { "x-paymaster-api-key": opts.paymasterApiKey }
|
|
879
|
+
});
|
|
880
|
+
const signer = opts.createSigner ? await opts.createSigner(`${opts.identity.userId}:${opts.appSalt}`) : await WebCryptoSigner.loadOrCreate({ keyId: `${opts.identity.userId}:${opts.appSalt}` });
|
|
881
|
+
const devicePubkey = await signer.getPublicKey();
|
|
882
|
+
const backup = BackupSigner.fromCode(opts.code);
|
|
883
|
+
const backupAdapter = new StarknetAdapter({ classHash, signer: backup, provider });
|
|
884
|
+
const backendUrl = opts.backendUrl ?? "https://cavos.xyz";
|
|
885
|
+
const registry = opts.registry ?? (opts.appId ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network: opts.network }) : defaultRegistry);
|
|
886
|
+
const existing = await registry.lookup(opts.identity.userId);
|
|
887
|
+
if (!existing) {
|
|
888
|
+
throw new Error("kit: no account found for this identity \u2014 nothing to recover");
|
|
889
|
+
}
|
|
890
|
+
const backupAccount = new starknet.Account({
|
|
891
|
+
provider,
|
|
892
|
+
address: existing.address,
|
|
893
|
+
signer: new StarknetDeviceSigner(backup),
|
|
894
|
+
paymaster,
|
|
895
|
+
cairoVersion: "1"
|
|
896
|
+
});
|
|
897
|
+
const alreadyAuthed = await backupAdapter.isAuthorizedSigner(existing.address, devicePubkey);
|
|
898
|
+
if (!alreadyAuthed) {
|
|
899
|
+
const res = await backupAccount.executePaymasterTransaction(
|
|
900
|
+
[backupAdapter.buildAddSigner(existing.address, devicePubkey)],
|
|
901
|
+
{ feeMode: { mode: "sponsored" } }
|
|
902
|
+
);
|
|
903
|
+
try {
|
|
904
|
+
await provider.waitForTransaction(res.transaction_hash);
|
|
905
|
+
} catch (e) {
|
|
906
|
+
console.warn("[Cavos] recovery add_signer receipt wait failed:", e);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
const adapter = new StarknetAdapter({ classHash, signer, provider });
|
|
910
|
+
const account = new starknet.Account({
|
|
911
|
+
provider,
|
|
912
|
+
address: existing.address,
|
|
913
|
+
signer: new StarknetDeviceSigner(signer),
|
|
914
|
+
paymaster,
|
|
915
|
+
cairoVersion: "1"
|
|
916
|
+
});
|
|
917
|
+
return new _Cavos(opts.identity, existing.address, "ready", account, adapter, devicePubkey);
|
|
918
|
+
}
|
|
919
|
+
};
|
|
920
|
+
var defaultRegistry = new InMemoryWalletRegistry();
|
|
921
|
+
var DEVICE_REQUEST_DEDUP_MS = 5 * 60 * 1e3;
|
|
922
|
+
var lastDeviceRequest = /* @__PURE__ */ new Map();
|
|
923
|
+
async function isDeployed(provider, address) {
|
|
924
|
+
try {
|
|
925
|
+
const classHash = await provider.getClassHashAt(address);
|
|
926
|
+
return !!classHash && classHash !== "0x0";
|
|
927
|
+
} catch {
|
|
928
|
+
return false;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// src/auth/AuthProvider.ts
|
|
933
|
+
var StaticIdentity = class {
|
|
934
|
+
constructor(identity) {
|
|
935
|
+
this.identity = identity;
|
|
936
|
+
}
|
|
937
|
+
async authenticate() {
|
|
938
|
+
return this.identity;
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
var CavosAuth = class {
|
|
942
|
+
constructor(opts = {}) {
|
|
943
|
+
this.opts = opts;
|
|
944
|
+
/** Most recent nonce sent to the backend (for the pending OAuth/OTP request). */
|
|
945
|
+
this.pendingNonce = null;
|
|
946
|
+
this.last = null;
|
|
947
|
+
this.backendUrl = opts.backendUrl ?? "https://cavos.xyz";
|
|
948
|
+
}
|
|
949
|
+
/** Redirect URL for Google login (open it; user returns to your redirectUri). */
|
|
950
|
+
async getGoogleOAuthUrl(redirectUri) {
|
|
951
|
+
return this.oauthUrl("google", redirectUri);
|
|
952
|
+
}
|
|
953
|
+
/** Redirect URL for Apple login. */
|
|
954
|
+
async getAppleOAuthUrl(redirectUri) {
|
|
955
|
+
return this.oauthUrl("apple", redirectUri);
|
|
956
|
+
}
|
|
957
|
+
async oauthUrl(provider, redirectUri) {
|
|
958
|
+
if (typeof window === "undefined") throw new Error("kit/auth: OAuth requires a browser");
|
|
959
|
+
const params = new URLSearchParams({
|
|
960
|
+
nonce: this.freshNonce(),
|
|
961
|
+
redirect_uri: redirectUri ?? window.location.href,
|
|
962
|
+
...this.opts.appId ? { app_id: this.opts.appId } : {}
|
|
963
|
+
});
|
|
964
|
+
const { url } = await this.get(`/api/oauth/${provider}?${params}`);
|
|
965
|
+
return url;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Resolve the identity from an OAuth callback. The auth data is carried in the
|
|
969
|
+
* `auth_data` (or `zk_auth_data`) query param on return. We only extract `sub`.
|
|
970
|
+
*/
|
|
971
|
+
async handleCallback(authDataOrSearch) {
|
|
972
|
+
const authData = extractAuthData(authDataOrSearch);
|
|
973
|
+
return this.identityFromAuthData(authData, "oauth");
|
|
974
|
+
}
|
|
975
|
+
/** Send a one-time code to an email (Firebase OTP). */
|
|
976
|
+
async sendOtp(email) {
|
|
977
|
+
await this.post("/api/oauth/firebase/otp/request", {
|
|
978
|
+
email,
|
|
979
|
+
nonce: this.freshNonce(),
|
|
980
|
+
...this.opts.appId ? { app_id: this.opts.appId } : {}
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
/** Send a passwordless magic-link sign-in email (Firebase). */
|
|
984
|
+
async sendMagicLink(email) {
|
|
985
|
+
await this.post("/api/oauth/firebase/magic-link", {
|
|
986
|
+
email,
|
|
987
|
+
nonce: this.freshNonce(),
|
|
988
|
+
...this.opts.appId ? { app_id: this.opts.appId } : {},
|
|
989
|
+
...typeof window !== "undefined" ? { redirect_uri: window.location.href } : {}
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
/** Verify the OTP and resolve the identity. */
|
|
993
|
+
async verifyOtp(email, code) {
|
|
994
|
+
const res = await this.post("/api/oauth/firebase/otp/verify", {
|
|
995
|
+
email,
|
|
996
|
+
code,
|
|
997
|
+
nonce: this.consumeNonce(),
|
|
998
|
+
...this.opts.appId ? { app_id: this.opts.appId } : {}
|
|
999
|
+
});
|
|
1000
|
+
return this.identityFromAuthData(res.id_token ?? res.jwt ?? res.token ?? JSON.stringify(res), "otp", email);
|
|
1001
|
+
}
|
|
1002
|
+
/** AuthProvider: returns the identity resolved by the last login step. */
|
|
1003
|
+
async authenticate() {
|
|
1004
|
+
if (!this.last) throw new Error("kit/auth: no identity yet \u2014 complete a login first");
|
|
1005
|
+
return this.last;
|
|
1006
|
+
}
|
|
1007
|
+
// ── internals ──────────────────────────────────────────────────────────────
|
|
1008
|
+
/**
|
|
1009
|
+
* Build an `Identity` from whatever the backend returned. The Cavos backend
|
|
1010
|
+
* wraps the user id in a JWT (its `sub` claim); for the device model we only
|
|
1011
|
+
* need that stable id — the signature is never checked on-chain.
|
|
1012
|
+
*/
|
|
1013
|
+
async identityFromAuthData(authData, provider, emailOverride) {
|
|
1014
|
+
let token = authData;
|
|
1015
|
+
try {
|
|
1016
|
+
const parsed = JSON.parse(authData);
|
|
1017
|
+
token = parsed.id_token ?? parsed.jwt ?? parsed.token ?? authData;
|
|
1018
|
+
} catch {
|
|
1019
|
+
}
|
|
1020
|
+
const claims = parseJwt(token);
|
|
1021
|
+
return this.remember({
|
|
1022
|
+
userId: String(claims.sub ?? claims.user_id ?? claims.uid),
|
|
1023
|
+
email: claims.email ?? emailOverride,
|
|
1024
|
+
provider: claims.firebase?.sign_in_provider ?? claims.provider ?? provider
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
/** Generate (and remember) the nonce the Cavos backend expects on requests. */
|
|
1028
|
+
freshNonce() {
|
|
1029
|
+
const bytes = crypto.getRandomValues(new Uint8Array(31));
|
|
1030
|
+
const h = starknet.hash.computePoseidonHashOnElements([bytesToChunks(bytes)]);
|
|
1031
|
+
this.pendingNonce = starknet.num.toHex(h);
|
|
1032
|
+
return this.pendingNonce;
|
|
1033
|
+
}
|
|
1034
|
+
/** Return the pending nonce (for the verify step), clearing it. */
|
|
1035
|
+
consumeNonce() {
|
|
1036
|
+
if (!this.pendingNonce) return this.freshNonce();
|
|
1037
|
+
const n = this.pendingNonce;
|
|
1038
|
+
this.pendingNonce = null;
|
|
1039
|
+
return n;
|
|
1040
|
+
}
|
|
1041
|
+
remember(id) {
|
|
1042
|
+
this.last = id;
|
|
1043
|
+
return id;
|
|
1044
|
+
}
|
|
1045
|
+
async get(path) {
|
|
1046
|
+
const r = await fetch(`${this.backendUrl}${path}`);
|
|
1047
|
+
if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);
|
|
1048
|
+
return r.json();
|
|
1049
|
+
}
|
|
1050
|
+
async post(path, body) {
|
|
1051
|
+
const r = await fetch(`${this.backendUrl}${path}`, {
|
|
1052
|
+
method: "POST",
|
|
1053
|
+
headers: { "Content-Type": "application/json" },
|
|
1054
|
+
body: JSON.stringify(body)
|
|
1055
|
+
});
|
|
1056
|
+
if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);
|
|
1057
|
+
return r.json();
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
function extractAuthData(input) {
|
|
1061
|
+
if (input.includes("auth_data=") || input.includes("zk_auth_data=")) {
|
|
1062
|
+
const params = new URLSearchParams(input.startsWith("?") ? input : `?${input}`);
|
|
1063
|
+
return params.get("auth_data") ?? params.get("zk_auth_data") ?? input;
|
|
1064
|
+
}
|
|
1065
|
+
return input;
|
|
1066
|
+
}
|
|
1067
|
+
function parseJwt(jwt) {
|
|
1068
|
+
const part = jwt.split(".")[1];
|
|
1069
|
+
if (!part) throw new Error("kit/auth: malformed JWT");
|
|
1070
|
+
const json = atob(part.replace(/-/g, "+").replace(/_/g, "/"));
|
|
1071
|
+
return JSON.parse(json);
|
|
1072
|
+
}
|
|
1073
|
+
function bytesToChunks(bytes) {
|
|
1074
|
+
let w = 0n;
|
|
1075
|
+
for (const b of bytes.subarray(0, 31)) w = w << 8n | BigInt(b);
|
|
1076
|
+
return w;
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
exports.BackupSigner = BackupSigner;
|
|
1080
|
+
exports.Cavos = Cavos;
|
|
1081
|
+
exports.CavosAuth = CavosAuth;
|
|
1082
|
+
exports.DEVICE_ACCOUNT_CLASS_HASH = DEVICE_ACCOUNT_CLASS_HASH;
|
|
1083
|
+
exports.HttpRecoveryClient = HttpRecoveryClient;
|
|
1084
|
+
exports.HttpWalletRegistry = HttpWalletRegistry;
|
|
1085
|
+
exports.InMemoryWalletRegistry = InMemoryWalletRegistry;
|
|
1086
|
+
exports.STARKNET_NETWORKS = STARKNET_NETWORKS;
|
|
1087
|
+
exports.StarknetAdapter = StarknetAdapter;
|
|
1088
|
+
exports.StarknetDeviceSigner = StarknetDeviceSigner;
|
|
1089
|
+
exports.StaticIdentity = StaticIdentity;
|
|
1090
|
+
exports.UDC_ADDRESS = UDC_ADDRESS;
|
|
1091
|
+
exports.WebCryptoSigner = WebCryptoSigner;
|
|
1092
|
+
exports.bigIntTo32Bytes = bigIntTo32Bytes;
|
|
1093
|
+
exports.bytesToBigInt = bytesToBigInt;
|
|
1094
|
+
exports.bytesToHex = bytesToHex;
|
|
1095
|
+
exports.deriveAddressSeed = deriveAddressSeed;
|
|
1096
|
+
exports.deriveBackupKey = deriveBackupKey;
|
|
1097
|
+
exports.generateRecoveryCode = generateRecoveryCode;
|
|
1098
|
+
exports.hexToBytes = hexToBytes;
|
|
1099
|
+
exports.recoverYParity = recoverYParity;
|
|
1100
|
+
exports.signatureToFelts = signatureToFelts;
|
|
1101
|
+
exports.u256ToFelts = u256ToFelts;
|
|
1102
|
+
//# sourceMappingURL=index.js.map
|
|
1103
|
+
//# sourceMappingURL=index.js.map
|