@cavos/kit 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +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/identity.ts","../src/chains/solana/constants.ts","../src/chains/solana/SolanaAdapter.ts","../src/chains/solana/SolanaRelayer.ts","../src/recovery/BackupSigner.ts","../src/crypto/webauthn.ts","../src/chains/solana/CavosSolana.ts","../src/chains/stellar/constants.ts","../src/chains/stellar/StellarAdapter.ts","../src/chains/stellar/StellarRelayer.ts","../src/chains/stellar/CavosStellar.ts","../src/recovery/HttpRecoveryClient.ts","../src/Cavos.ts","../src/auth/AuthProvider.ts","../src/auth/CavosAuth.ts","../src/signer/PasskeySigner.ts"],"names":["p256","sha256","hash","num","Signer","PublicKey","TransactionInstruction","SystemProgram","SYSVAR_INSTRUCTIONS_PUBKEY","ix","lowS","buf","tx","Transaction","randomBytes","pbkdf2","hkdf","Connection","isSigner","sendAndConfirmTransaction","SECP256R1_N","rpc","xdr","Address","StrKey","encodeLowSSignature","nativeToScVal","Account","TransactionBuilder","BASE_FEE","Operation","scValToNative","defaultRegistry","address","toHex","fromHex","RpcProvider","PaymasterRpc","account"],"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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AAI,CAAA,EAAG,OAAO,IAAA;AACjD,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA,EAAG,OAAO,IAAA;AAC/B,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,WAAW,MAAA,EAA4B;AAC9C,EAAA,MAAM,KAAA,GAAQ,IAAI,WAAA,EAAY,CAAE,OAAO,MAAM,CAAA;AAC7C,EAAA,OAAO,KAAA,CAAM,MAAA,IAAU,EAAA,GAAK,KAAA,GAAQF,cAAO,KAAK,CAAA;AAClD;AAIA,SAAS,IAAI,KAAA,EAAiC;AAC5C,EAAA,OAAO,MAAM,KAAA,EAAM;AACrB","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/**\n * Serialize raw bytes into the calldata a Cairo `ByteArray` deserializes from:\n * [ num_full_words, ...full_words(31 bytes each), pending_word, pending_len ]\n * Each full word is 31 big-endian bytes; the pending word holds the trailing\n * `< 31` bytes. Used to pass `authenticator_data` / `client_data_json` to the\n * passkey-approval entrypoint.\n */\nexport function bytesToByteArrayCalldata(bytes: Uint8Array): string[] {\n const CHUNK = 31;\n const fullCount = Math.floor(bytes.length / CHUNK);\n const out: string[] = [String(fullCount)];\n for (let i = 0; i < fullCount; i++) {\n out.push(\"0x\" + bytesToBigInt(bytes.subarray(i * CHUNK, i * CHUNK + CHUNK)).toString(16));\n }\n const rem = bytes.subarray(fullCount * CHUNK);\n out.push(\"0x\" + (rem.length ? bytesToBigInt(rem).toString(16) : \"0\"));\n out.push(String(rem.length));\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 *\n * Sepolia re-declared 2026-07-01 with the passkey-approval surface + BATCHED\n * multi-chain challenge (one passkey prompt approves a device on all chains).\n * Mainnet still runs the prior class (no passkey) until it is re-declared.\n */\nexport const DEVICE_ACCOUNT_CLASS_HASH: Record<StarknetNetwork, string> = {\n sepolia: \"0x25cbc5423e8ee895febb0ef2c3945b408da44d0039d915fbdd681fe6b6ba66b\",\n mainnet: \"0x1840aded59e8a0d2b440a134cb9079a7fc11b06c77f58ed189ab436a034ca6a\",\n};\n","import { hash, num } from \"starknet\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { ChainAdapter, ChainCall, ComputeAddressParams } from \"../ChainAdapter\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { signatureToFelts } from \"../../crypto/signature\";\nimport { u256ToFelts, bigIntTo32Bytes, bytesToByteArrayCalldata, bytesToBigInt } from \"../../crypto/encoding\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\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 // --- passkey approvers ---\n\n buildAddApprover(accountAddress: string, passkey: DevicePublicKey): ChainCall {\n return { contractAddress: accountAddress, entrypoint: \"add_approver\", calldata: pubkeyCalldata(passkey) };\n }\n\n buildRemoveApprover(accountAddress: string, passkey: DevicePublicKey): ChainCall {\n return { contractAddress: accountAddress, entrypoint: \"remove_approver\", calldata: pubkeyCalldata(passkey) };\n }\n\n async isApprover(accountAddress: string, passkey: 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_approver\",\n calldata: pubkeyCalldata(passkey),\n });\n return BigInt(res[0] ?? 0) !== 0n;\n }\n\n async getPasskeyNonce(accountAddress: string): Promise<bigint> {\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: \"get_passkey_nonce\",\n calldata: [],\n });\n return BigInt(res[0] ?? 0);\n }\n\n /** This chain's leaf for approving `add_signer(newSigner)` at `nonce`:\n * `sha256(new_x || new_y || nonce)` (coords 32B BE, nonce 16B BE). The batch\n * challenge the passkey signs is `sha256(concat(leaves))` across chains. */\n passkeyLeaf(newSigner: DevicePublicKey, nonce: bigint): Uint8Array {\n const msg = new Uint8Array(32 + 32 + 16);\n msg.set(bigIntTo32Bytes(newSigner.x), 0);\n msg.set(bigIntTo32Bytes(newSigner.y), 32);\n msg.set(bigIntTo32Bytes(nonce).subarray(16), 64); // low 16 bytes = u128 BE\n return sha256(msg);\n }\n\n /** Passkey-authorized `add_signer` call. `leaves`/`leafIndex` place this chain's\n * leaf in the multi-chain batch (single chain → `[leaf]`, index 0). `yParity`\n * matches the raw `(r, s)` — the contract normalizes high-S internally. */\n buildAddSignerViaPasskey(\n accountAddress: string,\n newSigner: DevicePublicKey,\n nonce: bigint,\n leaves: Uint8Array[],\n leafIndex: number,\n assertion: PasskeyAssertion,\n yParity: boolean,\n ): ChainCall {\n const [rl, rh] = u256ToFelts(assertion.r);\n const [sl, sh] = u256ToFelts(assertion.s);\n const leavesCalldata: string[] = [String(leaves.length)];\n for (const leaf of leaves) {\n const [lo, hi] = u256ToFelts(bytesToBigInt(leaf));\n leavesCalldata.push(num.toHex(lo), num.toHex(hi));\n }\n return {\n contractAddress: accountAddress,\n entrypoint: \"add_signer_via_passkey\",\n calldata: [\n ...pubkeyCalldata(newSigner), // new_x, new_y (u256 pairs)\n num.toHex(nonce),\n ...leavesCalldata, // Array<u256> leaves\n String(leafIndex),\n ...bytesToByteArrayCalldata(assertion.authenticatorData),\n ...bytesToByteArrayCalldata(assertion.clientDataJSON),\n String(assertion.challengeOffset),\n num.toHex(rl), num.toHex(rh),\n num.toHex(sl), num.toHex(sh),\n yParity ? \"0x1\" : \"0x0\",\n ],\n };\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 { hash } from \"starknet\";\nimport { sha256 } from \"@noble/hashes/sha256\";\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/**\n * Solana variant: a 32-byte `address_seed` for the Cavos device-account PDA.\n * Uses the SAME identity input as Starknet (`userId + appSalt`) but hashes with\n * SHA-256 instead of Poseidon, since Solana has no native Poseidon and the PDA\n * seed is raw bytes. The same user therefore maps to a stable, app-scoped\n * address on each chain (different address spaces, one identity).\n */\nexport function deriveAddressSeedSolana({ userId, appSalt }: IdentityInput): Uint8Array {\n return sha256(new TextEncoder().encode(`cavos:solana:v1:${userId}:${appSalt}`));\n}\n\n/**\n * Stellar variant: a 32-byte `address_seed` used as the Soroban account's seed\n * and folded (with the initial device signer) into the factory deploy salt.\n * Same identity input as the other chains, SHA-256 hashed, with a Stellar-scoped\n * domain so the same user maps to a distinct address per chain.\n */\nexport function deriveAddressSeedStellar({ userId, appSalt }: IdentityInput): Uint8Array {\n return sha256(new TextEncoder().encode(`cavos:stellar:v1:${userId}:${appSalt}`));\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","/** Cavos device-account program + Solana primitives. */\n\n/** Deployed `cavos-device-account` program id (see account-contracts/solana). */\nexport const DEVICE_ACCOUNT_PROGRAM_ID =\n \"FHnoYNfYAmFrwt18gcBGG7G1S5q3RAbCBvrV2D29izNJ\";\n\n/** Native secp256r1 signature-verify precompile (SIMD-0075). */\nexport const SECP256R1_PROGRAM_ID =\n \"Secp256r1SigVerify1111111111111111111111111\";\n\n/** PDA seed prefix, must match the program's `ACCOUNT_SEED`. */\nexport const ACCOUNT_SEED = \"cavos-account\";\n\n/** Domain separators, must match the program's signed-message domains. */\nexport const DOMAIN_ADD = \"cavos:add_signer:v1\";\nexport const DOMAIN_REMOVE = \"cavos:remove_signer:v1\";\nexport const DOMAIN_TRANSFER = \"cavos:transfer:v1\";\n/** Arbitrary execution (CPI). The signed message commits to sha256 of the\n * canonical Borsh serialization of the instruction set — see `buildExecute`. */\nexport const DOMAIN_EXECUTE = \"cavos:execute:v1\";\nexport const DOMAIN_ADD_APPROVER = \"cavos:add_approver:v1\";\nexport const DOMAIN_REMOVE_APPROVER = \"cavos:remove_approver:v1\";\n\n/** secp256r1 (P-256) curve order, for low-S normalization. */\nexport const SECP256R1_N =\n 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;\n\nexport const SOLANA_NETWORKS = {\n \"solana-devnet\": \"https://api.devnet.solana.com\",\n \"solana-mainnet\": \"https://api.mainnet-beta.solana.com\",\n \"solana-localnet\": \"http://127.0.0.1:8899\",\n} as const;\n\nexport type SolanaNetwork = keyof typeof SOLANA_NETWORKS;\n","import {\n Connection,\n PublicKey,\n SystemProgram,\n SYSVAR_INSTRUCTIONS_PUBKEY,\n TransactionInstruction,\n} from \"@solana/web3.js\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { bigIntTo32Bytes } from \"../../crypto/encoding\";\nimport {\n ACCOUNT_SEED,\n DEVICE_ACCOUNT_PROGRAM_ID,\n DOMAIN_ADD,\n DOMAIN_REMOVE,\n DOMAIN_TRANSFER,\n DOMAIN_EXECUTE,\n DOMAIN_ADD_APPROVER,\n DOMAIN_REMOVE_APPROVER,\n SECP256R1_N,\n SECP256R1_PROGRAM_ID,\n} from \"./constants\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\n\nconst COMPRESSED_PUBKEY_SIZE = 33;\nconst SIGNATURE_SIZE = 64;\nconst CURRENT_IX = 0xffff;\n\n/** An account meta candidate for a CPI instruction inside `execute`. Mirrors the\n * on-chain `AccountMetaCandidate` (Borsh). */\nexport interface InstructionAccount {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\n/** A CPI instruction the device key authorizes via `execute`. Mirrors the\n * on-chain `InstructionData` (Borsh). Serialized canonically and hashed before\n * signing, so a signature binds exactly this instruction set. */\nexport interface InstructionData {\n programId: string;\n accounts: InstructionAccount[];\n data: Uint8Array;\n}\n\nexport interface SolanaAdapterOptions {\n /** Cavos device-account program id (defaults to the deployed one). */\n programId?: string;\n /** RPC connection for reads (`isAuthorizedSigner`) and nonce fetch. */\n connection?: Connection;\n /** Device signer used to authorize guarded actions. */\n signer?: DeviceSigner;\n}\n\n/**\n * Solana adapter for the Cavos device-signer account. Unlike Starknet (where the\n * account contract verifies the P-256 signature in `__validate__`), Solana\n * verifies it natively via the secp256r1 precompile, so every guarded action is\n * a two-instruction bundle: `[secp256r1 precompile ix, program ix]`. This adapter\n * derives the account PDA, builds those bundles, and reuses the same\n * `DeviceSigner` (P-256 / WebCrypto) as every other chain.\n */\nexport class SolanaAdapter {\n readonly chain = \"solana\" as const;\n readonly programId: PublicKey;\n\n constructor(private readonly opts: SolanaAdapterOptions = {}) {\n this.programId = new PublicKey(opts.programId ?? DEVICE_ACCOUNT_PROGRAM_ID);\n }\n\n /** Deterministic account address: PDA of [seed, address_seed, initial_signer_x]. */\n computeAddress(addressSeed: Uint8Array, initialSigner: DevicePublicKey): string {\n return this.pda(addressSeed, compressedPubkey(initialSigner)).toBase58();\n }\n\n private pda(addressSeed: Uint8Array, initialCompressed: Uint8Array): PublicKey {\n const [pda] = PublicKey.findProgramAddressSync(\n [\n Buffer.from(ACCOUNT_SEED),\n Buffer.from(addressSeed),\n Buffer.from(initialCompressed.slice(1, 33)), // x-coordinate\n ],\n this.programId\n );\n return pda;\n }\n\n /** `initialize` instruction creating the account with its first device signer. */\n buildInitialize(\n addressSeed: Uint8Array,\n payer: string,\n initialSigner: DevicePublicKey\n ): TransactionInstruction {\n const initialCompressed = compressedPubkey(initialSigner);\n const account = this.pda(addressSeed, initialCompressed);\n const data = Buffer.concat([\n anchorDiscriminator(\"initialize\"),\n Buffer.from(addressSeed), // [u8;32]\n Buffer.from(initialCompressed), // [u8;33]\n ]);\n return new TransactionInstruction({\n programId: this.programId,\n keys: [\n { pubkey: account, isSigner: false, isWritable: true },\n { pubkey: new PublicKey(payer), isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n }\n\n /** `[precompile, add_signer]` bundle, authorized by an existing device signer. */\n async buildAddSigner(\n account: string,\n newSigner: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const newCompressed = compressedPubkey(newSigner);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_ADD),\n accountPk.toBuffer(),\n newCompressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"add_signer\"), Buffer.from(newCompressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** `[precompile, remove_signer]` bundle, authorized by an existing device signer. */\n async buildRemoveSigner(\n account: string,\n signer: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const compressed = compressedPubkey(signer);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_REMOVE),\n accountPk.toBuffer(),\n compressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"remove_signer\"), Buffer.from(compressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** `[precompile, add_approver]` bundle enrolling a passkey approver (device-signed). */\n async buildAddApprover(\n account: string,\n passkey: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const compressed = compressedPubkey(passkey);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_ADD_APPROVER),\n accountPk.toBuffer(),\n compressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"add_approver\"), Buffer.from(compressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** `[precompile, remove_approver]` bundle (device-signed). */\n async buildRemoveApprover(\n account: string,\n passkey: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const compressed = compressedPubkey(passkey);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_REMOVE_APPROVER),\n accountPk.toBuffer(),\n compressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"remove_approver\"), Buffer.from(compressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** This chain's leaf for approving `add_signer(newSigner)` at `nonce`:\n * `sha256(compressed(new_signer) || passkey_nonce_le8)`. The batch challenge the\n * passkey signs is `sha256(concat(leaves))` across chains. */\n passkeyLeaf(newSigner: DevicePublicKey, nonce: bigint): Uint8Array {\n return sha256(concatBytes(compressedPubkey(newSigner), u64le(nonce)));\n }\n\n /**\n * `[precompile(passkey), add_signer_via_passkey]` bundle. The precompile ix\n * verifies the PASSKEY's WebAuthn assertion over `authData || sha256(clientDataJSON)`;\n * the program ix binds the challenge to `newSigner` + the passkey nonce and adds\n * the signer. No device signature — a gasless relayer can submit it.\n */\n buildAddSignerViaPasskey(\n account: string,\n newSigner: DevicePublicKey,\n passkey: DevicePublicKey,\n leaves: Uint8Array[],\n leafIndex: number,\n assertion: PasskeyAssertion\n ): TransactionInstruction[] {\n const accountPk = new PublicKey(account);\n const newCompressed = compressedPubkey(newSigner);\n const passkeyCompressed = compressedPubkey(passkey);\n\n // Precompile message = authData || sha256(clientDataJSON); the precompile\n // hashes it once → the WebAuthn signed digest.\n const clientHash = sha256(assertion.clientDataJSON);\n const message = concatBytes(assertion.authenticatorData, clientHash);\n const signature = encodeLowSSignature(assertion.r, assertion.s);\n const precompileIx = buildSecp256r1Instruction(passkeyCompressed, signature, message);\n\n // Borsh Vec<[u8; 32]> leaves: u32 len + len*32 bytes.\n const leavesBlob = Buffer.concat([u32le(leaves.length), ...leaves.map((l) => Buffer.from(l))]);\n const data = Buffer.concat([\n anchorDiscriminator(\"add_signer_via_passkey\"),\n Buffer.from(newCompressed),\n leavesBlob,\n u32le(leafIndex),\n serializeVecU8(assertion.authenticatorData),\n serializeVecU8(assertion.clientDataJSON),\n u32le(assertion.challengeOffset),\n ]);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data,\n });\n return [precompileIx, ix];\n }\n\n /** Read whether `passkey` is a registered approver. */\n async isApprover(account: string, passkey: DevicePublicKey): Promise<boolean> {\n const approvers = await this.fetchApprovers(new PublicKey(account));\n const target = Buffer.from(compressedPubkey(passkey)).toString(\"hex\");\n return approvers.some((a) => Buffer.from(a).toString(\"hex\") === target);\n }\n\n /** Read the current passkey-approval nonce. */\n async passkeyNonce(account: string): Promise<bigint> {\n const info = await this.requireConnection().getAccountInfo(new PublicKey(account));\n if (!info) return 0n;\n const d = info.data;\n const signersLenOff = 8 + 32 + 1 + 8 + COMPRESSED_PUBKEY_SIZE; // 82\n const signerCount = d.readUInt32LE(signersLenOff);\n const approversLenOff = signersLenOff + 4 + signerCount * COMPRESSED_PUBKEY_SIZE;\n const approverCount = d.readUInt32LE(approversLenOff);\n const passkeyNonceOff = approversLenOff + 4 + approverCount * COMPRESSED_PUBKEY_SIZE;\n return readU64le(d, passkeyNonceOff);\n }\n\n /** `[precompile, execute_transfer]` bundle moving lamports out of the account. */\n async buildExecuteTransfer(\n account: string,\n destination: string,\n amount: bigint\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const destPk = new PublicKey(destination);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_TRANSFER),\n accountPk.toBuffer(),\n destPk.toBuffer(),\n u64le(amount),\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: [\n { pubkey: accountPk, isSigner: false, isWritable: true },\n { pubkey: destPk, isSigner: false, isWritable: true },\n { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },\n ],\n data: Buffer.concat([anchorDiscriminator(\"execute_transfer\"), u64le(amount)]),\n });\n return [precompileIx, ix];\n }\n\n /**\n * `[precompile, execute]` bundle running arbitrary CPI instructions with the\n * account PDA as signer. The device key signs over\n * `DOMAIN_EXECUTE || account || sha256(canonical(instructions)) || nonce`, so\n * the signature commits to the EXACT instruction set the program will invoke —\n * no account/data substitution is possible after signing.\n *\n * The instructions' accounts are passed to the program via `remaining_accounts`\n * (flattened, in order); the program enforces an exact, ordered mapping.\n */\n async buildExecute(\n account: string,\n instructions: InstructionData[]\n ): Promise<TransactionInstruction[]> {\n if (instructions.length === 0) throw new Error(\"kit/solana: execute requires at least one instruction\");\n\n const accountPk = new PublicKey(account);\n const nonce = await this.fetchNonce(accountPk);\n\n // Canonical Borsh serialization MUST match the on-chain\n // `hash_instructions` (sha256 over the concatenated `InstructionData`).\n const blob = serializeInstructions(instructions);\n const ixsHash = sha256(blob);\n\n const message = concatBytes(\n Buffer.from(DOMAIN_EXECUTE),\n accountPk.toBuffer(),\n Buffer.from(ixsHash),\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n\n // The program ix carries the instructions in its data; the accounts they\n // reference are flattened into `remaining_accounts` in order. The wire format\n // is discriminator + Borsh Vec<u8>(blob) = discriminator + u32_len + blob.\n // The signed hash (above) is over the inner `blob` only — no length prefix —\n // matching the program's parse and the relay's allowlist parser.\n const blobLen = Buffer.alloc(4);\n new DataView(blobLen.buffer).setUint32(0, blob.length, true);\n const data = Buffer.concat([anchorDiscriminator(\"execute\"), blobLen, blob]);\n const remainingAccounts: Array<{ pubkey: PublicKey; isSigner: false; isWritable: boolean }> = [];\n for (const ix of instructions) {\n for (const acc of ix.accounts) {\n remainingAccounts.push({\n pubkey: new PublicKey(acc.pubkey),\n isSigner: false, // signer flags are part of the signed InstructionData\n isWritable: acc.isWritable,\n });\n }\n // The CPI target program must be a remaining_account too — invoke_signed\n // needs it loaded. Appended (not part of the signed account list).\n remainingAccounts.push({\n pubkey: new PublicKey(ix.programId),\n isSigner: false,\n isWritable: false,\n });\n }\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: [\n { pubkey: accountPk, isSigner: false, isWritable: true },\n { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },\n ...remainingAccounts,\n ],\n data,\n });\n return [precompileIx, ix];\n }\n\n /** Read whether `signer` is currently an authorized signer of `account`. */\n async isAuthorizedSigner(account: string, signer: DevicePublicKey): Promise<boolean> {\n const signers = await this.fetchSigners(new PublicKey(account));\n const target = Buffer.from(compressedPubkey(signer)).toString(\"hex\");\n return signers.some((s) => Buffer.from(s).toString(\"hex\") === target);\n }\n\n private guardedKeys(account: PublicKey) {\n return [\n { pubkey: account, isSigner: false, isWritable: true },\n { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },\n ];\n }\n\n /** Sign `message` with the device key and build the matching precompile ix. */\n private async signToPrecompile(\n message: Uint8Array\n ): Promise<{ precompileIx: TransactionInstruction }> {\n if (!this.opts.signer) throw new Error(\"kit/solana: signer required to authorize\");\n const pubkey = await this.opts.signer.getPublicKey();\n // The signer signs sha256(message); the precompile recomputes sha256(message).\n const sig = await this.opts.signer.sign(message as Uint8Array);\n const signature = encodeLowSSignature(sig.r, sig.s);\n const precompileIx = buildSecp256r1Instruction(\n compressedPubkey(pubkey),\n signature,\n message\n );\n return { precompileIx };\n }\n\n private async fetchNonce(account: PublicKey): Promise<bigint> {\n const info = await this.requireConnection().getAccountInfo(account);\n if (!info) return 0n;\n // layout: 8 disc + 32 address_seed + 1 bump + 8 nonce(LE) + 33 initial_signer + ...\n // nonce is right after bump, so its offset is unaffected by initial_signer.\n return readU64le(info.data, 41);\n }\n\n private async fetchSigners(account: PublicKey): Promise<Uint8Array[]> {\n const info = await this.requireConnection().getAccountInfo(account);\n if (!info) return [];\n const d = info.data;\n // layout: 8 disc + 32 address_seed + 1 bump + 8 nonce + 33 initial_signer + 4 vec_len + signers\n const lenOffset = 8 + 32 + 1 + 8 + COMPRESSED_PUBKEY_SIZE; // = 82\n const count = d.readUInt32LE(lenOffset);\n const out: Uint8Array[] = [];\n let off = lenOffset + 4;\n for (let i = 0; i < count; i++) {\n out.push(Uint8Array.from(d.subarray(off, off + COMPRESSED_PUBKEY_SIZE)));\n off += COMPRESSED_PUBKEY_SIZE;\n }\n return out;\n }\n\n private async fetchApprovers(account: PublicKey): Promise<Uint8Array[]> {\n const info = await this.requireConnection().getAccountInfo(account);\n if (!info) return [];\n const d = info.data;\n const signersLenOff = 8 + 32 + 1 + 8 + COMPRESSED_PUBKEY_SIZE; // 82\n const signerCount = d.readUInt32LE(signersLenOff);\n const approversLenOff = signersLenOff + 4 + signerCount * COMPRESSED_PUBKEY_SIZE;\n const count = d.readUInt32LE(approversLenOff);\n const out: Uint8Array[] = [];\n let off = approversLenOff + 4;\n for (let i = 0; i < count; i++) {\n out.push(Uint8Array.from(d.subarray(off, off + COMPRESSED_PUBKEY_SIZE)));\n off += COMPRESSED_PUBKEY_SIZE;\n }\n return out;\n }\n\n private requireConnection(): Connection {\n if (!this.opts.connection) throw new Error(\"kit/solana: connection required for reads\");\n return this.opts.connection;\n }\n}\n\n/** Compressed SEC1 P-256 pubkey (33 bytes) from {x, y}. */\nexport function compressedPubkey(pk: DevicePublicKey): Uint8Array {\n const out = new Uint8Array(COMPRESSED_PUBKEY_SIZE);\n out[0] = pk.y % 2n === 0n ? 0x02 : 0x03;\n out.set(bigIntTo32Bytes(pk.x), 1);\n return out;\n}\n\n/** Encode (r, s) as raw 64-byte r‖s, normalized to low-S (precompile requires it). */\nexport function encodeLowSSignature(r: bigint, s: bigint): Uint8Array {\n const lowS = s > SECP256R1_N / 2n ? SECP256R1_N - s : s;\n const out = new Uint8Array(SIGNATURE_SIZE);\n out.set(bigIntTo32Bytes(r), 0);\n out.set(bigIntTo32Bytes(lowS), 32);\n return out;\n}\n\n/** Build the native secp256r1 precompile instruction (single self-contained sig). */\nexport function buildSecp256r1Instruction(\n compressed: Uint8Array,\n signature: Uint8Array,\n message: Uint8Array\n): TransactionInstruction {\n const headerLen = 2;\n const offsetsLen = 14;\n const pubkeyOffset = headerLen + offsetsLen;\n const sigOffset = pubkeyOffset + COMPRESSED_PUBKEY_SIZE;\n const msgOffset = sigOffset + SIGNATURE_SIZE;\n const data = Buffer.alloc(msgOffset + message.length);\n\n data.writeUInt8(1, 0);\n data.writeUInt8(0, 1);\n let o = headerLen;\n data.writeUInt16LE(sigOffset, o); o += 2;\n data.writeUInt16LE(CURRENT_IX, o); o += 2;\n data.writeUInt16LE(pubkeyOffset, o); o += 2;\n data.writeUInt16LE(CURRENT_IX, o); o += 2;\n data.writeUInt16LE(msgOffset, o); o += 2;\n data.writeUInt16LE(message.length, o); o += 2;\n data.writeUInt16LE(CURRENT_IX, o); o += 2;\n Buffer.from(compressed).copy(data, pubkeyOffset);\n Buffer.from(signature).copy(data, sigOffset);\n Buffer.from(message).copy(data, msgOffset);\n\n return new TransactionInstruction({\n keys: [],\n programId: new PublicKey(SECP256R1_PROGRAM_ID),\n data,\n });\n}\n\n/** Anchor instruction discriminator = sha256(\"global:<name>\")[..8]. */\nexport function anchorDiscriminator(name: string): Buffer {\n return Buffer.from(sha256(`global:${name}`).slice(0, 8));\n}\n\nfunction u32le(n: number): Buffer {\n const b = Buffer.alloc(4);\n b.writeUInt32LE(n);\n return b;\n}\n\nfunction u64le(n: bigint | number): Buffer {\n const b = Buffer.alloc(8);\n // Avoid Buffer.writeBigUInt64LE: the browser `buffer` polyfill doesn't\n // implement the BigInt methods. Use DataView instead.\n new DataView(b.buffer, b.byteOffset, 8).setBigUint64(0, BigInt(n), true);\n return b;\n}\n\nfunction readU64le(buf: Buffer, offset: number): bigint {\n return new DataView(buf.buffer, buf.byteOffset, buf.length).getBigUint64(\n offset,\n true,\n );\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((n, p) => n + p.length, 0);\n const out = new Uint8Array(total);\n let off = 0;\n for (const p of parts) {\n out.set(p, off);\n off += p.length;\n }\n return out;\n}\n\n// ─── Canonical Borsh serialization for `execute` ────────────────────────────\n// MUST match the on-chain `InstructionData`/`AccountMetaCandidate` AnchorSer\n// layout byte-for-byte: `hash_instructions` hashes this and the program\n// requires the precompile-verified message to commit to the same hash. Changing\n// the byte layout here breaks signature binding (and recovery of past sigs).\n\n/** Serialize a single `InstructionData` exactly as Anchor's Borsh derive would. */\nfunction serializeInstruction(ix: InstructionData): Buffer {\n const programId = new PublicKey(ix.programId).toBuffer(); // 32 bytes\n const accounts = serializeAccounts(ix.accounts);\n const data = serializeVecU8(ix.data);\n return Buffer.concat([programId, accounts, data]);\n}\n\nfunction serializeAccounts(metas: InstructionAccount[]): Buffer {\n const len = Buffer.alloc(4);\n new DataView(len.buffer).setUint32(0, metas.length, true);\n const parts = metas.map(serializeAccountMeta);\n return Buffer.concat([len, ...parts]);\n}\n\nfunction serializeAccountMeta(meta: InstructionAccount): Buffer {\n const pubkey = new PublicKey(meta.pubkey).toBuffer(); // 32 bytes\n return Buffer.concat([pubkey, Buffer.from([meta.isSigner ? 1 : 0, meta.isWritable ? 1 : 0])]);\n}\n\nfunction serializeVecU8(data: Uint8Array): Buffer {\n const len = Buffer.alloc(4);\n new DataView(len.buffer).setUint32(0, data.length, true);\n return Buffer.concat([len, Buffer.from(data)]);\n}\n\n/** Serialize the full instruction set — the bytes `hash_instructions` hashes. */\nexport function serializeInstructions(instructions: InstructionData[]): Buffer {\n return Buffer.concat(instructions.map(serializeInstruction));\n}\n","import {\n Connection,\n PublicKey,\n Transaction,\n type TransactionInstruction,\n} from \"@solana/web3.js\";\nimport type { SolanaNetwork } from \"./constants\";\n\nexport interface SolanaRelayerOptions {\n /** Base URL of the Cavos backend exposing /api/solana/relay. */\n baseUrl: string;\n /** Cavos App ID (authorizes the sponsored request). */\n appId: string;\n network: SolanaNetwork;\n /** Connection used only to fetch a recent blockhash before serializing. */\n connection: Connection;\n}\n\n/**\n * Client for the Cavos Solana sponsoring relayer. Lets the SDK submit\n * device-account transactions WITHOUT the integrator holding a fee-payer\n * keypair: the relayer co-signs as fee payer and pays the fee/rent. The relayer\n * only pays — the device signature inside the instructions (verified by the\n * secp256r1 precompile) is what authorizes the action, and it does not bind the\n * fee payer, so sponsorship needs no re-signing.\n */\nexport class SolanaRelayer {\n private feePayer?: PublicKey;\n\n constructor(private readonly opts: SolanaRelayerOptions) {}\n\n /** The relayer's fee-payer pubkey (fetched + cached from the backend). */\n async getFeePayer(): Promise<PublicKey> {\n if (this.feePayer) return this.feePayer;\n const res = await fetch(`${this.opts.baseUrl}/api/solana/relay?network=${this.opts.network}`);\n if (!res.ok) throw new Error(`kit/solana: relayer fee-payer lookup failed (${res.status})`);\n const { fee_payer } = (await res.json()) as { fee_payer: string };\n this.feePayer = new PublicKey(fee_payer);\n return this.feePayer;\n }\n\n /**\n * Build a tx with the relayer as fee payer, serialize it unsigned, and POST it\n * to the relayer to co-sign + submit. Returns the confirmed signature.\n */\n async send(instructions: TransactionInstruction[]): Promise<string> {\n const feePayer = await this.getFeePayer();\n const { blockhash } = await this.opts.connection.getLatestBlockhash(\"confirmed\");\n const tx = new Transaction();\n tx.feePayer = feePayer;\n tx.recentBlockhash = blockhash;\n tx.add(...instructions);\n\n const serialized = tx\n .serialize({ requireAllSignatures: false, verifySignatures: false })\n .toString(\"base64\");\n\n const res = await fetch(`${this.opts.baseUrl}/api/solana/relay`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n app_id: this.opts.appId,\n network: this.opts.network,\n transaction: serialized,\n }),\n });\n if (!res.ok) {\n const detail = await res.text().catch(() => \"\");\n throw new Error(`kit/solana: relay failed (${res.status}) ${detail}`);\n }\n const { signature } = (await res.json()) as { signature: string };\n return signature;\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","/**\n * WebAuthn (passkey) helpers for the passkey-approval flow.\n *\n * A passkey is a synced secp256r1 credential (iCloud Keychain / Google Password\n * Manager). We use it as an on-chain \"approver\" that can authorize `add_signer`\n * from ANY browser — so a user never has to return to an already-authorized\n * device to onboard a new one.\n *\n * Unlike a silent device key (which signs `sha256(txHash)`), a passkey signs\n * `sha256(authenticatorData || sha256(clientDataJSON))`, with the challenge\n * embedded (base64url) in `clientDataJSON`. These helpers parse an assertion and\n * reproduce exactly what the on-chain contracts recompute.\n */\nimport { p256 } from \"@noble/curves/p256\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { DevicePublicKey } from \"../signer/DeviceSigner\";\nimport { bytesToBigInt } from \"./encoding\";\n\n/** A parsed passkey assertion, chain-agnostic. */\nexport interface PasskeyAssertion {\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n /** ECDSA signature components (raw, as returned by the authenticator). */\n r: bigint;\n s: bigint;\n /** Byte index where the base64url challenge starts inside clientDataJSON. */\n challengeOffset: number;\n}\n\n/** base64url (no padding) of a byte array. */\nexport function base64urlEncode(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n const b64 = typeof btoa !== \"undefined\" ? btoa(bin) : Buffer.from(bytes).toString(\"base64\");\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Parse a DER (ASN.1) ECDSA signature into its `{ r, s }` components. */\nexport function derToRs(der: Uint8Array): { r: bigint; s: bigint } {\n // SEQUENCE(0x30) len INTEGER(0x02) rlen r INTEGER(0x02) slen s\n let i = 0;\n if (der[i++] !== 0x30) throw new Error(\"kit/webauthn: bad DER (no SEQUENCE)\");\n if (der[i] & 0x80) i += 1 + (der[i] & 0x7f); // skip long-form length\n else i += 1;\n if (der[i++] !== 0x02) throw new Error(\"kit/webauthn: bad DER (no r INTEGER)\");\n const rlen = der[i++];\n const r = bytesToBigInt(der.subarray(i, i + rlen));\n i += rlen;\n if (der[i++] !== 0x02) throw new Error(\"kit/webauthn: bad DER (no s INTEGER)\");\n const slen = der[i++];\n const s = bytesToBigInt(der.subarray(i, i + slen));\n return { r, s };\n}\n\n/** Extract the P-256 public key `{ x, y }` from a DER SPKI blob (as returned by\n * `AuthenticatorAttestationResponse.getPublicKey()`). The uncompressed EC point\n * is the trailing 65 bytes (`0x04 || X || Y`). */\nexport function spkiToPublicKey(spki: Uint8Array): DevicePublicKey {\n const idx = spki.lastIndexOf(0x04, spki.length - 65);\n const start = spki.length - 65;\n const prefix = spki[start];\n if (prefix !== 0x04) {\n // Fall back to scanning for the 0x04 uncompressed marker.\n if (idx < 0) throw new Error(\"kit/webauthn: no uncompressed EC point in SPKI\");\n return { x: bytesToBigInt(spki.subarray(idx + 1, idx + 33)), y: bytesToBigInt(spki.subarray(idx + 33, idx + 65)) };\n }\n return {\n x: bytesToBigInt(spki.subarray(start + 1, start + 33)),\n y: bytesToBigInt(spki.subarray(start + 33, start + 65)),\n };\n}\n\n/**\n * Batch challenge over ordered per-chain leaves: `sha256(leaf_0 ‖ … ‖ leaf_n)`.\n * A single passkey assertion over this challenge authorizes `add_signer` on every\n * chain in the batch (each chain verifies only its own leaf sits at its index).\n * For a single chain the batch is one leaf, so the challenge is `sha256(leaf)`.\n */\nexport function batchChallenge(leaves: Uint8Array[]): Uint8Array {\n const total = leaves.reduce((n, l) => n + l.length, 0);\n const cat = new Uint8Array(total);\n let o = 0;\n for (const l of leaves) {\n cat.set(l, o);\n o += l.length;\n }\n return sha256(cat);\n}\n\n/** The WebAuthn signed digest: `sha256(authenticatorData || sha256(clientDataJSON))`. */\nexport function webauthnDigest(authenticatorData: Uint8Array, clientDataJSON: Uint8Array): Uint8Array {\n const clientHash = sha256(clientDataJSON);\n const msg = new Uint8Array(authenticatorData.length + clientHash.length);\n msg.set(authenticatorData, 0);\n msg.set(clientHash, authenticatorData.length);\n return sha256(msg);\n}\n\n/** Both candidate public keys recoverable from `(r, s)` over `digest`, tagged\n * with their y-parity. On a fresh browser the assertion does not carry the\n * pubkey, so the caller identifies the real one via the on-chain `is_approver`\n * view. */\nexport function recoverCandidatePublicKeys(\n r: bigint,\n s: bigint,\n digest: Uint8Array,\n): { publicKey: DevicePublicKey; yParity: boolean }[] {\n const out: { publicKey: DevicePublicKey; yParity: boolean }[] = [];\n for (const bit of [0, 1] as const) {\n try {\n const point = new p256.Signature(r, s).addRecoveryBit(bit).recoverPublicKey(digest).toAffine();\n out.push({ publicKey: { x: point.x, y: point.y }, yParity: bit === 1 });\n } catch {\n // not recoverable for this bit\n }\n }\n return out;\n}\n\n/** Normalize `s` to the low half of the curve order (required by the Stellar\n * and Solana verifiers, which do not normalize on-chain). */\nexport function lowS(s: bigint): bigint {\n const n = p256.CURVE.n;\n return s > n / 2n ? n - s : s;\n}\n\n/** Byte offset of the base64url `challenge` string inside `clientDataJSON`. */\nexport function challengeOffsetOf(clientDataJSON: Uint8Array, challengeB64: string): number {\n const text = new TextDecoder().decode(clientDataJSON);\n const idx = text.indexOf(challengeB64);\n if (idx < 0) throw new Error(\"kit/webauthn: challenge not found in clientDataJSON\");\n // clientDataJSON is ASCII, so the char index equals the byte index.\n return idx;\n}\n","import {\n Connection,\n Keypair,\n PublicKey,\n Transaction,\n sendAndConfirmTransaction,\n type TransactionInstruction,\n} from \"@solana/web3.js\";\nimport type { AuthProvider, Identity } from \"../../auth/AuthProvider\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { WebCryptoSigner } from \"../../signer/WebCryptoSigner\";\nimport type { WalletRegistry } from \"../../registry/WalletRegistry\";\nimport { InMemoryWalletRegistry } from \"../../registry/WalletRegistry\";\nimport { HttpWalletRegistry } from \"../../registry/HttpWalletRegistry\";\nimport { deriveAddressSeedSolana } from \"../../identity\";\nimport { SolanaAdapter } from \"./SolanaAdapter\";\nimport type { InstructionData } from \"./SolanaAdapter\";\nimport { SolanaRelayer } from \"./SolanaRelayer\";\nimport { SOLANA_NETWORKS, type SolanaNetwork } from \"./constants\";\nimport { BackupSigner, deriveBackupKey } from \"../../recovery/BackupSigner\";\nimport type { PasskeySigner, PasskeyEnrollParams } from \"../../signer/PasskeySigner\";\nimport { webauthnDigest, recoverCandidatePublicKeys, batchChallenge } from \"../../crypto/webauthn\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\n\nexport interface ConnectSolanaOptions {\n network: SolanaNetwork;\n /** Authenticated user (pass `identity` directly, or an `auth` provider). */\n auth?: AuthProvider;\n identity?: Identity;\n appSalt: string;\n appId?: string;\n backendUrl?: string;\n registry?: WalletRegistry;\n /** RPC override (else the network default). */\n rpcUrl?: string;\n /** Cavos device-account program id override. */\n programId?: string;\n /** Override the device signer factory (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n /**\n * Gasless sponsorship via the Cavos relayer. When set (or when `appId` +\n * `backendUrl` are given), transactions are co-signed + paid by the Cavos\n * relayer, so the integrator needs NO fee-payer keypair — the user's silent\n * device key (which holds no SOL) gets a seedless, gasless experience.\n */\n relayer?: SolanaRelayer;\n /**\n * Self-funded fallback: a fee-payer keypair the integrator funds. Used only\n * when no `relayer` is configured (tests / advanced). Sponsored relaying is\n * the default path when `appId` is provided.\n */\n feePayer?: Keypair;\n}\n\nexport type ConnectStatus = \"ready\" | \"needs-device-approval\";\n\n/**\n * Options for recovering a Solana account after losing every device signer.\n * Mirrors `RecoveryOptions` (Starknet), adapted to the Solana path: the backup\n * key signs the `add_signer` bundle via the secp256r1 precompile and the Cavos\n * relayer sponsors it (no fee-payer keypair needed).\n */\nexport interface RecoverSolanaOptions {\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 /** Solana network the account lives on. */\n network: SolanaNetwork;\n appSalt: string;\n appId?: string;\n backendUrl?: string;\n registry?: WalletRegistry;\n /** RPC override (else the network default). */\n rpcUrl?: string;\n /** Cavos device-account program id override. */\n programId?: string;\n /** Override the new device's signer (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n /** Gasless sponsorship via the Cavos relayer (defaults to hosted when appId set). */\n relayer?: SolanaRelayer;\n /** Self-funded fallback when no relayer is configured (tests / advanced). */\n feePayer?: Keypair;\n}\n\n/**\n * High-level Solana entry — the Solana analogue of `Cavos.connect`. One call\n * derives the deterministic device-bound account, deploys it (PDA `initialize`)\n * if needed, registers it for cross-device recognition, and returns a ready\n * handle whose silent P-256 device key authorizes every action through the\n * native secp256r1 precompile.\n *\n * const cavos = await CavosSolana.connect({ network: \"solana-devnet\", identity, appSalt, feePayer });\n * if (cavos.status === \"ready\") await cavos.execute(amount, dest);\n *\n * Gasless by default: when an `appId` is provided the Cavos relayer co-signs +\n * pays (no fee-payer keypair needed). `feePayer` is the self-funded fallback.\n */\nexport class CavosSolana {\n /** Discriminant for the `CavosWallet` union — narrows `execute()` per chain. */\n readonly chain = \"solana\" as const;\n\n private constructor(\n readonly identity: Identity,\n readonly address: string,\n readonly status: ConnectStatus,\n readonly connection: Connection,\n private readonly adapter: SolanaAdapter,\n private readonly devicePubkey: DevicePublicKey,\n private readonly relayer?: SolanaRelayer,\n private readonly feePayer?: Keypair,\n ) {}\n\n get publicKey(): DevicePublicKey {\n return this.devicePubkey;\n }\n\n static async connect(opts: ConnectSolanaOptions): Promise<CavosSolana> {\n const identity = opts.identity ?? (await opts.auth?.authenticate());\n if (!identity) throw new Error(\"kit/solana: connect requires `identity` or `auth`\");\n\n // Client-side read RPC. The integrator SHOULD pass their own `rpcUrl` — the\n // public default is rate-limited and unfit for production. (This is separate\n // from the relayer's server-side RPC, which Cavos operates.) Warn loudly when\n // hitting mainnet on the shared public endpoint.\n if (opts.network === \"solana-mainnet\" && !opts.rpcUrl) {\n console.warn(\n \"[cavos] Using the public mainnet-beta RPC. Pass `rpcUrl` with your own \" +\n \"provider (Helius/Triton/QuickNode) for production — the public endpoint is rate-limited.\",\n );\n }\n const connection = new Connection(opts.rpcUrl ?? SOLANA_NETWORKS[opts.network], \"confirmed\");\n\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 SolanaAdapter({ programId: opts.programId, connection, signer });\n const addressSeed = deriveAddressSeedSolana({ userId: identity.userId, appSalt: opts.appSalt });\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\n // Default to gasless sponsorship via the Cavos relayer when an appId is set,\n // so the integrator needs no fee payer. `feePayer` is the self-funded fallback.\n const relayer =\n opts.relayer ??\n (opts.appId\n ? new SolanaRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network, connection })\n : undefined);\n\n // Returning user on another device? The address is device-bound, so the\n // registry (not the identity alone) recognizes it. A new device is flagged\n // needs-device-approval (add it from an existing device) — same model as Starknet.\n const existing = await registry.lookup(identity.userId);\n if (existing) {\n const isSigner = await adapter.isAuthorizedSigner(existing.address, devicePubkey);\n return new CavosSolana(\n identity,\n existing.address,\n isSigner ? \"ready\" : \"needs-device-approval\",\n connection,\n adapter,\n devicePubkey,\n relayer,\n opts.feePayer,\n );\n }\n\n const address = adapter.computeAddress(addressSeed, devicePubkey);\n const deployed = (await connection.getAccountInfo(new PublicKey(address))) !== null;\n\n if (!deployed) {\n // Whoever pays must be the `initialize` payer/fee payer: the relayer (when\n // sponsoring) or the self-funded feePayer.\n if (relayer) {\n const payer = await relayer.getFeePayer();\n const ix = adapter.buildInitialize(addressSeed, payer.toBase58(), devicePubkey);\n await relayer.send([ix]);\n } else if (opts.feePayer) {\n const ix = adapter.buildInitialize(addressSeed, opts.feePayer.publicKey.toBase58(), devicePubkey);\n await sendAndConfirmTransaction(connection, new Transaction().add(ix), [opts.feePayer]);\n } else {\n throw new Error(\"kit/solana: a relayer (appId) or feePayer is required to initialize a new account\");\n }\n }\n\n await registry.register({ userId: identity.userId, address, initialSigner: devicePubkey });\n const isSigner = await adapter.isAuthorizedSigner(address, devicePubkey);\n return new CavosSolana(\n identity,\n address,\n isSigner ? \"ready\" : \"needs-device-approval\",\n connection,\n adapter,\n devicePubkey,\n relayer,\n opts.feePayer,\n );\n }\n\n /** Authorize an additional device signer (device-signed via precompile). */\n async addSigner(pubkey: DevicePublicKey): Promise<string> {\n const ixs = await this.adapter.buildAddSigner(this.address, pubkey);\n return this.send(ixs);\n }\n\n /**\n * Enroll a passkey as an approver (2FA-style step-up). Device-signed + gasless;\n * requires a ready device. Idempotent. Returns the passkey pubkey + tx hash.\n */\n async enrollPasskey(\n passkey: PasskeySigner,\n params: PasskeyEnrollParams,\n ): Promise<{ publicKey: DevicePublicKey; transactionHash?: string }> {\n const enrolled = await passkey.enroll(params);\n const { transactionHash } = await this.addApprover(enrolled.publicKey);\n return { publicKey: enrolled.publicKey, transactionHash };\n }\n\n /** Register an already-enrolled passkey pubkey as an approver (gasless).\n * Idempotent. Lets one passkey be registered across chains without re-prompting. */\n async addApprover(pubkey: DevicePublicKey): Promise<{ transactionHash?: string }> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: addApprover requires a ready, authorized device\");\n }\n if (await this.adapter.isApprover(this.address, pubkey)) return {};\n const ixs = await this.adapter.buildAddApprover(this.address, pubkey);\n const transactionHash = await this.send(ixs);\n return { transactionHash };\n }\n\n /**\n * From a fresh browser (status `needs-device-approval`), approve adding THIS\n * device with the user's synced passkey. Gasless via the relayer — the bundle\n * carries the passkey's WebAuthn assertion, so no device signature is needed.\n */\n async approveThisDeviceWithPasskey(passkey: PasskeySigner): Promise<string> {\n if (this.status === \"ready\") {\n throw new Error(\"kit/solana: this device is already an authorized signer\");\n }\n const { leaf, nonce } = await this.passkeyLeafForThisDevice();\n const leaves = [leaf];\n const assertion = await passkey.assert(batchChallenge(leaves));\n const { transactionHash } = await this.submitPasskeyApproval(assertion, leaves, 0, nonce);\n return transactionHash;\n }\n\n /** This device's leaf + passkey nonce for a (possibly multi-chain) batch. */\n async passkeyLeafForThisDevice(): Promise<{ leaf: Uint8Array; nonce: bigint }> {\n const nonce = await this.adapter.passkeyNonce(this.address);\n return { leaf: this.adapter.passkeyLeaf(this.devicePubkey, nonce), nonce };\n }\n\n /** Submit `add_signer_via_passkey` given a shared assertion + batch position.\n * Used by `approveThisDeviceWithPasskey` and `approveDeviceEverywhere`. */\n async submitPasskeyApproval(\n assertion: PasskeyAssertion,\n leaves: Uint8Array[],\n leafIndex: number,\n _nonce: bigint,\n ): Promise<{ transactionHash: string }> {\n const digest = webauthnDigest(assertion.authenticatorData, assertion.clientDataJSON);\n const candidates = recoverCandidatePublicKeys(assertion.r, assertion.s, digest);\n let approver: DevicePublicKey | null = null;\n for (const cand of candidates) {\n if (await this.adapter.isApprover(this.address, cand.publicKey)) {\n approver = cand.publicKey;\n break;\n }\n }\n if (!approver) throw new Error(\"kit/solana: this passkey is not a registered approver\");\n const ixs = this.adapter.buildAddSignerViaPasskey(\n this.address, this.devicePubkey, approver, leaves, leafIndex, assertion,\n );\n return { transactionHash: await this.send(ixs) };\n }\n\n /** Move `amount` lamports out of the account to `destination` (device-signed). */\n async execute(amount: bigint, destination: string): Promise<string> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: this device is not yet an authorized signer of the wallet\");\n }\n const ixs = await this.adapter.buildExecuteTransfer(this.address, destination, amount);\n return this.send(ixs);\n }\n\n /**\n * Run arbitrary CPI `instructions` with the account PDA as signer (device-\n * signed). The signature commits to sha256 of the canonical Borsh\n * serialization of the instructions, so it binds exactly the operations the\n * program will invoke. Unlocks SPL transfers, swaps, staking, etc.\n *\n * What the relayer will sponsor is constrained by the app's Solana program\n * allowlist (configured in the dashboard) — programs outside the allowlist are\n * rejected before co-signing.\n */\n async executeInstructions(instructions: InstructionData[]): Promise<string> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: this device is not yet an authorized signer of the wallet\");\n }\n const ixs = await this.adapter.buildExecute(this.address, instructions);\n return this.send(ixs);\n }\n\n /**\n * Register the backup signer derived from `code` as an authorized signer of this\n * account (device-signed via precompile). Idempotent: returns without a tx if\n * the backup signer is already registered. The code never leaves the device —\n * only the derived public key travels on-chain.\n *\n * Self-custodial: anyone who can re-derive the backup key from the code (i.e.\n * the rightful owner) can later recover the account with `CavosSolana.recover`.\n * Run this once, on a registered device, and have the user store the code.\n */\n async setupRecovery(code: string): Promise<string | undefined> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: setupRecovery requires a ready, registered device\");\n }\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 the\n * new device, and returns a ready CavosSolana 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 * This mirrors `Cavos.recover` (Starknet): the backup key is just another\n * authorized signer, so recovery is an `add_signer(newDevice)` bundle signed by\n * the backup key. The on-chain program needs no recovery-specific entrypoint.\n */\n static async recover(opts: RecoverSolanaOptions): Promise<CavosSolana> {\n if (opts.network === \"solana-mainnet\" && !opts.rpcUrl) {\n console.warn(\n \"[cavos] Using the public mainnet-beta RPC. Pass `rpcUrl` with your own \" +\n \"provider (Helius/Triton/QuickNode) for production — the public endpoint is rate-limited.\",\n );\n }\n const connection = new Connection(opts.rpcUrl ?? SOLANA_NETWORKS[opts.network], \"confirmed\");\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. The\n // adapter signs every bundle with whatever `signer` it's constructed with,\n // so a backup-backed adapter produces backup-signed `add_signer` bundles.\n const backup = BackupSigner.fromCode(opts.code);\n const backupAdapter = new SolanaAdapter({\n programId: opts.programId,\n connection,\n signer: backup,\n });\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/solana: no account found for this identity — nothing to recover\");\n }\n\n const relayer =\n opts.relayer ??\n (opts.appId\n ? new SolanaRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network, connection })\n : undefined);\n\n // Authorise the new device, signed by the backup key (sponsored by the relayer,\n // or self-funded). The account address is unchanged.\n const alreadyAuthed = await backupAdapter.isAuthorizedSigner(existing.address, devicePubkey);\n if (!alreadyAuthed) {\n const ixs = await backupAdapter.buildAddSigner(existing.address, devicePubkey);\n if (relayer) {\n await relayer.send(ixs);\n } else if (opts.feePayer) {\n await sendAndConfirmTransaction(connection, new Transaction().add(...ixs), [opts.feePayer]);\n } else {\n throw new Error(\"kit/solana: a relayer (appId) or feePayer is required to recover\");\n }\n }\n\n // Hand control to the new device's signer for all future operations.\n const adapter = new SolanaAdapter({ programId: opts.programId, connection, signer });\n return new CavosSolana(\n opts.identity,\n existing.address,\n \"ready\",\n connection,\n adapter,\n devicePubkey,\n relayer,\n opts.feePayer,\n );\n }\n\n private async send(ixs: TransactionInstruction[]): Promise<string> {\n // Prefer the sponsored relayer (no fee payer needed); fall back to self-funded.\n if (this.relayer) return this.relayer.send(ixs);\n if (this.feePayer) {\n return sendAndConfirmTransaction(this.connection, new Transaction().add(...ixs), [this.feePayer]);\n }\n throw new Error(\"kit/solana: no relayer or feePayer configured to submit transactions\");\n }\n}\n\nconst defaultRegistry = new InMemoryWalletRegistry();\n","/** Cavos device-account primitives on Stellar / Soroban. */\n\n/**\n * Deployed `cavos-account-factory` contract id per network (see\n * account-contracts/stellar/deployments). The factory is the fixed deployer that\n * makes account addresses a deterministic function of (identity, device pubkey).\n */\nexport const FACTORY_CONTRACT_ID = {\n // Re-deployed 2026-07-01 with the passkey-approval device-account wasm (batched\n // multi-chain challenge). The factory pins the wasm hash immutably, so a new\n // wasm needs a new factory → new account addresses; testnet has no prod wallets.\n \"stellar-testnet\": \"CBCJIODXIEBOXXD66KCUCF7ZDYJARKI4ZIVQOVWPULOBH5XGNCDP6W3I\",\n // Set once the factory is deployed to mainnet (its address differs — network id\n // is part of contract-address derivation).\n \"stellar-mainnet\": \"\",\n} as const;\n\n/** Uploaded Wasm hash of `cavos-device-account` (informational / verification). */\nexport const DEVICE_ACCOUNT_WASM_HASH = {\n \"stellar-testnet\": \"2671b085578e59a385ef5a5664e42f0450322fe3249539f588e1263ed5a31dce\",\n \"stellar-mainnet\": \"\",\n} as const;\n\nexport const STELLAR_NETWORKS = {\n \"stellar-testnet\": {\n rpcUrl: \"https://soroban-testnet.stellar.org\",\n passphrase: \"Test SDF Network ; September 2015\",\n },\n \"stellar-mainnet\": {\n rpcUrl: \"https://soroban-rpc.mainnet.stellar.gateway.fm\",\n passphrase: \"Public Global Stellar Network ; September 2015\",\n },\n} as const;\n\nexport type StellarNetwork = keyof typeof STELLAR_NETWORKS;\n\n/** Native XLM Stellar Asset Contract (SAC) id per network — the token the demo\n * moves. Any SEP-41 token contract works; this is a convenience default. */\nexport const NATIVE_SAC_ID = {\n \"stellar-testnet\": \"CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC\",\n \"stellar-mainnet\": \"CAS3J7GYLGXMF6TDJBBYYSE3HQ6BBSMLNUQ34T6TZMYMW2EVH34XOWMA\",\n} as const;\n","import {\n Address,\n Operation,\n StrKey,\n hash,\n nativeToScVal,\n scValToNative,\n xdr,\n rpc,\n} from \"@stellar/stellar-sdk\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { DeviceSigner, DevicePublicKey, DeviceSignature } from \"../../signer/DeviceSigner\";\nimport { bigIntTo32Bytes } from \"../../crypto/encoding\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\nimport {\n FACTORY_CONTRACT_ID,\n STELLAR_NETWORKS,\n type StellarNetwork,\n} from \"./constants\";\n\n/** secp256r1 (P-256) curve order — for low-S normalization (verifier requires it). */\nconst SECP256R1_N =\n 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;\n\nexport interface StellarAdapterOptions {\n network: StellarNetwork;\n /** RPC override (else the network default). */\n rpcUrl?: string;\n /** Factory contract id override (else the per-network default). */\n factoryId?: string;\n /** The device signer that authorizes account operations. */\n signer: DeviceSigner;\n}\n\n/**\n * Stellar / Soroban implementation of the Cavos device-account surface. Unlike\n * Starknet (`buildSignature(txHash: bigint)`) the Soroban signing unit is a\n * 32-byte Soroban *auth-entry* preimage, so — as the Solana adapter did for its\n * own model — this adapter exposes chain-native methods rather than the generic\n * `ChainAdapter` shape. Its job:\n * - derive the deterministic account address off-chain (matches the factory),\n * - build the factory/account/token invocations as host functions, and\n * - sign a Soroban authorization entry with the silent P-256 device key,\n * producing the `Vec<DeviceSignature>` ScVal that the contract's\n * `__check_auth` verifies.\n */\nexport class StellarAdapter {\n readonly chain = \"stellar\" as const;\n readonly network: StellarNetwork;\n readonly passphrase: string;\n private readonly rpcUrl: string;\n private readonly factoryId: string;\n private readonly signer: DeviceSigner;\n private _server?: rpc.Server;\n\n constructor(opts: StellarAdapterOptions) {\n this.network = opts.network;\n this.passphrase = STELLAR_NETWORKS[opts.network].passphrase;\n this.rpcUrl = opts.rpcUrl ?? STELLAR_NETWORKS[opts.network].rpcUrl;\n this.factoryId = opts.factoryId ?? FACTORY_CONTRACT_ID[opts.network];\n if (!this.factoryId) {\n throw new Error(`kit/stellar: no factory contract id configured for ${opts.network}`);\n }\n this.signer = opts.signer;\n }\n\n server(): rpc.Server {\n if (!this._server) {\n this._server = new rpc.Server(this.rpcUrl, {\n allowHttp: this.rpcUrl.startsWith(\"http://\"),\n });\n }\n return this._server;\n }\n\n private networkId(): Buffer {\n return hash(Buffer.from(this.passphrase));\n }\n\n /**\n * Deterministic account address for `(addressSeed, initialSigner)` — computed\n * off-chain, byte-identical to the factory's on-chain `account_address`.\n * `contractId = sha256(HashIdPreimage(networkId, factory, salt))` with\n * `salt = sha256(addressSeed || sec1(initialSigner))`.\n */\n computeAddress(addressSeed: Uint8Array, initialSigner: DevicePublicKey): string {\n const salt = this.accountSalt(addressSeed, initialSigner);\n const preimage = xdr.HashIdPreimage.envelopeTypeContractId(\n new xdr.HashIdPreimageContractId({\n networkId: this.networkId(),\n contractIdPreimage: xdr.ContractIdPreimage.contractIdPreimageFromAddress(\n new xdr.ContractIdPreimageFromAddress({\n address: new Address(this.factoryId).toScAddress(),\n salt,\n }),\n ),\n }),\n );\n return StrKey.encodeContract(hash(preimage.toXDR()));\n }\n\n /** `salt = sha256(addressSeed(32) || sec1(initialSigner)(65))` — matches the factory. */\n accountSalt(addressSeed: Uint8Array, initialSigner: DevicePublicKey): Buffer {\n return hash(Buffer.concat([Buffer.from(addressSeed), Buffer.from(sec1Pubkey(initialSigner))]));\n }\n\n /** Host function: `factory.deploy(address_seed, initial_signer)`. */\n buildDeploy(addressSeed: Uint8Array, initialSigner: DevicePublicKey): xdr.HostFunction {\n return invokeFunc(this.factoryId, \"deploy\", [\n bytesScVal(addressSeed),\n bytesScVal(sec1Pubkey(initialSigner)),\n ]);\n }\n\n /** Host function: `account.add_signer(new_signer)` (requires device auth). */\n buildAddSigner(accountAddress: string, signer: DevicePublicKey): xdr.HostFunction {\n return invokeFunc(accountAddress, \"add_signer\", [bytesScVal(sec1Pubkey(signer))]);\n }\n\n /** Host function: `account.remove_signer(signer)` (requires device auth). */\n buildRemoveSigner(accountAddress: string, signer: DevicePublicKey): xdr.HostFunction {\n return invokeFunc(accountAddress, \"remove_signer\", [bytesScVal(sec1Pubkey(signer))]);\n }\n\n /** Host function: `account.add_approver(passkey)` (requires device auth). */\n buildAddApprover(accountAddress: string, passkey: DevicePublicKey): xdr.HostFunction {\n return invokeFunc(accountAddress, \"add_approver\", [bytesScVal(sec1Pubkey(passkey))]);\n }\n\n /** Host function: `account.remove_approver(passkey)` (requires device auth). */\n buildRemoveApprover(accountAddress: string, passkey: DevicePublicKey): xdr.HostFunction {\n return invokeFunc(accountAddress, \"remove_approver\", [bytesScVal(sec1Pubkey(passkey))]);\n }\n\n /** This chain's leaf for approving `add_signer(newSigner)` at `nonce`:\n * `sha256(sec1(new_signer) || nonce_be8)`. The batch challenge the passkey signs\n * is `sha256(concat(leaves))` across chains. */\n passkeyLeaf(newSigner: DevicePublicKey, nonce: bigint): Uint8Array {\n const msg = new Uint8Array(65 + 8);\n msg.set(sec1Pubkey(newSigner), 0);\n const n = new Uint8Array(8);\n let v = nonce;\n for (let i = 7; i >= 0; i--) {\n n[i] = Number(v & 0xffn);\n v >>= 8n;\n }\n msg.set(n, 65);\n return sha256(msg);\n }\n\n /** Host function: passkey-authorized `add_signer_via_passkey` (no device auth —\n * authorized by the embedded WebAuthn assertion, so any relayer can submit).\n * `leaves`/`leafIndex` place this chain's leaf in the multi-chain batch. */\n buildAddSignerViaPasskey(\n accountAddress: string,\n newSigner: DevicePublicKey,\n passkey: DevicePublicKey,\n nonce: bigint,\n leaves: Uint8Array[],\n leafIndex: number,\n assertion: PasskeyAssertion,\n ): xdr.HostFunction {\n const sig = encodeLowSSignature({ r: assertion.r, s: assertion.s, yParity: false });\n const leavesScVal = xdr.ScVal.scvVec(leaves.map((l) => bytesScVal(l)));\n return invokeFunc(accountAddress, \"add_signer_via_passkey\", [\n bytesScVal(sec1Pubkey(newSigner)),\n bytesScVal(sec1Pubkey(passkey)),\n nativeToScVal(nonce, { type: \"u64\" }),\n leavesScVal,\n nativeToScVal(leafIndex, { type: \"u32\" }),\n bytesScVal(assertion.authenticatorData),\n bytesScVal(assertion.clientDataJSON),\n nativeToScVal(assertion.challengeOffset, { type: \"u32\" }),\n bytesScVal(sig),\n ]);\n }\n\n /** Read whether `passkey` is a registered approver (read-only simulation). */\n async isApprover(\n accountAddress: string,\n passkey: DevicePublicKey,\n readSource: string,\n ): Promise<boolean> {\n if (!(await this.isDeployed(accountAddress))) return false;\n const { Account, TransactionBuilder, BASE_FEE } = await import(\"@stellar/stellar-sdk\");\n const src = new Account(readSource, \"0\");\n const op = Operation.invokeHostFunction({\n func: invokeFunc(accountAddress, \"is_approver\", [bytesScVal(sec1Pubkey(passkey))]),\n auth: [],\n });\n const tx = new TransactionBuilder(src, { fee: BASE_FEE, networkPassphrase: this.passphrase })\n .addOperation(op)\n .setTimeout(30)\n .build();\n const sim = await this.server().simulateTransaction(tx);\n if (rpc.Api.isSimulationError(sim)) {\n throw new Error(`kit/stellar: is_approver simulation failed: ${sim.error}`);\n }\n if (!sim.result?.retval) return false;\n return scValToNative(sim.result.retval) === true;\n }\n\n /** Read the current passkey-approval nonce (read-only simulation). */\n async passkeyNonce(accountAddress: string, readSource: string): Promise<bigint> {\n if (!(await this.isDeployed(accountAddress))) return 0n;\n const { Account, TransactionBuilder, BASE_FEE } = await import(\"@stellar/stellar-sdk\");\n const src = new Account(readSource, \"0\");\n const op = Operation.invokeHostFunction({\n func: invokeFunc(accountAddress, \"passkey_nonce\", []),\n auth: [],\n });\n const tx = new TransactionBuilder(src, { fee: BASE_FEE, networkPassphrase: this.passphrase })\n .addOperation(op)\n .setTimeout(30)\n .build();\n const sim = await this.server().simulateTransaction(tx);\n if (rpc.Api.isSimulationError(sim)) {\n throw new Error(`kit/stellar: passkey_nonce simulation failed: ${sim.error}`);\n }\n if (!sim.result?.retval) return 0n;\n return BigInt(scValToNative(sim.result.retval));\n }\n\n /** Host function: SEP-41 `token.transfer(from=account, to, amount)` (device auth). */\n buildTransfer(\n tokenId: string,\n accountAddress: string,\n destination: string,\n amount: bigint,\n ): xdr.HostFunction {\n return invokeFunc(tokenId, \"transfer\", [\n new Address(accountAddress).toScVal(),\n new Address(destination).toScVal(),\n nativeToScVal(amount, { type: \"i128\" }),\n ]);\n }\n\n /**\n * Sign a Soroban authorization entry with the silent device key, producing the\n * `Vec<DeviceSignature>` the account's `__check_auth` verifies. The device\n * signs `sha256(preimage)` (WebCrypto hashes once more internally), which is\n * exactly what the contract recomputes. Mutates + returns the entry.\n */\n async signAuthEntry(\n entry: xdr.SorobanAuthorizationEntry,\n validUntilLedger: number,\n ): Promise<xdr.SorobanAuthorizationEntry> {\n const addrCreds = entry.credentials().address();\n addrCreds.signatureExpirationLedger(validUntilLedger);\n\n const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId: this.networkId(),\n nonce: addrCreds.nonce(),\n signatureExpirationLedger: validUntilLedger,\n invocation: entry.rootInvocation(),\n }),\n );\n const payload = hash(preimage.toXDR());\n const sig = await this.signer.sign(new Uint8Array(payload));\n const pubkey = await this.signer.getPublicKey();\n addrCreds.signature(deviceSignatureScVal(pubkey, sig));\n return entry;\n }\n\n /**\n * Read a SEP-41 token balance of `account` via a read-only simulation of\n * `token.balance(account)`. Returns 0 when the account isn't deployed or holds\n * none. `readSource` is any funded G-account (used only for the simulation).\n */\n async readBalance(tokenId: string, account: string, readSource: string): Promise<bigint> {\n if (!(await this.isDeployed(account))) return 0n;\n const { Account, TransactionBuilder, BASE_FEE } = await import(\"@stellar/stellar-sdk\");\n const src = new Account(readSource, \"0\");\n const op = Operation.invokeHostFunction({\n func: invokeFunc(tokenId, \"balance\", [new Address(account).toScVal()]),\n auth: [],\n });\n const tx = new TransactionBuilder(src, { fee: BASE_FEE, networkPassphrase: this.passphrase })\n .addOperation(op)\n .setTimeout(30)\n .build();\n const sim = await this.server().simulateTransaction(tx);\n if (rpc.Api.isSimulationError(sim) || !sim.result?.retval) return 0n;\n return BigInt(scValToNative(sim.result.retval) as string | number | bigint);\n }\n\n /** Whether the account contract instance exists on-chain (is deployed). */\n async isDeployed(accountAddress: string): Promise<boolean> {\n try {\n const res = await this.server().getContractData(\n accountAddress,\n xdr.ScVal.scvLedgerKeyContractInstance(),\n rpc.Durability.Persistent,\n );\n return !!res;\n } catch {\n return false;\n }\n }\n\n /**\n * Read whether `signer` is a currently-authorized signer of the account, via a\n * read-only simulation of `account.is_authorized(signer)`. `readSource` is any\n * funded G-account (used only for the simulation's source/sequence).\n */\n async isAuthorizedSigner(\n accountAddress: string,\n signer: DevicePublicKey,\n readSource: string,\n ): Promise<boolean> {\n if (!(await this.isDeployed(accountAddress))) return false;\n const { Account, TransactionBuilder, BASE_FEE } = await import(\"@stellar/stellar-sdk\");\n const src = new Account(readSource, \"0\");\n const op = Operation.invokeHostFunction({\n func: invokeFunc(accountAddress, \"is_authorized\", [bytesScVal(sec1Pubkey(signer))]),\n auth: [],\n });\n const tx = new TransactionBuilder(src, { fee: BASE_FEE, networkPassphrase: this.passphrase })\n .addOperation(op)\n .setTimeout(30)\n .build();\n const sim = await this.server().simulateTransaction(tx);\n if (rpc.Api.isSimulationError(sim)) {\n throw new Error(`kit/stellar: is_authorized simulation failed: ${sim.error}`);\n }\n if (!sim.result?.retval) return false;\n return scValToNative(sim.result.retval) === true;\n }\n}\n\n/** SEC-1 uncompressed P-256 public key (65 bytes: 0x04 || X || Y). */\nexport function sec1Pubkey(pk: DevicePublicKey): Uint8Array {\n const out = new Uint8Array(65);\n out[0] = 0x04;\n out.set(bigIntTo32Bytes(pk.x), 1);\n out.set(bigIntTo32Bytes(pk.y), 33);\n return out;\n}\n\n/** Raw 64-byte `r || s`, normalized to low-S (secp256r1_verify requires it). */\nexport function encodeLowSSignature(sig: DeviceSignature): Uint8Array {\n const lowS = sig.s > SECP256R1_N / 2n ? SECP256R1_N - sig.s : sig.s;\n const out = new Uint8Array(64);\n out.set(bigIntTo32Bytes(sig.r), 0);\n out.set(bigIntTo32Bytes(lowS), 32);\n return out;\n}\n\n/**\n * The `Vec<DeviceSignature>` ScVal the contract's `__check_auth` decodes. Each\n * element is a struct `{ public_key: BytesN<65>, signature: BytesN<64> }`.\n * Soroban serializes a struct as a symbol-keyed map sorted by key; `public_key`\n * precedes `signature`, so `nativeToScVal` (which sorts) yields the exact layout.\n */\nexport function deviceSignatureScVal(\n pubkey: DevicePublicKey,\n sig: DeviceSignature,\n): xdr.ScVal {\n const element = nativeToScVal(\n {\n public_key: Buffer.from(sec1Pubkey(pubkey)),\n signature: Buffer.from(encodeLowSSignature(sig)),\n },\n { type: { public_key: [\"symbol\", \"bytes\"], signature: [\"symbol\", \"bytes\"] } },\n );\n return xdr.ScVal.scvVec([element]);\n}\n\nfunction invokeFunc(contractId: string, method: string, args: xdr.ScVal[]): xdr.HostFunction {\n return xdr.HostFunction.hostFunctionTypeInvokeContract(\n new xdr.InvokeContractArgs({\n contractAddress: new Address(contractId).toScAddress(),\n functionName: method,\n args,\n }),\n );\n}\n\nfunction bytesScVal(bytes: Uint8Array): xdr.ScVal {\n return xdr.ScVal.scvBytes(Buffer.from(bytes));\n}\n","import type { StellarNetwork } from \"./constants\";\n\nexport interface StellarRelayerOptions {\n /** Base URL of the Cavos backend exposing /api/stellar/relay. */\n baseUrl: string;\n /** Cavos App ID (authorizes the sponsored request). */\n appId: string;\n network: StellarNetwork;\n}\n\n/**\n * Client for the Cavos Stellar sponsoring relayer. On Stellar the account is a\n * *contract*, which cannot be a transaction source — so the relayer's own\n * G-account is the transaction source AND fee payer. The user's silent device\n * key never pays: it only signs the Soroban *authorization entry* (verified by\n * the account's `__check_auth`), which is independent of who submits or pays.\n * That gives a seedless, gasless experience with no fee-payer keypair on the\n * integrator side — the same \"relayer pays, device authorizes\" split as Solana.\n *\n * The SDK builds the fully-assembled transaction (source = relayer, Soroban auth\n * entries already device-signed) and hands its unsigned XDR to the relayer, which\n * validates it against its allowlist, signs the envelope and submits.\n */\nexport class StellarRelayer {\n private source?: string;\n\n constructor(private readonly opts: StellarRelayerOptions) {}\n\n /** The relayer's source/fee-payer G-account (fetched + cached from the backend). */\n async getSource(): Promise<string> {\n if (this.source) return this.source;\n const res = await fetch(`${this.opts.baseUrl}/api/stellar/relay?network=${this.opts.network}`);\n if (!res.ok) throw new Error(`kit/stellar: relayer source lookup failed (${res.status})`);\n const { fee_payer } = (await res.json()) as { fee_payer: string };\n this.source = fee_payer;\n return this.source;\n }\n\n /**\n * POST the assembled, device-authorized transaction XDR to the relayer to sign\n * the envelope + submit. Returns the confirmed transaction hash.\n */\n async submit(transactionXdr: string): Promise<string> {\n const res = await fetch(`${this.opts.baseUrl}/api/stellar/relay`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n app_id: this.opts.appId,\n network: this.opts.network,\n transaction: transactionXdr,\n }),\n });\n if (!res.ok) {\n const detail = await res.text().catch(() => \"\");\n throw new Error(`kit/stellar: relay failed (${res.status}) ${detail}`);\n }\n const { hash } = (await res.json()) as { hash: string };\n return hash;\n }\n}\n","import {\n Account,\n Address,\n BASE_FEE,\n Operation,\n TransactionBuilder,\n rpc,\n xdr,\n type Keypair,\n type Transaction,\n} from \"@stellar/stellar-sdk\";\nimport type { AuthProvider, Identity } from \"../../auth/AuthProvider\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { WebCryptoSigner } from \"../../signer/WebCryptoSigner\";\nimport type { WalletRegistry } from \"../../registry/WalletRegistry\";\nimport { InMemoryWalletRegistry } from \"../../registry/WalletRegistry\";\nimport { HttpWalletRegistry } from \"../../registry/HttpWalletRegistry\";\nimport { deriveAddressSeedStellar } from \"../../identity\";\nimport { BackupSigner, deriveBackupKey } from \"../../recovery/BackupSigner\";\nimport type { PasskeySigner, PasskeyEnrollParams } from \"../../signer/PasskeySigner\";\nimport { webauthnDigest, recoverCandidatePublicKeys, batchChallenge } from \"../../crypto/webauthn\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\nimport { StellarAdapter } from \"./StellarAdapter\";\nimport { StellarRelayer } from \"./StellarRelayer\";\nimport { NATIVE_SAC_ID, type StellarNetwork } from \"./constants\";\n\nexport interface ConnectStellarOptions {\n network: StellarNetwork;\n /** Authenticated user (pass `identity` directly, or an `auth` provider). */\n auth?: AuthProvider;\n identity?: Identity;\n appSalt: string;\n appId?: string;\n backendUrl?: string;\n registry?: WalletRegistry;\n /** RPC override (else the network default). */\n rpcUrl?: string;\n /** Factory contract id override (else the per-network default). */\n factoryId?: string;\n /** Override the device signer factory (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n /**\n * Gasless sponsorship via the Cavos relayer. When set (or when `appId` +\n * `backendUrl` are given) the relayer is the transaction source + fee payer, so\n * the integrator needs NO Stellar keypair — the silent device key (which holds\n * no XLM) gets a seedless, gasless experience.\n */\n relayer?: StellarRelayer;\n /**\n * Self-funded fallback: a Stellar `Keypair` that is the transaction source +\n * fee payer. Used only when no `relayer` is configured (tests / advanced).\n */\n sourceKeypair?: Keypair;\n}\n\nexport interface RecoverStellarOptions extends Omit<ConnectStellarOptions, \"auth\"> {\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}\n\nexport type ConnectStatus = \"ready\" | \"needs-device-approval\";\n\n/**\n * High-level Stellar entry — the Soroban analogue of `Cavos.connect` /\n * `CavosSolana.connect`. One call derives the deterministic device-bound account,\n * deploys it via the factory if needed, registers it for cross-device\n * recognition, and returns a ready handle whose silent P-256 device key\n * authorizes every action through the account's `__check_auth`.\n *\n * const cavos = await CavosStellar.connect({ network: \"stellar-testnet\", identity, appSalt, relayer });\n * if (cavos.status === \"ready\") await cavos.execute(10_000_000n, dest); // 1 XLM\n *\n * Gasless by default: with an `appId` the Cavos relayer is the tx source + fee\n * payer. `sourceKeypair` is the self-funded fallback.\n */\nexport class CavosStellar {\n /** Discriminant for the `CavosWallet` union — narrows `execute()` per chain. */\n readonly chain = \"stellar\" as const;\n\n private constructor(\n readonly identity: Identity,\n readonly address: string,\n readonly status: ConnectStatus,\n readonly network: StellarNetwork,\n private readonly adapter: StellarAdapter,\n private readonly devicePubkey: DevicePublicKey,\n private readonly relayer?: StellarRelayer,\n private readonly sourceKeypair?: Keypair,\n ) {}\n\n get publicKey(): DevicePublicKey {\n return this.devicePubkey;\n }\n\n static async connect(opts: ConnectStellarOptions): Promise<CavosStellar> {\n const identity = opts.identity ?? (await opts.auth?.authenticate());\n if (!identity) throw new Error(\"kit/stellar: connect requires `identity` or `auth`\");\n\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 StellarAdapter({\n network: opts.network,\n rpcUrl: opts.rpcUrl,\n factoryId: opts.factoryId,\n signer,\n });\n const addressSeed = deriveAddressSeedStellar({ userId: identity.userId, appSalt: opts.appSalt });\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 relayer =\n opts.relayer ??\n (opts.appId\n ? new StellarRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network })\n : undefined);\n\n const build = (\n address: string,\n status: ConnectStatus,\n ): CavosStellar =>\n new CavosStellar(identity, address, status, opts.network, adapter, devicePubkey, relayer, opts.sourceKeypair);\n\n const self = build(\"\", \"needs-device-approval\");\n const readSource = await self.resolveSource();\n\n // Returning user on another device? The address is device-bound, so the\n // registry (not identity alone) recognizes it. A new device is flagged\n // needs-device-approval — same model as Starknet/Solana.\n const existing = await registry.lookup(identity.userId);\n if (existing) {\n const isSigner = await adapter.isAuthorizedSigner(existing.address, devicePubkey, readSource);\n return build(existing.address, isSigner ? \"ready\" : \"needs-device-approval\");\n }\n\n const address = adapter.computeAddress(addressSeed, devicePubkey);\n if (!(await adapter.isDeployed(address))) {\n const func = adapter.buildDeploy(addressSeed, devicePubkey);\n // Deploy needs NO device auth (factory deploys; account doesn't exist yet),\n // so `authAccount` is undefined — nothing to sign, just the relayer/self pays.\n await self.submitHostFunction(func, undefined);\n }\n\n await registry.register({ userId: identity.userId, address, initialSigner: devicePubkey });\n const isSigner = await adapter.isAuthorizedSigner(address, devicePubkey, readSource);\n return build(address, isSigner ? \"ready\" : \"needs-device-approval\");\n }\n\n /** Authorize an additional device signer (device-signed via `__check_auth`). */\n async addSigner(pubkey: DevicePublicKey): Promise<string> {\n const func = this.adapter.buildAddSigner(this.address, pubkey);\n return this.submitHostFunction(func, this.address);\n }\n\n /**\n * Enroll a passkey as an approver (2FA-style step-up). Device-signed + gasless;\n * requires a ready device. Idempotent. Returns the passkey pubkey + tx hash.\n */\n async enrollPasskey(\n passkey: PasskeySigner,\n params: PasskeyEnrollParams,\n ): Promise<{ publicKey: DevicePublicKey; transactionHash?: string }> {\n const enrolled = await passkey.enroll(params);\n const { transactionHash } = await this.addApprover(enrolled.publicKey);\n return { publicKey: enrolled.publicKey, transactionHash };\n }\n\n /** Register an already-enrolled passkey pubkey as an approver (gasless).\n * Idempotent. Lets one passkey be registered across chains without re-prompting. */\n async addApprover(pubkey: DevicePublicKey): Promise<{ transactionHash?: string }> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/stellar: addApprover requires a ready, authorized device\");\n }\n const readSource = await this.resolveSource();\n if (await this.adapter.isApprover(this.address, pubkey, readSource)) return {};\n const func = this.adapter.buildAddApprover(this.address, pubkey);\n const transactionHash = await this.submitHostFunction(func, this.address);\n return { transactionHash };\n }\n\n /**\n * From a fresh browser (status `needs-device-approval`), approve adding THIS\n * device using the user's synced passkey. Gasless via the relayer — the call\n * carries the WebAuthn assertion, so no device signature is needed. Returns the\n * tx hash. No trip back to an already-authorized device.\n */\n async approveThisDeviceWithPasskey(passkey: PasskeySigner): Promise<string> {\n if (this.status === \"ready\") {\n throw new Error(\"kit/stellar: this device is already an authorized signer\");\n }\n const { leaf, nonce } = await this.passkeyLeafForThisDevice();\n const leaves = [leaf];\n const assertion = await passkey.assert(batchChallenge(leaves));\n const { transactionHash } = await this.submitPasskeyApproval(assertion, leaves, 0, nonce);\n return transactionHash;\n }\n\n /** This device's leaf + passkey nonce for a (possibly multi-chain) batch. */\n async passkeyLeafForThisDevice(): Promise<{ leaf: Uint8Array; nonce: bigint }> {\n const readSource = await this.resolveSource();\n const nonce = await this.adapter.passkeyNonce(this.address, readSource);\n return { leaf: this.adapter.passkeyLeaf(this.devicePubkey, nonce), nonce };\n }\n\n /** Submit `add_signer_via_passkey` given a shared assertion + batch position.\n * No device auth entry — authorized purely by the passkey assertion. */\n async submitPasskeyApproval(\n assertion: PasskeyAssertion,\n leaves: Uint8Array[],\n leafIndex: number,\n nonce: bigint,\n ): Promise<{ transactionHash: string }> {\n const readSource = await this.resolveSource();\n const digest = webauthnDigest(assertion.authenticatorData, assertion.clientDataJSON);\n const candidates = recoverCandidatePublicKeys(assertion.r, assertion.s, digest);\n let approver: DevicePublicKey | null = null;\n for (const cand of candidates) {\n if (await this.adapter.isApprover(this.address, cand.publicKey, readSource)) {\n approver = cand.publicKey;\n break;\n }\n }\n if (!approver) throw new Error(\"kit/stellar: this passkey is not a registered approver\");\n const func = this.adapter.buildAddSignerViaPasskey(\n this.address, this.devicePubkey, approver, nonce, leaves, leafIndex, assertion,\n );\n return { transactionHash: await this.submitHostFunction(func, undefined) };\n }\n\n /** Move `amount` stroops of native XLM to `destination` (device-signed). */\n async execute(amount: bigint, destination: string): Promise<string> {\n return this.executeTransfer(NATIVE_SAC_ID[this.network], amount, destination);\n }\n\n /** Read this account's balance of `tokenId` (defaults to native XLM), in stroops. */\n async balance(tokenId: string = NATIVE_SAC_ID[this.network]): Promise<bigint> {\n const readSource = await this.resolveSource();\n return this.adapter.readBalance(tokenId, this.address, readSource);\n }\n\n /** Transfer `amount` of any SEP-41 token out of the account (device-signed). */\n async executeTransfer(tokenId: string, amount: bigint, destination: string): Promise<string> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/stellar: this device is not yet an authorized signer of the wallet\");\n }\n const func = this.adapter.buildTransfer(tokenId, this.address, destination, amount);\n return this.submitHostFunction(func, this.address);\n }\n\n /**\n * Register the backup signer derived from `code` as an authorized signer of\n * this account (device-signed). Idempotent. The code never leaves the device —\n * only the derived public key travels on-chain. Mirrors the other chains.\n */\n async setupRecovery(code: string): Promise<string | undefined> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/stellar: setupRecovery requires a ready, registered device\");\n }\n const { publicKey: backupPubkey } = deriveBackupKey(code);\n const readSource = await this.resolveSource();\n if (await this.adapter.isAuthorizedSigner(this.address, backupPubkey, readSource)) return undefined;\n return this.addSigner(backupPubkey);\n }\n\n /**\n * Recover an account after losing every device signer: derive the backup key\n * from `code`, use it (not the new device) to authorize `add_signer(newDevice)`,\n * and return a ready handle bound to the new device. The address is unchanged.\n */\n static async recover(opts: RecoverStellarOptions): Promise<CavosStellar> {\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 tx: it's the only signer that can authorize\n // adding the new device after all device keys are lost. Build an adapter\n // whose signer IS the backup key so the auth entry is backup-signed.\n const backup = BackupSigner.fromCode(opts.code);\n const backupAdapter = new StellarAdapter({\n network: opts.network,\n rpcUrl: opts.rpcUrl,\n factoryId: opts.factoryId,\n signer: backup,\n });\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/stellar: no account found for this identity — nothing to recover\");\n }\n const relayer =\n opts.relayer ??\n (opts.appId\n ? new StellarRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network })\n : undefined);\n\n // A CavosStellar bound to the backup adapter, used only to authorize add_signer.\n const backupHandle = new CavosStellar(\n opts.identity,\n existing.address,\n \"ready\",\n opts.network,\n backupAdapter,\n devicePubkey,\n relayer,\n opts.sourceKeypair,\n );\n const readSource = await backupHandle.resolveSource();\n if (!(await backupAdapter.isAuthorizedSigner(existing.address, devicePubkey, readSource))) {\n await backupHandle.addSigner(devicePubkey);\n }\n\n // Hand control to the new device's signer for all future operations.\n const adapter = new StellarAdapter({\n network: opts.network,\n rpcUrl: opts.rpcUrl,\n factoryId: opts.factoryId,\n signer,\n });\n return new CavosStellar(\n opts.identity,\n existing.address,\n \"ready\",\n opts.network,\n adapter,\n devicePubkey,\n relayer,\n opts.sourceKeypair,\n );\n }\n\n /** The transaction source/fee-payer G-address (relayer or self-funded). */\n private async resolveSource(): Promise<string> {\n if (this.relayer) return this.relayer.getSource();\n if (this.sourceKeypair) return this.sourceKeypair.publicKey();\n throw new Error(\"kit/stellar: a relayer (appId) or sourceKeypair is required\");\n }\n\n /**\n * Build → simulate → device-sign auth → assemble → submit an invoke-contract\n * host function. `authAccount` is the account whose `__check_auth` must sign the\n * operation's Soroban auth entry (undefined for a plain factory deploy).\n */\n private async submitHostFunction(\n func: xdr.HostFunction,\n authAccount: string | undefined,\n ): Promise<string> {\n const server = this.adapter.server();\n const sourceAddr = await this.resolveSource();\n\n // Simulation ignores the source sequence, so a throwaway seq is fine here —\n // this avoids double-incrementing the real relayer sequence between builds.\n const simSource = new Account(sourceAddr, \"0\");\n const unsignedOp = Operation.invokeHostFunction({ func, auth: [] });\n const simTx = new TransactionBuilder(simSource, {\n fee: BASE_FEE,\n networkPassphrase: this.adapter.passphrase,\n })\n .addOperation(unsignedOp)\n .setTimeout(180)\n .build();\n\n const sim = await server.simulateTransaction(simTx);\n if (rpc.Api.isSimulationError(sim)) {\n throw new Error(`kit/stellar: simulation failed: ${sim.error}`);\n }\n\n const validUntil = (await server.getLatestLedger()).sequence + 100;\n const entries = sim.result?.auth ?? [];\n const signedAuth: xdr.SorobanAuthorizationEntry[] = [];\n for (const entry of entries) {\n if (authAccount && isAddressCredentialFor(entry, authAccount)) {\n signedAuth.push(await this.adapter.signAuthEntry(entry, validUntil));\n } else {\n signedAuth.push(entry);\n }\n }\n\n // Final tx: real sequence + the device-signed auth entries. assembleTransaction\n // preserves the op's existing auth (only fills sorobanData + resource fee).\n const account = await server.getAccount(sourceAddr);\n const finalOp = Operation.invokeHostFunction({ func, auth: signedAuth });\n const built = new TransactionBuilder(account, {\n fee: BASE_FEE,\n networkPassphrase: this.adapter.passphrase,\n })\n .addOperation(finalOp)\n .setTimeout(180)\n .build();\n\n // Re-simulate WITH the signed auth so the resource estimate includes the cost\n // of running `__check_auth` (secp256r1_verify + sha256). The first simulation\n // ran in recording mode with no signatures, so it under-counted CPU and the\n // tx would fail on-chain with RESOURCE_LIMIT_EXCEEDED.\n const authSim = await server.simulateTransaction(built);\n if (rpc.Api.isSimulationError(authSim)) {\n throw new Error(`kit/stellar: auth simulation failed: ${authSim.error}`);\n }\n const assembled = rpc.assembleTransaction(built, authSim).build();\n\n // Relayer signs the envelope + submits (gasless). Self-funded signs locally.\n if (this.relayer) {\n return this.relayer.submit(assembled.toXDR());\n }\n if (this.sourceKeypair) {\n assembled.sign(this.sourceKeypair);\n return this.sendAndConfirm(assembled);\n }\n throw new Error(\"kit/stellar: no relayer or sourceKeypair configured to submit\");\n }\n\n /** Submit a signed tx via RPC and poll to confirmation. Returns the hash. */\n private async sendAndConfirm(tx: Transaction): Promise<string> {\n const server = this.adapter.server();\n const sent = await server.sendTransaction(tx);\n if (sent.status === \"ERROR\") {\n throw new Error(`kit/stellar: submit rejected: ${JSON.stringify(sent.errorResult)}`);\n }\n const hash = sent.hash;\n for (let i = 0; i < 30; i++) {\n const got = await server.getTransaction(hash);\n if (got.status === rpc.Api.GetTransactionStatus.SUCCESS) return hash;\n if (got.status === rpc.Api.GetTransactionStatus.FAILED) {\n throw new Error(`kit/stellar: tx ${hash} failed`);\n }\n await new Promise((r) => setTimeout(r, 1000));\n }\n throw new Error(`kit/stellar: tx ${hash} not confirmed in time`);\n }\n}\n\n/** Whether an auth entry is an Address credential for `accountAddress`. */\nfunction isAddressCredentialFor(entry: xdr.SorobanAuthorizationEntry, accountAddress: string): boolean {\n const creds = entry.credentials();\n if (creds.switch() !== xdr.SorobanCredentialsType.sorobanCredentialsAddress()) return false;\n return Address.fromScAddress(creds.address().address()).toString() === accountAddress;\n}\n\nconst defaultRegistry = new InMemoryWalletRegistry();\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 { Account, RpcProvider, PaymasterRpc, hash, num, type Call } from \"starknet\";\nimport type { Keypair } from \"@solana/web3.js\";\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 { CavosSolana } from \"./chains/solana/CavosSolana\";\nimport type { SolanaRelayer } from \"./chains/solana/SolanaRelayer\";\nimport type { SolanaNetwork } from \"./chains/solana/constants\";\nimport { CavosStellar } from \"./chains/stellar/CavosStellar\";\nimport type { StellarRelayer } from \"./chains/stellar/StellarRelayer\";\nimport type { StellarNetwork } from \"./chains/stellar/constants\";\nimport type { Keypair as StellarKeypair } from \"@stellar/stellar-sdk\";\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 type { PasskeySigner, PasskeyEnrollParams } from \"./signer/PasskeySigner\";\nimport { webauthnDigest, recoverCandidatePublicKeys, batchChallenge } from \"./crypto/webauthn\";\nimport type { PasskeyAssertion } from \"./crypto/webauthn\";\nimport {\n CAVOS_PAYMASTER_URL,\n DEVICE_ACCOUNT_CLASS_HASH,\n STARKNET_NETWORKS,\n type StarknetNetwork,\n} from \"./chains/starknet/constants\";\n\n/** The chains the unified `Cavos.connect` can target. */\nexport type Chain = \"starknet\" | \"solana\" | \"stellar\";\n\n/**\n * Environment selector. `Cavos.connect` resolves it to the chain's concrete\n * network: starknet → sepolia/mainnet, solana → solana-devnet/solana-mainnet.\n */\nexport type NetworkEnv = \"mainnet\" | \"testnet\";\n\n/** Resolve the abstract `{ chain, network }` to each chain's concrete network. */\nconst STARKNET_ENV: Record<NetworkEnv, StarknetNetwork> = {\n mainnet: \"mainnet\",\n testnet: \"sepolia\",\n};\nconst SOLANA_ENV: Record<NetworkEnv, SolanaNetwork> = {\n mainnet: \"solana-mainnet\",\n testnet: \"solana-devnet\",\n};\nconst STELLAR_ENV: Record<NetworkEnv, StellarNetwork> = {\n mainnet: \"stellar-mainnet\",\n testnet: \"stellar-testnet\",\n};\n\n/** A connected wallet: discriminated by `chain`, so `execute()` stays native. */\nexport type CavosWallet = Cavos | CavosSolana | CavosStellar;\n\nexport interface ConnectOptions {\n /** Target chain. The returned wallet is discriminated by this same value. */\n chain: Chain;\n /** Environment. Resolved to sepolia/devnet (testnet) or mainnet per chain. */\n network: NetworkEnv;\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 (Starknet). Defaults to HttpRecoveryClient when\n * `appId` is set; used to request addition of this device when it isn't a\n * signer yet.\n */\n recovery?: RecoveryClient;\n rpcUrl?: string;\n /** Override the device signer factory (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n\n // --- Starknet-only ---\n /** Cavos paymaster API key (sponsors deploy + execute). Required for Starknet. */\n paymasterApiKey?: string;\n paymasterUrl?: string;\n classHash?: string;\n\n // --- Solana-only ---\n /** Cavos device-account program id override. */\n programId?: string;\n /** Gasless sponsorship relayer (defaults to the hosted one when `appId` set). */\n relayer?: SolanaRelayer;\n /** Self-funded fee-payer fallback when no relayer is configured. */\n feePayer?: Keypair;\n\n // --- Stellar-only ---\n /** Gasless sponsorship relayer (defaults to the hosted one when `appId` set). */\n stellarRelayer?: StellarRelayer;\n /** Self-funded source/fee-payer Stellar keypair when no relayer is configured. */\n stellarSourceKeypair?: StellarKeypair;\n /** Factory contract id override (else the per-network default). */\n factoryId?: string;\n}\n\n/** The Starknet-specific connect options, resolved from the unified ones. */\ninterface StarknetConnectOptions {\n network: StarknetNetwork;\n auth?: AuthProvider;\n identity?: Identity;\n appSalt: string;\n appId?: string;\n backendUrl?: string;\n registry?: WalletRegistry;\n recovery?: RecoveryClient;\n paymasterApiKey: string;\n paymasterUrl?: string;\n rpcUrl?: string;\n classHash?: string;\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 /** Environment (recovery is Starknet-only): testnet → sepolia, mainnet. */\n network: NetworkEnv;\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 /** Discriminant for the `CavosWallet` union — narrows `execute()` per chain. */\n readonly chain = \"starknet\" as const;\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 /** Paymaster URL + API key, for the sponsored passkey-approval path. */\n private readonly paymaster?: { url: string; apiKey?: string },\n ) {}\n\n /**\n * Unified entry point. Pick a `chain` and an `network` environment; the kit\n * resolves the concrete network (sepolia/devnet for testnet, mainnet for\n * mainnet) and returns a chain-native wallet. The result is a discriminated\n * union (`wallet.chain`), so `execute()` keeps each chain's native signature:\n *\n * const wallet = await Cavos.connect({ chain: \"solana\", network: \"testnet\", identity, appSalt, appId });\n * if (wallet.chain === \"starknet\") await wallet.execute(calls);\n * else await wallet.execute(amount, dest);\n */\n static async connect(opts: ConnectOptions): Promise<CavosWallet> {\n if (opts.chain === \"solana\") {\n return CavosSolana.connect({\n network: SOLANA_ENV[opts.network],\n ...(opts.auth ? { auth: opts.auth } : {}),\n ...(opts.identity ? { identity: opts.identity } : {}),\n appSalt: opts.appSalt,\n ...(opts.appId ? { appId: opts.appId } : {}),\n ...(opts.backendUrl ? { backendUrl: opts.backendUrl } : {}),\n ...(opts.registry ? { registry: opts.registry } : {}),\n ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}),\n ...(opts.programId ? { programId: opts.programId } : {}),\n ...(opts.createSigner ? { createSigner: opts.createSigner } : {}),\n ...(opts.relayer ? { relayer: opts.relayer } : {}),\n ...(opts.feePayer ? { feePayer: opts.feePayer } : {}),\n });\n }\n if (opts.chain === \"stellar\") {\n return CavosStellar.connect({\n network: STELLAR_ENV[opts.network],\n ...(opts.auth ? { auth: opts.auth } : {}),\n ...(opts.identity ? { identity: opts.identity } : {}),\n appSalt: opts.appSalt,\n ...(opts.appId ? { appId: opts.appId } : {}),\n ...(opts.backendUrl ? { backendUrl: opts.backendUrl } : {}),\n ...(opts.registry ? { registry: opts.registry } : {}),\n ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}),\n ...(opts.factoryId ? { factoryId: opts.factoryId } : {}),\n ...(opts.createSigner ? { createSigner: opts.createSigner } : {}),\n ...(opts.stellarRelayer ? { relayer: opts.stellarRelayer } : {}),\n ...(opts.stellarSourceKeypair ? { sourceKeypair: opts.stellarSourceKeypair } : {}),\n });\n }\n if (!opts.paymasterApiKey) {\n throw new Error(\"kit: `paymasterApiKey` is required for Starknet connections\");\n }\n return Cavos.connectStarknet({\n network: STARKNET_ENV[opts.network],\n auth: opts.auth,\n identity: opts.identity,\n appSalt: opts.appSalt,\n appId: opts.appId,\n backendUrl: opts.backendUrl,\n registry: opts.registry,\n recovery: opts.recovery,\n paymasterApiKey: opts.paymasterApiKey,\n paymasterUrl: opts.paymasterUrl,\n rpcUrl: opts.rpcUrl,\n classHash: opts.classHash,\n createSigner: opts.createSigner,\n });\n }\n\n private static async connectStarknet(opts: StarknetConnectOptions): 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 paymasterUrl = opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[opts.network];\n const paymasterConfig = { url: paymasterUrl, apiKey: opts.paymasterApiKey };\n const paymaster = new PaymasterRpc({\n nodeUrl: paymasterUrl,\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 paymasterConfig,\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 paymasterConfig,\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 * Enroll a passkey as an APPROVER so the user can later add devices from any\n * browser (2FA-style step-up). Requires a ready device (the enrollment call is\n * device-signed and gasless). Idempotent: a no-op if the passkey is already an\n * approver. Call this whenever the app decides to prompt \"turn on device\n * approvals\". Returns the passkey's public key + the enrollment tx hash.\n */\n async enrollPasskey(\n passkey: PasskeySigner,\n params: PasskeyEnrollParams,\n ): Promise<{ publicKey: DevicePublicKey; transactionHash?: string }> {\n const enrolled = await passkey.enroll(params);\n const { transactionHash } = await this.addApprover(enrolled.publicKey);\n return { publicKey: enrolled.publicKey, transactionHash };\n }\n\n /**\n * Register an ALREADY-enrolled passkey public key as an approver (gasless,\n * device-signed). Idempotent. Use this to register ONE passkey across multiple\n * chains without re-prompting `passkey.enroll()` on each: enroll once, then\n * call `addApprover(pubkey)` on each chain's wallet.\n */\n async addApprover(pubkey: DevicePublicKey): Promise<{ transactionHash?: string }> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit: addApprover requires a ready, authorized device\");\n }\n if (await this.adapter.isApprover(this.address, pubkey)) return {};\n const { transactionHash } = await this.execute([\n this.adapter.buildAddApprover(this.address, pubkey),\n ]);\n return { transactionHash };\n }\n\n /**\n * From a brand-new browser (status `needs-device-approval`), use the user's\n * synced passkey to authorize adding THIS device — no trip back to an already-\n * authorized device.\n *\n * `add_signer_via_passkey` is a public external authorized by the embedded\n * WebAuthn assertion (no device signature), so by default we sponsor it through\n * the Cavos paymaster's `paymaster_executeDirectTransaction` (the forwarder's\n * `execute_sponsored` runs a generic call — it does NOT require SNIP-9). Pass a\n * custom `submit` to route it through your own relayer instead. Returns the tx.\n */\n async approveThisDeviceWithPasskey(opts: {\n passkey: PasskeySigner;\n submit?: (call: ChainCall) => Promise<{ transactionHash: string }>;\n }): Promise<{ transactionHash: string }> {\n if (this.status === \"ready\") {\n throw new Error(\"kit: this device is already an authorized signer\");\n }\n const { leaf, nonce } = await this.passkeyLeafForThisDevice();\n const leaves = [leaf];\n const assertion = await opts.passkey.assert(batchChallenge(leaves));\n return this.submitPasskeyApproval(assertion, leaves, 0, nonce, opts.submit);\n }\n\n /** This device's leaf + the current passkey nonce, for a (possibly multi-chain)\n * passkey approval batch. See `approveDeviceEverywhere`. */\n async passkeyLeafForThisDevice(): Promise<{ leaf: Uint8Array; nonce: bigint }> {\n const nonce = await this.adapter.getPasskeyNonce(this.address);\n return { leaf: this.adapter.passkeyLeaf(this.devicePubkey, nonce), nonce };\n }\n\n /** Submit `add_signer_via_passkey` given a (shared) assertion + this chain's\n * position in the batch. The assertion doesn't carry the passkey pubkey, so we\n * recover both candidates and pick the enrolled approver via the on-chain view\n * (no backend). Defaults to sponsoring through the paymaster. */\n async submitPasskeyApproval(\n assertion: PasskeyAssertion,\n leaves: Uint8Array[],\n leafIndex: number,\n nonce: bigint,\n submit?: (call: ChainCall) => Promise<{ transactionHash: string }>,\n ): Promise<{ transactionHash: string }> {\n const digest = webauthnDigest(assertion.authenticatorData, assertion.clientDataJSON);\n const candidates = recoverCandidatePublicKeys(assertion.r, assertion.s, digest);\n let yParity: boolean | null = null;\n for (const cand of candidates) {\n if (await this.adapter.isApprover(this.address, cand.publicKey)) {\n yParity = cand.yParity;\n break;\n }\n }\n if (yParity === null) {\n throw new Error(\"kit: this passkey is not a registered approver of the wallet\");\n }\n const call = this.adapter.buildAddSignerViaPasskey(\n this.address, this.devicePubkey, nonce, leaves, leafIndex, assertion, yParity,\n );\n if (submit) return submit(call);\n if (!this.paymaster) {\n throw new Error(\"kit: no paymaster configured — pass a `submit` relayer to approveThisDeviceWithPasskey\");\n }\n return paymasterExecuteDirect(this.paymaster, this.address, call);\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 network = STARKNET_ENV[opts.network];\n const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[network];\n if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${network}`);\n\n const provider = new RpcProvider({\n nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[network].rpcUrl,\n });\n const paymaster = new PaymasterRpc({\n nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[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 })\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/** A chain wallet that can approve THIS device via a passkey (implemented by\n * `Cavos`, `CavosSolana`, `CavosStellar`). */\nexport interface PasskeyApprovable {\n readonly chain: string;\n readonly status: string;\n passkeyLeafForThisDevice(): Promise<{ leaf: Uint8Array; nonce: bigint }>;\n submitPasskeyApproval(\n assertion: PasskeyAssertion,\n leaves: Uint8Array[],\n leafIndex: number,\n nonce: bigint,\n ): Promise<{ transactionHash: string }>;\n}\n\n/**\n * Approve THIS device across several chains with a SINGLE passkey prompt. Each\n * chain is a separate account, so the device must be added per chain — but one\n * WebAuthn assertion over the batch challenge (`sha256(concat(leaves))`) suffices\n * for all of them. Only wallets whose status is `needs-device-approval` are\n * touched. Returns the per-chain tx hashes.\n *\n * await approveDeviceEverywhere([starknet, solana, stellar], passkey);\n */\nexport async function approveDeviceEverywhere(\n wallets: PasskeyApprovable[],\n passkey: PasskeySigner,\n): Promise<{ chain: string; transactionHash: string }[]> {\n const targets = wallets.filter((w) => w.status === \"needs-device-approval\");\n if (targets.length === 0) return [];\n const infos = await Promise.all(targets.map((w) => w.passkeyLeafForThisDevice()));\n const leaves = infos.map((i) => i.leaf);\n // ONE prompt: the passkey signs the batch challenge over every chain's leaf.\n const assertion = await passkey.assert(batchChallenge(leaves));\n const out: { chain: string; transactionHash: string }[] = [];\n for (let i = 0; i < targets.length; i++) {\n const { transactionHash } = await targets[i].submitPasskeyApproval(\n assertion, leaves, i, infos[i].nonce,\n );\n out.push({ chain: targets[i].chain, transactionHash });\n }\n return out;\n}\n\n/**\n * Sponsor a single call through the Cavos paymaster's `paymaster_executeDirectTransaction`\n * (AVNU-fork extension). In sponsored mode the forwarder runs a generic\n * `call_contract_syscall` (no SNIP-9 / device signature required), so the\n * passkey-authorized `add_signer_via_passkey` external is paid for by the\n * paymaster's relayer. The account's on-chain check (approver membership +\n * challenge binding) is the real authorization.\n */\nasync function paymasterExecuteDirect(\n paymaster: { url: string; apiKey?: string },\n userAddress: string,\n call: ChainCall,\n): Promise<{ transactionHash: string }> {\n const body = {\n jsonrpc: \"2.0\",\n id: 1,\n method: \"paymaster_executeDirectTransaction\",\n params: {\n transaction: {\n type: \"invoke\",\n invoke: {\n user_address: userAddress,\n execute_from_outside_call: {\n to: call.contractAddress,\n selector: hash.getSelectorFromName(call.entrypoint),\n calldata: call.calldata.map((c) => num.toHex(c)),\n },\n },\n },\n parameters: { version: \"0x1\", fee_mode: { mode: \"sponsored\" } },\n },\n };\n const res = await fetch(paymaster.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(paymaster.apiKey ? { \"x-paymaster-api-key\": paymaster.apiKey } : {}),\n },\n body: JSON.stringify(body),\n });\n const json = await res.json();\n if (json.error) {\n throw new Error(`kit: paymaster passkey approval failed: ${JSON.stringify(json.error)}`);\n }\n return { transactionHash: json.result?.transaction_hash ?? json.result?.tracking_id };\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","import { sha256 } from \"@noble/hashes/sha256\";\nimport type { DevicePublicKey } from \"./DeviceSigner\";\nimport {\n base64urlEncode,\n challengeOffsetOf,\n derToRs,\n spkiToPublicKey,\n type PasskeyAssertion,\n} from \"../crypto/webauthn\";\n\nexport interface PasskeySignerOptions {\n /** Relying-Party id (usually the eTLD+1). Defaults to `window.location.hostname`. */\n rpId?: string;\n /** Human-readable RP name shown in the OS passkey UI. */\n rpName?: string;\n}\n\nexport interface PasskeyEnrollParams {\n /** Stable user handle for the credential (e.g. the account address or userId). */\n userId: string;\n /** Account name shown in the OS passkey UI (e.g. an email). */\n userName: string;\n displayName?: string;\n}\n\nexport interface EnrolledPasskey {\n publicKey: DevicePublicKey;\n credentialId: Uint8Array;\n}\n\n/**\n * Browser passkey signer. Creates a discoverable (resident) secp256r1 credential\n * that syncs across the user's devices (iCloud Keychain / Google Password\n * Manager), and produces WebAuthn assertions used to authorize `add_signer`.\n *\n * This is a step-up primitive: the app decides WHEN to enroll (e.g. after\n * onboarding, as a \"turn on device approvals\" / 2FA moment). Enrollment\n * registers the passkey on-chain as an approver; later, from any browser, an\n * assertion approves adding that browser's new device key.\n */\nexport class PasskeySigner {\n private readonly rpId: string;\n private readonly rpName: string;\n\n constructor(opts: PasskeySignerOptions = {}) {\n if (typeof window === \"undefined\" || !navigator.credentials) {\n throw new Error(\"kit/passkey: WebAuthn is only available in a browser\");\n }\n this.rpId = opts.rpId ?? window.location.hostname;\n this.rpName = opts.rpName ?? this.rpId;\n // WebAuthn requires the RP ID to be a registrable domain (or \"localhost\").\n // An IP address always fails with a cryptic \"invalid domain\" — surface an\n // actionable message instead (common when devs test over a LAN IP).\n if (isIpAddress(this.rpId)) {\n throw new Error(\n `kit/passkey: passkeys can't use an IP address as the domain (\"${this.rpId}\"). ` +\n \"Use http://localhost, a real HTTPS domain, or a tunnel (cloudflared/ngrok) — \" +\n \"or pass an explicit `rpId`. (The silent device key works over an IP; passkeys don't.)\",\n );\n }\n }\n\n /** True if this platform advertises a usable passkey (platform authenticator). */\n static async isSupported(): Promise<boolean> {\n if (typeof window === \"undefined\" || !window.PublicKeyCredential) return false;\n try {\n return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n } catch {\n return false;\n }\n }\n\n /** Create a new synced passkey and return its P-256 public key. */\n async enroll(params: PasskeyEnrollParams): Promise<EnrolledPasskey> {\n const challenge = crypto.getRandomValues(new Uint8Array(32));\n const cred = (await navigator.credentials.create({\n publicKey: {\n challenge: buf(challenge),\n rp: { id: this.rpId, name: this.rpName },\n user: {\n id: buf(userHandle(params.userId)),\n name: params.userName,\n displayName: params.displayName ?? params.userName,\n },\n pubKeyCredParams: [{ type: \"public-key\", alg: -7 }], // ES256 (P-256)\n authenticatorSelection: {\n residentKey: \"required\",\n requireResidentKey: true,\n userVerification: \"preferred\",\n },\n attestation: \"none\",\n },\n })) as PublicKeyCredential | null;\n if (!cred) throw new Error(\"kit/passkey: enrollment cancelled\");\n\n const response = cred.response as AuthenticatorAttestationResponse;\n const spki = new Uint8Array(response.getPublicKey()!);\n return { publicKey: spkiToPublicKey(spki), credentialId: new Uint8Array(cred.rawId) };\n }\n\n /**\n * Produce a WebAuthn assertion over `challenge` (a 32-byte value the caller\n * derives from the signer being added + the on-chain nonce). Uses discoverable\n * credentials — no `allowCredentials` — so it works on a brand-new browser.\n */\n async assert(challenge: Uint8Array): Promise<PasskeyAssertion> {\n const cred = (await navigator.credentials.get({\n publicKey: {\n challenge: buf(challenge),\n rpId: this.rpId,\n allowCredentials: [],\n userVerification: \"preferred\",\n },\n })) as PublicKeyCredential | null;\n if (!cred) throw new Error(\"kit/passkey: assertion cancelled\");\n\n const response = cred.response as AuthenticatorAssertionResponse;\n const authenticatorData = new Uint8Array(response.authenticatorData);\n const clientDataJSON = new Uint8Array(response.clientDataJSON);\n const { r, s } = derToRs(new Uint8Array(response.signature));\n const challengeOffset = challengeOffsetOf(clientDataJSON, base64urlEncode(challenge));\n return { authenticatorData, clientDataJSON, r, s, challengeOffset };\n }\n}\n\n/**\n * WebAuthn requires the user handle to be 1..64 bytes. `userId` may be longer\n * (e.g. a 66-char Starknet address), so hash anything over 64 bytes to a stable\n * 32-byte handle. The handle is opaque — only its stability matters.\n */\n/** True for IPv4/IPv6 literals — WebAuthn rejects these as an RP ID. */\nfunction isIpAddress(host: string): boolean {\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host)) return true; // IPv4\n if (host.includes(\":\")) return true; // IPv6 literal\n return false;\n}\n\nfunction userHandle(userId: string): Uint8Array {\n const bytes = new TextEncoder().encode(userId);\n return bytes.length <= 64 ? bytes : sha256(bytes);\n}\n\n/** Coerce a `Uint8Array` to the `BufferSource` the WebAuthn DOM types want\n * (works around the TS5.7 `ArrayBufferLike` vs `ArrayBuffer` mismatch). */\nfunction buf(bytes: Uint8Array): BufferSource {\n return bytes.slice() as unknown as BufferSource;\n}\n"]}
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/identity.ts","../src/chains/solana/constants.ts","../src/chains/solana/SolanaAdapter.ts","../src/chains/solana/SolanaRelayer.ts","../src/recovery/BackupSigner.ts","../src/crypto/webauthn.ts","../src/chains/solana/CavosSolana.ts","../src/chains/stellar/constants.ts","../node_modules/@noble/ciphers/src/utils.ts","../node_modules/@noble/ciphers/src/_polyval.ts","../node_modules/@noble/ciphers/src/aes.ts","../src/chains/stellar/envelope.ts","../src/chains/stellar/datamap.ts","../src/chains/stellar/StellarAdapter.ts","../src/chains/stellar/keys.ts","../src/chains/stellar/StellarRelayer.ts","../src/chains/stellar/CavosStellar.ts","../src/chains/stellar/DeviceUnwrapKey.ts","../src/chains/stellar/WebCryptoDeviceUnwrapKey.ts","../src/recovery/HttpRecoveryClient.ts","../src/Cavos.ts","../src/auth/AuthProvider.ts","../src/auth/CavosAuth.ts","../src/chains/stellar/PasskeyPrf.ts","../src/signer/PasskeySigner.ts"],"names":["clean","p256","sha256","hash","num","Signer","PublicKey","TransactionInstruction","SystemProgram","SYSVAR_INSTRUCTIONS_PUBKEY","ix","lowS","buf","tx","Transaction","randomBytes","pbkdf2","hkdf","Connection","isSigner","sendAndConfirmTransaction","isLE","BLOCK_SIZE","POLY","mul2","sbox","sbox2","t0","t1","t2","t3","Horizon","TransactionBuilder","BASE_FEE","Operation","Asset","Account","Keypair","IDB_NAME","IDB_STORE","assertSecureContext","idbPut","idbGet","openDb","toHex","fromHex","RpcProvider","PaymasterRpc","address","defaultRegistry","account","cavos","res","isIpAddress","userHandle"],"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,MAAW,KAAK,KAAA,EAAO,GAAA,GAAO,GAAA,IAAO,EAAA,GAAM,OAAO,CAAC,CAAA;AACnD,EAAA,OAAO,GAAA;AACT;AAEO,SAAS,WAAW,KAAA,EAA2B;AACpD,EAAA,IAAI,CAAA,GAAI,IAAA;AACR,EAAA,KAAA,MAAW,CAAA,IAAK,OAAO,CAAA,IAAK,CAAA,CAAE,SAAS,EAAE,CAAA,CAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAA;AAC1D,EAAA,OAAO,CAAA;AACT;AAEO,SAAS,WAAW,GAAA,EAAyB;AACl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AA;AACjD,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA,EAAG,OAAO,IAAA;AAC/B,EAAA,OAAO,KAAA;AACT;AAEA,SAASC,YAAW,MAAA,EAA4B;AAC9C,EAAA,MAAM,KAAA,GAAQ,IAAI,WAAA,EAAY,CAAE,OAAO,MAAM,CAAA;AAC7C,EAAA,OAAO,KAAA,CAAM,MAAA,IAAU,EAAA,GAAK,KAAA,GAAQpD,cAAO,KAAK,CAAA;AAClD;AAIA,SAASU,KAAI,KAAA,EAAiC;AAC5C,EAAA,OAAO,MAAM,KAAA,EAAM;AACrB","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/**\n * Serialize raw bytes into the calldata a Cairo `ByteArray` deserializes from:\n * [ num_full_words, ...full_words(31 bytes each), pending_word, pending_len ]\n * Each full word is 31 big-endian bytes; the pending word holds the trailing\n * `< 31` bytes. Used to pass `authenticator_data` / `client_data_json` to the\n * passkey-approval entrypoint.\n */\nexport function bytesToByteArrayCalldata(bytes: Uint8Array): string[] {\n const CHUNK = 31;\n const fullCount = Math.floor(bytes.length / CHUNK);\n const out: string[] = [String(fullCount)];\n for (let i = 0; i < fullCount; i++) {\n out.push(\"0x\" + bytesToBigInt(bytes.subarray(i * CHUNK, i * CHUNK + CHUNK)).toString(16));\n }\n const rem = bytes.subarray(fullCount * CHUNK);\n out.push(\"0x\" + (rem.length ? bytesToBigInt(rem).toString(16) : \"0\"));\n out.push(String(rem.length));\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 *\n * Sepolia re-declared 2026-07-04:\n * - Deploy attestation REMOVED — `initialize` takes only the device pubkey.\n * - `is_valid_signature` returns VALIDATED pre-init so the SNIP-9 outside-\n * execution path (used by the paymaster's `deploy_and_invoke`) can carry\n * the `initialize` call before any signer is registered. `__execute__`\n * still enforces that ONLY `initialize` runs in that state.\n * Mainnet still runs the prior class (with attestation) until it is re-declared.\n */\nexport const DEVICE_ACCOUNT_CLASS_HASH: Record<StarknetNetwork, string> = {\n sepolia: \"0x765f000b7021577aa0d6c206fb3d8ac73571686b3e76b9dc9b6d59a372e8c2c\",\n mainnet: \"0x1840aded59e8a0d2b440a134cb9079a7fc11b06c77f58ed189ab436a034ca6a\",\n};\n","import { hash, num } from \"starknet\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { ChainAdapter, ChainCall, ComputeAddressParams } from \"../ChainAdapter\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { signatureToFelts } from \"../../crypto/signature\";\nimport { u256ToFelts, bigIntTo32Bytes, bytesToByteArrayCalldata, bytesToBigInt } from \"../../crypto/encoding\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\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 /**\n * Deterministic address = f(addressSeed) ONLY. The device pubkey is NOT\n * part of the derivation — anti-squatting is the integrator's responsibility\n * (keep `appSalt` secret; deploy on first login). This makes the address\n * recomputable by the user from (userId, appSalt) alone, even after losing\n * every device.\n *\n * `initialSigner` in `ComputeAddressParams` is IGNORED on Starknet (kept in\n * the shared type for Solana/Stellar, which still include it).\n */\n computeAddress({ addressSeed, salt }: ComputeAddressParams): string {\n return hash.calculateContractAddressFromHash(\n num.toHex(salt ?? addressSeed),\n this.opts.classHash,\n this.constructorCalldata(addressSeed),\n 0, // deployerAddress 0 => deterministic counterfactual address\n );\n }\n\n /**\n * UDC deploy call. The constructor takes ONLY the seed — no device pubkey —\n * so the account is born with no signers. The caller MUST follow up with\n * `buildInitialize` in the same multicall (or a separate tx) to register the\n * first device signer; otherwise the account is unusable.\n */\n buildDeploy(params: ComputeAddressParams): ChainCall[] {\n const salt = params.salt ?? params.addressSeed;\n const calldata = this.constructorCalldata(params.addressSeed);\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]. Device pubkey is registered post-deploy via initialize. */\n constructorCalldata(addressSeed: bigint): string[] {\n return [num.toHex(addressSeed)];\n }\n\n /**\n * `initialize` call: registers the first device signer. Callable only while\n * the account has no signers (one-shot). In production this is bundled with\n * the UDC deploy in a single sponsored multicall — see `connectStarknet`.\n * Anti-squatting is NOT enforced on-chain.\n */\n buildInitialize(accountAddress: string, devicePubkey: DevicePublicKey): ChainCall {\n return {\n contractAddress: accountAddress,\n entrypoint: \"initialize\",\n calldata: pubkeyCalldata(devicePubkey),\n };\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 // --- passkey approvers ---\n\n buildAddApprover(accountAddress: string, passkey: DevicePublicKey): ChainCall {\n return { contractAddress: accountAddress, entrypoint: \"add_approver\", calldata: pubkeyCalldata(passkey) };\n }\n\n buildRemoveApprover(accountAddress: string, passkey: DevicePublicKey): ChainCall {\n return { contractAddress: accountAddress, entrypoint: \"remove_approver\", calldata: pubkeyCalldata(passkey) };\n }\n\n async isApprover(accountAddress: string, passkey: 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_approver\",\n calldata: pubkeyCalldata(passkey),\n });\n return BigInt(res[0] ?? 0) !== 0n;\n }\n\n /** True if the account has at least one passkey registered as an approver.\n * Lets the UI decide whether to offer passkey approval before prompting. */\n async hasPasskeyApprover(accountAddress: string): 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: \"get_approver_count\",\n calldata: [],\n });\n return BigInt(res[0] ?? 0) > 0n;\n }\n\n async getPasskeyNonce(accountAddress: string): Promise<bigint> {\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: \"get_passkey_nonce\",\n calldata: [],\n });\n return BigInt(res[0] ?? 0);\n }\n\n /** This chain's leaf for approving `add_signer(newSigner)` at `nonce`:\n * `sha256(new_x || new_y || nonce)` (coords 32B BE, nonce 16B BE). The batch\n * challenge the passkey signs is `sha256(concat(leaves))` across chains. */\n passkeyLeaf(newSigner: DevicePublicKey, nonce: bigint): Uint8Array {\n const msg = new Uint8Array(32 + 32 + 16);\n msg.set(bigIntTo32Bytes(newSigner.x), 0);\n msg.set(bigIntTo32Bytes(newSigner.y), 32);\n msg.set(bigIntTo32Bytes(nonce).subarray(16), 64); // low 16 bytes = u128 BE\n return sha256(msg);\n }\n\n /** Passkey-authorized `add_signer` call. `leaves`/`leafIndex` place this chain's\n * leaf in the multi-chain batch (single chain → `[leaf]`, index 0). `yParity`\n * matches the raw `(r, s)` — the contract normalizes high-S internally. */\n buildAddSignerViaPasskey(\n accountAddress: string,\n newSigner: DevicePublicKey,\n nonce: bigint,\n leaves: Uint8Array[],\n leafIndex: number,\n assertion: PasskeyAssertion,\n yParity: boolean,\n ): ChainCall {\n const [rl, rh] = u256ToFelts(assertion.r);\n const [sl, sh] = u256ToFelts(assertion.s);\n const leavesCalldata: string[] = [String(leaves.length)];\n for (const leaf of leaves) {\n const [lo, hi] = u256ToFelts(bytesToBigInt(leaf));\n leavesCalldata.push(num.toHex(lo), num.toHex(hi));\n }\n return {\n contractAddress: accountAddress,\n entrypoint: \"add_signer_via_passkey\",\n calldata: [\n ...pubkeyCalldata(newSigner), // new_x, new_y (u256 pairs)\n num.toHex(nonce),\n ...leavesCalldata, // Array<u256> leaves\n String(leafIndex),\n ...bytesToByteArrayCalldata(assertion.authenticatorData),\n ...bytesToByteArrayCalldata(assertion.clientDataJSON),\n String(assertion.challengeOffset),\n num.toHex(rl), num.toHex(rh),\n num.toHex(sl), num.toHex(sh),\n yParity ? \"0x1\" : \"0x0\",\n ],\n };\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 { hash } from \"starknet\";\nimport { sha256 } from \"@noble/hashes/sha256\";\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/**\n * Solana variant: a 32-byte `address_seed` for the Cavos device-account PDA.\n * Uses the SAME identity input as Starknet (`userId + appSalt`) but hashes with\n * SHA-256 instead of Poseidon, since Solana has no native Poseidon and the PDA\n * seed is raw bytes. The same user therefore maps to a stable, app-scoped\n * address on each chain (different address spaces, one identity).\n */\nexport function deriveAddressSeedSolana({ userId, appSalt }: IdentityInput): Uint8Array {\n return sha256(new TextEncoder().encode(`cavos:solana:v1:${userId}:${appSalt}`));\n}\n\n/**\n * Stellar variant: a 32-byte `address_seed` used as the Soroban account's seed\n * and folded (with the initial device signer) into the factory deploy salt.\n * Same identity input as the other chains, SHA-256 hashed, with a Stellar-scoped\n * domain so the same user maps to a distinct address per chain.\n */\nexport function deriveAddressSeedStellar({ userId, appSalt }: IdentityInput): Uint8Array {\n return sha256(new TextEncoder().encode(`cavos:stellar:v1:${userId}:${appSalt}`));\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","/** Cavos device-account program + Solana primitives. */\n\n/** Deployed `cavos-device-account` program id (see account-contracts/solana). */\nexport const DEVICE_ACCOUNT_PROGRAM_ID =\n \"FHnoYNfYAmFrwt18gcBGG7G1S5q3RAbCBvrV2D29izNJ\";\n\n/** Native secp256r1 signature-verify precompile (SIMD-0075). */\nexport const SECP256R1_PROGRAM_ID =\n \"Secp256r1SigVerify1111111111111111111111111\";\n\n/** PDA seed prefix, must match the program's `ACCOUNT_SEED`. */\nexport const ACCOUNT_SEED = \"cavos-account\";\n\n/** Domain separators, must match the program's signed-message domains. */\nexport const DOMAIN_ADD = \"cavos:add_signer:v1\";\nexport const DOMAIN_REMOVE = \"cavos:remove_signer:v1\";\nexport const DOMAIN_TRANSFER = \"cavos:transfer:v1\";\n/** Arbitrary execution (CPI). The signed message commits to sha256 of the\n * canonical Borsh serialization of the instruction set — see `buildExecute`. */\nexport const DOMAIN_EXECUTE = \"cavos:execute:v1\";\nexport const DOMAIN_ADD_APPROVER = \"cavos:add_approver:v1\";\nexport const DOMAIN_REMOVE_APPROVER = \"cavos:remove_approver:v1\";\n\n/** secp256r1 (P-256) curve order, for low-S normalization. */\nexport const SECP256R1_N =\n 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;\n\nexport const SOLANA_NETWORKS = {\n \"solana-devnet\": \"https://api.devnet.solana.com\",\n \"solana-mainnet\": \"https://api.mainnet-beta.solana.com\",\n \"solana-localnet\": \"http://127.0.0.1:8899\",\n} as const;\n\nexport type SolanaNetwork = keyof typeof SOLANA_NETWORKS;\n","import {\n Connection,\n PublicKey,\n SystemProgram,\n SYSVAR_INSTRUCTIONS_PUBKEY,\n TransactionInstruction,\n} from \"@solana/web3.js\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { bigIntTo32Bytes } from \"../../crypto/encoding\";\nimport {\n ACCOUNT_SEED,\n DEVICE_ACCOUNT_PROGRAM_ID,\n DOMAIN_ADD,\n DOMAIN_REMOVE,\n DOMAIN_TRANSFER,\n DOMAIN_EXECUTE,\n DOMAIN_ADD_APPROVER,\n DOMAIN_REMOVE_APPROVER,\n SECP256R1_N,\n SECP256R1_PROGRAM_ID,\n} from \"./constants\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\n\nconst COMPRESSED_PUBKEY_SIZE = 33;\nconst SIGNATURE_SIZE = 64;\nconst CURRENT_IX = 0xffff;\n\n/** An account meta candidate for a CPI instruction inside `execute`. Mirrors the\n * on-chain `AccountMetaCandidate` (Borsh). */\nexport interface InstructionAccount {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\n/** A CPI instruction the device key authorizes via `execute`. Mirrors the\n * on-chain `InstructionData` (Borsh). Serialized canonically and hashed before\n * signing, so a signature binds exactly this instruction set. */\nexport interface InstructionData {\n programId: string;\n accounts: InstructionAccount[];\n data: Uint8Array;\n}\n\nexport interface SolanaAdapterOptions {\n /** Cavos device-account program id (defaults to the deployed one). */\n programId?: string;\n /** RPC connection for reads (`isAuthorizedSigner`) and nonce fetch. */\n connection?: Connection;\n /** Device signer used to authorize guarded actions. */\n signer?: DeviceSigner;\n}\n\n/**\n * Solana adapter for the Cavos device-signer account. Unlike Starknet (where the\n * account contract verifies the P-256 signature in `__validate__`), Solana\n * verifies it natively via the secp256r1 precompile, so every guarded action is\n * a two-instruction bundle: `[secp256r1 precompile ix, program ix]`. This adapter\n * derives the account PDA, builds those bundles, and reuses the same\n * `DeviceSigner` (P-256 / WebCrypto) as every other chain.\n */\nexport class SolanaAdapter {\n readonly chain = \"solana\" as const;\n readonly programId: PublicKey;\n\n constructor(private readonly opts: SolanaAdapterOptions = {}) {\n this.programId = new PublicKey(opts.programId ?? DEVICE_ACCOUNT_PROGRAM_ID);\n }\n\n /**\n * Deterministic account address: PDA of [ACCOUNT_SEED, addressSeed] — the\n * device pubkey is NOT part of the seeds, so the address is recomputable\n * from (userId, appSalt) alone. Anti-squatting is the integrator's\n * responsibility (keep `appSalt` secret; deploy on first login).\n */\n computeAddress(addressSeed: Uint8Array): string {\n return this.pda(addressSeed).toBase58();\n }\n\n private pda(addressSeed: Uint8Array): PublicKey {\n const [pda] = PublicKey.findProgramAddressSync(\n [Buffer.from(ACCOUNT_SEED), Buffer.from(addressSeed)],\n this.programId,\n );\n return pda;\n }\n\n /**\n * `initialize` instruction: creates the account PDA and registers the first\n * device signer. No attestation is required — anti-squatting is NOT enforced\n * on-chain.\n */\n buildInitialize(\n addressSeed: Uint8Array,\n payer: string,\n initialSigner: DevicePublicKey,\n ): TransactionInstruction[] {\n const initialCompressed = compressedPubkey(initialSigner);\n const account = this.pda(addressSeed);\n const data = Buffer.concat([\n anchorDiscriminator(\"initialize\"),\n Buffer.from(addressSeed), // [u8;32]\n Buffer.from(initialCompressed), // [u8;33]\n ]);\n const programIx = new TransactionInstruction({\n programId: this.programId,\n keys: [\n { pubkey: account, isSigner: false, isWritable: true },\n { pubkey: new PublicKey(payer), isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return [programIx];\n }\n\n /** `[precompile, add_signer]` bundle, authorized by an existing device signer. */\n async buildAddSigner(\n account: string,\n newSigner: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const newCompressed = compressedPubkey(newSigner);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_ADD),\n accountPk.toBuffer(),\n newCompressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"add_signer\"), Buffer.from(newCompressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** `[precompile, remove_signer]` bundle, authorized by an existing device signer. */\n async buildRemoveSigner(\n account: string,\n signer: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const compressed = compressedPubkey(signer);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_REMOVE),\n accountPk.toBuffer(),\n compressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"remove_signer\"), Buffer.from(compressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** `[precompile, add_approver]` bundle enrolling a passkey approver (device-signed). */\n async buildAddApprover(\n account: string,\n passkey: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const compressed = compressedPubkey(passkey);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_ADD_APPROVER),\n accountPk.toBuffer(),\n compressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"add_approver\"), Buffer.from(compressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** `[precompile, remove_approver]` bundle (device-signed). */\n async buildRemoveApprover(\n account: string,\n passkey: DevicePublicKey\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const compressed = compressedPubkey(passkey);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_REMOVE_APPROVER),\n accountPk.toBuffer(),\n compressed,\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data: Buffer.concat([anchorDiscriminator(\"remove_approver\"), Buffer.from(compressed)]),\n });\n return [precompileIx, ix];\n }\n\n /** This chain's leaf for approving `add_signer(newSigner)` at `nonce`:\n * `sha256(compressed(new_signer) || passkey_nonce_le8)`. The batch challenge the\n * passkey signs is `sha256(concat(leaves))` across chains. */\n passkeyLeaf(newSigner: DevicePublicKey, nonce: bigint): Uint8Array {\n return sha256(concatBytes(compressedPubkey(newSigner), u64le(nonce)));\n }\n\n /**\n * `[precompile(passkey), add_signer_via_passkey]` bundle. The precompile ix\n * verifies the PASSKEY's WebAuthn assertion over `authData || sha256(clientDataJSON)`;\n * the program ix binds the challenge to `newSigner` + the passkey nonce and adds\n * the signer. No device signature — a gasless relayer can submit it.\n */\n buildAddSignerViaPasskey(\n account: string,\n newSigner: DevicePublicKey,\n passkey: DevicePublicKey,\n leaves: Uint8Array[],\n leafIndex: number,\n assertion: PasskeyAssertion\n ): TransactionInstruction[] {\n const accountPk = new PublicKey(account);\n const newCompressed = compressedPubkey(newSigner);\n const passkeyCompressed = compressedPubkey(passkey);\n\n // Precompile message = authData || sha256(clientDataJSON); the precompile\n // hashes it once → the WebAuthn signed digest.\n const clientHash = sha256(assertion.clientDataJSON);\n const message = concatBytes(assertion.authenticatorData, clientHash);\n const signature = encodeLowSSignature(assertion.r, assertion.s);\n const precompileIx = buildSecp256r1Instruction(passkeyCompressed, signature, message);\n\n // Borsh Vec<[u8; 32]> leaves: u32 len + len*32 bytes.\n const leavesBlob = Buffer.concat([u32le(leaves.length), ...leaves.map((l) => Buffer.from(l))]);\n const data = Buffer.concat([\n anchorDiscriminator(\"add_signer_via_passkey\"),\n Buffer.from(newCompressed),\n leavesBlob,\n u32le(leafIndex),\n serializeVecU8(assertion.authenticatorData),\n serializeVecU8(assertion.clientDataJSON),\n u32le(assertion.challengeOffset),\n ]);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: this.guardedKeys(accountPk),\n data,\n });\n return [precompileIx, ix];\n }\n\n /** Read whether `passkey` is a registered approver. */\n /** True if the account has at least one passkey registered as an approver. */\n async hasPasskeyApprover(account: string): Promise<boolean> {\n const approvers = await this.fetchApprovers(new PublicKey(account));\n return approvers.length > 0;\n }\n\n async isApprover(account: string, passkey: DevicePublicKey): Promise<boolean> {\n const approvers = await this.fetchApprovers(new PublicKey(account));\n const target = Buffer.from(compressedPubkey(passkey)).toString(\"hex\");\n return approvers.some((a) => Buffer.from(a).toString(\"hex\") === target);\n }\n\n /** Read the current passkey-approval nonce. */\n async passkeyNonce(account: string): Promise<bigint> {\n const info = await this.requireConnection().getAccountInfo(new PublicKey(account));\n if (!info) return 0n;\n const d = info.data;\n const signersLenOff = 8 + 32 + 1 + 8 + COMPRESSED_PUBKEY_SIZE; // 82\n const signerCount = d.readUInt32LE(signersLenOff);\n const approversLenOff = signersLenOff + 4 + signerCount * COMPRESSED_PUBKEY_SIZE;\n const approverCount = d.readUInt32LE(approversLenOff);\n const passkeyNonceOff = approversLenOff + 4 + approverCount * COMPRESSED_PUBKEY_SIZE;\n return readU64le(d, passkeyNonceOff);\n }\n\n /** `[precompile, execute_transfer]` bundle moving lamports out of the account. */\n async buildExecuteTransfer(\n account: string,\n destination: string,\n amount: bigint\n ): Promise<TransactionInstruction[]> {\n const accountPk = new PublicKey(account);\n const destPk = new PublicKey(destination);\n const nonce = await this.fetchNonce(accountPk);\n const message = concatBytes(\n Buffer.from(DOMAIN_TRANSFER),\n accountPk.toBuffer(),\n destPk.toBuffer(),\n u64le(amount),\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: [\n { pubkey: accountPk, isSigner: false, isWritable: true },\n { pubkey: destPk, isSigner: false, isWritable: true },\n { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },\n ],\n data: Buffer.concat([anchorDiscriminator(\"execute_transfer\"), u64le(amount)]),\n });\n return [precompileIx, ix];\n }\n\n /**\n * `[precompile, execute]` bundle running arbitrary CPI instructions with the\n * account PDA as signer. The device key signs over\n * `DOMAIN_EXECUTE || account || sha256(canonical(instructions)) || nonce`, so\n * the signature commits to the EXACT instruction set the program will invoke —\n * no account/data substitution is possible after signing.\n *\n * The instructions' accounts are passed to the program via `remaining_accounts`\n * (flattened, in order); the program enforces an exact, ordered mapping.\n */\n async buildExecute(\n account: string,\n instructions: InstructionData[]\n ): Promise<TransactionInstruction[]> {\n if (instructions.length === 0) throw new Error(\"kit/solana: execute requires at least one instruction\");\n\n const accountPk = new PublicKey(account);\n const nonce = await this.fetchNonce(accountPk);\n\n // Canonical Borsh serialization MUST match the on-chain\n // `hash_instructions` (sha256 over the concatenated `InstructionData`).\n const blob = serializeInstructions(instructions);\n const ixsHash = sha256(blob);\n\n const message = concatBytes(\n Buffer.from(DOMAIN_EXECUTE),\n accountPk.toBuffer(),\n Buffer.from(ixsHash),\n u64le(nonce)\n );\n const { precompileIx } = await this.signToPrecompile(message);\n\n // The program ix carries the instructions in its data; the accounts they\n // reference are flattened into `remaining_accounts` in order. The wire format\n // is discriminator + Borsh Vec<u8>(blob) = discriminator + u32_len + blob.\n // The signed hash (above) is over the inner `blob` only — no length prefix —\n // matching the program's parse and the relay's allowlist parser.\n const blobLen = Buffer.alloc(4);\n new DataView(blobLen.buffer).setUint32(0, blob.length, true);\n const data = Buffer.concat([anchorDiscriminator(\"execute\"), blobLen, blob]);\n const remainingAccounts: Array<{ pubkey: PublicKey; isSigner: false; isWritable: boolean }> = [];\n for (const ix of instructions) {\n for (const acc of ix.accounts) {\n remainingAccounts.push({\n pubkey: new PublicKey(acc.pubkey),\n isSigner: false, // signer flags are part of the signed InstructionData\n isWritable: acc.isWritable,\n });\n }\n // The CPI target program must be a remaining_account too — invoke_signed\n // needs it loaded. Appended (not part of the signed account list).\n remainingAccounts.push({\n pubkey: new PublicKey(ix.programId),\n isSigner: false,\n isWritable: false,\n });\n }\n const ix = new TransactionInstruction({\n programId: this.programId,\n keys: [\n { pubkey: accountPk, isSigner: false, isWritable: true },\n { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },\n ...remainingAccounts,\n ],\n data,\n });\n return [precompileIx, ix];\n }\n\n /** Read whether `signer` is currently an authorized signer of `account`. */\n async isAuthorizedSigner(account: string, signer: DevicePublicKey): Promise<boolean> {\n const signers = await this.fetchSigners(new PublicKey(account));\n const target = Buffer.from(compressedPubkey(signer)).toString(\"hex\");\n return signers.some((s) => Buffer.from(s).toString(\"hex\") === target);\n }\n\n private guardedKeys(account: PublicKey) {\n return [\n { pubkey: account, isSigner: false, isWritable: true },\n { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },\n ];\n }\n\n /** Sign `message` with the device key and build the matching precompile ix. */\n private async signToPrecompile(\n message: Uint8Array\n ): Promise<{ precompileIx: TransactionInstruction }> {\n if (!this.opts.signer) throw new Error(\"kit/solana: signer required to authorize\");\n const pubkey = await this.opts.signer.getPublicKey();\n // The signer signs sha256(message); the precompile recomputes sha256(message).\n const sig = await this.opts.signer.sign(message as Uint8Array);\n const signature = encodeLowSSignature(sig.r, sig.s);\n const precompileIx = buildSecp256r1Instruction(\n compressedPubkey(pubkey),\n signature,\n message\n );\n return { precompileIx };\n }\n\n private async fetchNonce(account: PublicKey): Promise<bigint> {\n const info = await this.requireConnection().getAccountInfo(account);\n if (!info) return 0n;\n // layout: 8 disc + 32 address_seed + 1 bump + 8 nonce(LE) + 33 initial_signer + ...\n // nonce is right after bump, so its offset is unaffected by initial_signer.\n return readU64le(info.data, 41);\n }\n\n private async fetchSigners(account: PublicKey): Promise<Uint8Array[]> {\n const info = await this.requireConnection().getAccountInfo(account);\n if (!info) return [];\n const d = info.data;\n // layout: 8 disc + 32 address_seed + 1 bump + 8 nonce + 33 initial_signer + 4 vec_len + signers\n const lenOffset = 8 + 32 + 1 + 8 + COMPRESSED_PUBKEY_SIZE; // = 82\n const count = d.readUInt32LE(lenOffset);\n const out: Uint8Array[] = [];\n let off = lenOffset + 4;\n for (let i = 0; i < count; i++) {\n out.push(Uint8Array.from(d.subarray(off, off + COMPRESSED_PUBKEY_SIZE)));\n off += COMPRESSED_PUBKEY_SIZE;\n }\n return out;\n }\n\n private async fetchApprovers(account: PublicKey): Promise<Uint8Array[]> {\n const info = await this.requireConnection().getAccountInfo(account);\n if (!info) return [];\n const d = info.data;\n const signersLenOff = 8 + 32 + 1 + 8 + COMPRESSED_PUBKEY_SIZE; // 82\n const signerCount = d.readUInt32LE(signersLenOff);\n const approversLenOff = signersLenOff + 4 + signerCount * COMPRESSED_PUBKEY_SIZE;\n const count = d.readUInt32LE(approversLenOff);\n const out: Uint8Array[] = [];\n let off = approversLenOff + 4;\n for (let i = 0; i < count; i++) {\n out.push(Uint8Array.from(d.subarray(off, off + COMPRESSED_PUBKEY_SIZE)));\n off += COMPRESSED_PUBKEY_SIZE;\n }\n return out;\n }\n\n private requireConnection(): Connection {\n if (!this.opts.connection) throw new Error(\"kit/solana: connection required for reads\");\n return this.opts.connection;\n }\n}\n\n/** Compressed SEC1 P-256 pubkey (33 bytes) from {x, y}. */\nexport function compressedPubkey(pk: DevicePublicKey): Uint8Array {\n const out = new Uint8Array(COMPRESSED_PUBKEY_SIZE);\n out[0] = pk.y % 2n === 0n ? 0x02 : 0x03;\n out.set(bigIntTo32Bytes(pk.x), 1);\n return out;\n}\n\n/** Encode (r, s) as raw 64-byte r‖s, normalized to low-S (precompile requires it). */\nexport function encodeLowSSignature(r: bigint, s: bigint): Uint8Array {\n const lowS = s > SECP256R1_N / 2n ? SECP256R1_N - s : s;\n const out = new Uint8Array(SIGNATURE_SIZE);\n out.set(bigIntTo32Bytes(r), 0);\n out.set(bigIntTo32Bytes(lowS), 32);\n return out;\n}\n\n/** Build the native secp256r1 precompile instruction (single self-contained sig). */\nexport function buildSecp256r1Instruction(\n compressed: Uint8Array,\n signature: Uint8Array,\n message: Uint8Array\n): TransactionInstruction {\n const headerLen = 2;\n const offsetsLen = 14;\n const pubkeyOffset = headerLen + offsetsLen;\n const sigOffset = pubkeyOffset + COMPRESSED_PUBKEY_SIZE;\n const msgOffset = sigOffset + SIGNATURE_SIZE;\n const data = Buffer.alloc(msgOffset + message.length);\n\n data.writeUInt8(1, 0);\n data.writeUInt8(0, 1);\n let o = headerLen;\n data.writeUInt16LE(sigOffset, o); o += 2;\n data.writeUInt16LE(CURRENT_IX, o); o += 2;\n data.writeUInt16LE(pubkeyOffset, o); o += 2;\n data.writeUInt16LE(CURRENT_IX, o); o += 2;\n data.writeUInt16LE(msgOffset, o); o += 2;\n data.writeUInt16LE(message.length, o); o += 2;\n data.writeUInt16LE(CURRENT_IX, o); o += 2;\n Buffer.from(compressed).copy(data, pubkeyOffset);\n Buffer.from(signature).copy(data, sigOffset);\n Buffer.from(message).copy(data, msgOffset);\n\n return new TransactionInstruction({\n keys: [],\n programId: new PublicKey(SECP256R1_PROGRAM_ID),\n data,\n });\n}\n\n/** Anchor instruction discriminator = sha256(\"global:<name>\")[..8]. */\nexport function anchorDiscriminator(name: string): Buffer {\n return Buffer.from(sha256(`global:${name}`).slice(0, 8));\n}\n\nfunction u32le(n: number): Buffer {\n const b = Buffer.alloc(4);\n b.writeUInt32LE(n);\n return b;\n}\n\nfunction u64le(n: bigint | number): Buffer {\n const b = Buffer.alloc(8);\n // Avoid Buffer.writeBigUInt64LE: the browser `buffer` polyfill doesn't\n // implement the BigInt methods. Use DataView instead.\n new DataView(b.buffer, b.byteOffset, 8).setBigUint64(0, BigInt(n), true);\n return b;\n}\n\nfunction readU64le(buf: Buffer, offset: number): bigint {\n return new DataView(buf.buffer, buf.byteOffset, buf.length).getBigUint64(\n offset,\n true,\n );\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((n, p) => n + p.length, 0);\n const out = new Uint8Array(total);\n let off = 0;\n for (const p of parts) {\n out.set(p, off);\n off += p.length;\n }\n return out;\n}\n\n// ─── Canonical Borsh serialization for `execute` ────────────────────────────\n// MUST match the on-chain `InstructionData`/`AccountMetaCandidate` AnchorSer\n// layout byte-for-byte: `hash_instructions` hashes this and the program\n// requires the precompile-verified message to commit to the same hash. Changing\n// the byte layout here breaks signature binding (and recovery of past sigs).\n\n/** Serialize a single `InstructionData` exactly as Anchor's Borsh derive would. */\nfunction serializeInstruction(ix: InstructionData): Buffer {\n const programId = new PublicKey(ix.programId).toBuffer(); // 32 bytes\n const accounts = serializeAccounts(ix.accounts);\n const data = serializeVecU8(ix.data);\n return Buffer.concat([programId, accounts, data]);\n}\n\nfunction serializeAccounts(metas: InstructionAccount[]): Buffer {\n const len = Buffer.alloc(4);\n new DataView(len.buffer).setUint32(0, metas.length, true);\n const parts = metas.map(serializeAccountMeta);\n return Buffer.concat([len, ...parts]);\n}\n\nfunction serializeAccountMeta(meta: InstructionAccount): Buffer {\n const pubkey = new PublicKey(meta.pubkey).toBuffer(); // 32 bytes\n return Buffer.concat([pubkey, Buffer.from([meta.isSigner ? 1 : 0, meta.isWritable ? 1 : 0])]);\n}\n\nfunction serializeVecU8(data: Uint8Array): Buffer {\n const len = Buffer.alloc(4);\n new DataView(len.buffer).setUint32(0, data.length, true);\n return Buffer.concat([len, Buffer.from(data)]);\n}\n\n/** Serialize the full instruction set — the bytes `hash_instructions` hashes. */\nexport function serializeInstructions(instructions: InstructionData[]): Buffer {\n return Buffer.concat(instructions.map(serializeInstruction));\n}\n","import {\n Connection,\n PublicKey,\n Transaction,\n type TransactionInstruction,\n} from \"@solana/web3.js\";\nimport type { SolanaNetwork } from \"./constants\";\n\nexport interface SolanaRelayerOptions {\n /** Base URL of the Cavos backend exposing /api/solana/relay. */\n baseUrl: string;\n /** Cavos App ID (authorizes the sponsored request). */\n appId: string;\n network: SolanaNetwork;\n /** Connection used only to fetch a recent blockhash before serializing. */\n connection: Connection;\n}\n\n/**\n * Client for the Cavos Solana sponsoring relayer. Lets the SDK submit\n * device-account transactions WITHOUT the integrator holding a fee-payer\n * keypair: the relayer co-signs as fee payer and pays the fee/rent. The relayer\n * only pays — the device signature inside the instructions (verified by the\n * secp256r1 precompile) is what authorizes the action, and it does not bind the\n * fee payer, so sponsorship needs no re-signing.\n */\nexport class SolanaRelayer {\n private feePayer?: PublicKey;\n\n constructor(private readonly opts: SolanaRelayerOptions) {}\n\n /** The relayer's fee-payer pubkey (fetched + cached from the backend). */\n async getFeePayer(): Promise<PublicKey> {\n if (this.feePayer) return this.feePayer;\n const res = await fetch(`${this.opts.baseUrl}/api/solana/relay?network=${this.opts.network}`);\n if (!res.ok) throw new Error(`kit/solana: relayer fee-payer lookup failed (${res.status})`);\n const { fee_payer } = (await res.json()) as { fee_payer: string };\n this.feePayer = new PublicKey(fee_payer);\n return this.feePayer;\n }\n\n /**\n * Build a tx with the relayer as fee payer, serialize it unsigned, and POST it\n * to the relayer to co-sign + submit. Returns the confirmed signature.\n */\n async send(instructions: TransactionInstruction[]): Promise<string> {\n const feePayer = await this.getFeePayer();\n const { blockhash } = await this.opts.connection.getLatestBlockhash(\"confirmed\");\n const tx = new Transaction();\n tx.feePayer = feePayer;\n tx.recentBlockhash = blockhash;\n tx.add(...instructions);\n\n const serialized = tx\n .serialize({ requireAllSignatures: false, verifySignatures: false })\n .toString(\"base64\");\n\n const res = await fetch(`${this.opts.baseUrl}/api/solana/relay`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n app_id: this.opts.appId,\n network: this.opts.network,\n transaction: serialized,\n }),\n });\n if (!res.ok) {\n const detail = await res.text().catch(() => \"\");\n throw new Error(`kit/solana: relay failed (${res.status}) ${detail}`);\n }\n const { signature } = (await res.json()) as { signature: string };\n return signature;\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","/**\n * WebAuthn (passkey) helpers for the passkey-approval flow.\n *\n * A passkey is a synced secp256r1 credential (iCloud Keychain / Google Password\n * Manager). We use it as an on-chain \"approver\" that can authorize `add_signer`\n * from ANY browser — so a user never has to return to an already-authorized\n * device to onboard a new one.\n *\n * Unlike a silent device key (which signs `sha256(txHash)`), a passkey signs\n * `sha256(authenticatorData || sha256(clientDataJSON))`, with the challenge\n * embedded (base64url) in `clientDataJSON`. These helpers parse an assertion and\n * reproduce exactly what the on-chain contracts recompute.\n */\nimport { p256 } from \"@noble/curves/p256\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport type { DevicePublicKey } from \"../signer/DeviceSigner\";\nimport { bytesToBigInt } from \"./encoding\";\n\n/** A parsed passkey assertion, chain-agnostic. */\nexport interface PasskeyAssertion {\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n /** ECDSA signature components (raw, as returned by the authenticator). */\n r: bigint;\n s: bigint;\n /** Byte index where the base64url challenge starts inside clientDataJSON. */\n challengeOffset: number;\n}\n\n/** base64url (no padding) of a byte array. */\nexport function base64urlEncode(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n const b64 = typeof btoa !== \"undefined\" ? btoa(bin) : Buffer.from(bytes).toString(\"base64\");\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Parse a DER (ASN.1) ECDSA signature into its `{ r, s }` components. */\nexport function derToRs(der: Uint8Array): { r: bigint; s: bigint } {\n // SEQUENCE(0x30) len INTEGER(0x02) rlen r INTEGER(0x02) slen s\n let i = 0;\n if (der[i++] !== 0x30) throw new Error(\"kit/webauthn: bad DER (no SEQUENCE)\");\n if (der[i] & 0x80) i += 1 + (der[i] & 0x7f); // skip long-form length\n else i += 1;\n if (der[i++] !== 0x02) throw new Error(\"kit/webauthn: bad DER (no r INTEGER)\");\n const rlen = der[i++];\n const r = bytesToBigInt(der.subarray(i, i + rlen));\n i += rlen;\n if (der[i++] !== 0x02) throw new Error(\"kit/webauthn: bad DER (no s INTEGER)\");\n const slen = der[i++];\n const s = bytesToBigInt(der.subarray(i, i + slen));\n return { r, s };\n}\n\n/** Extract the P-256 public key `{ x, y }` from a DER SPKI blob (as returned by\n * `AuthenticatorAttestationResponse.getPublicKey()`). The uncompressed EC point\n * is the trailing 65 bytes (`0x04 || X || Y`). */\nexport function spkiToPublicKey(spki: Uint8Array): DevicePublicKey {\n const idx = spki.lastIndexOf(0x04, spki.length - 65);\n const start = spki.length - 65;\n const prefix = spki[start];\n if (prefix !== 0x04) {\n // Fall back to scanning for the 0x04 uncompressed marker.\n if (idx < 0) throw new Error(\"kit/webauthn: no uncompressed EC point in SPKI\");\n return { x: bytesToBigInt(spki.subarray(idx + 1, idx + 33)), y: bytesToBigInt(spki.subarray(idx + 33, idx + 65)) };\n }\n return {\n x: bytesToBigInt(spki.subarray(start + 1, start + 33)),\n y: bytesToBigInt(spki.subarray(start + 33, start + 65)),\n };\n}\n\n/**\n * Batch challenge over ordered per-chain leaves: `sha256(leaf_0 ‖ … ‖ leaf_n)`.\n * A single passkey assertion over this challenge authorizes `add_signer` on every\n * chain in the batch (each chain verifies only its own leaf sits at its index).\n * For a single chain the batch is one leaf, so the challenge is `sha256(leaf)`.\n */\nexport function batchChallenge(leaves: Uint8Array[]): Uint8Array {\n const total = leaves.reduce((n, l) => n + l.length, 0);\n const cat = new Uint8Array(total);\n let o = 0;\n for (const l of leaves) {\n cat.set(l, o);\n o += l.length;\n }\n return sha256(cat);\n}\n\n/** The WebAuthn signed digest: `sha256(authenticatorData || sha256(clientDataJSON))`. */\nexport function webauthnDigest(authenticatorData: Uint8Array, clientDataJSON: Uint8Array): Uint8Array {\n const clientHash = sha256(clientDataJSON);\n const msg = new Uint8Array(authenticatorData.length + clientHash.length);\n msg.set(authenticatorData, 0);\n msg.set(clientHash, authenticatorData.length);\n return sha256(msg);\n}\n\n/** Both candidate public keys recoverable from `(r, s)` over `digest`, tagged\n * with their y-parity. On a fresh browser the assertion does not carry the\n * pubkey, so the caller identifies the real one via the on-chain `is_approver`\n * view. */\nexport function recoverCandidatePublicKeys(\n r: bigint,\n s: bigint,\n digest: Uint8Array,\n): { publicKey: DevicePublicKey; yParity: boolean }[] {\n const out: { publicKey: DevicePublicKey; yParity: boolean }[] = [];\n for (const bit of [0, 1] as const) {\n try {\n const point = new p256.Signature(r, s).addRecoveryBit(bit).recoverPublicKey(digest).toAffine();\n out.push({ publicKey: { x: point.x, y: point.y }, yParity: bit === 1 });\n } catch {\n // not recoverable for this bit\n }\n }\n return out;\n}\n\n/** Normalize `s` to the low half of the curve order (required by the Stellar\n * and Solana verifiers, which do not normalize on-chain). */\nexport function lowS(s: bigint): bigint {\n const n = p256.CURVE.n;\n return s > n / 2n ? n - s : s;\n}\n\n/** Byte offset of the base64url `challenge` string inside `clientDataJSON`. */\nexport function challengeOffsetOf(clientDataJSON: Uint8Array, challengeB64: string): number {\n const text = new TextDecoder().decode(clientDataJSON);\n const idx = text.indexOf(challengeB64);\n if (idx < 0) throw new Error(\"kit/webauthn: challenge not found in clientDataJSON\");\n // clientDataJSON is ASCII, so the char index equals the byte index.\n return idx;\n}\n","import {\n Connection,\n Keypair,\n PublicKey,\n Transaction,\n sendAndConfirmTransaction,\n type TransactionInstruction,\n} from \"@solana/web3.js\";\nimport type { AuthProvider, Identity } from \"../../auth/AuthProvider\";\nimport type { DeviceSigner, DevicePublicKey } from \"../../signer/DeviceSigner\";\nimport { WebCryptoSigner } from \"../../signer/WebCryptoSigner\";\nimport type { WalletRegistry } from \"../../registry/WalletRegistry\";\nimport { InMemoryWalletRegistry } from \"../../registry/WalletRegistry\";\nimport { HttpWalletRegistry } from \"../../registry/HttpWalletRegistry\";\nimport { deriveAddressSeedSolana } from \"../../identity\";\nimport { SolanaAdapter } from \"./SolanaAdapter\";\nimport type { InstructionData } from \"./SolanaAdapter\";\nimport { SolanaRelayer } from \"./SolanaRelayer\";\nimport { SOLANA_NETWORKS, type SolanaNetwork } from \"./constants\";\nimport { BackupSigner, deriveBackupKey } from \"../../recovery/BackupSigner\";\nimport type { PasskeySigner, PasskeyEnrollParams } from \"../../signer/PasskeySigner\";\nimport type { ExecuteOptions } from \"../../chains/ChainAdapter\";\nimport { webauthnDigest, recoverCandidatePublicKeys, batchChallenge } from \"../../crypto/webauthn\";\nimport type { PasskeyAssertion } from \"../../crypto/webauthn\";\n\nexport interface ConnectSolanaOptions {\n network: SolanaNetwork;\n /** Authenticated user (pass `identity` directly, or an `auth` provider). */\n auth?: AuthProvider;\n identity?: Identity;\n appSalt: string;\n appId?: string;\n backendUrl?: string;\n registry?: WalletRegistry;\n /** RPC override (else the network default). */\n rpcUrl?: string;\n /** Cavos device-account program id override. */\n programId?: string;\n /** Override the device signer factory (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n /**\n * Gasless sponsorship via the Cavos relayer. When set (or when `appId` +\n * `backendUrl` are given), transactions are co-signed + paid by the Cavos\n * relayer, so the integrator needs NO fee-payer keypair — the user's silent\n * device key (which holds no SOL) gets a seedless, gasless experience.\n */\n relayer?: SolanaRelayer;\n /**\n * Self-funded fallback: a fee-payer keypair the integrator funds. Used only\n * when no `relayer` is configured (tests / advanced). Sponsored relaying is\n * the default path when `appId` is provided.\n */\n feePayer?: Keypair;\n}\n\nexport type ConnectStatus = \"ready\" | \"needs-device-approval\";\n\n/**\n * Options for recovering a Solana account after losing every device signer.\n * Mirrors `RecoveryOptions` (Starknet), adapted to the Solana path: the backup\n * key signs the `add_signer` bundle via the secp256r1 precompile and the Cavos\n * relayer sponsors it (no fee-payer keypair needed).\n */\nexport interface RecoverSolanaOptions {\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 /** Solana network the account lives on. */\n network: SolanaNetwork;\n appSalt: string;\n appId?: string;\n backendUrl?: string;\n registry?: WalletRegistry;\n /** RPC override (else the network default). */\n rpcUrl?: string;\n /** Cavos device-account program id override. */\n programId?: string;\n /** Override the new device's signer (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n /** Gasless sponsorship via the Cavos relayer (defaults to hosted when appId set). */\n relayer?: SolanaRelayer;\n /** Self-funded fallback when no relayer is configured (tests / advanced). */\n feePayer?: Keypair;\n}\n\n/**\n * High-level Solana entry — the Solana analogue of `Cavos.connect`. One call\n * derives the deterministic device-bound account, deploys it (PDA `initialize`)\n * if needed, registers it for cross-device recognition, and returns a ready\n * handle whose silent P-256 device key authorizes every action through the\n * native secp256r1 precompile.\n *\n * const cavos = await CavosSolana.connect({ network: \"solana-devnet\", identity, appSalt, feePayer });\n * if (cavos.status === \"ready\") await cavos.execute(amount, dest);\n *\n * Gasless by default: when an `appId` is provided the Cavos relayer co-signs +\n * pays (no fee-payer keypair needed). `feePayer` is the self-funded fallback.\n */\nexport class CavosSolana {\n /** Discriminant for the `CavosWallet` union — narrows `execute()` per chain. */\n readonly chain = \"solana\" as const;\n /** True when this connect just created a brand-new account (first sign-up). */\n isNewAccount = false;\n\n private constructor(\n readonly identity: Identity,\n readonly address: string,\n readonly status: ConnectStatus,\n readonly connection: Connection,\n private readonly adapter: SolanaAdapter,\n private readonly devicePubkey: DevicePublicKey,\n private readonly relayer?: SolanaRelayer,\n private readonly feePayer?: Keypair,\n ) {}\n\n get publicKey(): DevicePublicKey {\n return this.devicePubkey;\n }\n\n static async connect(opts: ConnectSolanaOptions): Promise<CavosSolana> {\n const identity = opts.identity ?? (await opts.auth?.authenticate());\n if (!identity) throw new Error(\"kit/solana: connect requires `identity` or `auth`\");\n\n // Client-side read RPC. The integrator SHOULD pass their own `rpcUrl` — the\n // public default is rate-limited and unfit for production. (This is separate\n // from the relayer's server-side RPC, which Cavos operates.) Warn loudly when\n // hitting mainnet on the shared public endpoint.\n if (opts.network === \"solana-mainnet\" && !opts.rpcUrl) {\n console.warn(\n \"[cavos] Using the public mainnet-beta RPC. Pass `rpcUrl` with your own \" +\n \"provider (Helius/Triton/QuickNode) for production — the public endpoint is rate-limited.\",\n );\n }\n const connection = new Connection(opts.rpcUrl ?? SOLANA_NETWORKS[opts.network], \"confirmed\");\n\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 SolanaAdapter({ programId: opts.programId, connection, signer });\n const addressSeed = deriveAddressSeedSolana({ userId: identity.userId, appSalt: opts.appSalt });\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\n // Default to gasless sponsorship via the Cavos relayer when an appId is set,\n // so the integrator needs no fee payer. `feePayer` is the self-funded fallback.\n const relayer =\n opts.relayer ??\n (opts.appId\n ? new SolanaRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network, connection })\n : undefined);\n\n // Returning user on another device? The address is device-bound, so the\n // registry (not the identity alone) recognizes it. A new device is flagged\n // needs-device-approval (add it from an existing device) — same model as Starknet.\n const existing = await registry.lookup(identity.userId);\n if (existing) {\n const isSigner = await adapter.isAuthorizedSigner(existing.address, devicePubkey);\n return new CavosSolana(\n identity,\n existing.address,\n isSigner ? \"ready\" : \"needs-device-approval\",\n connection,\n adapter,\n devicePubkey,\n relayer,\n opts.feePayer,\n );\n }\n\n const address = adapter.computeAddress(addressSeed);\n const deployed = (await connection.getAccountInfo(new PublicKey(address))) !== null;\n\n if (!deployed) {\n // Deploy: register the first device signer via `initialize`. Anti-squatting\n // is NOT enforced on-chain — it is the integrator's responsibility to keep\n // `appSalt` secret and to deploy each account on the user's first login.\n //\n // Whoever pays must be the `initialize` payer/fee payer: the relayer (when\n // sponsoring) or the self-funded feePayer. buildInitialize returns the\n // program ix to register the first signer.\n if (relayer) {\n const payer = await relayer.getFeePayer();\n const ixs = adapter.buildInitialize(addressSeed, payer.toBase58(), devicePubkey);\n await relayer.send(ixs);\n } else if (opts.feePayer) {\n const ixs = adapter.buildInitialize(addressSeed, opts.feePayer.publicKey.toBase58(), devicePubkey);\n await sendAndConfirmTransaction(connection, new Transaction().add(...ixs), [opts.feePayer]);\n } else {\n throw new Error(\"kit/solana: a relayer (appId) or feePayer is required to initialize a new account\");\n }\n }\n\n await registry.register({ userId: identity.userId, address, initialSigner: devicePubkey });\n const isSigner = await adapter.isAuthorizedSigner(address, devicePubkey);\n const wallet = new CavosSolana(\n identity,\n address,\n isSigner ? \"ready\" : \"needs-device-approval\",\n connection,\n adapter,\n devicePubkey,\n relayer,\n opts.feePayer,\n );\n // First sign-up: a fresh initialize that made this device an authorized signer.\n wallet.isNewAccount = !deployed && isSigner;\n return wallet;\n }\n\n /** Authorize an additional device signer (device-signed via precompile). */\n async addSigner(pubkey: DevicePublicKey): Promise<string> {\n const ixs = await this.adapter.buildAddSigner(this.address, pubkey);\n return this.send(ixs);\n }\n\n /**\n * Enroll a passkey as an approver (2FA-style step-up). Device-signed + gasless;\n * requires a ready device. Idempotent. Returns the passkey pubkey + tx hash.\n */\n async enrollPasskey(\n passkey: PasskeySigner,\n params: PasskeyEnrollParams,\n ): Promise<{ publicKey: DevicePublicKey; transactionHash?: string }> {\n const enrolled = await passkey.enroll(params);\n const { transactionHash } = await this.addApprover(enrolled.publicKey);\n return { publicKey: enrolled.publicKey, transactionHash };\n }\n\n /** Register an already-enrolled passkey pubkey as an approver (gasless).\n * Idempotent. Lets one passkey be registered across chains without re-prompting. */\n async addApprover(pubkey: DevicePublicKey): Promise<{ transactionHash?: string }> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: addApprover requires a ready, authorized device\");\n }\n if (await this.adapter.isApprover(this.address, pubkey)) return {};\n const ixs = await this.adapter.buildAddApprover(this.address, pubkey);\n const transactionHash = await this.send(ixs);\n return { transactionHash };\n }\n\n /** True if this account already has a passkey enrolled as an approver, so a\n * new device can be approved with the passkey instead of the email flow. */\n async hasPasskey(): Promise<boolean> {\n return this.adapter.hasPasskeyApprover(this.address);\n }\n\n /** Re-read (from chain) whether THIS device is now an authorized signer.\n * Used to poll for readiness after a passkey approval before it's indexed. */\n async isReady(): Promise<boolean> {\n return this.adapter.isAuthorizedSigner(this.address, this.devicePubkey);\n }\n\n /**\n * From a fresh browser (status `needs-device-approval`), approve adding THIS\n * device with the user's synced passkey. Gasless via the relayer — the bundle\n * carries the passkey's WebAuthn assertion, so no device signature is needed.\n */\n async approveThisDeviceWithPasskey(passkey: PasskeySigner): Promise<string> {\n if (this.status === \"ready\") {\n throw new Error(\"kit/solana: this device is already an authorized signer\");\n }\n const { leaf, nonce } = await this.passkeyLeafForThisDevice();\n const leaves = [leaf];\n const assertion = await passkey.assert(batchChallenge(leaves));\n const { transactionHash } = await this.submitPasskeyApproval(assertion, leaves, 0, nonce);\n return transactionHash;\n }\n\n /** This device's leaf + passkey nonce for a (possibly multi-chain) batch. */\n async passkeyLeafForThisDevice(): Promise<{ leaf: Uint8Array; nonce: bigint }> {\n const nonce = await this.adapter.passkeyNonce(this.address);\n return { leaf: this.adapter.passkeyLeaf(this.devicePubkey, nonce), nonce };\n }\n\n /** Submit `add_signer_via_passkey` given a shared assertion + batch position.\n * Used by `approveThisDeviceWithPasskey` and `approveDeviceEverywhere`. */\n async submitPasskeyApproval(\n assertion: PasskeyAssertion,\n leaves: Uint8Array[],\n leafIndex: number,\n _nonce: bigint,\n ): Promise<{ transactionHash: string }> {\n const digest = webauthnDigest(assertion.authenticatorData, assertion.clientDataJSON);\n const candidates = recoverCandidatePublicKeys(assertion.r, assertion.s, digest);\n let approver: DevicePublicKey | null = null;\n for (const cand of candidates) {\n if (await this.adapter.isApprover(this.address, cand.publicKey)) {\n approver = cand.publicKey;\n break;\n }\n }\n if (!approver) throw new Error(\"kit/solana: this passkey is not a registered approver\");\n const ixs = this.adapter.buildAddSignerViaPasskey(\n this.address, this.devicePubkey, approver, leaves, leafIndex, assertion,\n );\n return { transactionHash: await this.send(ixs) };\n }\n\n /** Move `amount` lamports out of the account to `destination` (device-signed). */\n async execute(amount: bigint, destination: string, opts?: ExecuteOptions): Promise<string> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: this device is not yet an authorized signer of the wallet\");\n }\n const ixs = await this.adapter.buildExecuteTransfer(this.address, destination, amount);\n return this.send(ixs, opts);\n }\n\n /**\n * Run arbitrary CPI `instructions` with the account PDA as signer (device-\n * signed). The signature commits to sha256 of the canonical Borsh\n * serialization of the instructions, so it binds exactly the operations the\n * program will invoke. Unlocks SPL transfers, swaps, staking, etc.\n *\n * What the relayer will sponsor is constrained by the app's Solana program\n * allowlist (configured in the dashboard) — programs outside the allowlist are\n * rejected before co-signing. Pass `{ sponsored: false }` to bypass the relayer\n * and pay the fee from a configured `feePayer` (e.g. for allowlisted programs\n * the relayer rejects, or to test the device signature end-to-end).\n */\n async executeInstructions(\n instructions: InstructionData[],\n opts?: ExecuteOptions,\n ): Promise<string> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: this device is not yet an authorized signer of the wallet\");\n }\n const ixs = await this.adapter.buildExecute(this.address, instructions);\n return this.send(ixs, opts);\n }\n\n /**\n * Register the backup signer derived from `code` as an authorized signer of this\n * account (device-signed via precompile). Idempotent: returns without a tx if\n * the backup signer is already registered. The code never leaves the device —\n * only the derived public key travels on-chain.\n *\n * Self-custodial: anyone who can re-derive the backup key from the code (i.e.\n * the rightful owner) can later recover the account with `CavosSolana.recover`.\n * Run this once, on a registered device, and have the user store the code.\n */\n async setupRecovery(code: string): Promise<string | undefined> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit/solana: setupRecovery requires a ready, registered device\");\n }\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 the\n * new device, and returns a ready CavosSolana 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 * This mirrors `Cavos.recover` (Starknet): the backup key is just another\n * authorized signer, so recovery is an `add_signer(newDevice)` bundle signed by\n * the backup key. The on-chain program needs no recovery-specific entrypoint.\n */\n static async recover(opts: RecoverSolanaOptions): Promise<CavosSolana> {\n if (opts.network === \"solana-mainnet\" && !opts.rpcUrl) {\n console.warn(\n \"[cavos] Using the public mainnet-beta RPC. Pass `rpcUrl` with your own \" +\n \"provider (Helius/Triton/QuickNode) for production — the public endpoint is rate-limited.\",\n );\n }\n const connection = new Connection(opts.rpcUrl ?? SOLANA_NETWORKS[opts.network], \"confirmed\");\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. The\n // adapter signs every bundle with whatever `signer` it's constructed with,\n // so a backup-backed adapter produces backup-signed `add_signer` bundles.\n const backup = BackupSigner.fromCode(opts.code);\n const backupAdapter = new SolanaAdapter({\n programId: opts.programId,\n connection,\n signer: backup,\n });\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/solana: no account found for this identity — nothing to recover\");\n }\n\n const relayer =\n opts.relayer ??\n (opts.appId\n ? new SolanaRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network, connection })\n : undefined);\n\n // Authorise the new device, signed by the backup key (sponsored by the relayer,\n // or self-funded). The account address is unchanged.\n const alreadyAuthed = await backupAdapter.isAuthorizedSigner(existing.address, devicePubkey);\n if (!alreadyAuthed) {\n const ixs = await backupAdapter.buildAddSigner(existing.address, devicePubkey);\n if (relayer) {\n await relayer.send(ixs);\n } else if (opts.feePayer) {\n await sendAndConfirmTransaction(connection, new Transaction().add(...ixs), [opts.feePayer]);\n } else {\n throw new Error(\"kit/solana: a relayer (appId) or feePayer is required to recover\");\n }\n }\n\n // Hand control to the new device's signer for all future operations.\n const adapter = new SolanaAdapter({ programId: opts.programId, connection, signer });\n return new CavosSolana(\n opts.identity,\n existing.address,\n \"ready\",\n connection,\n adapter,\n devicePubkey,\n relayer,\n opts.feePayer,\n );\n }\n\n /**\n * Submit a built instruction bundle. Sponsored by default (relayer pays the\n * fee); pass `{ sponsored: false }` to self-fund via the configured `feePayer`.\n * The device signature is embedded inside the secp256r1 precompile instruction,\n * NOT applied as a Solana tx signature — so switching only changes who pays,\n * never the signing identity.\n */\n private async send(ixs: TransactionInstruction[], opts?: ExecuteOptions): Promise<string> {\n const sponsored = opts?.sponsored !== false;\n if (sponsored && this.relayer) return this.relayer.send(ixs);\n if (this.feePayer) {\n return sendAndConfirmTransaction(this.connection, new Transaction().add(...ixs), [this.feePayer]);\n }\n throw new Error(\n `kit/solana: cannot ${sponsored ? \"sponsor\" : \"self-fund\"} — no ${sponsored ? \"relayer\" : \"feePayer\"} configured`,\n );\n }\n}\n\nconst defaultRegistry = new InMemoryWalletRegistry();\n","/** Classic-Stellar (`G…`) network configuration.\n *\n * This is now THE Stellar implementation in the kit (the Soroban `C…`\n * device-account path was removed — `G…` classic multisig is the default). Classic\n * Stellar uses Horizon (not the Soroban RPC) to load account state and submit\n * transactions. */\n\nexport const STELLAR_NETWORKS = {\n \"stellar-testnet\": {\n passphrase: \"Test SDF Network ; September 2015\",\n },\n \"stellar-mainnet\": {\n passphrase: \"Public Global Stellar Network ; September 2015\",\n },\n} as const;\n\nexport type StellarNetwork = keyof typeof STELLAR_NETWORKS;\n\nexport const HORIZON_URL = {\n \"stellar-testnet\": \"https://horizon-testnet.stellar.org\",\n \"stellar-mainnet\": \"https://horizon.stellar.org\",\n} as const;\n\n/** Native XLM has 7 decimals (stroops). */\nexport const XLM_DECIMALS = 7;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is boolean. */\nexport function abool(b: boolean): void {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/**\n * Asserts something is hash\n * TODO: remove\n * @deprecated\n */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\nexport type IHash = {\n (data: string | Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// Used in micro\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\n// Used in micro, ff1\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// TODO: remove\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async (): Promise<void> => {};\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n// TODO: remove\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: string | Uint8Array): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = copyBytes(data);\n else throw new Error('Uint8Array expected, got ' + typeof data);\n return data;\n}\n\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n */\nexport function overlapBytes(a: Uint8Array, b: Uint8Array): boolean {\n return (\n a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)\n */\nexport function complexOverlapBytes(input: Uint8Array, output: Uint8Array): void {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Used in ARX only\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// TODO: remove\n/** For runtime check if class implements interface. */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: string | Uint8Array): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\n\n/** Sync cipher: takes byte array and returns byte array. */\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\n/** Async cipher e.g. from built-in WebCrypto. */\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise<Uint8Array>;\n decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;\n};\n\n/** Cipher with `output` argument which can optimize by doing 1 less allocation. */\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n/**\n * Params are outside of return type, so it is accessible before calling constructor.\n * If function support multiple nonceLength's, we return the best one.\n */\nexport type CipherParams = {\n blockSize: number;\n nonceLength?: number;\n tagLength?: number;\n varSizeNonce?: boolean;\n};\n/** ARX cipher, like salsa or chacha. */\nexport type ARXCipher = ((\n key: Uint8Array,\n nonce: Uint8Array,\n AAD?: Uint8Array\n) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n};\nexport type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n params: P,\n constructor: C\n): C & P => {\n function wrappedCipher(key: Uint8Array, ...args: any[]): CipherWithOutput {\n // Validate key\n abytes(key);\n\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE) throw new Error('Non little-endian hardware is not yet supported');\n\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n if (!nonce) throw new Error('nonce / iv required');\n if (params.varSizeNonce) abytes(nonce);\n else abytes(nonce, params.nonceLength);\n }\n\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined) {\n abytes(args[1]);\n }\n\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength: number, output?: Uint8Array) => {\n if (output !== undefined) {\n if (fnLength !== 2) throw new Error('cipher output not supported');\n abytes(output);\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data: Uint8Array, output?: Uint8Array) {\n if (called) throw new Error('cannot encrypt() twice with same key + nonce');\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return (cipher as CipherWithOutput).encrypt(data, output);\n },\n decrypt(data: Uint8Array, output?: Uint8Array) {\n abytes(data);\n if (tagl && data.length < tagl)\n throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return (cipher as CipherWithOutput).decrypt(data, output);\n },\n };\n\n return wrCipher;\n }\n\n Object.assign(wrappedCipher, params);\n return wrappedCipher as C & P;\n};\n\n/** Represents salsa / chacha stream. */\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(\n expectedLength: number,\n out?: Uint8Array,\n onlyAligned = true\n): Uint8Array {\n if (out === undefined) return new Uint8Array(expectedLength);\n if (out.length !== expectedLength)\n throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);\n if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n return out;\n}\n\n/** Polyfill for Safari 14. */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): Uint8Array {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(aadLength), isLE);\n setBigUint64(view, 8, BigInt(dataLength), isLE);\n return num;\n}\n\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes: Uint8Array): boolean {\n return bytes.byteOffset % 4 === 0;\n}\n\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n","/**\n * GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n *\n * Implemented in terms of GHash with conversion function for keys\n * GCM GHASH from\n * [NIST SP800-38d](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf),\n * SIV from\n * [RFC 8452](https://datatracker.ietf.org/doc/html/rfc8452).\n *\n * GHASH modulo: x^128 + x^7 + x^2 + x + 1\n * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\n *\n * @module\n */\n// prettier-ignore\nimport {\n abytes, aexists, aoutput,\n clean, copyBytes, createView, Hash, type Input, toBytes, u32,\n} from './utils.ts';\n\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0: number, s1: number, s2: number, s3: number) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\n\nconst swapLE = (n: number) =>\n (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k: Uint8Array): Uint8Array {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\n\ntype Value = { s0: number; s1: number; s2: number; s3: number };\n\nconst estimateWindow = (bytes: number) => {\n if (bytes > 64 * 1024) return 8;\n if (bytes > 1024) return 4;\n return 2;\n};\n\nclass GHASH implements Hash<GHASH> {\n readonly blockLen = BLOCK_SIZE;\n readonly outputLen = BLOCK_SIZE;\n protected s0 = 0;\n protected s1 = 0;\n protected s2 = 0;\n protected s3 = 0;\n protected finished = false;\n protected t: Value[];\n private W: number;\n private windowSize: number;\n // We select bits per window adaptively based on expectedLength\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles: Value[] = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error('ghash: invalid window size, expected 2, 4 or 8');\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items: Value[] = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit) continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n protected _updateBlock(s0: number, s1: number, s2: number, s3: number) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest(): Uint8Array {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\n\nclass Polyval extends GHASH {\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n abytes(key);\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data: Input): this {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(\n swapLE(b32[i * 4 + 3]),\n swapLE(b32[i * 4 + 2]),\n swapLE(b32[i * 4 + 1]),\n swapLE(b32[i * 4 + 0])\n );\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(\n swapLE(ZEROS32[3]),\n swapLE(ZEROS32[2]),\n swapLE(ZEROS32[1]),\n swapLE(ZEROS32[0])\n );\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\n\nexport type CHashPV = ReturnType<typeof wrapConstructorWithKey>;\nfunction wrapConstructorWithKey<H extends Hash<H>>(\n hashCons: (key: Input, expectedLength?: number) => Hash<H>\n): {\n (msg: Input, key: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(key: Input, expectedLength?: number): Hash<H>;\n} {\n const hashC = (msg: Input, key: Input): Uint8Array =>\n hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input, expectedLength?: number) => hashCons(key, expectedLength);\n return hashC;\n}\n\n/** GHash MAC for AES-GCM. */\nexport const ghash: CHashPV = wrapConstructorWithKey(\n (key, expectedLength) => new GHASH(key, expectedLength)\n);\n\n/** Polyval MAC for AES-SIV. */\nexport const polyval: CHashPV = wrapConstructorWithKey(\n (key, expectedLength) => new Polyval(key, expectedLength)\n);\n","/**\n * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)\n * a.k.a. Advanced Encryption Standard\n * is a variant of Rijndael block cipher, standardized by NIST in 2001.\n * We provide the fastest available pure JS implementation.\n *\n * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n * 1. **S-box**, table substitution\n * 2. **Shift rows**, cyclic shift left of all rows of data array\n * 3. **Mix columns**, multiplying every column by fixed polynomial\n * 4. **Add round key**, round_key xor i-th column of array\n *\n * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)\n * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)\n * @module\n */\nimport { ghash, polyval } from './_polyval.ts';\n// prettier-ignore\nimport {\n abytes, clean, complexOverlapBytes, concatBytes,\n copyBytes, createView, equalBytes, getOutput, isAligned32, overlapBytes,\n setBigUint64, u32, u64Lengths, u8, wrapCipher,\n type Cipher, type CipherWithOutput,\n} from './utils.ts';\n\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n\n// TODO: remove multiplication, binary ops only\nfunction mul2(n: number) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n\nfunction mul(a: number, b: number) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n\n// Rotate u32 by 8\nconst rotr32_8 = (n: number) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n: number) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox: Uint8Array, fn: (n: number) => number) {\n if (sbox.length !== 256) throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n\nconst tableEncoding = /* @__PURE__ */ genTtable(\n sbox,\n (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)\n);\nconst tableDecoding = /* @__PURE__ */ genTtable(\n invSbox,\n (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)\n);\n\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;\n return p;\n})();\n\n/** Key expansion used in CTR. */\nfunction expandKeyLE(key: Uint8Array): Uint32Array {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key)) toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n: number) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4) t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\n\nfunction expandKeyDecLE(key: Uint8Array): Uint32Array {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n\n// Apply tables\nfunction apply0123(\n T01: Uint32Array,\n T23: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n) {\n return (\n T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]\n );\n}\n\nfunction applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) {\n return (\n sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)\n );\n}\n\nfunction encrypt(\n xk: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n): { s0: number; s1: number; s2: number; s3: number } {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(\n xk: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n): {\n s0: number;\n s1: number;\n s2: number;\n s3: number;\n} {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0: number = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1: number = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2: number = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3: number = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\n// TODO: investigate merging with ctr32\nfunction ctrCounter(\n xk: Uint32Array,\n nonce: Uint8Array,\n src: Uint8Array,\n dst?: Uint8Array\n): Uint8Array {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n complexOverlapBytes(src, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(\n xk: Uint32Array,\n isLE: boolean,\n nonce: Uint8Array,\n src: Uint8Array,\n dst?: Uint8Array\n): Uint8Array {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getOutput(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr: ((key: Uint8Array, nonce: Uint8Array) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function aesctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput {\n function processCtr(buf: Uint8Array, dst?: Uint8Array) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst)) throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf)) toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst),\n };\n }\n);\n\nfunction validateBlockDecrypt(data: Uint8Array) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(\n 'aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE\n );\n }\n}\n\nfunction validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext)) plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n dst = getOutput(outLen, dst);\n complexOverlapBytes(plaintext, dst);\n const o = u32(dst);\n return { b, o, out: dst };\n}\n\nfunction validatePCKS(data: Uint8Array, pcks5: boolean) {\n if (!pcks5) return data;\n const len = data.length;\n if (!len) throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16) throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte) throw new Error('aes/pcks5: wrong padding');\n return out;\n}\n\nfunction padPCKS(left: Uint8Array) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;\n return tmp32;\n}\n\n/** Options for ECB and CBC. */\nexport type BlockOpts = { disablePadding?: boolean };\n\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb: ((key: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {\n blockSize: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16 },\n function aesecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext: Uint8Array, dst?: Uint8Array) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext: Uint8Array, dst?: Uint8Array) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n dst = getOutput(ciphertext.length, dst);\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n complexOverlapBytes(ciphertext, dst);\n const b = u32(ciphertext);\n const o = u32(dst);\n for (let i = 0; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return validatePCKS(dst, pcks5);\n },\n };\n }\n);\n\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc: ((key: Uint8Array, iv: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function aescbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext: Uint8Array, dst?: Uint8Array) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length; ) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext: Uint8Array, dst?: Uint8Array) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n dst = getOutput(ciphertext.length, dst);\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n complexOverlapBytes(ciphertext, dst);\n const b = u32(ciphertext);\n const o = u32(dst);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length; ) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n clean(...toClean);\n return validatePCKS(dst, pcks5);\n },\n };\n }\n);\n\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb: ((key: Uint8Array, iv: Uint8Array) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function aescfb(key: Uint8Array, iv: Uint8Array): CipherWithOutput {\n function processCfb(src: Uint8Array, isEncrypt: boolean, dst?: Uint8Array) {\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n if (overlapBytes(src, dst)) throw new Error('overlapping src and dst not supported.');\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src)) toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length; ) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCfb(ciphertext, false, dst),\n };\n }\n);\n\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(\n fn: typeof ghash,\n isLE: boolean,\n key: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n) {\n const aadLength = AAD ? AAD.length : 0;\n const h = fn.create(key, data.length + aadLength);\n if (AAD) h.update(AAD);\n const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);\n h.update(data);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n\n/**\n * GCM: Galois/Counter Mode.\n * Modern, parallel version of CTR, with MAC.\n * Be careful: MACs can be forged.\n * Unsafe to use random nonces under the same key, due to collision chance.\n * As for nonce size, prefer 12-byte, instead of 8-byte.\n */\nexport const gcm: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n varSizeNonce: true;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },\n function aesgcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8) throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n } else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext: Uint8Array) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n }\n);\n\nconst limit = (name: string, min: number, max: number) => (value: number) => {\n if (!Number.isSafeInteger(value) || min > value || value > max) {\n const minmax = '[' + min + '..' + max + ']';\n throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);\n }\n};\n\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const gcmsiv: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n varSizeNonce: true;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },\n function aessiv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key, 16, 24, 32);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined) AAD_LIMIT(AAD.length);\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean: (Uint8Array | Uint32Array)[] = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce)) toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext: Uint8Array) {\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey, tag];\n if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey];\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n }\n);\n\n/**\n * AES-GCM-SIV, not AES-SIV.\n * This is legace name, use `gcmsiv` export instead.\n * @deprecated\n */\nexport const siv: typeof gcmsiv = gcmsiv;\n\nfunction isBytes32(a: unknown): a is Uint32Array {\n return (\n a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array')\n );\n}\n\nfunction encryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\nfunction decryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek: Uint8Array, out: Uint8Array) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32) throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16) encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek: Uint8Array, out: Uint8Array) {\n if (out.length - 8 >= 2 ** 32) throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1) decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1);\n }\n xk.fill(0);\n },\n};\n\nconst AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw: ((kek: Uint8Array) => Cipher) & {\n blockSize: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 8 },\n (kek: Uint8Array): Cipher => ({\n encrypt(plaintext: Uint8Array) {\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV)) throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n })\n);\n\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\n\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp: ((kek: Uint8Array) => Cipher) & {\n blockSize: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 8 },\n (kek: Uint8Array): Cipher => ({\n encrypt(plaintext: Uint8Array) {\n if (!plaintext.length) throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n // 16 because should have at least one block\n if (ciphertext.length < 16) throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0) throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n })\n);\n\n/** Unsafe low-level internal methods. May change at any time. */\nexport const unsafe: {\n expandKeyLE: typeof expandKeyLE;\n expandKeyDecLE: typeof expandKeyDecLE;\n encrypt: typeof encrypt;\n decrypt: typeof decrypt;\n encryptBlock: typeof encryptBlock;\n decryptBlock: typeof decryptBlock;\n ctrCounter: typeof ctrCounter;\n ctr32: typeof ctr32;\n} = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n","import { gcm } from \"@noble/ciphers/aes\";\nimport { 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\";\n\n/**\n * Envelope encryption for the classic-G control key.\n *\n * The control key's 32-byte seed is the one secret that authorizes the account.\n * It is never stored in the clear. Instead:\n *\n * 1. A random 256-bit **DEK** (data-encryption key) encrypts the control seed\n * once → `ciphertext` (stored on-chain in a `cv:ct` data entry).\n * 2. The DEK itself is **wrapped** independently by each unlock factor's KEK\n * (key-encryption key), producing one small blob per factor:\n * - device P-256 (ECIES) → silent daily unlock, per-device, non-syncable\n * - passkey PRF → recovery / new-device anchor (synced, portable)\n * - recovery code → offline backup (optional in v1)\n *\n * Adding a factor (e.g. approving a new device) only re-wraps the DEK for that\n * factor; the control ciphertext never changes. Losing a factor is just dropping\n * its wrap. This is the classic-multisig analogue of `add_signer`, done in the\n * account's own on-chain data entries with no backend and no registry.\n *\n * All primitives are AES-256-GCM (authenticated) + HKDF-SHA256, pure `@noble/*`.\n */\n\n/** AES-GCM nonce length (96-bit, the standard). */\nconst NONCE_LEN = 12;\n\n/** HKDF `info` strings, one per factor, so the same underlying secret can never\n * produce the same KEK across factors. Never change (breaks existing wraps). */\nconst RECOVERY_INFO = \"cavos-stellar-dek-recovery\";\nconst PASSKEY_INFO = \"cavos-stellar-dek-passkey\";\nconst ECIES_INFO = \"cavos-stellar-dek-ecies\";\n\n/** PBKDF2 iterations for the recovery-code KEK — matches the recovery signer's\n * brute-force brake so a stolen envelope can't be attacked cheaply offline. */\nconst RECOVERY_PBKDF2_ITERATIONS = 210_000;\nconst RECOVERY_KDF_SALT = \"cavos-stellar-recovery-v1\";\n\n/** A DEK-wrap blob: `nonce || AES-GCM(kek, dek)`. Self-contained (nonce inline). */\nexport type WrappedDEK = Uint8Array;\n\n/** Fresh 256-bit data-encryption key. One per account, generated at creation. */\nexport function generateDEK(): Uint8Array {\n return randomBytes(32);\n}\n\n/** Encrypt the control seed under the DEK → `nonce || ct`. */\nexport function sealControlSeed(controlSeed: Uint8Array, dek: Uint8Array): Uint8Array {\n const nonce = randomBytes(NONCE_LEN);\n const ct = gcm(dek, nonce).encrypt(controlSeed);\n return concat(nonce, ct);\n}\n\n/** Decrypt the control seed (`nonce || ct`) under the DEK. Throws on tamper. */\nexport function openControlSeed(sealed: Uint8Array, dek: Uint8Array): Uint8Array {\n const { nonce, ct } = splitNonce(sealed);\n return gcm(dek, nonce).decrypt(ct);\n}\n\n/** Wrap the DEK under a raw 32-byte KEK → `nonce || AES-GCM(kek, dek)`. */\nexport function wrapDEK(dek: Uint8Array, kek: Uint8Array): WrappedDEK {\n const nonce = randomBytes(NONCE_LEN);\n return concat(nonce, gcm(kek, nonce).encrypt(dek));\n}\n\n/** Unwrap the DEK from a `nonce || ct` blob under a raw 32-byte KEK. */\nexport function unwrapDEK(wrapped: WrappedDEK, kek: Uint8Array): Uint8Array {\n const { nonce, ct } = splitNonce(wrapped);\n return gcm(kek, nonce).decrypt(ct);\n}\n\n// ---------------------------------------------------------------------------\n// Factor KEK derivations\n// ---------------------------------------------------------------------------\n\n/** KEK from a human recovery code (PBKDF2-stretched, then HKDF-scoped). The same\n * normalised code yields the same KEK on any device. */\nexport function deriveRecoveryKEK(code: string): Uint8Array {\n const normalised = code.trim().replace(/\\s+/g, \" \").toLowerCase();\n if (!normalised) throw new Error(\"kit/stellar: recovery code is empty\");\n const stretched = pbkdf2(sha256, new TextEncoder().encode(normalised), new TextEncoder().encode(RECOVERY_KDF_SALT), {\n c: RECOVERY_PBKDF2_ITERATIONS,\n dkLen: 32,\n });\n return hkdf(sha256, stretched, undefined, RECOVERY_INFO, 32);\n}\n\n/** KEK from a WebAuthn PRF output (32 bytes the authenticator returns for our\n * fixed PRF salt). HKDF-scoped so the raw PRF secret is never used directly. */\nexport function derivePasskeyKEK(prfOutput: Uint8Array): Uint8Array {\n if (prfOutput.length < 32) throw new Error(\"kit/stellar: passkey PRF output too short\");\n return hkdf(sha256, prfOutput, undefined, PASSKEY_INFO, 32);\n}\n\n// ---------------------------------------------------------------------------\n// Device factor: ECIES over P-256\n// ---------------------------------------------------------------------------\n\n/**\n * ECIES-wrap the DEK to a device's P-256 public key (SEC1 uncompressed, 65\n * bytes). Returns `ephPubCompressed(33) || nonce(12) || ct` — self-contained.\n * An ephemeral keypair makes each wrap use a fresh shared secret; the device\n * unwraps with its private scalar. The ephemeral public key is bound into the\n * KEK via the HKDF salt so it can't be swapped.\n */\nexport function eciesWrapDEK(dek: Uint8Array, recipientPubSec1: Uint8Array): Uint8Array {\n const ephPriv = p256.utils.randomPrivateKey();\n const ephPubCompressed = p256.getPublicKey(ephPriv, true); // 33 bytes\n const kek = eciesKEK(p256.getSharedSecret(ephPriv, recipientPubSec1, false), ephPubCompressed);\n const wrapped = wrapDEK(dek, kek);\n return concat(ephPubCompressed, wrapped);\n}\n\n/** ECIES-unwrap the DEK with the device's private scalar (32 bytes). */\nexport function eciesUnwrapDEK(blob: Uint8Array, recipientPrivScalar: Uint8Array): Uint8Array {\n const ephPubCompressed = blob.subarray(0, 33);\n const wrapped = blob.subarray(33);\n const kek = eciesKEK(p256.getSharedSecret(recipientPrivScalar, ephPubCompressed, false), ephPubCompressed);\n return unwrapDEK(wrapped, kek);\n}\n\n/**\n * Derive the ECIES KEK from a raw ECDH result. We hash ONLY the shared secret's\n * X coordinate (bytes 1..33 of the uncompressed `04||X||Y` point), because that\n * is exactly what WebCrypto's `deriveBits({name:\"ECDH\"}, …)` returns — so a\n * browser `WebCryptoDeviceUnwrapKey` and a raw-scalar `LocalDeviceUnwrapKey`\n * derive the identical KEK for the same wrap. The ephemeral public key is bound\n * in as the HKDF salt so it can't be swapped.\n */\nexport function eciesKEK(sharedUncompressed: Uint8Array, ephPubCompressed: Uint8Array): Uint8Array {\n return eciesKEKFromX(sharedUncompressed.subarray(1, 33), ephPubCompressed);\n}\n\n/** ECIES KEK straight from the 32-byte ECDH X coordinate — the form WebCrypto's\n * `deriveBits` returns, so the browser unwrap path derives the identical KEK. */\nexport function eciesKEKFromX(sharedX: Uint8Array, ephPubCompressed: Uint8Array): Uint8Array {\n return hkdf(sha256, sharedX, ephPubCompressed, ECIES_INFO, 32);\n}\n\n// ---------------------------------------------------------------------------\n// 64-byte chunking (Stellar MANAGE_DATA value limit)\n// ---------------------------------------------------------------------------\n\n/** Stellar data-entry values are capped at 64 bytes; blobs larger than that\n * (e.g. an ECIES device wrap) are split across ordered `<key>:<i>` entries. */\nexport const DATA_ENTRY_MAX = 64;\n\n/** Split a blob into ≤64-byte chunks, in order. A blob that already fits\n * returns a single chunk. */\nexport function chunkTo64(blob: Uint8Array): Uint8Array[] {\n if (blob.length <= DATA_ENTRY_MAX) return [blob];\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < blob.length; i += DATA_ENTRY_MAX) {\n chunks.push(blob.subarray(i, i + DATA_ENTRY_MAX));\n }\n return chunks;\n}\n\n/** Reassemble an ordered list of chunks back into the original blob. */\nexport function unchunk(chunks: Uint8Array[]): Uint8Array {\n const total = chunks.reduce((n, c) => n + c.length, 0);\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.length;\n }\n return out;\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\nfunction splitNonce(blob: Uint8Array): { nonce: Uint8Array; ct: Uint8Array } {\n return { nonce: blob.subarray(0, NONCE_LEN), ct: blob.subarray(NONCE_LEN) };\n}\n","import { chunkTo64, unchunk } from \"./envelope\";\n\n/**\n * On-chain layout of the control-key envelope in the account's classic\n * `MANAGE_DATA` entries. Stellar caps both the data-entry *key* and *value* at 64\n * bytes, so every logical blob is split into ≤64-byte chunks written under\n * ordered, indexed keys. Enumerating the account's data entries (returned whole\n * by Horizon) is enough to reconstruct the envelope — no separate index needed,\n * which keeps the account self-describing and backend-free.\n *\n * Keys (all under the `cv:` namespace):\n * cv:ct/<i> sealed control seed (DEK-encrypted)\n * cv:wd:<slot>/<i> device ECIES DEK-wrap, one <slot> per device\n * cv:wp/<i> passkey-PRF DEK-wrap (recovery / new-device anchor)\n * cv:wr/<i> recovery-code DEK-wrap (optional)\n * cv:v single-byte envelope version\n */\n\nexport const CT_BASE = \"cv:ct\";\nexport const PASSKEY_BASE = \"cv:wp\";\nexport const RECOVERY_BASE = \"cv:wr\";\nexport const VERSION_KEY = \"cv:v\";\nexport const ENVELOPE_VERSION = 1;\n\n/** `cv:wd:<slot>` base key for a device envelope slot. */\nexport function deviceBase(slot: string): string {\n return `cv:wd:${slot}`;\n}\n\n/** In-memory shape of the account's control-key envelope. */\nexport interface AccountEnvelope {\n /** Sealed control seed (`sealControlSeed` output). */\n ct: Uint8Array;\n /** Per-device ECIES DEK-wraps, keyed by device slot id. */\n deviceWraps: Record<string, Uint8Array>;\n /** Passkey-PRF DEK-wrap, if a passkey factor is enrolled. */\n passkeyWrap?: Uint8Array;\n /** Recovery-code DEK-wrap, if the user set one up. */\n recoveryWrap?: Uint8Array;\n}\n\n/** Serialize an envelope into `MANAGE_DATA` name→value entries (raw bytes). */\nexport function toDataEntries(env: AccountEnvelope): Record<string, Uint8Array> {\n const out: Record<string, Uint8Array> = {};\n writeChunked(out, CT_BASE, env.ct);\n for (const [slot, blob] of Object.entries(env.deviceWraps)) {\n writeChunked(out, deviceBase(slot), blob);\n }\n if (env.passkeyWrap) writeChunked(out, PASSKEY_BASE, env.passkeyWrap);\n if (env.recoveryWrap) writeChunked(out, RECOVERY_BASE, env.recoveryWrap);\n out[VERSION_KEY] = Uint8Array.of(ENVELOPE_VERSION);\n return out;\n}\n\n/** Reconstruct an envelope from an account's data entries (name→bytes). */\nexport function fromDataEntries(entries: Record<string, Uint8Array>): AccountEnvelope {\n const ct = readChunked(entries, CT_BASE);\n if (!ct) throw new Error(\"kit/stellar: account has no control-seed ciphertext (cv:ct)\");\n\n const deviceWraps: Record<string, Uint8Array> = {};\n const seenSlots = new Set<string>();\n for (const key of Object.keys(entries)) {\n const m = key.match(/^cv:wd:([^/]+)\\/\\d+$/);\n if (m) seenSlots.add(m[1]);\n }\n for (const slot of seenSlots) {\n const blob = readChunked(entries, deviceBase(slot));\n if (blob) deviceWraps[slot] = blob;\n }\n\n return {\n ct,\n deviceWraps,\n passkeyWrap: readChunked(entries, PASSKEY_BASE),\n recoveryWrap: readChunked(entries, RECOVERY_BASE),\n };\n}\n\n/** Just the `MANAGE_DATA` entries for one device slot — used when re-wrapping the\n * DEK for a newly approved device (a single classic tx, no full re-write). */\nexport function deviceWrapEntries(slot: string, blob: Uint8Array): Record<string, Uint8Array> {\n const out: Record<string, Uint8Array> = {};\n writeChunked(out, deviceBase(slot), blob);\n return out;\n}\n\nfunction writeChunked(out: Record<string, Uint8Array>, base: string, blob: Uint8Array): void {\n const chunks = chunkTo64(blob);\n chunks.forEach((chunk, i) => {\n out[`${base}/${i}`] = chunk;\n });\n}\n\nfunction readChunked(entries: Record<string, Uint8Array>, base: string): Uint8Array | undefined {\n const chunks: Uint8Array[] = [];\n for (let i = 0; ; i++) {\n const chunk = entries[`${base}/${i}`];\n if (!chunk) break;\n chunks.push(chunk);\n }\n return chunks.length ? unchunk(chunks) : undefined;\n}\n","import {\n Account,\n Asset,\n BASE_FEE,\n Horizon,\n Keypair,\n Operation,\n TransactionBuilder,\n type Transaction,\n type FeeBumpTransaction,\n} from \"@stellar/stellar-sdk\";\nimport { HORIZON_URL, STELLAR_NETWORKS, type StellarNetwork } from \"./constants\";\nimport { toDataEntries, type AccountEnvelope } from \"./datamap\";\n\nexport interface StellarAdapterOptions {\n network: StellarNetwork;\n /** Horizon URL override (else the per-network default). */\n horizonUrl?: string;\n}\n\n/** How long a built transaction stays valid before it must be rebuilt. */\nconst TX_TIMEOUT = 180;\n\n/**\n * Classic-Stellar (`G…`) multisig account adapter.\n *\n * Unlike the Soroban `StellarAdapter` (contract `C…` accounts authorized by a\n * `__check_auth` device signature) this operates on a *classic* account whose\n * signing is ordinary ed25519 multisig:\n *\n * - the **master** key (deterministic from identity) names the `G…` address and\n * is set to weight 0 at creation — powerless afterwards;\n * - the **control** key (random, weight 1, thresholds 1) is the real signer,\n * recovered by decrypting the on-chain envelope (see `envelope.ts`).\n *\n * The adapter builds/read classic transactions and account state via Horizon; it\n * never holds a secret — callers pass in the `Keypair`s to sign with. Gasless\n * submission is a fee-bump whose fee source is the relayer (Phase 3).\n */\nexport class StellarAdapter {\n readonly chain = \"stellar\" as const;\n readonly network: StellarNetwork;\n readonly passphrase: string;\n private readonly horizonUrl: string;\n private _server?: Horizon.Server;\n\n constructor(opts: StellarAdapterOptions) {\n this.network = opts.network;\n this.passphrase = STELLAR_NETWORKS[opts.network].passphrase;\n this.horizonUrl = opts.horizonUrl ?? HORIZON_URL[opts.network];\n }\n\n server(): Horizon.Server {\n if (!this._server) {\n this._server = new Horizon.Server(this.horizonUrl, {\n allowHttp: this.horizonUrl.startsWith(\"http://\"),\n });\n }\n return this._server;\n }\n\n /** Whether the classic account already exists on-chain. */\n async isDeployed(address: string): Promise<boolean> {\n try {\n await this.server().loadAccount(address);\n return true;\n } catch (e) {\n if (isNotFound(e)) return false;\n throw e;\n }\n }\n\n /** Read the account's `MANAGE_DATA` entries as raw bytes (name → value). */\n async loadDataEntries(address: string): Promise<Record<string, Uint8Array>> {\n const account = await this.server().loadAccount(address);\n const out: Record<string, Uint8Array> = {};\n for (const [name, b64] of Object.entries(account.data_attr ?? {})) {\n out[name] = new Uint8Array(Buffer.from(b64 as string, \"base64\"));\n }\n return out;\n }\n\n /** Native XLM balance in stroops. Returns 0n if the account doesn't exist. */\n async balance(address: string): Promise<bigint> {\n try {\n const account = await this.server().loadAccount(address);\n const native = account.balances.find((b) => b.asset_type === \"native\");\n return native ? toStroops(native.balance) : 0n;\n } catch (e) {\n if (isNotFound(e)) return 0n;\n throw e;\n }\n }\n\n /**\n * Build the account-creation transaction (source = funder, the relayer or a\n * self-funded keypair):\n * 1. `createAccount` funds the deterministic `G…` master address,\n * 2. `manageData` writes the control-key envelope entries (authorized by the\n * still-weight-1 master),\n * 3. `setOptions` adds the control signer (weight 1), sets all thresholds to\n * 1, and zeroes the master weight — after this the master can never sign.\n *\n * The returned tx must be signed by BOTH the master keypair (for the account's\n * own ops) and the funder (source + fee). Sponsorship of reserves is layered on\n * in Phase 3.\n */\n async buildCreateTx(params: {\n funder: string;\n masterAddress: string;\n controlAddress: string;\n envelope: AccountEnvelope;\n /** Starting balance in stroops (must cover base reserve + entries). */\n startingBalance: bigint;\n }): Promise<Transaction> {\n const funderAccount = await this.server().loadAccount(params.funder);\n const builder = new TransactionBuilder(funderAccount, {\n fee: BASE_FEE,\n networkPassphrase: this.passphrase,\n });\n\n builder.addOperation(\n Operation.createAccount({\n destination: params.masterAddress,\n startingBalance: fromStroops(params.startingBalance),\n }),\n );\n\n for (const [name, value] of Object.entries(toDataEntries(params.envelope))) {\n builder.addOperation(\n Operation.manageData({ name, value: Buffer.from(value), source: params.masterAddress }),\n );\n }\n\n builder.addOperation(\n Operation.setOptions({\n source: params.masterAddress,\n masterWeight: 0,\n lowThreshold: 1,\n medThreshold: 1,\n highThreshold: 1,\n signer: { ed25519PublicKey: params.controlAddress, weight: 1 },\n }),\n );\n\n return builder.setTimeout(TX_TIMEOUT).build();\n }\n\n /**\n * Build a **sponsored** account-creation transaction whose source is the\n * relayer. Wraps the account setup in `beginSponsoringFutureReserves` /\n * `endSponsoringFutureReserves`, so the relayer (not the user) pays every\n * reserve — the account is created with a 0 starting balance and holds no\n * locked XLM of the user's. Ops:\n * 0. beginSponsoringFutureReserves(G) source = relayer\n * 1. createAccount(G, 0) source = relayer\n * 2. manageData(cv:… envelope) source = G (master-signed)\n * 3. setOptions(control signer, master → 0) source = G\n * 4. endSponsoringFutureReserves() source = G\n *\n * Signed by the master (for the G ops, while it's still weight 1); the relayer\n * co-signs (source + fee + sponsorship) before submitting.\n */\n async buildSponsoredCreateTx(params: {\n relayer: string;\n masterAddress: string;\n controlAddress: string;\n envelope: AccountEnvelope;\n }): Promise<Transaction> {\n const relayerAccount = await this.server().loadAccount(params.relayer);\n const builder = new TransactionBuilder(relayerAccount, {\n fee: BASE_FEE,\n networkPassphrase: this.passphrase,\n });\n\n builder.addOperation(\n Operation.beginSponsoringFutureReserves({ sponsoredId: params.masterAddress, source: params.relayer }),\n );\n builder.addOperation(\n Operation.createAccount({ destination: params.masterAddress, startingBalance: \"0\", source: params.relayer }),\n );\n for (const [name, value] of Object.entries(toDataEntries(params.envelope))) {\n builder.addOperation(\n Operation.manageData({ name, value: Buffer.from(value), source: params.masterAddress }),\n );\n }\n builder.addOperation(\n Operation.setOptions({\n source: params.masterAddress,\n masterWeight: 0,\n lowThreshold: 1,\n medThreshold: 1,\n highThreshold: 1,\n signer: { ed25519PublicKey: params.controlAddress, weight: 1 },\n }),\n );\n builder.addOperation(Operation.endSponsoringFutureReserves({ source: params.masterAddress }));\n\n return builder.setTimeout(TX_TIMEOUT).build();\n }\n\n /**\n * Build a classic native-XLM payment as an *inner* transaction whose source is\n * the account itself (`G…`), signed by the control key. Wrap it in a fee-bump\n * (see `wrapFeeBump`) so the relayer pays the fee — gasless.\n */\n async buildPaymentTx(params: {\n from: string;\n to: string;\n /** Amount in stroops. */\n amount: bigint;\n }): Promise<Transaction> {\n const source = await this.server().loadAccount(params.from);\n return new TransactionBuilder(source, { fee: BASE_FEE, networkPassphrase: this.passphrase })\n .addOperation(\n Operation.payment({\n destination: params.to,\n asset: Asset.native(),\n amount: fromStroops(params.amount),\n }),\n )\n .setTimeout(TX_TIMEOUT)\n .build();\n }\n\n /**\n * Build a data-entry write (e.g. re-wrapping the DEK for a newly approved\n * device) as an inner tx sourced by the account, signed by the control key.\n */\n async buildDataTx(params: { account: string; entries: Record<string, Uint8Array> }): Promise<Transaction> {\n const source = await this.server().loadAccount(params.account);\n const builder = new TransactionBuilder(source, { fee: BASE_FEE, networkPassphrase: this.passphrase });\n for (const [name, value] of Object.entries(params.entries)) {\n builder.addOperation(Operation.manageData({ name, value: Buffer.from(value) }));\n }\n return builder.setTimeout(TX_TIMEOUT).build();\n }\n\n /**\n * Build a **sponsored** data-entry write whose source is the relayer, so the\n * relayer (not the 0-balance account) pays the reserve of any NEW subentry.\n * Adding a factor (passkey / recovery) or a device slot creates a data entry\n * that needs ~0.5 XLM of reserve; a sponsored account holds no XLM, so — like\n * account creation — the write must be wrapped in begin/endSponsoringFuture\n * reserves with the relayer as sponsor. Ops:\n * 0. beginSponsoringFutureReserves(account) source = relayer\n * 1..n. manageData(cv:…) source = account (control-signed)\n * last. endSponsoringFutureReserves() source = account\n *\n * Signed by the control key (account ops) + the relayer (source + fee + sponsor).\n */\n async buildSponsoredDataTx(params: {\n relayer: string;\n account: string;\n entries: Record<string, Uint8Array>;\n }): Promise<Transaction> {\n const relayerAccount = await this.server().loadAccount(params.relayer);\n const builder = new TransactionBuilder(relayerAccount, {\n fee: BASE_FEE,\n networkPassphrase: this.passphrase,\n });\n builder.addOperation(\n Operation.beginSponsoringFutureReserves({ sponsoredId: params.account, source: params.relayer }),\n );\n for (const [name, value] of Object.entries(params.entries)) {\n builder.addOperation(Operation.manageData({ name, value: Buffer.from(value), source: params.account }));\n }\n builder.addOperation(Operation.endSponsoringFutureReserves({ source: params.account }));\n return builder.setTimeout(TX_TIMEOUT).build();\n }\n\n /** Wrap a control-signed inner tx in a fee-bump whose fee source is `feeSource`\n * (the relayer). The inner tx pays nothing; the relayer pays all fees. */\n wrapFeeBump(inner: Transaction, feeSource: string): FeeBumpTransaction {\n return TransactionBuilder.buildFeeBumpTransaction(feeSource, BASE_FEE, inner, this.passphrase);\n }\n\n /** Submit a fully-signed classic transaction and return its hash. Throws with\n * the Horizon result codes on failure. */\n async submit(tx: Transaction | FeeBumpTransaction): Promise<string> {\n try {\n const res = await this.server().submitTransaction(tx);\n return res.hash;\n } catch (e) {\n throw new Error(`kit/stellar: submit failed: ${horizonError(e)}`);\n }\n }\n\n /** Build an `Account` handle for a known address + sequence (avoids a Horizon\n * round-trip when the caller already has the sequence). */\n accountAt(address: string, sequence: string): Account {\n return new Account(address, sequence);\n }\n}\n\nfunction isNotFound(e: unknown): boolean {\n const status = (e as { response?: { status?: number }; status?: number })?.response?.status ??\n (e as { status?: number })?.status;\n return status === 404;\n}\n\nfunction horizonError(e: unknown): string {\n const codes = (e as { response?: { data?: { extras?: { result_codes?: unknown } } } })?.response?.data?.extras\n ?.result_codes;\n return codes ? JSON.stringify(codes) : String((e as Error)?.message ?? e);\n}\n\n/** 7-dp XLM string → stroops (integer). */\nfunction toStroops(amount: string): bigint {\n const [whole, frac = \"\"] = amount.split(\".\");\n const fracPadded = (frac + \"0000000\").slice(0, 7);\n return BigInt(whole) * 10_000_000n + BigInt(fracPadded);\n}\n\n/** Stroops → 7-dp XLM string (the stellar-sdk amount format). */\nfunction fromStroops(stroops: bigint): string {\n const neg = stroops < 0n;\n const abs = neg ? -stroops : stroops;\n const whole = abs / 10_000_000n;\n const frac = (abs % 10_000_000n).toString().padStart(7, \"0\");\n return `${neg ? \"-\" : \"\"}${whole}.${frac}`;\n}\n\n/** Sign helpers — the adapter never holds keys, so signing is done by callers,\n * but these keep the (control/master) signing idiom in one place. */\nexport function signWith(tx: Transaction, ...keypairs: Keypair[]): Transaction {\n tx.sign(...keypairs);\n return tx;\n}\n","import { Keypair } from \"@stellar/stellar-sdk\";\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { randomBytes } from \"@noble/hashes/utils\";\nimport { deriveAddressSeedStellar } from \"../../identity\";\nimport type { IdentityInput } from \"../../identity\";\n\n/**\n * Key derivation for the classic Stellar (`G…`) multisig account.\n *\n * A partner integration requires classic ed25519 `G…` addresses, which the\n * Soroban device-account (`C…`) model cannot provide. Instead of a smart\n * contract, we use a *classic multisig* account whose UX still matches the rest\n * of Cavos (social login → deterministic address, silent signing, gasless,\n * self-custodial, NO backend, NO registry):\n *\n * - The **master key** is derived deterministically from the user identity, so\n * the same user always resolves to the same `G…` address on any device with\n * nothing but their login. It is set to **weight 0** at account creation:\n * public and address-defining, but powerless to sign anything.\n * - The **control key** is a random ed25519 key (weight 1, threshold 1) — the\n * real signer. Its 32-byte seed is never stored in the clear; it lives\n * envelope-encrypted in the account's own on-chain data entries (see\n * `envelope.ts`), unlocked per-device by a P-256 device factor.\n *\n * This module is pure `@noble/*` + stellar-sdk keypair math (no WebCrypto/DOM),\n * so the identical derivation runs in the browser and React Native.\n */\n\n/** HKDF info that scopes the master-key derivation. Bumping it re-derives a new\n * master-key space (and therefore new addresses) — never change per-user. */\nconst MASTER_HKDF_INFO = \"cavos-stellar-master\";\n\n/**\n * Deterministically derive the 32-byte ed25519 seed of the account's master key\n * from the user identity. Folds the shared cross-chain address seed\n * (`userId + appSalt`) through HKDF with a Stellar-master-scoped `info`, so this\n * seed is independent of the seeds used by the Soroban path or other chains.\n */\nexport function deriveStellarMasterSeed(identity: IdentityInput): Uint8Array {\n const ikm = deriveAddressSeedStellar(identity);\n return hkdf(sha256, ikm, undefined, MASTER_HKDF_INFO, 32);\n}\n\n/**\n * The account's master `Keypair`. Its public key IS the classic `G…` address of\n * the account. Deterministic: same identity → same keypair on every device.\n * Set to weight 0 at creation, so this keypair can never actually authorize a\n * transaction — it only names the account.\n */\nexport function deriveStellarMasterKeypair(identity: IdentityInput): Keypair {\n return Keypair.fromRawEd25519Seed(Buffer.from(deriveStellarMasterSeed(identity)));\n}\n\n/**\n * The deterministic `G…` address for an identity, derivable offline from login\n * alone — no chain read, no registry. This is what makes the account\n * self-custodial and backend-free: the address is a pure function of identity.\n */\nexport function deriveStellarAddress(identity: IdentityInput): string {\n return deriveStellarMasterKeypair(identity).publicKey();\n}\n\n/** A freshly generated control key: the real (weight-1) signer of the account.\n * Returns both the `Keypair` and its raw 32-byte seed (the secret that the\n * envelope encrypts). Generated once at account creation, then only ever\n * recovered by decrypting the on-chain envelope. */\nexport function generateControlKey(): { keypair: Keypair; seed: Uint8Array } {\n const seed = randomBytes(32);\n return { keypair: Keypair.fromRawEd25519Seed(Buffer.from(seed)), seed };\n}\n\n/** Rebuild the control `Keypair` from a decrypted 32-byte seed. */\nexport function controlKeypairFromSeed(seed: Uint8Array): Keypair {\n if (seed.length !== 32) throw new Error(\"kit/stellar: control seed must be 32 bytes\");\n return Keypair.fromRawEd25519Seed(Buffer.from(seed));\n}\n","import type { StellarNetwork } from \"./constants\";\n\nexport interface StellarRelayerOptions {\n /** Base URL of the Cavos backend exposing /api/stellar/relay. */\n baseUrl: string;\n /** Cavos App ID (authorizes the sponsored request). */\n appId: string;\n network: StellarNetwork;\n}\n\n/** What the transaction is, so the backend applies the right validation gate.\n * - `create` sponsored account creation (relayer = source + sponsor)\n * - `fee-bump` a control-signed payment wrapped in a relayer fee-bump\n * - `sponsored-data` a control-signed data write (add factor/device slot) whose\n * new subentry reserves the relayer sponsors */\nexport type StellarRelayKind = \"create\" | \"fee-bump\" | \"sponsored-data\";\n\n/**\n * Client for the classic-G sponsoring relayer. Unlike the Soroban relayer (which\n * is the tx *source*), the classic relayer plays two roles:\n * - **create**: it is the tx source + fee payer AND sponsors the new account's\n * reserves (`begin/endSponsoringFutureReserves`), so the user locks no XLM.\n * The SDK sends a master-signed create tx; the relayer co-signs + submits.\n * - **fee-bump**: the user's control-signed inner tx (source = their `G…`) is\n * wrapped in a fee-bump whose fee source is the relayer. The relayer signs the\n * outer envelope only — it pays the fee, never moves the user's funds.\n *\n * Either way the relayer is a fee payer / reserve sponsor, never a custodian.\n */\nexport class StellarRelayer {\n private source?: string;\n\n constructor(private readonly opts: StellarRelayerOptions) {}\n\n /** The relayer's source/fee-payer/sponsor G-account (fetched + cached). */\n async getSource(): Promise<string> {\n if (this.source) return this.source;\n const res = await fetch(`${this.opts.baseUrl}/api/stellar/relay?network=${this.opts.network}`);\n if (!res.ok) throw new Error(`kit/stellar: relayer source lookup failed (${res.status})`);\n const { fee_payer } = (await res.json()) as { fee_payer: string };\n this.source = fee_payer;\n return this.source;\n }\n\n /** POST a (partially) signed transaction XDR for the relayer to co-sign + submit.\n * `kind` selects the validation gate. Returns the confirmed transaction hash. */\n async submit(kind: StellarRelayKind, transactionXdr: string): Promise<string> {\n const res = await fetch(`${this.opts.baseUrl}/api/stellar/relay`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n app_id: this.opts.appId,\n network: this.opts.network,\n kind,\n transaction: transactionXdr,\n }),\n });\n if (!res.ok) {\n const detail = await res.text().catch(() => \"\");\n throw new Error(`kit/stellar: relay failed (${res.status}) ${detail}`);\n }\n const { hash } = (await res.json()) as { hash: string };\n return hash;\n }\n}\n","import { Keypair } from \"@stellar/stellar-sdk\";\nimport type { AuthProvider, Identity } from \"../../auth/AuthProvider\";\nimport { StellarAdapter } from \"./StellarAdapter\";\nimport {\n deriveStellarMasterKeypair,\n generateControlKey,\n controlKeypairFromSeed,\n} from \"./keys\";\nimport {\n generateDEK,\n sealControlSeed,\n openControlSeed,\n wrapDEK,\n eciesWrapDEK,\n deriveRecoveryKEK,\n derivePasskeyKEK,\n unwrapDEK,\n} from \"./envelope\";\nimport {\n fromDataEntries,\n deviceWrapEntries,\n PASSKEY_BASE,\n RECOVERY_BASE,\n type AccountEnvelope,\n} from \"./datamap\";\nimport { chunkTo64 } from \"./envelope\";\nimport type { DeviceUnwrapKey } from \"./DeviceUnwrapKey\";\nimport { StellarRelayer } from \"./StellarRelayer\";\nimport type { StellarNetwork } from \"./constants\";\nimport type { Transaction } from \"@stellar/stellar-sdk\";\nimport type { ExecuteOptions } from \"../../chains/ChainAdapter\";\n\n/** Default starting balance (stroops) for a new account: covers the 1 XLM base\n * reserve + ~0.5 XLM per subentry (data entries + control signer) with headroom\n * for fees and future factor entries. ~5 XLM, recoverable when merged.\n * Sponsorship (Phase 3) will move this cost to the relayer. */\nconst DEFAULT_STARTING_BALANCE = 50_000_000n;\n\nexport interface ConnectStellarOptions {\n network: StellarNetwork;\n /** Authenticated user (pass `identity` directly, or an `auth` provider). */\n auth?: AuthProvider;\n identity?: Identity;\n appSalt: string;\n /** This device's P-256 ECDH unwrap key (provisioned + persisted per device). */\n deviceKey: DeviceUnwrapKey;\n /**\n * Gasless sponsorship via the Cavos classic relayer. When set (or when `appId` +\n * `backendUrl` are given) the relayer is the tx source + fee payer AND sponsors\n * the account's reserves — the user locks no XLM and pays no fees.\n */\n relayer?: StellarRelayer;\n /** Cavos App ID — enables the default relayer when no `relayer` is passed. */\n appId?: string;\n /** Cavos backend base URL (default https://cavos.xyz). */\n backendUrl?: string;\n /**\n * Self-funded funder + fee payer: creates + submits classic transactions\n * directly (the account pays its own reserves + fees). The advanced /\n * self-hosted fallback used when no relayer is configured.\n */\n sourceKeypair?: Keypair;\n /** Horizon URL override. */\n horizonUrl?: string;\n /** Starting balance for a fresh account, in stroops. */\n startingBalance?: bigint;\n}\n\nexport type StellarConnectStatus = \"ready\" | \"needs-device-approval\";\n\n/** The DEK + control keypair recovered by opening any single unlock factor. */\ninterface Unlocked {\n control: Keypair;\n dek: Uint8Array;\n}\n\n/**\n * High-level entry for the classic-Stellar (`G…`) multisig account — the classic\n * analogue of `CavosStellar` (Soroban). One `connect` derives the deterministic\n * `G…` address, creates the account if needed, and on a known device unlocks the\n * control key from the on-chain envelope so `execute` signs silently.\n *\n * Multiple unlock **factors** all wrap the same DEK, so opening any one yields the\n * control key:\n * - **device** (P-256 ECIES): silent daily signing, per-device, non-syncable;\n * - **passkey** (WebAuthn PRF): synced anchor to approve a new device / recover;\n * - **recovery code**: offline backup (optional).\n *\n * Self-custodial, no backend, no registry: the address is a pure function of\n * identity and the control key lives only in the account's own data entries.\n * Unlike the Soroban `CavosStellar`, this path uses NO wallet registry —\n * creation needs neither an org API key nor a relayer. The optional relayer is\n * only a fee payer + reserve sponsor (never a custodian or identity authority),\n * so a bad/absent relayer can cost fees but can never move funds or squat an\n * address.\n */\nexport class CavosStellar {\n // Discriminant for the `CavosWallet` union. Classic `G…` IS the Stellar chain\n // now (the Soroban `C…` path was removed), so this is \"stellar\".\n readonly chain = \"stellar\" as const;\n isNewAccount = false;\n private statusValue: StellarConnectStatus;\n\n private constructor(\n readonly identity: Identity,\n readonly address: string,\n status: StellarConnectStatus,\n readonly network: StellarNetwork,\n private readonly adapter: StellarAdapter,\n private readonly deviceKey: DeviceUnwrapKey,\n private control: Keypair | undefined,\n private dek: Uint8Array | undefined,\n private readonly relayer: StellarRelayer | undefined,\n ) {\n this.statusValue = status;\n }\n\n get status(): StellarConnectStatus {\n return this.statusValue;\n }\n\n static async connect(opts: ConnectStellarOptions): Promise<CavosStellar> {\n const identity = opts.identity ?? (await opts.auth?.authenticate());\n if (!identity) throw new Error(\"kit/stellar: connect requires `identity` or `auth`\");\n\n const adapter = new StellarAdapter({ network: opts.network, horizonUrl: opts.horizonUrl });\n const master = deriveStellarMasterKeypair({ userId: identity.userId, appSalt: opts.appSalt });\n const address = master.publicKey();\n const startingBalance = opts.startingBalance ?? DEFAULT_STARTING_BALANCE;\n\n const backendUrl = opts.backendUrl ?? \"https://cavos.xyz\";\n const relayer =\n opts.relayer ??\n (opts.appId\n ? new StellarRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network })\n : undefined);\n\n const build = (status: StellarConnectStatus, unlocked?: Unlocked): CavosStellar =>\n new CavosStellar(\n identity,\n address,\n status,\n opts.network,\n adapter,\n opts.deviceKey,\n unlocked?.control,\n unlocked?.dek,\n relayer,\n );\n\n if (await adapter.isDeployed(address)) {\n // Returning user: rebuild the control key from the on-chain envelope if this\n // device has a wrap slot; otherwise this is a new device awaiting approval.\n const unlocked = await unlockViaDevice(adapter, address, opts.deviceKey);\n return build(unlocked ? \"ready\" : \"needs-device-approval\", unlocked ?? undefined);\n }\n\n // First sign-up on this identity: create the account.\n if (!relayer && !opts.sourceKeypair) {\n throw new Error(\"kit/stellar: a relayer (appId) or sourceKeypair is required to create the account\");\n }\n const { keypair: control, seed: controlSeed } = generateControlKey();\n const dek = generateDEK();\n const envelope: AccountEnvelope = {\n ct: sealControlSeed(controlSeed, dek),\n deviceWraps: { [opts.deviceKey.slotId()]: eciesWrapDEK(dek, opts.deviceKey.publicKeySec1()) },\n };\n\n if (relayer) {\n // Gasless + sponsored: the relayer is source + fee payer + reserve sponsor.\n // Master signs its own account ops; the relayer co-signs the envelope.\n const relayerSource = await relayer.getSource();\n const tx = await adapter.buildSponsoredCreateTx({\n relayer: relayerSource,\n masterAddress: address,\n controlAddress: control.publicKey(),\n envelope,\n });\n tx.sign(master);\n await relayer.submit(\"create\", tx.toXDR());\n } else {\n const funder = opts.sourceKeypair!;\n const tx = await adapter.buildCreateTx({\n funder: funder.publicKey(),\n masterAddress: address,\n controlAddress: control.publicKey(),\n envelope,\n startingBalance,\n });\n // Master authorizes its own account ops (while still weight 1); funder is the\n // source + fee payer. After this tx the master is permanently weight 0.\n tx.sign(master, funder);\n await adapter.submit(tx);\n }\n\n const wallet = build(\"ready\", { control, dek });\n wallet.isNewAccount = true;\n return wallet;\n }\n\n /** Native XLM balance of the account, in stroops. */\n async balance(): Promise<bigint> {\n return this.adapter.balance(this.address);\n }\n\n /** True if the account has a passkey factor enrolled (`cv:wp`), so a new device\n * can be approved with the passkey instead of a recovery code. Mirrors the\n * other chains' `hasPasskey()` for the React provider. */\n async hasPasskey(): Promise<boolean> {\n try {\n const env = fromDataEntries(await this.adapter.loadDataEntries(this.address));\n return !!env.passkeyWrap;\n } catch {\n return false;\n }\n }\n\n /** Whether the control key is unlocked on this device (status ready). Classic\n * approvals land synchronously via Horizon, so this reflects state immediately\n * (no indexing delay to poll for). */\n async isReady(): Promise<boolean> {\n return this.statusValue === \"ready\";\n }\n\n /**\n * Move `amount` stroops of native XLM to `destination`, signed by the control\n * key. Sponsored by default (the relayer fee-bumps and pays the fee); pass\n * `{ sponsored: false }` to submit directly — the account pays its own (tiny)\n * fee from its XLM balance. The control key signs identically in both modes;\n * only the fee payer differs.\n */\n async execute(amount: bigint, destination: string, opts?: ExecuteOptions): Promise<string> {\n const control = this.requireControl();\n const inner = await this.adapter.buildPaymentTx({ from: this.address, to: destination, amount });\n return this.submitInner(inner, control, opts);\n }\n\n /**\n * Enroll a passkey as an unlock factor: wrap the DEK under the passkey's PRF\n * output and write the `cv:wp` entry. This is the synced anchor used to approve\n * a new device or recover — it survives device loss. Idempotent-ish: writing it\n * again just overwrites the wrap of the same DEK. Requires a ready device.\n */\n async enrollPasskey(prfOutput: Uint8Array): Promise<string> {\n const { control, dek } = this.requireUnlocked();\n const wrap = wrapDEK(dek, derivePasskeyKEK(prfOutput));\n return this.writeFactor(PASSKEY_BASE, wrap, control);\n }\n\n /**\n * Set up a recovery code as an unlock factor: wrap the DEK under the code's KEK\n * and write the `cv:wr` entry. Optional in v1 — the integrating app decides when\n * to surface it. The code never leaves the device; only the wrap goes on-chain.\n * Requires a ready device.\n */\n async setupRecovery(code: string): Promise<string> {\n const { control, dek } = this.requireUnlocked();\n const wrap = wrapDEK(dek, deriveRecoveryKEK(code));\n return this.writeFactor(RECOVERY_BASE, wrap, control);\n }\n\n /**\n * From a new browser/device (`needs-device-approval`), approve THIS device using\n * the user's synced passkey: unlock the DEK via the passkey factor, then wrap it\n * to this device's slot so future sessions unlock silently. Flips status to\n * `ready`. No trip back to an already-authorized device.\n */\n async approveThisDeviceWithPasskey(prfOutput: Uint8Array): Promise<string> {\n return this.approveThisDevice(\n await unlockViaPasskey(this.adapter, this.address, prfOutput),\n \"passkey\",\n );\n }\n\n /** Approve THIS device using the recovery code (same as the passkey path, for\n * the backup factor). */\n async approveThisDeviceWithRecovery(code: string): Promise<string> {\n return this.approveThisDevice(\n await unlockViaRecovery(this.adapter, this.address, code),\n \"recovery code\",\n );\n }\n\n /** The control key's public G address (the weight-1 real signer), for display. */\n get controlAddress(): string | undefined {\n return this.control?.publicKey();\n }\n\n // --- internals ----------------------------------------------------------\n\n private async approveThisDevice(unlocked: Unlocked | null, factor: string): Promise<string> {\n if (this.statusValue === \"ready\") {\n throw new Error(\"kit/stellar: this device is already authorized\");\n }\n if (!unlocked) {\n throw new Error(`kit/stellar: could not unlock the account with the ${factor} — wrong factor or not enrolled`);\n }\n const slot = this.deviceKey.slotId();\n const wrap = eciesWrapDEK(unlocked.dek, this.deviceKey.publicKeySec1());\n const hash = await this.submitDataWrite(deviceWrapEntries(slot, wrap), unlocked.control);\n // This device is now a silent-unlock factor.\n this.control = unlocked.control;\n this.dek = unlocked.dek;\n this.statusValue = \"ready\";\n return hash;\n }\n\n /** Write a single-factor wrap (passkey/recovery) into the account data entries,\n * signed by the control key. Overwrites cleanly if the base already existed and\n * the new blob has the same chunk count. */\n private async writeFactor(base: string, wrap: Uint8Array, control: Keypair): Promise<string> {\n const entries: Record<string, Uint8Array> = {};\n chunkTo64(wrap).forEach((chunk, i) => {\n entries[`${base}/${i}`] = chunk;\n });\n return this.submitDataWrite(entries, control);\n }\n\n /**\n * Sign an inner (account-sourced) payment tx with the control key and submit it:\n * - sponsored (default) → with a relayer, wrap in a fee-bump (relayer pays\n * the fee) and POST; falls back to self-funded if no relayer;\n * - `{ sponsored: false }` → submit directly (the account pays its own fee).\n * Payments add no subentries, so no reserve sponsorship is needed here.\n */\n private async submitInner(\n inner: Transaction,\n control: Keypair,\n opts?: ExecuteOptions,\n ): Promise<string> {\n inner.sign(control);\n const sponsored = opts?.sponsored !== false;\n if (sponsored && this.relayer) {\n const feeSource = await this.relayer.getSource();\n const bump = this.adapter.wrapFeeBump(inner, feeSource);\n return this.relayer.submit(\"fee-bump\", bump.toXDR());\n }\n // Self-funded: submit the account-sourced inner tx directly; the account pays\n // the (tiny) fee out of its own balance.\n return this.adapter.submit(inner);\n }\n\n /**\n * Write data entries (add a factor / device slot) — which create NEW subentries\n * that each need ~0.5 XLM of reserve. A relayer-sponsored account holds no XLM,\n * so the write must be sponsored by the relayer (source + sponsor), exactly like\n * account creation — a plain fee-bump would fail with `op_low_reserve`.\n * - sponsored (default) → with a relayer, build a sponsored write (relayer\n * source + begin/end sponsoring), control-sign the account ops, relay\n * co-signs + submits; falls back to self-funded if no relayer;\n * - `{ sponsored: false }` → the account writes directly (it must hold its\n * own reserve for the new subentries).\n */\n private async submitDataWrite(\n entries: Record<string, Uint8Array>,\n control: Keypair,\n opts?: ExecuteOptions,\n ): Promise<string> {\n const sponsored = opts?.sponsored !== false;\n if (sponsored && this.relayer) {\n const relayerSource = await this.relayer.getSource();\n const tx = await this.adapter.buildSponsoredDataTx({\n relayer: relayerSource,\n account: this.address,\n entries,\n });\n tx.sign(control); // account-sourced manageData + endSponsoring\n return this.relayer.submit(\"sponsored-data\", tx.toXDR());\n }\n const tx = await this.adapter.buildDataTx({ account: this.address, entries });\n tx.sign(control);\n return this.adapter.submit(tx);\n }\n\n private requireControl(): Keypair {\n if (this.statusValue !== \"ready\" || !this.control) {\n throw new Error(\"kit/stellar: control key not unlocked on this device (needs approval)\");\n }\n return this.control;\n }\n\n private requireUnlocked(): Unlocked {\n const control = this.requireControl();\n if (!this.dek) throw new Error(\"kit/stellar: DEK unavailable on this device\");\n return { control, dek: this.dek };\n }\n}\n\n/** Rebuild the control keypair from the on-chain envelope using this device's\n * ECIES wrap. Returns null if this device has no slot or the wrap can't open. */\nasync function unlockViaDevice(\n adapter: StellarAdapter,\n address: string,\n deviceKey: DeviceUnwrapKey,\n): Promise<Unlocked | null> {\n const env = await loadEnvelope(adapter, address);\n const wrap = env.deviceWraps[deviceKey.slotId()];\n if (!wrap) return null;\n try {\n const dek = await deviceKey.unwrap(wrap);\n return openControl(env, dek);\n } catch {\n return null;\n }\n}\n\n/** Unlock via the passkey PRF factor (`cv:wp`). */\nasync function unlockViaPasskey(\n adapter: StellarAdapter,\n address: string,\n prfOutput: Uint8Array,\n): Promise<Unlocked | null> {\n const env = await loadEnvelope(adapter, address);\n if (!env.passkeyWrap) return null;\n try {\n const dek = unwrapDEK(env.passkeyWrap, derivePasskeyKEK(prfOutput));\n return openControl(env, dek);\n } catch {\n return null;\n }\n}\n\n/** Unlock via the recovery-code factor (`cv:wr`). */\nasync function unlockViaRecovery(\n adapter: StellarAdapter,\n address: string,\n code: string,\n): Promise<Unlocked | null> {\n const env = await loadEnvelope(adapter, address);\n if (!env.recoveryWrap) return null;\n try {\n const dek = unwrapDEK(env.recoveryWrap, deriveRecoveryKEK(code));\n return openControl(env, dek);\n } catch {\n return null;\n }\n}\n\nasync function loadEnvelope(adapter: StellarAdapter, address: string): Promise<AccountEnvelope> {\n return fromDataEntries(await adapter.loadDataEntries(address));\n}\n\nfunction openControl(env: AccountEnvelope, dek: Uint8Array): Unlocked {\n const controlSeed = openControlSeed(env.ct, dek);\n return { control: controlKeypairFromSeed(controlSeed), dek };\n}\n","import { p256 } from \"@noble/curves/p256\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { randomBytes } from \"@noble/hashes/utils\";\nimport { eciesUnwrapDEK } from \"./envelope\";\n\n/**\n * The device's P-256 **ECDH** key used only to unwrap the account DEK.\n *\n * Note this is a SEPARATE key from the `DeviceSigner` (which is an ECDSA signing\n * key, non-extractable, and therefore cannot do ECDH). This key is per-device\n * and non-syncable — losing the device loses only this convenience factor, not\n * the account (the passkey / recovery factors survive). Its public key goes into\n * the account's `cv:wd:<id>` on-chain envelope slot; the DEK is ECIES-wrapped to\n * it so daily unlock is silent.\n *\n * `LocalDeviceUnwrapKey` holds a raw scalar (Node / tests / React Native secure\n * storage). The browser implementation wraps a non-extractable WebCrypto ECDH\n * key and overrides `unwrap` with `deriveBits`; it never exposes the scalar.\n */\nexport interface DeviceUnwrapKey {\n /** SEC1 *uncompressed* (65-byte) public key — the ECIES recipient key that is\n * published on-chain in the device's envelope slot. */\n publicKeySec1(): Uint8Array;\n /** A short, stable id for this device's envelope slot (`cv:wd:<id>`). */\n slotId(): string;\n /** Unwrap the account DEK from this device's ECIES blob. */\n unwrap(blob: Uint8Array): Promise<Uint8Array>;\n}\n\n/** Raw-scalar device unwrap key (Node / React Native). */\nexport class LocalDeviceUnwrapKey implements DeviceUnwrapKey {\n private constructor(private readonly scalar: Uint8Array) {}\n\n /** Generate a fresh device unwrap key. */\n static generate(): LocalDeviceUnwrapKey {\n return new LocalDeviceUnwrapKey(p256.utils.randomPrivateKey());\n }\n\n /** Rebuild from a persisted 32-byte scalar. */\n static fromScalar(scalar: Uint8Array): LocalDeviceUnwrapKey {\n if (scalar.length !== 32) throw new Error(\"kit/stellar: device unwrap scalar must be 32 bytes\");\n return new LocalDeviceUnwrapKey(scalar);\n }\n\n /** The raw scalar, for the caller to persist in secure storage. */\n export(): Uint8Array {\n return this.scalar;\n }\n\n publicKeySec1(): Uint8Array {\n return p256.getPublicKey(this.scalar, false);\n }\n\n slotId(): string {\n return deviceSlotId(this.publicKeySec1());\n }\n\n async unwrap(blob: Uint8Array): Promise<Uint8Array> {\n return eciesUnwrapDEK(blob, this.scalar);\n }\n}\n\n/** Stable short slot id for a device's envelope entry: first 8 hex of\n * `sha256(pubkey)`. Deterministic from the public key, so it's the same on\n * every read and can't collide in practice for a handful of devices. */\nexport function deviceSlotId(publicKeySec1: Uint8Array): string {\n const h = sha256(publicKeySec1);\n let s = \"\";\n for (const b of h.subarray(0, 4)) s += b.toString(16).padStart(2, \"0\");\n return s;\n}\n\n/** For tests: a random slot id (when no key is involved). */\nexport function randomSlotId(): string {\n let s = \"\";\n for (const b of randomBytes(4)) s += b.toString(16).padStart(2, \"0\");\n return s;\n}\n","import { p256 } from \"@noble/curves/p256\";\nimport { eciesKEKFromX, unwrapDEK } from \"./envelope\";\nimport { deviceSlotId, type DeviceUnwrapKey } from \"./DeviceUnwrapKey\";\n\n// A dedicated database (not WebCryptoSigner's \"cavos-kit\") so the two never\n// collide on IndexedDB version numbers.\nconst IDB_NAME = \"cavos-kit-stellar\";\nconst IDB_STORE = \"unwrap-keys\";\n\nexport interface WebCryptoUnwrapKeyOptions {\n /** Storage key for this device's unwrap key (e.g. `${userId}:${appSalt}`). One\n * ECDH key per (this value, browser profile). */\n keyId: string;\n}\n\ninterface StoredUnwrapKey {\n privateKey: CryptoKey; // non-extractable ECDH key; structured-cloneable\n publicRaw: Uint8Array; // SEC1 uncompressed (65 bytes)\n}\n\n/**\n * Browser `DeviceUnwrapKey`: a non-extractable P-256 **ECDH** key generated with\n * WebCrypto and persisted in IndexedDB. Distinct from `WebCryptoSigner` (an ECDSA\n * signing key) — a signing key can't do ECDH, so the classic-G envelope needs its\n * own key here. The private key never leaves WebCrypto: the account DEK is\n * unwrapped via `deriveBits` (raw ECDH), then AES-GCM in `@noble` on the derived\n * KEK. Per-device, non-syncable → losing the device loses only this convenience\n * factor, never the account (the passkey / recovery factors survive).\n */\nexport class WebCryptoDeviceUnwrapKey implements DeviceUnwrapKey {\n private constructor(\n private readonly privateKey: CryptoKey,\n private readonly publicRaw: Uint8Array,\n readonly keyId: string,\n ) {}\n\n /** Create a fresh device unwrap key and persist it. */\n static async create(opts: WebCryptoUnwrapKeyOptions): Promise<WebCryptoDeviceUnwrapKey> {\n assertSecureContext();\n const pair = await crypto.subtle.generateKey(\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false, // private key is NON-extractable\n [\"deriveBits\"],\n );\n const publicRaw = new Uint8Array(await crypto.subtle.exportKey(\"raw\", pair.publicKey)); // 65 bytes\n await idbPut(opts.keyId, { privateKey: pair.privateKey, publicRaw });\n return new WebCryptoDeviceUnwrapKey(pair.privateKey, publicRaw, opts.keyId);\n }\n\n /** Load an existing device unwrap key, or null if none exists yet. */\n static async load(opts: WebCryptoUnwrapKeyOptions): Promise<WebCryptoDeviceUnwrapKey | null> {\n const rec = await idbGet(opts.keyId);\n if (!rec) return null;\n return new WebCryptoDeviceUnwrapKey(rec.privateKey, rec.publicRaw, opts.keyId);\n }\n\n /** Load the device unwrap key, creating one on first use. */\n static async loadOrCreate(opts: WebCryptoUnwrapKeyOptions): Promise<WebCryptoDeviceUnwrapKey> {\n return (await WebCryptoDeviceUnwrapKey.load(opts)) ?? (await WebCryptoDeviceUnwrapKey.create(opts));\n }\n\n publicKeySec1(): Uint8Array {\n return this.publicRaw;\n }\n\n slotId(): string {\n return deviceSlotId(this.publicRaw);\n }\n\n async unwrap(blob: Uint8Array): Promise<Uint8Array> {\n const ephPubCompressed = blob.subarray(0, 33);\n const wrapped = blob.subarray(33);\n\n // WebCrypto only imports uncompressed points → decompress the ephemeral pubkey.\n const ephUncompressed = p256.ProjectivePoint.fromHex(ephPubCompressed).toRawBytes(false);\n const ephKey = await crypto.subtle.importKey(\n \"raw\",\n ephUncompressed as unknown as BufferSource,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n const sharedX = new Uint8Array(\n await crypto.subtle.deriveBits({ name: \"ECDH\", public: ephKey }, this.privateKey, 256),\n );\n const kek = eciesKEKFromX(sharedX, ephPubCompressed);\n return unwrapDEK(wrapped, kek);\n }\n}\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 );\n }\n}\n\n// --- minimal IndexedDB wrapper (mirrors WebCryptoSigner, separate store) ---\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: StoredUnwrapKey): 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<StoredUnwrapKey | null> {\n const db = await openDb();\n const result = await tx(db, \"readonly\", (store) => store.get(keyId));\n db.close();\n return (result as StoredUnwrapKey) ?? 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","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 { Account, RpcProvider, PaymasterRpc, hash, num, type Call } from \"starknet\";\nimport type { Keypair } from \"@solana/web3.js\";\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 { CavosSolana } from \"./chains/solana/CavosSolana\";\nimport type { SolanaRelayer } from \"./chains/solana/SolanaRelayer\";\nimport type { SolanaNetwork } from \"./chains/solana/constants\";\nimport { CavosStellar } from \"./chains/stellar/CavosStellar\";\nimport type { StellarRelayer } from \"./chains/stellar/StellarRelayer\";\nimport { WebCryptoDeviceUnwrapKey } from \"./chains/stellar/WebCryptoDeviceUnwrapKey\";\nimport type { DeviceUnwrapKey } from \"./chains/stellar/DeviceUnwrapKey\";\nimport type { StellarNetwork } from \"./chains/stellar/constants\";\nimport type { Keypair as StellarKeypair } from \"@stellar/stellar-sdk\";\nimport type { ChainCall, ExecuteOptions } 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 type { PasskeySigner, PasskeyEnrollParams } from \"./signer/PasskeySigner\";\nimport { webauthnDigest, recoverCandidatePublicKeys, batchChallenge } from \"./crypto/webauthn\";\nimport type { PasskeyAssertion } from \"./crypto/webauthn\";\nimport {\n CAVOS_PAYMASTER_URL,\n DEVICE_ACCOUNT_CLASS_HASH,\n STARKNET_NETWORKS,\n type StarknetNetwork,\n} from \"./chains/starknet/constants\";\n\n/** The chains the unified `Cavos.connect` can target. */\nexport type Chain = \"starknet\" | \"solana\" | \"stellar\";\n\n/**\n * Environment selector. `Cavos.connect` resolves it to the chain's concrete\n * network: starknet → sepolia/mainnet, solana → solana-devnet/solana-mainnet.\n */\nexport type NetworkEnv = \"mainnet\" | \"testnet\";\n\n/** Resolve the abstract `{ chain, network }` to each chain's concrete network. */\nconst STARKNET_ENV: Record<NetworkEnv, StarknetNetwork> = {\n mainnet: \"mainnet\",\n testnet: \"sepolia\",\n};\nconst SOLANA_ENV: Record<NetworkEnv, SolanaNetwork> = {\n mainnet: \"solana-mainnet\",\n testnet: \"solana-devnet\",\n};\nconst STELLAR_ENV: Record<NetworkEnv, StellarNetwork> = {\n mainnet: \"stellar-mainnet\",\n testnet: \"stellar-testnet\",\n};\n\n/** A connected wallet: discriminated by `chain`, so `execute()` stays native. */\nexport type CavosWallet = Cavos | CavosSolana | CavosStellar;\n\nexport interface ConnectOptions {\n /** Target chain. The returned wallet is discriminated by this same value. */\n chain: Chain;\n /** Environment. Resolved to sepolia/devnet (testnet) or mainnet per chain. */\n network: NetworkEnv;\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 (Starknet). Defaults to HttpRecoveryClient when\n * `appId` is set; used to request addition of this device when it isn't a\n * signer yet.\n */\n recovery?: RecoveryClient;\n rpcUrl?: string;\n /** Override the device signer factory (native / tests); default WebCrypto. */\n createSigner?: (keyId: string) => Promise<DeviceSigner>;\n\n // --- Starknet-only ---\n /** Cavos paymaster API key (sponsors deploy + execute). Required for Starknet. */\n paymasterApiKey?: string;\n paymasterUrl?: string;\n classHash?: string;\n\n // --- Solana-only ---\n /** Cavos device-account program id override. */\n programId?: string;\n /** Gasless sponsorship relayer (defaults to the hosted one when `appId` set). */\n relayer?: SolanaRelayer;\n /** Self-funded fee-payer fallback when no relayer is configured. */\n feePayer?: Keypair;\n\n // --- Stellar-only (classic `G…` multisig) ---\n /** Gasless sponsorship relayer (defaults to the hosted one when `appId` set). */\n stellarRelayer?: StellarRelayer;\n /** Self-funded source/fee-payer Stellar keypair when no relayer is configured. */\n stellarSourceKeypair?: StellarKeypair;\n /**\n * This device's ECDH unwrap key for the Stellar control-key envelope. Defaults\n * to a persisted `WebCryptoDeviceUnwrapKey` in the browser; pass your own on\n * React Native / server.\n */\n stellarDeviceKey?: DeviceUnwrapKey;\n}\n\n/** The Starknet-specific connect options, resolved from the unified ones. */\ninterface StarknetConnectOptions {\n network: StarknetNetwork;\n auth?: AuthProvider;\n identity?: Identity;\n appSalt: string;\n appId?: string;\n backendUrl?: string;\n registry?: WalletRegistry;\n recovery?: RecoveryClient;\n paymasterApiKey: string;\n paymasterUrl?: string;\n rpcUrl?: string;\n classHash?: string;\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 /** Environment (recovery is Starknet-only): testnet → sepolia, mainnet. */\n network: NetworkEnv;\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 /**\n * Skip the registry entirely by passing the account address directly. With\n * the seed-only derivation, the user can recompute the address from\n * (userId, appSalt) alone — so recovery no longer depends on the Cavos\n * backend. Pass this to make recovery fully self-custodial.\n */\n address?: string;\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 /** Discriminant for the `CavosWallet` union — narrows `execute()` per chain. */\n readonly chain = \"starknet\" as const;\n /** Request id of the pending device-addition, when status is needs-device-approval. */\n pendingRequestId: string | null = null;\n /** True when this connect just created & deployed a brand-new account (first\n * sign-up), so the UI can offer a one-time \"secure your account\" step. */\n isNewAccount = false;\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 /** Paymaster URL + API key, for the sponsored passkey-approval path. */\n private readonly paymaster?: { url: string; apiKey?: string },\n ) {}\n\n /**\n * Unified entry point. Pick a `chain` and an `network` environment; the kit\n * resolves the concrete network (sepolia/devnet for testnet, mainnet for\n * mainnet) and returns a chain-native wallet. The result is a discriminated\n * union (`wallet.chain`), so `execute()` keeps each chain's native signature:\n *\n * const wallet = await Cavos.connect({ chain: \"solana\", network: \"testnet\", identity, appSalt, appId });\n * if (wallet.chain === \"starknet\") await wallet.execute(calls);\n * else await wallet.execute(amount, dest);\n */\n static async connect(opts: ConnectOptions): Promise<CavosWallet> {\n if (opts.chain === \"solana\") {\n return CavosSolana.connect({\n network: SOLANA_ENV[opts.network],\n ...(opts.auth ? { auth: opts.auth } : {}),\n ...(opts.identity ? { identity: opts.identity } : {}),\n appSalt: opts.appSalt,\n ...(opts.appId ? { appId: opts.appId } : {}),\n ...(opts.backendUrl ? { backendUrl: opts.backendUrl } : {}),\n ...(opts.registry ? { registry: opts.registry } : {}),\n ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}),\n ...(opts.programId ? { programId: opts.programId } : {}),\n ...(opts.createSigner ? { createSigner: opts.createSigner } : {}),\n ...(opts.relayer ? { relayer: opts.relayer } : {}),\n ...(opts.feePayer ? { feePayer: opts.feePayer } : {}),\n });\n }\n if (opts.chain === \"stellar\") {\n // Classic `G…` account: resolve identity up-front so we can provision this\n // device's ECDH unwrap key (keyed by user + app) before connecting.\n const identity = opts.identity ?? (opts.auth ? await opts.auth.authenticate() : undefined);\n if (!identity) throw new Error(\"kit: Stellar connect requires `identity` or `auth`\");\n const deviceKey =\n opts.stellarDeviceKey ??\n (await WebCryptoDeviceUnwrapKey.loadOrCreate({ keyId: `${identity.userId}:${opts.appSalt}` }));\n return CavosStellar.connect({\n network: STELLAR_ENV[opts.network],\n identity,\n appSalt: opts.appSalt,\n deviceKey,\n ...(opts.appId ? { appId: opts.appId } : {}),\n ...(opts.backendUrl ? { backendUrl: opts.backendUrl } : {}),\n ...(opts.stellarRelayer ? { relayer: opts.stellarRelayer } : {}),\n ...(opts.stellarSourceKeypair ? { sourceKeypair: opts.stellarSourceKeypair } : {}),\n });\n }\n if (!opts.paymasterApiKey) {\n throw new Error(\"kit: `paymasterApiKey` is required for Starknet connections\");\n }\n return Cavos.connectStarknet({\n network: STARKNET_ENV[opts.network],\n auth: opts.auth,\n identity: opts.identity,\n appSalt: opts.appSalt,\n appId: opts.appId,\n backendUrl: opts.backendUrl,\n registry: opts.registry,\n recovery: opts.recovery,\n paymasterApiKey: opts.paymasterApiKey,\n paymasterUrl: opts.paymasterUrl,\n rpcUrl: opts.rpcUrl,\n classHash: opts.classHash,\n createSigner: opts.createSigner,\n });\n }\n\n private static async connectStarknet(opts: StarknetConnectOptions): 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 paymasterUrl = opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[opts.network];\n const paymasterConfig = { url: paymasterUrl, apiKey: opts.paymasterApiKey };\n const paymaster = new PaymasterRpc({\n nodeUrl: paymasterUrl,\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 paymasterConfig,\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 = f(addressSeed) ONLY. The device pubkey\n // no longer enters the derivation, so the address is recomputable from\n // (userId, appSalt) alone — recovery is self-custodial. The address may\n // already be deployed on-chain (same device reconnecting, or a re-run after\n // a deploy that succeeded before a timeout). Ask the chain before\n // deploying: re-deploying an existing account reverts.\n const address = adapter.computeAddress({ addressSeed });\n const account = makeAccount(address);\n const alreadyDeployed = await isDeployed(provider, address);\n\n if (!alreadyDeployed) {\n // Deploy + initialize atomically. The constructor takes only the seed\n // (so the address is seed-bound); `initialize` registers the first device\n // signer. Anti-squatting is NOT enforced on-chain — it is the integrator's\n // responsibility to keep `appSalt` secret and to deploy each account on\n // the user's first login.\n const deploymentData = {\n address,\n class_hash: classHash,\n salt: num.toHex(addressSeed),\n calldata: adapter.constructorCalldata(addressSeed),\n version: 1 as const,\n };\n // The initialize call rides in the same sponsored multicall as the deploy.\n // The paymaster submits deploy + initialize atomically; if initialize\n // fails, the deploy reverts too.\n const initCall = adapter.buildInitialize(address, devicePubkey);\n const deployRes = await account.executePaymasterTransaction([initCall], {\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 const cavos = new Cavos(\n identity,\n address,\n isSigner ? \"ready\" : \"needs-device-approval\",\n account,\n adapter,\n devicePubkey,\n paymasterConfig,\n );\n // First sign-up: a fresh deploy that made this device an authorized signer.\n cavos.isNewAccount = !alreadyDeployed && isSigner;\n return cavos;\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[], opts?: ExecuteOptions): 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 // `sponsored` defaults to true → paymaster pays the gas. Pass `sponsored:\n // false` to submit directly: the account pays its own fee from its ETH\n // balance (starknet.js' `Account.execute` ignores the paymaster entirely, so\n // the same Account instance works for both paths). Both return\n // { transaction_hash }.\n if (opts?.sponsored === false) {\n const res = await this.account.execute(calls as Call[]);\n return { transactionHash: res.transaction_hash };\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 /**\n * Authorize an additional device signer. Sponsored by default; pass\n * `{ sponsored: false }` to pay the fee from the account's own ETH balance.\n */\n async addSigner(\n pubkey: DevicePublicKey,\n opts?: ExecuteOptions,\n ): Promise<{ transactionHash: string }> {\n return this.execute([this.adapter.buildAddSigner(this.address, pubkey)], opts);\n }\n\n /**\n * Enroll a passkey as an APPROVER so the user can later add devices from any\n * browser (2FA-style step-up). Requires a ready device (the enrollment call is\n * device-signed and gasless). Idempotent: a no-op if the passkey is already an\n * approver. Call this whenever the app decides to prompt \"turn on device\n * approvals\". Returns the passkey's public key + the enrollment tx hash.\n */\n async enrollPasskey(\n passkey: PasskeySigner,\n params: PasskeyEnrollParams,\n opts?: ExecuteOptions,\n ): Promise<{ publicKey: DevicePublicKey; transactionHash?: string }> {\n const enrolled = await passkey.enroll(params);\n const { transactionHash } = await this.addApprover(enrolled.publicKey, opts);\n return { publicKey: enrolled.publicKey, transactionHash };\n }\n\n /**\n * Register an ALREADY-enrolled passkey public key as an approver (gasless by\n * default, device-signed). Idempotent. Use this to register ONE passkey across\n * multiple chains without re-prompting `passkey.enroll()` on each: enroll once,\n * then call `addApprover(pubkey)` on each chain's wallet. Pass\n * `{ sponsored: false }` to pay the fee from the account's own balance.\n */\n async addApprover(\n pubkey: DevicePublicKey,\n opts?: ExecuteOptions,\n ): Promise<{ transactionHash?: string }> {\n if (this.status !== \"ready\") {\n throw new Error(\"kit: addApprover requires a ready, authorized device\");\n }\n if (await this.adapter.isApprover(this.address, pubkey)) return {};\n const { transactionHash } = await this.execute(\n [this.adapter.buildAddApprover(this.address, pubkey)],\n opts,\n );\n // Confirm the approver is actually on-chain before returning: a new device\n // detects the passkey by reading `get_approver_count`, so a fire-and-forget\n // submit that never mines would leave the user stuck on the email flow.\n try {\n await this.account.waitForTransaction(transactionHash);\n } catch (e) {\n console.warn(\"[Cavos] add_approver receipt wait failed:\", e);\n }\n return { transactionHash };\n }\n\n /** True if this account already has a passkey enrolled as an approver, so a\n * new device can be approved with the passkey instead of the email flow. */\n async hasPasskey(): Promise<boolean> {\n return this.adapter.hasPasskeyApprover(this.address);\n }\n\n /** Re-read (from chain) whether THIS device is now an authorized signer.\n * Cheap and side-effect free — used to poll for readiness after a passkey /\n * device approval submits, before the new signer is indexed. */\n async isReady(): Promise<boolean> {\n return this.adapter.isAuthorizedSigner(this.address, this.devicePubkey);\n }\n\n /**\n * From a brand-new browser (status `needs-device-approval`), use the user's\n * synced passkey to authorize adding THIS device — no trip back to an already-\n * authorized device.\n *\n * `add_signer_via_passkey` is a public external authorized by the embedded\n * WebAuthn assertion (no device signature), so by default we sponsor it through\n * the Cavos paymaster's `paymaster_executeDirectTransaction` (the forwarder's\n * `execute_sponsored` runs a generic call — it does NOT require SNIP-9). Pass a\n * custom `submit` to route it through your own relayer instead. Returns the tx.\n */\n async approveThisDeviceWithPasskey(opts: {\n passkey: PasskeySigner;\n submit?: (call: ChainCall) => Promise<{ transactionHash: string }>;\n }): Promise<{ transactionHash: string }> {\n if (this.status === \"ready\") {\n throw new Error(\"kit: this device is already an authorized signer\");\n }\n const { leaf, nonce } = await this.passkeyLeafForThisDevice();\n const leaves = [leaf];\n const assertion = await opts.passkey.assert(batchChallenge(leaves));\n return this.submitPasskeyApproval(assertion, leaves, 0, nonce, opts.submit);\n }\n\n /** This device's leaf + the current passkey nonce, for a (possibly multi-chain)\n * passkey approval batch. See `approveDeviceEverywhere`. */\n async passkeyLeafForThisDevice(): Promise<{ leaf: Uint8Array; nonce: bigint }> {\n const nonce = await this.adapter.getPasskeyNonce(this.address);\n return { leaf: this.adapter.passkeyLeaf(this.devicePubkey, nonce), nonce };\n }\n\n /** Submit `add_signer_via_passkey` given a (shared) assertion + this chain's\n * position in the batch. The assertion doesn't carry the passkey pubkey, so we\n * recover both candidates and pick the enrolled approver via the on-chain view\n * (no backend). Defaults to sponsoring through the paymaster. */\n async submitPasskeyApproval(\n assertion: PasskeyAssertion,\n leaves: Uint8Array[],\n leafIndex: number,\n nonce: bigint,\n submit?: (call: ChainCall) => Promise<{ transactionHash: string }>,\n ): Promise<{ transactionHash: string }> {\n const digest = webauthnDigest(assertion.authenticatorData, assertion.clientDataJSON);\n const candidates = recoverCandidatePublicKeys(assertion.r, assertion.s, digest);\n let yParity: boolean | null = null;\n for (const cand of candidates) {\n if (await this.adapter.isApprover(this.address, cand.publicKey)) {\n yParity = cand.yParity;\n break;\n }\n }\n if (yParity === null) {\n throw new Error(\"kit: this passkey is not a registered approver of the wallet\");\n }\n const call = this.adapter.buildAddSignerViaPasskey(\n this.address, this.devicePubkey, nonce, leaves, leafIndex, assertion, yParity,\n );\n if (submit) return submit(call);\n if (!this.paymaster) {\n throw new Error(\"kit: no paymaster configured — pass a `submit` relayer to approveThisDeviceWithPasskey\");\n }\n return paymasterExecuteDirect(this.paymaster, this.address, call);\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(\n code: string,\n opts?: ExecuteOptions,\n ): 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, opts);\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 network = STARKNET_ENV[opts.network];\n const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[network];\n if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${network}`);\n\n const provider = new RpcProvider({\n nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[network].rpcUrl,\n });\n const paymaster = new PaymasterRpc({\n nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[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 // Address discovery: prefer an explicit `address` (self-custodial recovery\n // — the caller recomputed it from (userId, appSalt) alone), else fall back\n // to the hosted registry. With the seed-only derivation, the address no\n // longer depends on the (lost) device pubkey, so the caller can always\n // recompute it without the backend.\n const address = opts.address ?? (await lookupAddress(opts, backendUrl, network));\n if (!address) {\n throw new Error(\"kit: no account found for this identity — nothing to recover\");\n }\n const existing = { address } as { address: string };\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/**\n * Resolve the wallet address for a user via the registry. Used by `recover()`\n * when the caller didn't pass `address` explicitly. With the seed-only\n * derivation the caller can recompute the address from (userId, appSalt) and\n * bypass this entirely — but the registry is still convenient for the common\n * case where the user has Cavos available.\n */\nasync function lookupAddress(\n opts: RecoveryOptions,\n backendUrl: string,\n network: StarknetNetwork,\n): Promise<string | null> {\n const registry =\n opts.registry ??\n (opts.appId\n ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network })\n : defaultRegistry);\n const existing = await registry.lookup(opts.identity.userId);\n return existing?.address ?? null;\n}\n\n/** A chain wallet that can approve THIS device via a batched WebAuthn assertion\n * (implemented by `Cavos` and `CavosSolana`). Classic Stellar uses a WebAuthn PRF\n * factor instead (`CavosStellar.approveThisDeviceWithPasskey`), so it is\n * not part of this batch. */\nexport interface PasskeyApprovable {\n readonly chain: string;\n readonly status: string;\n passkeyLeafForThisDevice(): Promise<{ leaf: Uint8Array; nonce: bigint }>;\n submitPasskeyApproval(\n assertion: PasskeyAssertion,\n leaves: Uint8Array[],\n leafIndex: number,\n nonce: bigint,\n ): Promise<{ transactionHash: string }>;\n}\n\n/**\n * Approve THIS device across several chains with a SINGLE passkey prompt. Each\n * chain is a separate account, so the device must be added per chain — but one\n * WebAuthn assertion over the batch challenge (`sha256(concat(leaves))`) suffices\n * for all of them. Only wallets whose status is `needs-device-approval` are\n * touched. Returns the per-chain tx hashes.\n *\n * await approveDeviceEverywhere([starknet, solana], passkey);\n */\nexport async function approveDeviceEverywhere(\n wallets: PasskeyApprovable[],\n passkey: PasskeySigner,\n): Promise<{ chain: string; transactionHash?: string; error?: string }[]> {\n const targets = wallets.filter((w) => w.status === \"needs-device-approval\");\n if (targets.length === 0) return [];\n const infos = await Promise.all(targets.map((w) => w.passkeyLeafForThisDevice()));\n const leaves = infos.map((i) => i.leaf);\n // ONE prompt: the passkey signs the batch challenge over every chain's leaf.\n const assertion = await passkey.assert(batchChallenge(leaves));\n // Submit every chain IN PARALLEL (they're independent accounts) with error\n // ISOLATION: one chain's relay/RPC failure must not abort the others. The same\n // assertion authorizes all of them, so this is a single user gesture that fans\n // out to every chain at once. Failures are reported, never thrown.\n const settled = await Promise.allSettled(\n targets.map((w, i) => w.submitPasskeyApproval(assertion, leaves, i, infos[i].nonce)),\n );\n return settled.map((r, i) =>\n r.status === 'fulfilled'\n ? { chain: targets[i].chain, transactionHash: r.value.transactionHash }\n : {\n chain: targets[i].chain,\n error: r.reason instanceof Error ? r.reason.message : String(r.reason),\n },\n );\n}\n\n/**\n * Sponsor a single call through the Cavos paymaster's `paymaster_executeDirectTransaction`\n * (AVNU-fork extension). In sponsored mode the forwarder runs a generic\n * `call_contract_syscall` (no SNIP-9 / device signature required), so the\n * passkey-authorized `add_signer_via_passkey` external is paid for by the\n * paymaster's relayer. The account's on-chain check (approver membership +\n * challenge binding) is the real authorization.\n */\nasync function paymasterExecuteDirect(\n paymaster: { url: string; apiKey?: string },\n userAddress: string,\n call: ChainCall,\n): Promise<{ transactionHash: string }> {\n const body = {\n jsonrpc: \"2.0\",\n id: 1,\n method: \"paymaster_executeDirectTransaction\",\n params: {\n transaction: {\n type: \"invoke\",\n invoke: {\n user_address: userAddress,\n execute_from_outside_call: {\n to: call.contractAddress,\n selector: hash.getSelectorFromName(call.entrypoint),\n calldata: call.calldata.map((c) => num.toHex(c)),\n },\n },\n },\n parameters: { version: \"0x1\", fee_mode: { mode: \"sponsored\" } },\n },\n };\n const res = await fetch(paymaster.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(paymaster.apiKey ? { \"x-paymaster-api-key\": paymaster.apiKey } : {}),\n },\n body: JSON.stringify(body),\n });\n const json = await res.json();\n if (json.error) {\n throw new Error(`kit: paymaster passkey approval failed: ${JSON.stringify(json.error)}`);\n }\n return { transactionHash: json.result?.transaction_hash ?? json.result?.tracking_id };\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","import { sha256 } from \"@noble/hashes/sha256\";\n\n/**\n * WebAuthn **PRF** factor for the classic-G envelope.\n *\n * Unlike the Soroban passkey path (which needs an on-chain-verifiable *assertion\n * signature*), the classic-G account only needs a stable 32-byte secret to wrap\n * the DEK — exactly what the WebAuthn PRF extension provides: for a given\n * credential + input salt the authenticator returns the same 32 bytes on every\n * device the passkey syncs to (iCloud Keychain / Google Password Manager), and\n * that secret is derived inside the authenticator and never derivable by Cavos or\n * OAuth. That makes it the ideal synced anchor to approve a new device or recover.\n *\n * `getSecret()` returns the raw PRF output; callers pass it to\n * `derivePasskeyKEK` (via `CavosStellar.enrollPasskey` /\n * `approveThisDeviceWithPasskey`). Keeping this class free of any DEK/KEK logic\n * lets the account class stay runtime-agnostic and unit-testable.\n */\n\nexport interface PasskeyPrfOptions {\n /** Relying-Party id (usually the eTLD+1). Defaults to `window.location.hostname`. */\n rpId?: string;\n /** Human-readable RP name shown in the OS passkey UI. */\n rpName?: string;\n}\n\nexport interface PasskeyPrfEnrollParams {\n /** Stable user handle for the credential (e.g. the account address or userId). */\n userId: string;\n /** Account name shown in the OS passkey UI (e.g. an email). */\n userName: string;\n displayName?: string;\n}\n\n/** Fixed PRF input salt — scopes the derived secret to the classic-G DEK factor.\n * Stable forever: changing it changes every existing user's passkey secret. */\nconst PRF_SALT = sha256(new TextEncoder().encode(\"cavos-stellar-prf-v1\"));\n\nexport class PasskeyPrf {\n private readonly rpId: string;\n private readonly rpName: string;\n\n constructor(opts: PasskeyPrfOptions = {}) {\n if (typeof window === \"undefined\" || !navigator.credentials) {\n throw new Error(\"kit/passkey-prf: WebAuthn is only available in a browser\");\n }\n this.rpId = opts.rpId ?? window.location.hostname;\n this.rpName = opts.rpName ?? this.rpId;\n if (isIpAddress(this.rpId)) {\n throw new Error(\n `kit/passkey-prf: passkeys can't use an IP address as the domain (\"${this.rpId}\"). ` +\n \"Use http://localhost, a real HTTPS domain, or a tunnel — or pass an explicit `rpId`.\",\n );\n }\n }\n\n /** True if this platform advertises a usable passkey (platform authenticator). */\n static async isSupported(): Promise<boolean> {\n if (typeof window === \"undefined\" || !window.PublicKeyCredential) return false;\n try {\n return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n } catch {\n return false;\n }\n }\n\n /**\n * Create a new synced, discoverable passkey with the PRF extension enabled, then\n * immediately read its PRF secret. Returns the credential id and the 32-byte\n * secret so the caller can enroll the passkey factor in one step. Some\n * authenticators don't return PRF results on create — in that case `secret` is\n * undefined and the caller should follow up with `getSecret()`.\n */\n async enroll(params: PasskeyPrfEnrollParams): Promise<{ credentialId: Uint8Array; secret?: Uint8Array }> {\n const cred = (await navigator.credentials.create({\n publicKey: {\n challenge: buf(crypto.getRandomValues(new Uint8Array(32))),\n rp: { id: this.rpId, name: this.rpName },\n user: {\n id: buf(userHandle(params.userId)),\n name: params.userName,\n displayName: params.displayName ?? params.userName,\n },\n pubKeyCredParams: [{ type: \"public-key\", alg: -7 }], // ES256 (P-256)\n authenticatorSelection: {\n residentKey: \"required\",\n requireResidentKey: true,\n userVerification: \"required\",\n },\n attestation: \"none\",\n extensions: { prf: { eval: { first: buf(PRF_SALT) } } } as AuthenticationExtensionsClientInputs,\n },\n })) as PublicKeyCredential | null;\n if (!cred) throw new Error(\"kit/passkey-prf: enrollment cancelled\");\n return { credentialId: new Uint8Array(cred.rawId), secret: readPrf(cred) };\n }\n\n /**\n * Get the passkey's 32-byte PRF secret. Uses discoverable credentials (no\n * `allowCredentials`), so it works from a brand-new browser — the OS shows the\n * synced passkey picker. Throws if the authenticator doesn't support PRF.\n */\n async getSecret(): Promise<Uint8Array> {\n const cred = (await navigator.credentials.get({\n publicKey: {\n challenge: buf(crypto.getRandomValues(new Uint8Array(32))),\n rpId: this.rpId,\n allowCredentials: [],\n userVerification: \"required\",\n extensions: { prf: { eval: { first: buf(PRF_SALT) } } } as AuthenticationExtensionsClientInputs,\n },\n })) as PublicKeyCredential | null;\n if (!cred) throw new Error(\"kit/passkey-prf: assertion cancelled\");\n const secret = readPrf(cred);\n if (!secret) {\n throw new Error(\n \"kit/passkey-prf: this authenticator did not return a PRF result — PRF is unsupported here\",\n );\n }\n return secret;\n }\n}\n\n/** Read the 32-byte PRF `first` result from a credential's extension results. */\nfunction readPrf(cred: PublicKeyCredential): Uint8Array | undefined {\n const results = (cred.getClientExtensionResults() as { prf?: { results?: { first?: ArrayBuffer } } }).prf\n ?.results?.first;\n return results ? new Uint8Array(results) : undefined;\n}\n\nfunction isIpAddress(host: string): boolean {\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host)) return true;\n if (host.includes(\":\")) return true;\n return false;\n}\n\nfunction userHandle(userId: string): Uint8Array {\n const bytes = new TextEncoder().encode(userId);\n return bytes.length <= 64 ? bytes : sha256(bytes);\n}\n\nfunction buf(bytes: Uint8Array): BufferSource {\n return bytes.slice() as unknown as BufferSource;\n}\n","import { sha256 } from \"@noble/hashes/sha256\";\nimport type { DevicePublicKey } from \"./DeviceSigner\";\nimport {\n base64urlEncode,\n challengeOffsetOf,\n derToRs,\n spkiToPublicKey,\n type PasskeyAssertion,\n} from \"../crypto/webauthn\";\n\nexport interface PasskeySignerOptions {\n /** Relying-Party id (usually the eTLD+1). Defaults to `window.location.hostname`. */\n rpId?: string;\n /** Human-readable RP name shown in the OS passkey UI. */\n rpName?: string;\n}\n\nexport interface PasskeyEnrollParams {\n /** Stable user handle for the credential (e.g. the account address or userId). */\n userId: string;\n /** Account name shown in the OS passkey UI (e.g. an email). */\n userName: string;\n displayName?: string;\n}\n\nexport interface EnrolledPasskey {\n publicKey: DevicePublicKey;\n credentialId: Uint8Array;\n}\n\n/**\n * Browser passkey signer. Creates a discoverable (resident) secp256r1 credential\n * that syncs across the user's devices (iCloud Keychain / Google Password\n * Manager), and produces WebAuthn assertions used to authorize `add_signer`.\n *\n * This is a step-up primitive: the app decides WHEN to enroll (e.g. after\n * onboarding, as a \"turn on device approvals\" / 2FA moment). Enrollment\n * registers the passkey on-chain as an approver; later, from any browser, an\n * assertion approves adding that browser's new device key.\n */\nexport class PasskeySigner {\n private readonly rpId: string;\n private readonly rpName: string;\n\n constructor(opts: PasskeySignerOptions = {}) {\n if (typeof window === \"undefined\" || !navigator.credentials) {\n throw new Error(\"kit/passkey: WebAuthn is only available in a browser\");\n }\n this.rpId = opts.rpId ?? window.location.hostname;\n this.rpName = opts.rpName ?? this.rpId;\n // WebAuthn requires the RP ID to be a registrable domain (or \"localhost\").\n // An IP address always fails with a cryptic \"invalid domain\" — surface an\n // actionable message instead (common when devs test over a LAN IP).\n if (isIpAddress(this.rpId)) {\n throw new Error(\n `kit/passkey: passkeys can't use an IP address as the domain (\"${this.rpId}\"). ` +\n \"Use http://localhost, a real HTTPS domain, or a tunnel (cloudflared/ngrok) — \" +\n \"or pass an explicit `rpId`. (The silent device key works over an IP; passkeys don't.)\",\n );\n }\n }\n\n /** True if this platform advertises a usable passkey (platform authenticator). */\n static async isSupported(): Promise<boolean> {\n if (typeof window === \"undefined\" || !window.PublicKeyCredential) return false;\n try {\n return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n } catch {\n return false;\n }\n }\n\n /** Create a new synced passkey and return its P-256 public key. */\n async enroll(params: PasskeyEnrollParams): Promise<EnrolledPasskey> {\n const challenge = crypto.getRandomValues(new Uint8Array(32));\n const cred = (await navigator.credentials.create({\n publicKey: {\n challenge: buf(challenge),\n rp: { id: this.rpId, name: this.rpName },\n user: {\n id: buf(userHandle(params.userId)),\n name: params.userName,\n displayName: params.displayName ?? params.userName,\n },\n pubKeyCredParams: [{ type: \"public-key\", alg: -7 }], // ES256 (P-256)\n authenticatorSelection: {\n residentKey: \"required\",\n requireResidentKey: true,\n userVerification: \"preferred\",\n },\n attestation: \"none\",\n },\n })) as PublicKeyCredential | null;\n if (!cred) throw new Error(\"kit/passkey: enrollment cancelled\");\n\n const response = cred.response as AuthenticatorAttestationResponse;\n const spki = new Uint8Array(response.getPublicKey()!);\n return { publicKey: spkiToPublicKey(spki), credentialId: new Uint8Array(cred.rawId) };\n }\n\n /**\n * Produce a WebAuthn assertion over `challenge` (a 32-byte value the caller\n * derives from the signer being added + the on-chain nonce). Uses discoverable\n * credentials — no `allowCredentials` — so it works on a brand-new browser.\n */\n async assert(challenge: Uint8Array): Promise<PasskeyAssertion> {\n const cred = (await navigator.credentials.get({\n publicKey: {\n challenge: buf(challenge),\n rpId: this.rpId,\n allowCredentials: [],\n userVerification: \"preferred\",\n },\n })) as PublicKeyCredential | null;\n if (!cred) throw new Error(\"kit/passkey: assertion cancelled\");\n\n const response = cred.response as AuthenticatorAssertionResponse;\n const authenticatorData = new Uint8Array(response.authenticatorData);\n const clientDataJSON = new Uint8Array(response.clientDataJSON);\n const { r, s } = derToRs(new Uint8Array(response.signature));\n const challengeOffset = challengeOffsetOf(clientDataJSON, base64urlEncode(challenge));\n return { authenticatorData, clientDataJSON, r, s, challengeOffset };\n }\n}\n\n/**\n * WebAuthn requires the user handle to be 1..64 bytes. `userId` may be longer\n * (e.g. a 66-char Starknet address), so hash anything over 64 bytes to a stable\n * 32-byte handle. The handle is opaque — only its stability matters.\n */\n/** True for IPv4/IPv6 literals — WebAuthn rejects these as an RP ID. */\nfunction isIpAddress(host: string): boolean {\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host)) return true; // IPv4\n if (host.includes(\":\")) return true; // IPv6 literal\n return false;\n}\n\nfunction userHandle(userId: string): Uint8Array {\n const bytes = new TextEncoder().encode(userId);\n return bytes.length <= 64 ? bytes : sha256(bytes);\n}\n\n/** Coerce a `Uint8Array` to the `BufferSource` the WebAuthn DOM types want\n * (works around the TS5.7 `ArrayBufferLike` vs `ArrayBuffer` mismatch). */\nfunction buf(bytes: Uint8Array): BufferSource {\n return bytes.slice() as unknown as BufferSource;\n}\n"]}