@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crypto/encoding.ts","../src/crypto/signature.ts","../src/signer/WebCryptoSigner.ts","../src/chains/starknet/constants.ts","../src/chains/starknet/StarknetAdapter.ts","../src/chains/starknet/StarknetDeviceSigner.ts","../src/registry/WalletRegistry.ts","../src/registry/HttpWalletRegistry.ts","../src/recovery/HttpRecoveryClient.ts","../src/recovery/BackupSigner.ts","../src/identity.ts","../src/Cavos.ts","../src/auth/AuthProvider.ts","../src/auth/CavosAuth.ts"],"names":["p256","sha256","hash","num","Signer","toHex","fromHex","randomBytes","pbkdf2","hkdf","RpcProvider","PaymasterRpc","address","Account","account","isSigner"],"mappings":";;;;;;;;;;;;AAIA,IAAM,SAAA,GAAA,CAAa,MAAM,IAAA,IAAQ,EAAA;AAG1B,SAAS,YAAY,KAAA,EAAiC;AAC3D,EAAA,OAAO,CAAC,KAAA,GAAQ,SAAA,EAAW,KAAA,IAAS,IAAI,CAAA;AAC1C;AAGO,SAAS,cAAc,KAAA,EAA2B;AACvD,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,MA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AAS,SAAS,GAAA,EAAkB;AAClC,EAAA,MAAM,IAAA,GAAO,GAAA,CAAI,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAC7B,EAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,yBAAyB,CAAA;AACpD,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAC,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA;AACxB;AAGA,SAAS,cAAc,KAAA,EAA2B;AAChD,EAAA,IAAI,CAAA,GAAI,EAAA;AACR,EAAA,KAAA,MAAW,CAAA,IAAK,KAAA,CAAM,QAAA,CAAS,CAAA,EAAG,EAAE,GAAG,CAAA,GAAK,CAAA,IAAK,EAAA,GAAM,MAAA,CAAO,CAAC,CAAA;AAC/D,EAAA,OAAO,CAAA;AACT","file":"index.js","sourcesContent":["/**\n * Low-level encoding helpers shared across the kit.\n */\n\nconst U128_MASK = (1n << 128n) - 1n;\n\n/** Split a u256 into the `[low, high]` felt pair Cairo expects. */\nexport function u256ToFelts(value: bigint): [bigint, bigint] {\n return [value & U128_MASK, value >> 128n];\n}\n\n/** Big-endian bytes -> bigint. */\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n let out = 0n;\n for (const b of bytes) out = (out << 8n) | BigInt(b);\n return out;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n let s = \"0x\";\n for (const b of bytes) s += b.toString(16).padStart(2, \"0\");\n return s;\n}\n\nexport function hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n const padded = clean.length % 2 ? \"0\" + clean : clean;\n const out = new Uint8Array(padded.length / 2);\n for (let i = 0; i < out.length; i++) out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\n/** A felt/bigint -> 32-byte big-endian Uint8Array (the tx-hash width). */\nexport function bigIntTo32Bytes(value: bigint): Uint8Array {\n const out = new Uint8Array(32);\n let v = value;\n for (let i = 31; i >= 0; i--) {\n out[i] = Number(v & 0xffn);\n v >>= 8n;\n }\n return out;\n}\n","/**\n * secp256r1 signature helpers for silent device signers.\n */\nimport { p256 } from \"@noble/curves/p256\";\nimport type { DevicePublicKey, DeviceSignature } from \"../signer/DeviceSigner\";\nimport { u256ToFelts } from \"./encoding\";\n\n/**\n * Serialize a device signature to the felt array for `tx_info.signature`:\n * [ r_low, r_high, s_low, s_high, y_parity ]\n * exactly what DeviceAccount.__validate__ decodes.\n */\nexport function signatureToFelts(sig: DeviceSignature): bigint[] {\n const [rLow, rHigh] = u256ToFelts(sig.r);\n const [sLow, sHigh] = u256ToFelts(sig.s);\n return [rLow, rHigh, sLow, sHigh, sig.yParity ? 1n : 0n];\n}\n\n/**\n * Recover the parity bit of an (r, s) signature over `digest` for a known\n * pubkey. WebCrypto/Secure Enclave don't return a recovery id, so we derive it\n * by trying both candidates and matching the device's public key.\n */\nexport function recoverYParity(\n r: bigint,\n s: bigint,\n digest: Uint8Array,\n pubkey: DevicePublicKey,\n): boolean {\n for (const bit of [0, 1] as const) {\n try {\n const candidate = new p256.Signature(r, s).addRecoveryBit(bit);\n const point = candidate.recoverPublicKey(digest).toAffine();\n if (point.x === pubkey.x && point.y === pubkey.y) {\n return bit === 1;\n }\n } catch {\n // try the other bit\n }\n }\n throw new Error(\"kit/signature: could not recover parity for the given pubkey\");\n}\n","import { sha256 } from \"@noble/hashes/sha256\";\nimport type { DeviceSigner, DevicePublicKey, DeviceSignature } from \"./DeviceSigner\";\nimport { bytesToBigInt } from \"../crypto/encoding\";\nimport { recoverYParity } from \"../crypto/signature\";\n\nconst IDB_NAME = \"cavos-kit\";\nconst IDB_STORE = \"device-keys\";\n\nexport interface WebCryptoSignerOptions {\n /**\n * Storage key for the device's private key (e.g. the account address). One\n * silent key per (this value, browser profile).\n */\n keyId: string;\n}\n\ninterface StoredKey {\n privateKey: CryptoKey; // non-extractable; structured-cloneable\n x: bigint;\n y: bigint;\n}\n\n/**\n * Silent, device-bound signer for the browser. Generates a non-extractable\n * secp256r1 (P-256) key via WebCrypto and stores the `CryptoKey` in IndexedDB.\n * The private key is never exposed to JS and signing produces NO UI — there is\n * no passkey, no Face ID / Touch ID prompt. To the user it is invisible; they\n * only ever see the OAuth / email login used to derive their address.\n */\nexport class WebCryptoSigner implements DeviceSigner {\n private constructor(\n private readonly privateKey: CryptoKey,\n private readonly publicKey: DevicePublicKey,\n readonly keyId: string,\n ) {}\n\n /** Create a fresh device key (first run on this device) and persist it. */\n static async create(opts: WebCryptoSignerOptions): Promise<WebCryptoSigner> {\n assertSecureContext();\n const pair = await crypto.subtle.generateKey(\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false, // private key is NON-extractable\n [\"sign\", \"verify\"],\n );\n const publicKey = await exportPublicKey(pair.publicKey);\n await idbPut(opts.keyId, { privateKey: pair.privateKey, x: publicKey.x, y: publicKey.y });\n return new WebCryptoSigner(pair.privateKey, publicKey, opts.keyId);\n }\n\n /** Load an existing device key from storage, or null if none exists yet. */\n static async load(opts: WebCryptoSignerOptions): Promise<WebCryptoSigner | null> {\n const rec = await idbGet(opts.keyId);\n if (!rec) return null;\n return new WebCryptoSigner(rec.privateKey, { x: rec.x, y: rec.y }, opts.keyId);\n }\n\n /** Load the device key, creating one on first use. */\n static async loadOrCreate(opts: WebCryptoSignerOptions): Promise<WebCryptoSigner> {\n return (await WebCryptoSigner.load(opts)) ?? (await WebCryptoSigner.create(opts));\n }\n\n async getPublicKey(): Promise<DevicePublicKey> {\n return this.publicKey;\n }\n\n async sign(txHash: Uint8Array): Promise<DeviceSignature> {\n // WebCrypto ECDSA hashes the message with SHA-256 internally, then signs.\n const raw = new Uint8Array(\n await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n this.privateKey,\n txHash as unknown as BufferSource,\n ),\n );\n // IEEE P1363 form: r || s, 32 bytes each.\n const r = bytesToBigInt(raw.subarray(0, 32));\n const s = bytesToBigInt(raw.subarray(32, 64));\n const digest = sha256(txHash);\n const yParity = recoverYParity(r, s, digest, this.publicKey);\n return { r, s, yParity };\n }\n}\n\nasync function exportPublicKey(publicKey: CryptoKey): Promise<DevicePublicKey> {\n const raw = new Uint8Array(await crypto.subtle.exportKey(\"raw\", publicKey)); // 0x04 || X || Y\n return { x: bytesToBigInt(raw.subarray(1, 33)), y: bytesToBigInt(raw.subarray(33, 65)) };\n}\n\n/**\n * WebCrypto (`crypto.subtle`) is only available in secure contexts — HTTPS, or\n * `http://localhost`. Accessing the dev server over a LAN IP (e.g.\n * http://192.168.1.24:3000) is NOT secure, so `crypto.subtle` is undefined and\n * device-key generation would crash with a cryptic \"undefined is not an object\".\n * Fail early with an actionable message instead.\n */\nfunction assertSecureContext(): void {\n const ok =\n typeof crypto !== \"undefined\" &&\n typeof crypto.subtle !== \"undefined\" &&\n (typeof window === \"undefined\" || window.isSecureContext);\n if (!ok) {\n throw new Error(\n \"Cavos: WebCrypto is unavailable. Device keys require a secure context — use HTTPS, or http://localhost. \" +\n \"(For LAN/mobile dev testing, run `next dev --experimental-https`.)\",\n );\n }\n}\n\n// --- minimal IndexedDB wrapper ---\n\nfunction openDb(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(IDB_NAME, 1);\n req.onupgradeneeded = () => req.result.createObjectStore(IDB_STORE);\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nasync function idbPut(keyId: string, value: StoredKey): Promise<void> {\n const db = await openDb();\n await tx(db, \"readwrite\", (store) => store.put(value, keyId));\n db.close();\n}\n\nasync function idbGet(keyId: string): Promise<StoredKey | null> {\n const db = await openDb();\n const result = await tx(db, \"readonly\", (store) => store.get(keyId));\n db.close();\n return (result as StoredKey) ?? null;\n}\n\nfunction tx<T>(\n db: IDBDatabase,\n mode: IDBTransactionMode,\n run: (store: IDBObjectStore) => IDBRequest<T>,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const store = db.transaction(IDB_STORE, mode).objectStore(IDB_STORE);\n const req = run(store);\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n","/** Starknet network presets and well-known addresses for the kit. */\n\nexport const STARKNET_NETWORKS = {\n sepolia: {\n chainId: \"0x534e5f5345504f4c4941\", // SN_SEPOLIA\n rpcUrl: \"https://api.cartridge.gg/x/starknet/sepolia\",\n },\n mainnet: {\n chainId: \"0x534e5f4d41494e\", // SN_MAIN\n rpcUrl: \"https://api.cartridge.gg/x/starknet/mainnet\",\n },\n} as const;\n\nexport type StarknetNetwork = keyof typeof STARKNET_NETWORKS;\n\n/** Universal Deployer Contract (same address on mainnet & sepolia). */\nexport const UDC_ADDRESS =\n \"0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf\";\n\n/** Cavos-hosted SNIP-29 paymaster (same service @cavos/react uses). */\nexport const CAVOS_PAYMASTER_URL: Record<StarknetNetwork, string> = {\n sepolia: \"https://sepolia-paymaster.cavos.xyz\",\n mainnet: \"https://paymaster.cavos.xyz\",\n};\n\n/**\n * DeviceAccount class hash, per network. Populated from\n * `account-contracts/starknet/deployments/<network>.json` after declaring.\n * Left empty until the class is declared on each network.\n */\nexport const DEVICE_ACCOUNT_CLASS_HASH: Record<StarknetNetwork, string> = {\n sepolia: \"0x6c3c3426667b6d4adda18a0b8d8cc34c495a1ace7276c4470068ad4c324876d\",\n mainnet: \"\",\n};\n","import { hash, num } from \"starknet\";\nimport type { ChainAdapter, ChainCall, ComputeAddressParams } from \"../ChainAdapter\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { signatureToFelts } from \"../../crypto/signature\";\nimport { u256ToFelts, bigIntTo32Bytes } from \"../../crypto/encoding\";\nimport { UDC_ADDRESS } from \"./constants\";\n\nexport interface StarknetAdapterOptions {\n classHash: string;\n /** Read provider for `isAuthorizedSigner`. Optional for build-only usage. */\n provider?: { callContract(call: { contractAddress: string; entrypoint: string; calldata: string[] }): Promise<string[]> };\n /** Signer used to sign outgoing transactions. */\n signer?: DeviceSigner;\n}\n\n/** Starknet implementation of the device-signer account adapter. */\nexport class StarknetAdapter implements ChainAdapter {\n readonly chain = \"starknet\" as const;\n\n constructor(private readonly opts: StarknetAdapterOptions) {}\n\n computeAddress({ addressSeed, initialSigner, salt }: ComputeAddressParams): string {\n return hash.calculateContractAddressFromHash(\n num.toHex(salt ?? addressSeed),\n this.opts.classHash,\n this.constructorCalldata(addressSeed, initialSigner),\n 0, // deployerAddress 0 => deterministic counterfactual address\n );\n }\n\n /** Single UDC deploy; the constructor registers the first device signer, so\n * the account is ready the moment it is deployed (fits the paymaster's\n * deploy + execute_from_outside bundle). */\n buildDeploy(params: ComputeAddressParams): ChainCall[] {\n const salt = params.salt ?? params.addressSeed;\n const calldata = this.constructorCalldata(params.addressSeed, params.initialSigner);\n return [\n {\n contractAddress: UDC_ADDRESS,\n entrypoint: \"deployContract\",\n calldata: [\n this.opts.classHash,\n num.toHex(salt),\n \"0x0\", // unique = false -> deployer-independent address\n num.toHex(calldata.length),\n ...calldata,\n ],\n },\n ];\n }\n\n /** Constructor calldata: [address_seed, pub_x_low, pub_x_high, pub_y_low, pub_y_high]. */\n constructorCalldata(addressSeed: bigint, initialSigner: DevicePublicKey): string[] {\n return [num.toHex(addressSeed), ...pubkeyCalldata(initialSigner)];\n }\n\n buildAddSigner(accountAddress: string, signer: DevicePublicKey): ChainCall {\n return { contractAddress: accountAddress, entrypoint: \"add_signer\", calldata: pubkeyCalldata(signer) };\n }\n\n buildRemoveSigner(accountAddress: string, signer: DevicePublicKey): ChainCall {\n return { contractAddress: accountAddress, entrypoint: \"remove_signer\", calldata: pubkeyCalldata(signer) };\n }\n\n async isAuthorizedSigner(accountAddress: string, signer: DevicePublicKey): Promise<boolean> {\n if (!this.opts.provider) throw new Error(\"kit/starknet: provider required for reads\");\n const res = await this.opts.provider.callContract({\n contractAddress: accountAddress,\n entrypoint: \"is_authorized_signer\",\n calldata: pubkeyCalldata(signer),\n });\n return BigInt(res[0] ?? 0) !== 0n;\n }\n\n async buildSignature(txHash: bigint): Promise<string[]> {\n if (!this.opts.signer) throw new Error(\"kit/starknet: signer required to sign\");\n const sig = await this.opts.signer.sign(bigIntTo32Bytes(txHash));\n return signatureToFelts(sig).map((f) => num.toHex(f));\n }\n}\n\n/** Encode a P-256 pubkey as `[x_low, x_high, y_low, y_high]` (two u256s). */\nfunction pubkeyCalldata(pk: DevicePublicKey): string[] {\n const [xl, xh] = u256ToFelts(pk.x);\n const [yl, yh] = u256ToFelts(pk.y);\n return [num.toHex(xl), num.toHex(xh), num.toHex(yl), num.toHex(yh)];\n}\n","import { Signer, num, type ArraySignatureType } from \"starknet\";\nimport type { DeviceSigner } from \"../../signer/DeviceSigner\";\nimport { signatureToFelts } from \"../../crypto/signature\";\nimport { bigIntTo32Bytes } from \"../../crypto/encoding\";\n\n/**\n * A starknet.js `SignerInterface` backed by a device signer. Extends the base\n * `Signer` so all transaction/declare hash computation (v3) is reused; only the\n * raw hash-signing primitive is overridden to sign silently with the device key.\n *\n * Usage:\n * const account = new Account(provider, address, new StarknetDeviceSigner(device), \"1\");\n * await account.execute(calls); // DeviceAccount validates the device signature\n *\n * For gasless flows, hand this signer to your paymaster SDK (e.g. AVNU) the same\n * way you would any starknet.js signer.\n */\nexport class StarknetDeviceSigner extends Signer {\n constructor(private readonly device: DeviceSigner) {\n // Base `pk` is unused: device accounts have no single Stark private key.\n super(\"0x1\");\n }\n\n /** Device accounts are not controlled by a single Stark pubkey. */\n override async getPubKey(): Promise<string> {\n return \"0x0\";\n }\n\n /** Sign the computed tx hash silently with the device signer. */\n protected override async signRaw(msgHash: string): Promise<ArraySignatureType> {\n const sig = await this.device.sign(bigIntTo32Bytes(BigInt(msgHash)));\n return signatureToFelts(sig).map((f) => num.toHex(f));\n }\n}\n","import type { DevicePublicKey } from \"../signer/DeviceSigner\";\n\n/**\n * Off-chain map of `user_id -> wallet`. Because the account address is\n * `f(identity, first_device_pubkey)` (unforgeable, secure), it is NOT derivable\n * from the identity alone on a new device. The backend is the source of truth\n * for \"does this user already have a wallet?\" — enabling multi-device:\n *\n * - First device, unknown user -> deploy a new wallet, then `register`.\n * - Same user, new device -> `lookup` returns the existing wallet; the\n * new device is added as a signer (recovery\n * approval), NOT a new wallet.\n *\n * The backend implements this (it already manages the user<->address binding).\n */\nexport interface WalletRegistry {\n /** The user's existing wallet, or null if they don't have one yet. */\n lookup(userId: string): Promise<RegisteredWallet | null>;\n\n /** Record a freshly deployed wallet for the user (first device). */\n register(params: {\n userId: string;\n address: string;\n initialSigner: DevicePublicKey;\n }): Promise<void>;\n\n /** Note an additional device signer for the user's wallet (after approval). */\n addDevice?(params: {\n userId: string;\n address: string;\n signer: DevicePublicKey;\n }): Promise<void>;\n}\n\nexport interface RegisteredWallet {\n address: string;\n /** Public keys of the devices registered on this wallet (if tracked). */\n devices?: DevicePublicKey[];\n}\n\n/** Simple in-memory registry for demos / tests. */\nexport class InMemoryWalletRegistry implements WalletRegistry {\n private wallets = new Map<string, RegisteredWallet>();\n\n async lookup(userId: string): Promise<RegisteredWallet | null> {\n return this.wallets.get(userId) ?? null;\n }\n async register(params: { userId: string; address: string; initialSigner: DevicePublicKey }) {\n this.wallets.set(params.userId, { address: params.address, devices: [params.initialSigner] });\n }\n async addDevice(params: { userId: string; address: string; signer: DevicePublicKey }) {\n const w = this.wallets.get(params.userId);\n if (w) w.devices = [...(w.devices ?? []), params.signer];\n }\n}\n","import type { DevicePublicKey } from \"../signer/DeviceSigner\";\nimport type { WalletRegistry, RegisteredWallet } from \"./WalletRegistry\";\n\nexport interface HttpWalletRegistryOptions {\n /** Cavos backend base URL (e.g. https://cavos.xyz). */\n baseUrl: string;\n /** The Cavos App ID — authenticates the SDK calls (verifyAppId). */\n appId: string;\n /** Network the wallet lives on (e.g. \"sepolia\"). */\n network: string;\n}\n\n/** Serialize a bigint pubkey component for transport (hex string). */\nfunction toHex(n: bigint): string {\n return \"0x\" + n.toString(16);\n}\n\n/** Parse a hex/decimal string back to a bigint pubkey component. */\nfunction fromHex(s: string): bigint {\n return BigInt(s);\n}\n\n/**\n * WalletRegistry backed by the Cavos backend (`/api/wallets`). This is the\n * persistent, cross-device source of truth for `user_id -> wallet`. The backend\n * stores authorized device signers in `wallet_devices`; the registry maps a\n * backend `userId` (the OAuth `sub`) onto that wallet row.\n */\nexport class HttpWalletRegistry implements WalletRegistry {\n constructor(private readonly opts: HttpWalletRegistryOptions) {}\n\n async lookup(userId: string): Promise<RegisteredWallet | null> {\n const url = new URL(\"/api/wallets\", this.opts.baseUrl);\n url.searchParams.set(\"app_id\", this.opts.appId);\n url.searchParams.set(\"user_social_id\", userId);\n url.searchParams.set(\"network\", this.opts.network);\n\n const res = await fetch(url, { headers: { \"Content-Type\": \"application/json\" } });\n if (!res.ok) throw new Error(`registry lookup failed: ${res.status}`);\n const data = await res.json();\n if (!data.found || !data.address) return null;\n\n const devices: DevicePublicKey[] | undefined = Array.isArray(data.devices)\n ? data.devices.map((d: { pub_x: string; pub_y: string }) => ({\n x: fromHex(d.pub_x),\n y: fromHex(d.pub_y),\n }))\n : undefined;\n\n return { address: data.address, devices };\n }\n\n async register(params: {\n userId: string;\n address: string;\n initialSigner: DevicePublicKey;\n }): Promise<void> {\n const res = await fetch(new URL(\"/api/wallets\", this.opts.baseUrl), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n app_id: this.opts.appId,\n user_social_id: params.userId,\n network: this.opts.network,\n address: params.address,\n // Device-signer wallets send their initial signer (no encrypted blob).\n devices: [{ x: toHex(params.initialSigner.x), y: toHex(params.initialSigner.y) }],\n }),\n });\n if (!res.ok) {\n const t = await res.text().catch(() => \"\");\n throw new Error(`registry register failed: ${res.status} ${t}`);\n }\n }\n\n async addDevice?(params: {\n userId: string;\n address: string;\n signer: DevicePublicKey;\n }): Promise<void> {\n // The backend mirrors `wallet_devices` via the confirm endpoint after an\n // on-chain add_signer, so this is a no-op here (kept for interface parity).\n void params;\n }\n}\n","import type { DevicePublicKey } from \"../signer/DeviceSigner\";\nimport type { RecoveryClient, PendingDeviceRequest } from \"./RecoveryClient\";\n\nexport interface HttpRecoveryClientOptions {\n /** Cavos backend base URL (e.g. https://cavos.xyz). */\n baseUrl: string;\n /** The Cavos App ID — authenticates SDK calls. */\n appId: string;\n}\n\nfunction toHex(n: bigint): string {\n return \"0x\" + n.toString(16);\n}\nfunction fromHex(s: string): bigint {\n return BigInt(s);\n}\n\nfunction deviceLabel(): string {\n if (typeof navigator !== \"undefined\") {\n return navigator.userAgent || \"a new device\";\n }\n return \"a new device\";\n}\n\n/**\n * RecoveryClient backed by the Cavos backend's device-approval relay\n * (`/api/devices/request`). The relay holds NO keys — it stores the pending\n * request, emails the wallet owner, and mirrors the on-chain `add_signer` once a\n * registered device confirms.\n */\nexport class HttpRecoveryClient implements RecoveryClient {\n constructor(private readonly opts: HttpRecoveryClientOptions) {}\n\n async requestDeviceAddition(params: {\n userId: string;\n accountAddress: string;\n newSigner: DevicePublicKey;\n email?: string;\n deviceLabel?: string;\n }): Promise<{ requestId: string }> {\n const res = await fetch(new URL(\"/api/devices/request\", this.opts.baseUrl), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n app_id: this.opts.appId,\n wallet_address: params.accountAddress,\n new_pub_x: toHex(params.newSigner.x),\n new_pub_y: toHex(params.newSigner.y),\n device_label: params.deviceLabel ?? deviceLabel(),\n ...(params.email ? { email: params.email } : {}),\n }),\n });\n if (!res.ok) {\n const t = await res.text().catch(() => \"\");\n throw new Error(`requestDeviceAddition failed: ${res.status} ${t}`);\n }\n const data = await res.json();\n return { requestId: data.request_id };\n }\n\n async getPendingRequest(requestId: string): Promise<PendingDeviceRequest | null> {\n const url = new URL(\"/api/devices/request\", this.opts.baseUrl);\n url.searchParams.set(\"id\", requestId);\n const res = await fetch(url, { headers: { \"Content-Type\": \"application/json\" } });\n if (!res.ok) throw new Error(`getPendingRequest failed: ${res.status}`);\n const data = await res.json();\n if (!data.found) return null;\n\n const status = data.status as PendingDeviceRequest[\"status\"];\n return {\n requestId: data.request_id,\n appId: data.app_id,\n userId: \"\", // the approving device already knows its own identity\n accountAddress: data.wallet_address,\n newSigner: { x: fromHex(data.new_pub_x), y: fromHex(data.new_pub_y) },\n createdAt: data.created_at,\n status,\n };\n }\n\n async confirmDeviceAddition(params: {\n requestId: string;\n txHash: string;\n }): Promise<void> {\n const res = await fetch(\n new URL(`/api/devices/request/${params.requestId}/confirm`, this.opts.baseUrl),\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ tx_hash: params.txHash }),\n },\n );\n if (!res.ok) {\n const t = await res.text().catch(() => \"\");\n throw new Error(`confirmDeviceAddition failed: ${res.status} ${t}`);\n }\n }\n}\n","import { p256 } from \"@noble/curves/p256\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { pbkdf2 } from \"@noble/hashes/pbkdf2\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { randomBytes } from \"@noble/hashes/utils\";\nimport type { DeviceSigner, DevicePublicKey, DeviceSignature } from \"../signer/DeviceSigner\";\nimport { bytesToBigInt, bigIntTo32Bytes } from \"../crypto/encoding\";\nimport { recoverYParity } from \"../crypto/signature\";\n\n/**\n * Self-custodial account recovery via a backup signer derived from a code.\n *\n * The user generates a human-readable recovery code once (see\n * `generateRecoveryCode`). That code is stretched with PBKDF2 + HKDF into a\n * deterministic secp256r1 private key — the SAME key on every device that\n * enters the SAME code. The code never leaves the device: the backend and the\n * chain only ever see the derived public key, which is registered on-chain as\n * an ordinary signer via `add_signer`. Recovering access after losing every\n * device is therefore: enter the code → re-derive the backup key → sign an\n * `add_signer` for the new device. No guardian, no timelock, no custodial key.\n *\n * This module is intentionally chain-agnostic and free of WebCrypto/DOM calls:\n * the derivation is pure `@noble/*` math, so the identical code runs in the\n * browser, React Native, and (eventually) Solana / Stellar / EVM adapters.\n */\n\n/** Fixed domain-separation salt for `deriveBackupKey`. Bumped only to re-derive\n * a new key space (e.g. changing the KDF parameters). Never per-user. */\nconst BACKUP_KDF_SALT = \"cavos-recovery-v1\";\n/** PBKDF2 iteration count. High enough to make brute-forcing a strong code\n * infeasible, low enough that derivation stays well under a second. */\nconst BACKUP_PBKDF2_ITERATIONS = 210_000;\n/** HKDF info string, scopes the derived material to \"backup-signer\". */\nconst BACKUP_HKDF_INFO = \"cavos-backup-signer\";\n\n/** How many words make up a recovery code. 16 words @ 8 bits/word = 128 bits. */\nconst CODE_WORDS = 16;\n\n/**\n * Generate a fresh, human-readable recovery code. The caller MUST present this\n * to the user exactly once and never persist it server-side. ~128 bits of\n * entropy encoded as words from a fixed wordlist (BIP39-style but our own list,\n * so we don't pull a dependency on a BIP39 wordfile).\n */\nexport function generateRecoveryCode(): string {\n const bytes = randomBytes(CODE_WORDS);\n const words: string[] = [];\n for (const b of bytes) words.push(WORDLIST[b]);\n return words.join(\" \");\n}\n\n/**\n * Deterministically derive a secp256r1 keypair from a recovery code. Pure\n * function: the same normalised code always yields the same keypair, on any\n * runtime. Returns the raw 32-byte private key (so it can be wrapped in a\n * `BackupSigner` or fed to any chain adapter) plus the public key coordinates\n * the contract stores as an authorised signer.\n *\n * Normalisation trims surrounding whitespace and collapses runs of spaces, so\n * \"a b\" and \"a b\" derive the same key regardless of how the code was pasted.\n */\nexport function deriveBackupKey(code: string): {\n privateKey: Uint8Array;\n publicKey: DevicePublicKey;\n} {\n const normalised = code.trim().replace(/\\s+/g, \" \").toLowerCase();\n if (!normalised) throw new Error(\"kit: recovery code is empty\");\n\n // Stretch the low-entropy-ish human code into 32 bytes with PBKDF2, then mix\n // into a scoped seed with HKDF. PBKDF2 also serves as the brute-force brake.\n const stretched = pbkdf2(\n sha256,\n new TextEncoder().encode(normalised),\n new TextEncoder().encode(BACKUP_KDF_SALT),\n { c: BACKUP_PBKDF2_ITERATIONS, dkLen: 32 },\n );\n const seed = hkdf(sha256, stretched, undefined, BACKUP_HKDF_INFO, 32);\n\n // Reduce the seed to a valid secp256r1 scalar. The seed is 32 bytes (< n with\n // overwhelming probability); reducing mod n keeps it a valid private key\n // without bias that matters in practice for an HMAC-stretched 256-bit input.\n const d = bytesToBigInt(seed) % p256.CURVE.n;\n if (d === 0n) throw new Error(\"kit: derived backup key is zero (retry with a new code)\");\n\n const priv = bigIntTo32Bytes(d);\n // isCompressed = false → uncompressed point (0x04 || X || Y, 65 bytes), so the\n // X/Y split below is correct. The default would return a 33-byte compressed\n // point and the Y half would be empty.\n const pub = p256.getPublicKey(priv, false);\n return {\n privateKey: priv,\n publicKey: { x: bytesToBigInt(pub.subarray(1, 33)), y: bytesToBigInt(pub.subarray(33, 65)) },\n };\n}\n\n/**\n * A `DeviceSigner` backed by an in-memory backup key derived from a recovery\n * code. Used transiently during recovery to sign the `add_signer` that\n * authorises a new device — it is NOT persisted and should not be reused as a\n * device signer. The key material lives only for the duration of the recovery\n * transaction.\n */\nexport class BackupSigner implements DeviceSigner {\n private readonly privateKey: Uint8Array;\n private readonly publicKeyValue: DevicePublicKey;\n\n constructor(privateKey: Uint8Array, publicKey: DevicePublicKey) {\n this.privateKey = privateKey;\n this.publicKeyValue = publicKey;\n }\n\n /** Build a signer from a recovery code (derive + wrap in one step). */\n static fromCode(code: string): BackupSigner {\n const { privateKey, publicKey } = deriveBackupKey(code);\n return new BackupSigner(privateKey, publicKey);\n }\n\n async getPublicKey(): Promise<DevicePublicKey> {\n return this.publicKeyValue;\n }\n\n async sign(txHash: Uint8Array): Promise<DeviceSignature> {\n // Mirror the WebCrypto path exactly: WebCrypto's `subtle.sign({ hash:\n // 'SHA-256' }, key, txHash)` hashes `txHash` with SHA-256 and signs the\n // digest. `p256.sign(msgHash)` signs the bytes it's given WITHOUT hashing,\n // so we pre-hash here to produce the same (r, s) the contract verifies.\n const digest = sha256(txHash);\n const sig = p256.sign(digest, this.privateKey);\n const yParity = recoverYParity(sig.r, sig.s, digest, this.publicKeyValue);\n return { r: sig.r, s: sig.s, yParity };\n }\n}\n\n// 256 short, unambiguous, lowercase English words. Chosen to be hard to\n// misread and easy to type; not the full BIP39 list (we don't need 2048 — 8\n// bits/word is plenty at 16 words). Keep this list stable: changing it changes\n// the meaning of every existing recovery code. Must stay exactly 256 unique\n// entries so each byte value maps to one word.\nconst WORDLIST = [\n \"able\", \"acid\", \"amber\", \"apple\", \"arch\", \"arrow\", \"ashen\", \"atlas\",\n \"axis\", \"badge\", \"baker\", \"balm\", \"banner\", \"basin\", \"beacon\", \"bench\",\n \"beryl\", \"birch\", \"blade\", \"bloom\", \"bluer\", \"border\", \"brave\", \"brick\",\n \"brook\", \"cabin\", \"candle\", \"carbon\", \"cargo\", \"cedar\", \"chalk\", \"charm\",\n \"chrome\", \"cipher\", \"clam\", \"clasp\", \"cliff\", \"clock\", \"cobia\", \"comet\",\n \"coral\", \"cotton\", \"coves\", \"crane\", \"crest\", \"crow\", \"crystal\", \"curio\",\n \"dawn\", \"delta\", \"denim\", \"depth\", \"dewy\", \"digger\", \"docks\", \"dover\",\n \"drift\", \"dunes\", \"eagle\", \"ember\", \"echo\", \"eden\", \"elite\", \"ethic\",\n \"fable\", \"falcon\", \"fawn\", \"feather\", \"fern\", \"fjord\", \"flame\", \"flint\",\n \"forest\", \"forge\", \"frost\", \"garnet\", \"gemini\", \"glade\", \"glider\", \"glow\",\n \"granite\", \"grove\", \"guppy\", \"harbor\", \"haven\", \"hazel\", \"helio\", \"heron\",\n \"hickory\", \"honey\", \"horizon\", \"ivory\", \"jade\", \"jasper\", \"kestrel\", \"knot\",\n \"lagoon\", \"lattice\", \"laurel\", \"lavender\", \"lemon\", \"linden\", \"loon\", \"luger\",\n \"lumen\", \"lunar\", \"mango\", \"maple\", \"marble\", \"marsh\", \"meadow\", \"mercy\",\n \"mistle\", \"monsoon\", \"morning\", \"moss\", \"nacre\", \"nectar\", \"needle\", \"nimbus\",\n \"nova\", \"ocean\", \"onyx\", \"orbit\", \"otter\", \"palm\", \"panda\", \"pansy\",\n \"papaya\", \"passage\", \"pebble\", \"pelican\", \"pepper\", \"petal\", \"piano\", \"pierce\",\n \"pilot\", \"pioneer\", \"platinum\", \"plume\", \"poplar\", \"porpoise\", \"prairie\", \"prism\",\n \"pulsar\", \"quartz\", \"quasar\", \"quill\", \"quiver\", \"raven\", \"reef\", \"relic\",\n \"ridge\", \"ripple\", \"robin\", \"rocket\", \"rouge\", \"ruby\", \"saffron\", \"sage\",\n \"sail\", \"salmon\", \"sapphire\", \"scarab\", \"shadow\", \"shale\", \"sienna\", \"silica\",\n \"silver\", \"skyline\", \"slate\", \"sonar\", \"spruce\", \"starling\", \"stone\", \"sugar\",\n \"summit\", \"sunset\", \"swan\", \"tangent\", \"tarragon\", \"temple\", \"thistle\", \"thrush\",\n \"tiger\", \"topaz\", \"tundra\", \"turtle\", \"umber\", \"union\", \"valley\", \"vapor\",\n \"vector\", \"velvet\", \"violet\", \"vortex\", \"walnut\", \"whale\", \"winter\", \"wisp\",\n \"wisteria\", \"xenon\", \"yarrow\", \"zephyr\", \"zinc\", \"zodiac\", \"anchor\", \"basil\",\n \"cider\", \"daisy\", \"elfin\", \"ferry\", \"gimlet\", \"halcyon\", \"indigo\", \"juniper\",\n \"kindle\", \"lilac\", \"mantis\", \"nylon\", \"oracle\", \"parch\", \"quokka\", \"ramble\",\n \"thatch\", \"ultra\", \"vivid\", \"xylo\", \"yodel\", \"zesty\", \"arbor\", \"bliss\",\n \"calyx\", \"dwindle\", \"folio\", \"globe\", \"hymn\", \"ionic\", \"jolly\", \"knack\",\n \"lyric\", \"myrtle\", \"noble\", \"plumb\", \"quaint\", \"rustic\", \"satin\", \"timber\",\n \"urge\", \"vault\", \"whimsy\", \"yearn\", \"zenith\", \"ash\", \"beach\", \"dusk\",\n];\n","import { hash } from \"starknet\";\n\n/**\n * The address seed binds a wallet to a stable, backend-managed user identity.\n * The deterministic account address is derived from this seed + salt ONLY — never\n * from a device pubkey — so the same user resolves to the same wallet on any\n * device. The backend owns the user_id <-> address mapping off-chain.\n */\nexport interface IdentityInput {\n /** Stable, backend-managed user identifier (e.g. from email / magic link). */\n userId: string;\n /** Per-app salt, so the same user has distinct wallets across apps. */\n appSalt: string;\n}\n\n/** Derive the felt `address_seed` passed to the contract constructor. */\nexport function deriveAddressSeed({ userId, appSalt }: IdentityInput): bigint {\n // Poseidon over the identity components; stable and collision-resistant.\n const h = hash.computePoseidonHashOnElements([feltFromString(userId), feltFromString(appSalt)]);\n return BigInt(h);\n}\n\n/** Map an arbitrary UTF-8 string into a felt via Poseidon over its byte chunks. */\nfunction feltFromString(s: string): bigint {\n const bytes = new TextEncoder().encode(s);\n const chunks: bigint[] = [];\n for (let i = 0; i < bytes.length; i += 31) {\n let w = 0n;\n for (const b of bytes.subarray(i, i + 31)) w = (w << 8n) | BigInt(b);\n chunks.push(w);\n }\n if (chunks.length === 0) return 0n;\n if (chunks.length === 1) return chunks[0];\n return BigInt(hash.computePoseidonHashOnElements(chunks));\n}\n","import { Account, RpcProvider, PaymasterRpc, num, type Call } from \"starknet\";\nimport type { AuthProvider, Identity } from \"./auth/AuthProvider\";\nimport type { DeviceSigner, DevicePublicKey } from \"./signer/DeviceSigner\";\nimport { WebCryptoSigner } from \"./signer/WebCryptoSigner\";\nimport { StarknetAdapter } from \"./chains/starknet/StarknetAdapter\";\nimport { StarknetDeviceSigner } from \"./chains/starknet/StarknetDeviceSigner\";\nimport type { ChainCall } from \"./chains/ChainAdapter\";\nimport type { WalletRegistry } from \"./registry/WalletRegistry\";\nimport { InMemoryWalletRegistry } from \"./registry/WalletRegistry\";\nimport { HttpWalletRegistry } from \"./registry/HttpWalletRegistry\";\nimport type { RecoveryClient } from \"./recovery/RecoveryClient\";\nimport { HttpRecoveryClient } from \"./recovery/HttpRecoveryClient\";\nimport { BackupSigner, deriveBackupKey } from \"./recovery/BackupSigner\";\nimport { deriveAddressSeed } from \"./identity\";\nimport {\n CAVOS_PAYMASTER_URL,\n DEVICE_ACCOUNT_CLASS_HASH,\n STARKNET_NETWORKS,\n type StarknetNetwork,\n} from \"./chains/starknet/constants\";\n\nexport interface ConnectOptions {\n network: StarknetNetwork;\n /** Authenticated user (pass `identity` directly, or an `auth` provider). */\n auth?: AuthProvider;\n identity?: Identity;\n appSalt: string;\n /**\n * Cavos App ID. When set (with `backendUrl`), the kit uses the hosted\n * WalletRegistry + RecoveryClient by default for real multi-device support.\n */\n appId?: string;\n /** Cavos backend base URL. Defaults to https://cavos.xyz. */\n backendUrl?: string;\n /**\n * Off-chain user_id -> wallet map. Defaults to the hosted HttpWalletRegistry\n * when `appId` is set, else an in-memory registry (single-device only).\n */\n registry?: WalletRegistry;\n /**\n * Device-approval relay. Defaults to HttpRecoveryClient when `appId` is set;\n * used to request addition of this device when it isn't an authorized signer.\n */\n recovery?: RecoveryClient;\n /** Cavos paymaster API key (sponsors deploy + execute). */\n paymasterApiKey: string;\n paymasterUrl?: string;\n rpcUrl?: string;\n classHash?: string;\n /** Override the device signer factory (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n}\n\n/** Whether this device can already operate the wallet, or needs to be added. */\nexport type ConnectStatus = \"ready\" | \"needs-device-approval\";\n\n/** Options for recovering an account after losing every device signer. */\nexport interface RecoveryOptions {\n /** The recovery code the user stored when they ran setupRecovery. */\n code: string;\n /** Authenticated identity (same user who owns the account). */\n identity: Identity;\n network: StarknetNetwork;\n appSalt: string;\n paymasterApiKey: string;\n appId?: string;\n backendUrl?: string;\n rpcUrl?: string;\n paymasterUrl?: string;\n classHash?: string;\n /** Off-chain user_id -> wallet map. Defaults to the hosted registry. */\n registry?: WalletRegistry;\n /** Override the new device's signer (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n}\n\n/**\n * High-level Cavos wallet. One call logs the user in and returns a ready, gas-\n * sponsored smart account controlled by a silent device key.\n *\n * const cavos = await Cavos.connect({ network, identity, appSalt, registry, paymasterApiKey });\n * if (cavos.status === \"ready\") await cavos.execute(calls);\n *\n * The account address is `f(identity, device_pubkey)` — unforgeable, so it can't\n * be hijacked. The `registry` recognizes returning users across devices: a new\n * device on an existing account is flagged `needs-device-approval` (add it via\n * an already-registered device) instead of creating a second wallet.\n */\nexport class Cavos {\n /** Request id of the pending device-addition, when status is needs-device-approval. */\n pendingRequestId: string | null = null;\n\n private constructor(\n readonly identity: Identity,\n readonly address: string,\n readonly status: ConnectStatus,\n readonly account: Account,\n private readonly adapter: StarknetAdapter,\n private readonly devicePubkey: DevicePublicKey,\n ) {}\n\n static async connect(opts: ConnectOptions): Promise<Cavos> {\n const identity = opts.identity ?? (await opts.auth?.authenticate());\n if (!identity) throw new Error(\"kit: connect requires `identity` or `auth`\");\n\n const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[opts.network];\n if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${opts.network}`);\n\n const provider = new RpcProvider({\n nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[opts.network].rpcUrl,\n });\n const paymaster = new PaymasterRpc({\n nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[opts.network],\n headers: { \"x-paymaster-api-key\": opts.paymasterApiKey },\n });\n\n const addressSeed = deriveAddressSeed({ userId: identity.userId, appSalt: opts.appSalt });\n\n // This device's silent signer.\n const signer = opts.createSigner\n ? await opts.createSigner(`${identity.userId}:${opts.appSalt}`)\n : await WebCryptoSigner.loadOrCreate({ keyId: `${identity.userId}:${opts.appSalt}` });\n const devicePubkey = await signer.getPublicKey();\n\n const adapter = new StarknetAdapter({ classHash, signer, provider });\n const makeAccount = (address: string) =>\n new Account({\n provider,\n address,\n signer: new StarknetDeviceSigner(signer),\n paymaster,\n cairoVersion: \"1\",\n });\n\n // Returning user? The registry knows their wallet (address is device-bound,\n // so it isn't derivable from identity alone). Default to the hosted\n // HttpWalletRegistry when appId is provided, else an in-memory map.\n const backendUrl = opts.backendUrl ?? \"https://cavos.xyz\";\n const registry =\n opts.registry ??\n (opts.appId\n ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network: opts.network })\n : defaultRegistry);\n const recovery =\n opts.recovery ?? (opts.appId ? new HttpRecoveryClient({ baseUrl: backendUrl, appId: opts.appId }) : null);\n const existing = await registry.lookup(identity.userId);\n\n if (existing) {\n const account = makeAccount(existing.address);\n const isSigner = await adapter.isAuthorizedSigner(existing.address, devicePubkey);\n const cavos = new Cavos(\n identity,\n existing.address,\n isSigner ? \"ready\" : \"needs-device-approval\",\n account,\n adapter,\n devicePubkey,\n );\n\n // New device on an existing wallet: ask the backend to email the owner an\n // approval link. The approving device signs add_signer on-chain; this device\n // becomes \"ready\" after that. Best-effort: never blocks the connect result.\n //\n // De-duplicate within a short window so a page refresh, reconnect, or\n // rapid retry doesn't spam the owner with one email per attempt. The\n // backend already dedups by request id within its 24h TTL, but that still\n // re-sends the email on each fresh request id — this client-side guard\n // collapses the burst. We keep the last requestId and reuse it.\n if (!isSigner && recovery) {\n const dedup = lastDeviceRequest.get(identity.userId);\n const fresh = dedup && Date.now() - dedup.requestedAt < DEVICE_REQUEST_DEDUP_MS;\n try {\n if (fresh) {\n cavos.pendingRequestId = dedup!.requestId;\n } else {\n const { requestId } = await recovery.requestDeviceAddition({\n userId: identity.userId,\n accountAddress: existing.address,\n newSigner: devicePubkey,\n ...(identity.email ? { email: identity.email } : {}),\n });\n cavos.pendingRequestId = requestId;\n lastDeviceRequest.set(identity.userId, { requestId, requestedAt: Date.now() });\n }\n } catch (e) {\n console.warn(\"[Cavos] requestDeviceAddition failed:\", e);\n }\n }\n return cavos;\n }\n\n // Compute the deterministic address for (identity, this device). The address\n // is device-bound, so it's NOT in the registry for a new device — but it may\n // already be deployed on-chain (same device reconnecting, or a re-run after a\n // deploy that succeeded before a timeout). Ask the chain before deploying:\n // re-deploying an existing account reverts (\"contract already deployed\").\n const address = adapter.computeAddress({ addressSeed, initialSigner: devicePubkey });\n const account = makeAccount(address);\n const alreadyDeployed = await isDeployed(provider, address);\n\n if (!alreadyDeployed) {\n const deploymentData = {\n address,\n class_hash: classHash,\n salt: num.toHex(addressSeed),\n calldata: adapter.constructorCalldata(addressSeed, devicePubkey),\n version: 1 as const,\n };\n const deployRes = await account.executePaymasterTransaction([], {\n feeMode: { mode: \"sponsored\" },\n deploymentData,\n });\n // Wait for the deploy to land before declaring the device \"ready\". Assuming\n // readiness here would report \"ready\" if the tx silently failed or hadn't\n // indexed yet — and the user would hit a confusing error on their first tx.\n try {\n await provider.waitForTransaction(deployRes.transaction_hash);\n } catch (e) {\n console.warn(\"[Cavos] deploy receipt wait failed:\", e);\n }\n }\n\n // Record the wallet (idempotent for reconnects) and resolve readiness from\n // the chain: this device is \"ready\" iff its pubkey is an authorized signer.\n // We re-read even right after a fresh deploy, so a deploy that failed to\n // index (or silently reverted) surfaces as needs-device-approval rather than\n // a false \"ready\".\n await registry.register({ userId: identity.userId, address, initialSigner: devicePubkey });\n let isSigner: boolean;\n try {\n isSigner = await adapter.isAuthorizedSigner(address, devicePubkey);\n } catch (e) {\n // Fall back to the deploy assumption only if the chain read itself errors\n // (e.g. node hiccup right after indexing) — the deploy did submit.\n console.warn(\"[Cavos] isAuthorizedSigner read failed:\", e);\n isSigner = !alreadyDeployed;\n }\n\n return new Cavos(\n identity,\n address,\n isSigner ? \"ready\" : \"needs-device-approval\",\n account,\n adapter,\n devicePubkey,\n );\n }\n\n /** This device's public key (e.g. to request addition to an existing wallet). */\n get publicKey(): DevicePublicKey {\n return this.devicePubkey;\n }\n\n /** Execute a sponsored (gasless) multicall, signed silently by the device. */\n async execute(calls: ChainCall[]): Promise<{ transactionHash: string }> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit: this device is not yet an authorized signer of the wallet\");\n }\n const res = await this.account.executePaymasterTransaction(calls as Call[], {\n feeMode: { mode: \"sponsored\" },\n });\n return { transactionHash: res.transaction_hash };\n }\n\n /** Authorize an additional device signer (sponsored). Self-submitted. */\n async addSigner(pubkey: DevicePublicKey): Promise<{ transactionHash: string }> {\n return this.execute([this.adapter.buildAddSigner(this.address, pubkey)]);\n }\n\n /**\n * Register a self-custodial backup signer derived from `code`, so the account\n * can be recovered after the user loses every device. Idempotent: if the\n * derived backup key is already an authorised signer, this is a no-op.\n *\n * The code never leaves the device — only its deterministic public key is\n * added on-chain as an ordinary signer. Sponsor this like any other\n * add_signer (gasless). Returns the transaction hash (or undefined when the\n * backup was already set up).\n */\n async setupRecovery(code: string): Promise<{ transactionHash: string } | undefined> {\n const { publicKey: backupPubkey } = deriveBackupKey(code);\n // Skip the on-chain call if the backup signer is already registered.\n const already = await this.adapter.isAuthorizedSigner(this.address, backupPubkey);\n if (already) return undefined;\n return this.addSigner(backupPubkey);\n }\n\n /**\n * Recover an account after losing every device signer. Derives the backup key\n * from `code`, uses it (not the new device key) to sign an `add_signer` for\n * the new device, and returns a ready Cavos bound to the new device. The\n * account address is unchanged.\n *\n * Self-custodial: only someone holding the code (i.e. the rightful owner) can\n * re-derive the backup key. The backend never sees the code.\n */\n static async recover(opts: RecoveryOptions): Promise<Cavos> {\n const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[opts.network];\n if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${opts.network}`);\n\n const provider = new RpcProvider({\n nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[opts.network].rpcUrl,\n });\n const paymaster = new PaymasterRpc({\n nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[opts.network],\n headers: { \"x-paymaster-api-key\": opts.paymasterApiKey },\n });\n\n // The new device's signer (created/loaded the same way connect() does).\n const signer = opts.createSigner\n ? await opts.createSigner(`${opts.identity.userId}:${opts.appSalt}`)\n : await WebCryptoSigner.loadOrCreate({ keyId: `${opts.identity.userId}:${opts.appSalt}` });\n const devicePubkey = await signer.getPublicKey();\n\n // The backup key drives THIS transaction: it's the only signer that can\n // authorise adding the new device after all device keys are lost.\n const backup = BackupSigner.fromCode(opts.code);\n const backupAdapter = new StarknetAdapter({ classHash, signer: backup, provider });\n\n const backendUrl = opts.backendUrl ?? \"https://cavos.xyz\";\n const registry =\n opts.registry ??\n (opts.appId\n ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network: opts.network })\n : defaultRegistry);\n const existing = await registry.lookup(opts.identity.userId);\n if (!existing) {\n throw new Error(\"kit: no account found for this identity — nothing to recover\");\n }\n\n // Authorise the new device, signed by the backup key (sponsored).\n const backupAccount = new Account({\n provider,\n address: existing.address,\n signer: new StarknetDeviceSigner(backup),\n paymaster,\n cairoVersion: \"1\",\n });\n const alreadyAuthed = await backupAdapter.isAuthorizedSigner(existing.address, devicePubkey);\n if (!alreadyAuthed) {\n const res = await backupAccount.executePaymasterTransaction(\n [backupAdapter.buildAddSigner(existing.address, devicePubkey)],\n { feeMode: { mode: \"sponsored\" } },\n );\n try {\n await provider.waitForTransaction(res.transaction_hash);\n } catch (e) {\n console.warn(\"[Cavos] recovery add_signer receipt wait failed:\", e);\n }\n }\n\n // Hand control to the new device's signer for all future operations.\n const adapter = new StarknetAdapter({ classHash, signer, provider });\n const account = new Account({\n provider,\n address: existing.address,\n signer: new StarknetDeviceSigner(signer),\n paymaster,\n cairoVersion: \"1\",\n });\n return new Cavos(opts.identity, existing.address, \"ready\", account, adapter, devicePubkey);\n }\n}\n\n/**\n * Shared in-memory registry used when `ConnectOptions.registry` is omitted.\n * Module-level so a returning user is recognized within a single browser session\n * (real cross-device recognition needs an HTTP backend implementation).\n */\nconst defaultRegistry = new InMemoryWalletRegistry();\n\n/**\n * Client-side de-duplication of device-addition requests, keyed by user id. A\n * burst of connects (refresh, reconnect, retry) within this window reuses the\n * last requestId instead of emailing the owner again. Runtime-agnostic — works\n * without DOM/localStorage so the same code runs on native.\n */\nconst DEVICE_REQUEST_DEDUP_MS = 5 * 60 * 1000; // 5 minutes\nconst lastDeviceRequest = new Map<string, { requestId: string; requestedAt: number }>();\n\n/** Whether an account contract is already deployed at `address`. */\nasync function isDeployed(provider: RpcProvider, address: string): Promise<boolean> {\n try {\n const classHash = await provider.getClassHashAt(address);\n return !!classHash && classHash !== \"0x0\";\n } catch {\n return false;\n }\n}\n","/**\n * Identity for a Cavos wallet. Login (email / social / OTP) only ever produces a\n * stable `userId`; that's all the wallet needs to derive its address. Auth never\n * touches signing — the device key does that, silently.\n *\n * Privy-style UX: the user \"logs in\" and the wallet is provisioned behind the\n * scenes (device key + auto-deployed smart account). The app never handles keys.\n */\nexport interface Identity {\n /** Stable, backend-managed user identifier. */\n userId: string;\n /** Optional metadata (email, provider) for display only. */\n email?: string;\n provider?: \"google\" | \"apple\" | \"email\" | \"otp\" | string;\n}\n\n/**\n * Authenticates a user and returns their stable identity. Implementations:\n * - `CavosAuth` (hosted, mirrors `@cavos/react`: Google/Apple/email/OTP via the\n * Cavos backend) — the default, Privy-like experience.\n * - any custom provider (the app already authenticated the user elsewhere).\n */\nexport interface AuthProvider {\n authenticate(): Promise<Identity>;\n}\n\n/** Trivial provider when the app already has the user's stable id. */\nexport class StaticIdentity implements AuthProvider {\n constructor(private readonly identity: Identity) {}\n async authenticate(): Promise<Identity> {\n return this.identity;\n }\n}\n","import { hash, num } from \"starknet\";\nimport type { AuthProvider, Identity } from \"./AuthProvider\";\n\nexport interface CavosAuthOptions {\n /** Cavos backend base URL. Defaults to the hosted service (same as @cavos/react). */\n backendUrl?: string;\n /** App identifier registered with Cavos (the `appId` from the dashboard). */\n appId?: string;\n}\n\n/**\n * Hosted login (Privy-like) backed by the Cavos backend — same endpoints\n * `@cavos/react` uses (Google / Apple OAuth + Firebase email OTP). Login only\n * resolves a stable `userId` (the OAuth `sub` claim); it never touches signing.\n * Feed the returned `Identity` to `Cavos.connect`.\n *\n * const auth = new CavosAuth({ appId });\n * // social: open the returned URL; user returns, then:\n * const identity = await auth.handleCallback(window.location.search);\n * // or email OTP:\n * await auth.sendOtp(email); const identity = await auth.verifyOtp(email, code);\n * const cavos = await Cavos.connect({ network, appSalt, identity, paymasterApiKey });\n *\n * Device-signer model note: the backend issues a Cavos JWT (the same one react\n * uses for on-chain RSA verification). Here we only need the stable `sub` claim\n * from it — the RSA/JWKS/nonce machinery react relies on is dead weight for the\n * device model, because the device key (not the JWT) authorizes on-chain calls.\n * We still send a `nonce` (Poseidon over random bytes) since the backend expects\n * it on the request; the value itself is irrelevant to us.\n */\nexport class CavosAuth implements AuthProvider {\n private readonly backendUrl: string;\n /** Most recent nonce sent to the backend (for the pending OAuth/OTP request). */\n private pendingNonce: string | null = null;\n private last: Identity | null = null;\n\n constructor(private readonly opts: CavosAuthOptions = {}) {\n this.backendUrl = opts.backendUrl ?? \"https://cavos.xyz\";\n }\n\n /** Redirect URL for Google login (open it; user returns to your redirectUri). */\n async getGoogleOAuthUrl(redirectUri?: string): Promise<string> {\n return this.oauthUrl(\"google\", redirectUri);\n }\n\n /** Redirect URL for Apple login. */\n async getAppleOAuthUrl(redirectUri?: string): Promise<string> {\n return this.oauthUrl(\"apple\", redirectUri);\n }\n\n private async oauthUrl(provider: \"google\" | \"apple\", redirectUri?: string): Promise<string> {\n if (typeof window === \"undefined\") throw new Error(\"kit/auth: OAuth requires a browser\");\n const params = new URLSearchParams({\n nonce: this.freshNonce(),\n redirect_uri: redirectUri ?? window.location.href,\n ...(this.opts.appId ? { app_id: this.opts.appId } : {}),\n });\n const { url } = await this.get(`/api/oauth/${provider}?${params}`);\n return url;\n }\n\n /**\n * Resolve the identity from an OAuth callback. The auth data is carried in the\n * `auth_data` (or `zk_auth_data`) query param on return. We only extract `sub`.\n */\n async handleCallback(authDataOrSearch: string): Promise<Identity> {\n const authData = extractAuthData(authDataOrSearch);\n return this.identityFromAuthData(authData, \"oauth\");\n }\n\n /** Send a one-time code to an email (Firebase OTP). */\n async sendOtp(email: string): Promise<void> {\n await this.post(\"/api/oauth/firebase/otp/request\", {\n email,\n nonce: this.freshNonce(),\n ...(this.opts.appId ? { app_id: this.opts.appId } : {}),\n });\n }\n\n /** Send a passwordless magic-link sign-in email (Firebase). */\n async sendMagicLink(email: string): Promise<void> {\n await this.post(\"/api/oauth/firebase/magic-link\", {\n email,\n nonce: this.freshNonce(),\n ...(this.opts.appId ? { app_id: this.opts.appId } : {}),\n ...(typeof window !== \"undefined\" ? { redirect_uri: window.location.href } : {}),\n });\n }\n\n /** Verify the OTP and resolve the identity. */\n async verifyOtp(email: string, code: string): Promise<Identity> {\n const res = await this.post(\"/api/oauth/firebase/otp/verify\", {\n email,\n code,\n nonce: this.consumeNonce(),\n ...(this.opts.appId ? { app_id: this.opts.appId } : {}),\n });\n return this.identityFromAuthData(res.id_token ?? res.jwt ?? res.token ?? JSON.stringify(res), \"otp\", email);\n }\n\n /** AuthProvider: returns the identity resolved by the last login step. */\n async authenticate(): Promise<Identity> {\n if (!this.last) throw new Error(\"kit/auth: no identity yet — complete a login first\");\n return this.last;\n }\n\n // ── internals ──────────────────────────────────────────────────────────────\n\n /**\n * Build an `Identity` from whatever the backend returned. The Cavos backend\n * wraps the user id in a JWT (its `sub` claim); for the device model we only\n * need that stable id — the signature is never checked on-chain.\n */\n private async identityFromAuthData(\n authData: string,\n provider: string,\n emailOverride?: string,\n ): Promise<Identity> {\n let token = authData;\n try {\n const parsed = JSON.parse(authData);\n token = parsed.id_token ?? parsed.jwt ?? parsed.token ?? authData;\n } catch {\n // raw JWT\n }\n const claims = parseJwt(token);\n return this.remember({\n userId: String(claims.sub ?? claims.user_id ?? claims.uid),\n email: claims.email ?? emailOverride,\n provider: claims.firebase?.sign_in_provider ?? claims.provider ?? provider,\n });\n }\n\n /** Generate (and remember) the nonce the Cavos backend expects on requests. */\n private freshNonce(): string {\n // 31-byte random felt; matches the shape the backend validates, value is\n // irrelevant to the device-signer model.\n const bytes = crypto.getRandomValues(new Uint8Array(31));\n const h = hash.computePoseidonHashOnElements([bytesToChunks(bytes)]);\n this.pendingNonce = num.toHex(h);\n return this.pendingNonce;\n }\n\n /** Return the pending nonce (for the verify step), clearing it. */\n private consumeNonce(): string {\n if (!this.pendingNonce) return this.freshNonce();\n const n = this.pendingNonce;\n this.pendingNonce = null;\n return n;\n }\n\n private remember(id: Identity): Identity {\n this.last = id;\n return id;\n }\n\n private async get(path: string): Promise<any> {\n const r = await fetch(`${this.backendUrl}${path}`);\n if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);\n return r.json();\n }\n\n private async post(path: string, body: unknown): Promise<any> {\n const r = await fetch(`${this.backendUrl}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);\n return r.json();\n }\n}\n\n/** Pull the `auth_data` / `zk_auth_data` value out of a callback string. */\nfunction extractAuthData(input: string): string {\n if (input.includes(\"auth_data=\") || input.includes(\"zk_auth_data=\")) {\n const params = new URLSearchParams(input.startsWith(\"?\") ? input : `?${input}`);\n return params.get(\"auth_data\") ?? params.get(\"zk_auth_data\") ?? input;\n }\n return input;\n}\n\n/** Decode a JWT payload (no verification — the backend already validated it). */\nfunction parseJwt(jwt: string): any {\n const part = jwt.split(\".\")[1];\n if (!part) throw new Error(\"kit/auth: malformed JWT\");\n const json = atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return JSON.parse(json);\n}\n\n/** Pack a byte array into the felt252 chunks Poseidon hashes over. */\nfunction bytesToChunks(bytes: Uint8Array): bigint {\n let w = 0n;\n for (const b of bytes.subarray(0, 31)) w = (w << 8n) | BigInt(b);\n return w;\n}\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { BackupSigner, Cavos, CavosAuth, DEVICE_ACCOUNT_CLASS_HASH, HttpRecoveryClient, HttpWalletRegistry, InMemoryWalletRegistry, STARKNET_NETWORKS, StarknetAdapter, StarknetDeviceSigner, UDC_ADDRESS, WebCryptoSigner, bigIntTo32Bytes, bytesToBigInt, bytesToHex, deriveAddressSeed, deriveBackupKey, generateRecoveryCode, hexToBytes, recoverYParity, signatureToFelts, u256ToFelts } from './chunk-XWBX2ZIO.mjs';
|
|
2
|
+
|
|
3
|
+
// src/auth/AuthProvider.ts
|
|
4
|
+
var StaticIdentity = class {
|
|
5
|
+
constructor(identity) {
|
|
6
|
+
this.identity = identity;
|
|
7
|
+
}
|
|
8
|
+
async authenticate() {
|
|
9
|
+
return this.identity;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export { StaticIdentity };
|
|
14
|
+
//# sourceMappingURL=index.mjs.map
|
|
15
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth/AuthProvider.ts"],"names":[],"mappings":";;;AA2BO,IAAM,iBAAN,MAA6C;AAAA,EAClD,YAA6B,QAAA,EAAoB;AAApB,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EAAqB;AAAA,EAClD,MAAM,YAAA,GAAkC;AACtC,IAAA,OAAO,IAAA,CAAK,QAAA;AAAA,EACd;AACF","file":"index.mjs","sourcesContent":["/**\n * Identity for a Cavos wallet. Login (email / social / OTP) only ever produces a\n * stable `userId`; that's all the wallet needs to derive its address. Auth never\n * touches signing — the device key does that, silently.\n *\n * Privy-style UX: the user \"logs in\" and the wallet is provisioned behind the\n * scenes (device key + auto-deployed smart account). The app never handles keys.\n */\nexport interface Identity {\n /** Stable, backend-managed user identifier. */\n userId: string;\n /** Optional metadata (email, provider) for display only. */\n email?: string;\n provider?: \"google\" | \"apple\" | \"email\" | \"otp\" | string;\n}\n\n/**\n * Authenticates a user and returns their stable identity. Implementations:\n * - `CavosAuth` (hosted, mirrors `@cavos/react`: Google/Apple/email/OTP via the\n * Cavos backend) — the default, Privy-like experience.\n * - any custom provider (the app already authenticated the user elsewhere).\n */\nexport interface AuthProvider {\n authenticate(): Promise<Identity>;\n}\n\n/** Trivial provider when the app already has the user's stable id. */\nexport class StaticIdentity implements AuthProvider {\n constructor(private readonly identity: Identity) {}\n async authenticate(): Promise<Identity> {\n return this.identity;\n }\n}\n"]}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import react__default, { ReactNode } from 'react';
|
|
3
|
+
import { S as StarknetNetwork, C as ChainCall } from '../constants-C530TZFF.mjs';
|
|
4
|
+
|
|
5
|
+
interface CavosConfig {
|
|
6
|
+
/** Cavos App ID from the dashboard. */
|
|
7
|
+
appId?: string;
|
|
8
|
+
network: StarknetNetwork;
|
|
9
|
+
/** Per-app salt so the same user has distinct wallets per app. */
|
|
10
|
+
appSalt: string;
|
|
11
|
+
/** Cavos paymaster API key (sponsors deploy + execute). */
|
|
12
|
+
paymasterApiKey: string;
|
|
13
|
+
/** Override the Cavos auth backend (self-hosted / staging). */
|
|
14
|
+
authBackendUrl?: string;
|
|
15
|
+
/** Override the Starknet RPC. */
|
|
16
|
+
rpcUrl?: string;
|
|
17
|
+
}
|
|
18
|
+
interface CavosModalConfig {
|
|
19
|
+
appName?: string;
|
|
20
|
+
appLogo?: string;
|
|
21
|
+
providers?: ('google' | 'apple' | 'email')[];
|
|
22
|
+
/** How the built-in email provider authenticates. Defaults to magic link. */
|
|
23
|
+
emailMode?: 'magic-link' | 'otp';
|
|
24
|
+
primaryColor?: string;
|
|
25
|
+
/** 'light' (default) or 'dark'. */
|
|
26
|
+
theme?: 'light' | 'dark';
|
|
27
|
+
onSuccess?: (address: string) => void;
|
|
28
|
+
}
|
|
29
|
+
/** Minimal wallet-status surface the React layer (and modal) needs. */
|
|
30
|
+
interface WalletStatus {
|
|
31
|
+
/** True while the device-signer account is being deployed. */
|
|
32
|
+
isDeploying: boolean;
|
|
33
|
+
/** True once deployed and this device is an authorized signer. */
|
|
34
|
+
isReady: boolean;
|
|
35
|
+
/** True if this device still needs approval to operate the wallet. */
|
|
36
|
+
needsDeviceApproval: boolean;
|
|
37
|
+
/** True while waiting for the owner to approve this device from another device. */
|
|
38
|
+
awaitingApproval: boolean;
|
|
39
|
+
/** The pending device-addition request id, when awaitingApproval. */
|
|
40
|
+
pendingRequestId: string | null;
|
|
41
|
+
}
|
|
42
|
+
interface UserInfo {
|
|
43
|
+
userId: string;
|
|
44
|
+
email?: string;
|
|
45
|
+
provider?: string;
|
|
46
|
+
}
|
|
47
|
+
interface CavosContextValue {
|
|
48
|
+
/** Open / close the built-in auth modal. */
|
|
49
|
+
openModal: () => void;
|
|
50
|
+
closeModal: () => void;
|
|
51
|
+
isAuthenticated: boolean;
|
|
52
|
+
user: UserInfo | null;
|
|
53
|
+
address: string | null;
|
|
54
|
+
walletStatus: WalletStatus;
|
|
55
|
+
isLoading: boolean;
|
|
56
|
+
/** Last unrecoverable auth/connect error surfaced to the UI (e.g. a failed
|
|
57
|
+
* OAuth callback). Null while things are healthy. Cleared on a new attempt. */
|
|
58
|
+
authError: string | null;
|
|
59
|
+
/** Clear `authError` (e.g. when the user starts a new login attempt). */
|
|
60
|
+
clearAuthError: () => void;
|
|
61
|
+
/** OAuth social login — opens the provider's hosted flow. */
|
|
62
|
+
login: (provider: 'google' | 'apple') => Promise<void>;
|
|
63
|
+
/** Send a passwordless magic-link email. */
|
|
64
|
+
sendMagicLink: (email: string) => Promise<void>;
|
|
65
|
+
/** Send an email OTP code. */
|
|
66
|
+
sendOtp: (email: string) => Promise<void>;
|
|
67
|
+
/** Verify an email OTP / complete a magic link and deploy the wallet. */
|
|
68
|
+
verifyOtp: (email: string, code: string) => Promise<void>;
|
|
69
|
+
/** Resolve identity from an OAuth callback (?auth_data=…) and deploy. */
|
|
70
|
+
handleCallback: (authData: string) => Promise<void>;
|
|
71
|
+
/** Execute a sponsored (gasless) multicall, signed by the device key. */
|
|
72
|
+
execute: (calls: ChainCall[]) => Promise<{
|
|
73
|
+
transactionHash: string;
|
|
74
|
+
}>;
|
|
75
|
+
/** Authorize another device signer on this wallet (sponsored add_signer). */
|
|
76
|
+
addSigner: (pubkey: {
|
|
77
|
+
x: bigint;
|
|
78
|
+
y: bigint;
|
|
79
|
+
}) => Promise<{
|
|
80
|
+
transactionHash: string;
|
|
81
|
+
}>;
|
|
82
|
+
/** Re-request the device-approval email for the current pending request. */
|
|
83
|
+
resendDeviceApproval: () => Promise<void>;
|
|
84
|
+
/**
|
|
85
|
+
* Register a backup signer derived from `code` on the current account
|
|
86
|
+
* (gasless). The code is generated by the kit and shown to the user once.
|
|
87
|
+
* Resolves with the code so the caller can display it.
|
|
88
|
+
*/
|
|
89
|
+
setupRecovery: () => Promise<string>;
|
|
90
|
+
/**
|
|
91
|
+
* Recover access after losing every device. Requires the recovery code. Runs
|
|
92
|
+
* the full Cavos.recover flow and brings the provider to a ready state.
|
|
93
|
+
*/
|
|
94
|
+
recover: (code: string) => Promise<void>;
|
|
95
|
+
logout: () => void;
|
|
96
|
+
}
|
|
97
|
+
interface CavosProviderProps {
|
|
98
|
+
config: CavosConfig;
|
|
99
|
+
modal?: CavosModalConfig;
|
|
100
|
+
children: ReactNode;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Drop-in Cavos provider. Wrap your app once; descendants call `useCavos()`.
|
|
104
|
+
*
|
|
105
|
+
* <CavosProvider config={{ network: 'sepolia', appSalt, paymasterApiKey }}
|
|
106
|
+
* modal={{ appName: 'My App', theme: 'dark', emailMode: 'otp' }}>
|
|
107
|
+
* <App />
|
|
108
|
+
* </CavosProvider>
|
|
109
|
+
*
|
|
110
|
+
* Behind the scenes: login (social / email) resolves a stable identity, the kit
|
|
111
|
+
* deploys a device-signer smart account gaslessly, and `execute()` submits
|
|
112
|
+
* gasless multicalls signed silently by the browser's device key.
|
|
113
|
+
*/
|
|
114
|
+
declare function CavosProvider({ config, modal, children }: CavosProviderProps): react.JSX.Element;
|
|
115
|
+
declare function useCavos(): CavosContextValue;
|
|
116
|
+
|
|
117
|
+
interface CavosAuthModalProps {
|
|
118
|
+
open: boolean;
|
|
119
|
+
onClose: () => void;
|
|
120
|
+
onSuccess?: (address: string) => void;
|
|
121
|
+
appName?: string;
|
|
122
|
+
appLogo?: string;
|
|
123
|
+
providers?: ('google' | 'apple' | 'email')[];
|
|
124
|
+
emailMode?: 'magic-link' | 'otp';
|
|
125
|
+
primaryColor?: string;
|
|
126
|
+
/** 'light' (default) or 'dark' */
|
|
127
|
+
theme?: 'light' | 'dark';
|
|
128
|
+
}
|
|
129
|
+
declare function CavosAuthModal({ open, onClose, appName, providers, emailMode, primaryColor, theme, }: CavosAuthModalProps): react__default.JSX.Element | null;
|
|
130
|
+
declare function useCavosAuth(): {
|
|
131
|
+
openModal: () => void;
|
|
132
|
+
closeModal: () => void;
|
|
133
|
+
isAuthenticated: boolean;
|
|
134
|
+
address: string | null;
|
|
135
|
+
user: UserInfo | null;
|
|
136
|
+
walletStatus: WalletStatus;
|
|
137
|
+
logout: () => void;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export { CavosAuthModal, type CavosAuthModalProps, type CavosConfig, type CavosContextValue, type CavosModalConfig, CavosProvider, type CavosProviderProps, type UserInfo, type WalletStatus, useCavos, useCavosAuth };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import react__default, { ReactNode } from 'react';
|
|
3
|
+
import { S as StarknetNetwork, C as ChainCall } from '../constants-C530TZFF.js';
|
|
4
|
+
|
|
5
|
+
interface CavosConfig {
|
|
6
|
+
/** Cavos App ID from the dashboard. */
|
|
7
|
+
appId?: string;
|
|
8
|
+
network: StarknetNetwork;
|
|
9
|
+
/** Per-app salt so the same user has distinct wallets per app. */
|
|
10
|
+
appSalt: string;
|
|
11
|
+
/** Cavos paymaster API key (sponsors deploy + execute). */
|
|
12
|
+
paymasterApiKey: string;
|
|
13
|
+
/** Override the Cavos auth backend (self-hosted / staging). */
|
|
14
|
+
authBackendUrl?: string;
|
|
15
|
+
/** Override the Starknet RPC. */
|
|
16
|
+
rpcUrl?: string;
|
|
17
|
+
}
|
|
18
|
+
interface CavosModalConfig {
|
|
19
|
+
appName?: string;
|
|
20
|
+
appLogo?: string;
|
|
21
|
+
providers?: ('google' | 'apple' | 'email')[];
|
|
22
|
+
/** How the built-in email provider authenticates. Defaults to magic link. */
|
|
23
|
+
emailMode?: 'magic-link' | 'otp';
|
|
24
|
+
primaryColor?: string;
|
|
25
|
+
/** 'light' (default) or 'dark'. */
|
|
26
|
+
theme?: 'light' | 'dark';
|
|
27
|
+
onSuccess?: (address: string) => void;
|
|
28
|
+
}
|
|
29
|
+
/** Minimal wallet-status surface the React layer (and modal) needs. */
|
|
30
|
+
interface WalletStatus {
|
|
31
|
+
/** True while the device-signer account is being deployed. */
|
|
32
|
+
isDeploying: boolean;
|
|
33
|
+
/** True once deployed and this device is an authorized signer. */
|
|
34
|
+
isReady: boolean;
|
|
35
|
+
/** True if this device still needs approval to operate the wallet. */
|
|
36
|
+
needsDeviceApproval: boolean;
|
|
37
|
+
/** True while waiting for the owner to approve this device from another device. */
|
|
38
|
+
awaitingApproval: boolean;
|
|
39
|
+
/** The pending device-addition request id, when awaitingApproval. */
|
|
40
|
+
pendingRequestId: string | null;
|
|
41
|
+
}
|
|
42
|
+
interface UserInfo {
|
|
43
|
+
userId: string;
|
|
44
|
+
email?: string;
|
|
45
|
+
provider?: string;
|
|
46
|
+
}
|
|
47
|
+
interface CavosContextValue {
|
|
48
|
+
/** Open / close the built-in auth modal. */
|
|
49
|
+
openModal: () => void;
|
|
50
|
+
closeModal: () => void;
|
|
51
|
+
isAuthenticated: boolean;
|
|
52
|
+
user: UserInfo | null;
|
|
53
|
+
address: string | null;
|
|
54
|
+
walletStatus: WalletStatus;
|
|
55
|
+
isLoading: boolean;
|
|
56
|
+
/** Last unrecoverable auth/connect error surfaced to the UI (e.g. a failed
|
|
57
|
+
* OAuth callback). Null while things are healthy. Cleared on a new attempt. */
|
|
58
|
+
authError: string | null;
|
|
59
|
+
/** Clear `authError` (e.g. when the user starts a new login attempt). */
|
|
60
|
+
clearAuthError: () => void;
|
|
61
|
+
/** OAuth social login — opens the provider's hosted flow. */
|
|
62
|
+
login: (provider: 'google' | 'apple') => Promise<void>;
|
|
63
|
+
/** Send a passwordless magic-link email. */
|
|
64
|
+
sendMagicLink: (email: string) => Promise<void>;
|
|
65
|
+
/** Send an email OTP code. */
|
|
66
|
+
sendOtp: (email: string) => Promise<void>;
|
|
67
|
+
/** Verify an email OTP / complete a magic link and deploy the wallet. */
|
|
68
|
+
verifyOtp: (email: string, code: string) => Promise<void>;
|
|
69
|
+
/** Resolve identity from an OAuth callback (?auth_data=…) and deploy. */
|
|
70
|
+
handleCallback: (authData: string) => Promise<void>;
|
|
71
|
+
/** Execute a sponsored (gasless) multicall, signed by the device key. */
|
|
72
|
+
execute: (calls: ChainCall[]) => Promise<{
|
|
73
|
+
transactionHash: string;
|
|
74
|
+
}>;
|
|
75
|
+
/** Authorize another device signer on this wallet (sponsored add_signer). */
|
|
76
|
+
addSigner: (pubkey: {
|
|
77
|
+
x: bigint;
|
|
78
|
+
y: bigint;
|
|
79
|
+
}) => Promise<{
|
|
80
|
+
transactionHash: string;
|
|
81
|
+
}>;
|
|
82
|
+
/** Re-request the device-approval email for the current pending request. */
|
|
83
|
+
resendDeviceApproval: () => Promise<void>;
|
|
84
|
+
/**
|
|
85
|
+
* Register a backup signer derived from `code` on the current account
|
|
86
|
+
* (gasless). The code is generated by the kit and shown to the user once.
|
|
87
|
+
* Resolves with the code so the caller can display it.
|
|
88
|
+
*/
|
|
89
|
+
setupRecovery: () => Promise<string>;
|
|
90
|
+
/**
|
|
91
|
+
* Recover access after losing every device. Requires the recovery code. Runs
|
|
92
|
+
* the full Cavos.recover flow and brings the provider to a ready state.
|
|
93
|
+
*/
|
|
94
|
+
recover: (code: string) => Promise<void>;
|
|
95
|
+
logout: () => void;
|
|
96
|
+
}
|
|
97
|
+
interface CavosProviderProps {
|
|
98
|
+
config: CavosConfig;
|
|
99
|
+
modal?: CavosModalConfig;
|
|
100
|
+
children: ReactNode;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Drop-in Cavos provider. Wrap your app once; descendants call `useCavos()`.
|
|
104
|
+
*
|
|
105
|
+
* <CavosProvider config={{ network: 'sepolia', appSalt, paymasterApiKey }}
|
|
106
|
+
* modal={{ appName: 'My App', theme: 'dark', emailMode: 'otp' }}>
|
|
107
|
+
* <App />
|
|
108
|
+
* </CavosProvider>
|
|
109
|
+
*
|
|
110
|
+
* Behind the scenes: login (social / email) resolves a stable identity, the kit
|
|
111
|
+
* deploys a device-signer smart account gaslessly, and `execute()` submits
|
|
112
|
+
* gasless multicalls signed silently by the browser's device key.
|
|
113
|
+
*/
|
|
114
|
+
declare function CavosProvider({ config, modal, children }: CavosProviderProps): react.JSX.Element;
|
|
115
|
+
declare function useCavos(): CavosContextValue;
|
|
116
|
+
|
|
117
|
+
interface CavosAuthModalProps {
|
|
118
|
+
open: boolean;
|
|
119
|
+
onClose: () => void;
|
|
120
|
+
onSuccess?: (address: string) => void;
|
|
121
|
+
appName?: string;
|
|
122
|
+
appLogo?: string;
|
|
123
|
+
providers?: ('google' | 'apple' | 'email')[];
|
|
124
|
+
emailMode?: 'magic-link' | 'otp';
|
|
125
|
+
primaryColor?: string;
|
|
126
|
+
/** 'light' (default) or 'dark' */
|
|
127
|
+
theme?: 'light' | 'dark';
|
|
128
|
+
}
|
|
129
|
+
declare function CavosAuthModal({ open, onClose, appName, providers, emailMode, primaryColor, theme, }: CavosAuthModalProps): react__default.JSX.Element | null;
|
|
130
|
+
declare function useCavosAuth(): {
|
|
131
|
+
openModal: () => void;
|
|
132
|
+
closeModal: () => void;
|
|
133
|
+
isAuthenticated: boolean;
|
|
134
|
+
address: string | null;
|
|
135
|
+
user: UserInfo | null;
|
|
136
|
+
walletStatus: WalletStatus;
|
|
137
|
+
logout: () => void;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export { CavosAuthModal, type CavosAuthModalProps, type CavosConfig, type CavosContextValue, type CavosModalConfig, CavosProvider, type CavosProviderProps, type UserInfo, type WalletStatus, useCavos, useCavosAuth };
|