@qntx/wallet 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +145 -22
  2. package/dist/backup-CLzMs8DP.mjs +51 -0
  3. package/dist/backup-CLzMs8DP.mjs.map +1 -0
  4. package/dist/card.d.mts +12 -0
  5. package/dist/card.mjs +119 -0
  6. package/dist/card.mjs.map +1 -0
  7. package/dist/{chains-B-FmFmuV.d.mts → chains-u1M0CWkT.d.mts} +148 -31
  8. package/dist/chains.d.mts +11 -4
  9. package/dist/chains.mjs +19 -67
  10. package/dist/chains.mjs.map +1 -1
  11. package/dist/{channel-BLwce5hh.mjs → channel-BCZXU3pt.mjs} +105 -44
  12. package/dist/channel-BCZXU3pt.mjs.map +1 -0
  13. package/dist/check-C1fUpgva.mjs +193 -0
  14. package/dist/check-C1fUpgva.mjs.map +1 -0
  15. package/dist/{core-DaRwkTaV.mjs → core-Cx7p-0nG.mjs} +99 -19
  16. package/dist/core-Cx7p-0nG.mjs.map +1 -0
  17. package/dist/hardware-BL6zvhQh.d.mts +107 -0
  18. package/dist/hardware.d.mts +81 -0
  19. package/dist/hardware.mjs +446 -0
  20. package/dist/hardware.mjs.map +1 -0
  21. package/dist/host.d.mts +27 -19
  22. package/dist/host.mjs +440 -164
  23. package/dist/host.mjs.map +1 -1
  24. package/dist/{index-CEhrd0Pl.d.mts → index-UclKfprm.d.mts} +269 -19
  25. package/dist/index.d.mts +5 -3
  26. package/dist/index.mjs +3 -33
  27. package/dist/{internal-CAKfHjIg.mjs → internal-DwCus_Ws.mjs} +1 -6
  28. package/dist/internal-DwCus_Ws.mjs.map +1 -0
  29. package/dist/nostr.d.mts +2 -2
  30. package/dist/nostr.mjs +14 -14
  31. package/dist/nostr.mjs.map +1 -1
  32. package/dist/{protocol-fXHXJguP.mjs → protocol-DLE6lHmP.mjs} +475 -49
  33. package/dist/protocol-DLE6lHmP.mjs.map +1 -0
  34. package/dist/protocol.d.mts +5 -4
  35. package/dist/protocol.mjs +3 -3
  36. package/dist/secret-CbjbY5-f.mjs +25 -0
  37. package/dist/secret-CbjbY5-f.mjs.map +1 -0
  38. package/dist/sessions.d.mts +52 -0
  39. package/dist/sessions.mjs +71 -0
  40. package/dist/sessions.mjs.map +1 -0
  41. package/dist/spark.d.mts +3 -3
  42. package/dist/spark.mjs +5 -8
  43. package/dist/spark.mjs.map +1 -1
  44. package/dist/types-CRnacSqJ.d.mts +390 -0
  45. package/dist/types.d.mts +2 -2
  46. package/dist/types.mjs +7 -1
  47. package/dist/types.mjs.map +1 -1
  48. package/package.json +27 -13
  49. package/dist/channel-BLwce5hh.mjs.map +0 -1
  50. package/dist/core-DaRwkTaV.mjs.map +0 -1
  51. package/dist/index.mjs.map +0 -1
  52. package/dist/internal-CAKfHjIg.mjs.map +0 -1
  53. package/dist/protocol-fXHXJguP.mjs.map +0 -1
  54. package/dist/secret-CcjyF8D3.mjs +0 -205
  55. package/dist/secret-CcjyF8D3.mjs.map +0 -1
  56. package/dist/types-cAQAJBLi.d.mts +0 -260
package/dist/host.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.mjs","names":[],"sources":["../src/wallet.ts"],"sourcesContent":["/**\n * The host-facing `Wallet` (design/entry.mdx \"API\"): snapshot state, the core API groups, and the\n * glue between the kernel `Channel` and factor resolution. `connectKernel` is exported under the\n * `./host` subpath — reserved for host packages; applications must not use it. Protocol modules\n * (@qntx/wallet/nostr and future siblings) reach this wallet's channel through the registered\n * internals in internal.ts — never through the public type.\n */\n\nimport { base58, hex } from \"@scure/base\";\n\nimport { Channel } from \"./channel.ts\";\nimport type { MainPort, SetTimer } from \"./channel.ts\";\nimport {\n PASSKEY_PURPOSE_WALLET,\n passkeyName,\n requireCeremony,\n resolveFactor,\n resolveInitialFactor,\n vaultSaltBytes,\n walletSaltBytes,\n wireBytes,\n wirePassphrase,\n wireSecretText,\n resolveBackupFactor,\n resolveBackupUnlockFactor,\n defaultUnlockFactor,\n} from \"./factors.ts\";\nimport type { FactorMode, FactorSource, PasskeyCeremony, PrfResult } from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor, SignedEvent } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupApi,\n DataKeyApi,\n ExportedMnemonic,\n FactorInfo,\n InitialFactor,\n KeyInfo,\n KeysApi,\n LockReason,\n MnemonicDraft,\n PasskeyConfig,\n StatusPayload,\n UnlockFactor,\n VaultApi,\n Wallet,\n WalletInfo,\n WalletSnapshot,\n WalletsApi,\n} from \"./types.ts\";\n\nexport type ConnectOptions = {\n readonly spawn: () => MainPort;\n /** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */\n readonly factors: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly verifyEvent: (event: SignedEvent) => boolean;\n readonly ceremony: PasskeyCeremony | undefined;\n /** Timer source injected by the host package (globalThis timers on web/node). */\n readonly setTimer: SetTimer;\n /**\n * User-presence source: subscribes to activity signals and returns an unsubscribe the wallet\n * owns. Absent means the host has no presence signals (the kernel policy decides what counts).\n */\n readonly presence?: (onActivity: () => void) => () => void;\n /** Runs once inside `destroy()` — host-side cleanup (page listeners, timers). */\n readonly onDestroy?: () => void;\n};\n\n/** One `session.touch` at most per interval — the idle deadline slips at most this much early. */\nexport const PRESENCE_TOUCH_INTERVAL_MS = 30_000;\n\n/** Structural equality over plain snapshot data (validated protocol payloads only). */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((item, index) => deepEqual(item, b[index]))\n );\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every(\n (key) =>\n key in b &&\n deepEqual(\n (a as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n (b as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n ),\n )\n );\n}\n\nexport class KernelWallet implements Wallet {\n private readonly channel: Channel;\n private readonly factorMode: FactorMode;\n private readonly passkeyCfg: PasskeyConfig;\n private readonly ceremony: PasskeyCeremony | undefined;\n private readonly setTimer: SetTimer;\n private readonly onDestroy: (() => void) | undefined;\n private readonly unsubscribePresence: (() => void) | undefined;\n private presenceCooling = false;\n private cancelCooldown: (() => void) | undefined;\n private destroyed = false;\n\n private status: StatusPayload | undefined;\n private lockReason: LockReason | undefined;\n private verifying = 0;\n private snapshotValue: WalletSnapshot;\n private readonly listeners = new Set<() => void>();\n\n private constructor(options: ConnectOptions) {\n this.factorMode = options.factors;\n this.passkeyCfg = options.passkey;\n this.ceremony = options.ceremony;\n this.setTimer = options.setTimer;\n this.onDestroy = options.onDestroy;\n this.snapshotValue = {\n vault: \"uninitialized\",\n lockReason: undefined,\n verifying: false,\n factors: [],\n wallets: [],\n nostr: { keys: [] },\n importedKeys: [],\n backup: null,\n };\n this.channel = new Channel(\n options.spawn,\n {\n onStatus: (status) => {\n this.onStatus(status);\n },\n onLocked: (reason) => {\n this.lockReason = reason;\n this.markLocked();\n },\n onCrashed: () => {\n this.lockReason = \"crashed\";\n this.markLocked();\n },\n },\n options.setTimer,\n );\n // The wallet owns the subscription it creates: destroy() unsubscribes — no second owner.\n this.unsubscribePresence = options.presence?.(() => {\n this.onPresence();\n });\n registerInternals(this, {\n call: async (method, params, transfer) => this.channel.call(method, params, transfer),\n ready: async () => this.channel.ready,\n snapshot: () => this.snapshotValue,\n verifyEvent: options.verifyEvent,\n withVerifying: async (fn) => this.withVerifying(fn),\n resolveFactor: async (factor, transfer) => resolveFactor(this.factorSource, factor, transfer),\n createFactorParam: async (factor, transfer) => this.createFactorParam(factor, transfer),\n sessionOf: (result) => {\n this.sessionOf(result);\n },\n });\n }\n\n static async connect(options: ConnectOptions): Promise<KernelWallet> {\n const wallet = new KernelWallet(options);\n await wallet.channel.start();\n return wallet;\n }\n\n /** Runs a host-ceremony passkey call and adopts the returned session and wallet info. */\n private async hostPasskeyWallet(\n method: \"wallet.createWithPasskey\" | \"wallet.restoreWithPasskey\",\n result: PrfResult,\n factor: Factor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<WalletInfo> {\n const created = await this.channel.call(\n method,\n {\n ceremony: \"host\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfWallet: wireBytes(result.first, transfer, true),\n synced: result.synced,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n\n /**\n * Presence refresh, throttled to one touch per interval: once a touch fires, signals are ignored\n * until the cooldown elapses — no clock reads, just the injected timer. Touches only go out while\n * a session is held; failures are silent (a lock or respawn needs no handling).\n */\n private onPresence(): void {\n if (this.presenceCooling || this.destroyed || this.channel.session === undefined) {\n return;\n }\n this.presenceCooling = true;\n this.cancelCooldown = this.setTimer(PRESENCE_TOUCH_INTERVAL_MS, () => {\n this.presenceCooling = false;\n this.cancelCooldown = undefined;\n });\n void this.touchSession();\n }\n\n private async touchSession(): Promise<void> {\n try {\n await this.channel.call(\"session.touch\", null);\n } catch {\n // A racing lock or respawn needs no handling.\n }\n }\n\n /**\n * The worker is dead or replaced — no status will arrive from it, yet an unlocked vault is locked\n * now. Reflect that in the snapshot without waiting for the respawned kernel; other states\n * (uninitialized, corrupted, …) are the kernel's truth and stay untouched.\n */\n private markLocked(): void {\n if (this.status !== undefined && this.status.vault === \"unlocked\") {\n this.status = { ...this.status, vault: \"locked\" };\n }\n this.emit();\n }\n\n private onStatus(status: StatusPayload): void {\n if (this.lockReason === undefined && status.vault === \"locked\") {\n this.lockReason = \"cold-start\"; // locked at first sight, not by an action of ours\n }\n this.status = status;\n this.emit();\n }\n\n /**\n * Rebuilds the immutable snapshot and notifies subscribers — only when the content actually\n * changed (identical status events produce no new reference and no notification).\n */\n private emit(): void {\n const { status } = this;\n const next: WalletSnapshot = {\n vault: status === undefined ? \"uninitialized\" : status.vault,\n lockReason: this.lockReason,\n verifying: this.verifying > 0,\n factors: status === undefined ? [] : status.factors,\n wallets: status === undefined ? [] : status.wallets,\n nostr: { keys: status === undefined ? [] : status.nostr.keys },\n importedKeys: status === undefined ? [] : status.importedKeys,\n backup: status === undefined ? null : status.backup,\n };\n const current = this.snapshotValue;\n if (\n current.vault === next.vault &&\n current.lockReason === next.lockReason &&\n current.verifying === next.verifying &&\n deepEqual(current.factors, next.factors) &&\n deepEqual(current.wallets, next.wallets) &&\n deepEqual(current.nostr, next.nostr) &&\n deepEqual(current.importedKeys, next.importedKeys) &&\n deepEqual(current.backup, next.backup)\n ) {\n return;\n }\n this.snapshotValue = next;\n for (const listener of this.listeners) {\n listener();\n }\n }\n\n // Arrow properties: safe unbound, e.g. useSyncExternalStore(wallet.subscribe, wallet.getSnapshot).\n readonly getSnapshot = (): WalletSnapshot => this.snapshotValue;\n\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n private get factorSource(): FactorSource {\n return {\n mode: this.factorMode,\n passkey: this.passkeyCfg,\n ceremony: this.ceremony,\n factors: () => this.snapshotValue.factors,\n };\n }\n\n /** True while a ceremony or a factor-bearing request is in flight; drives `verifying`. */\n private async withVerifying<T>(fn: () => Promise<T>): Promise<T> {\n this.verifying++;\n this.emit();\n try {\n return await fn();\n } finally {\n this.verifying--;\n this.emit();\n }\n }\n\n private initialized(): boolean {\n return this.snapshotValue.vault !== \"uninitialized\";\n }\n\n /** The factor gate on create/import commands; keeps useless ceremonies from firing. */\n private async createFactorParam(\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<Factor | undefined> {\n if (this.initialized()) {\n if (factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n return undefined;\n }\n if (factor === undefined && this.factorMode === \"software\") {\n throw new WalletError(\"invalid-input\", \"an initial factor is required\");\n }\n return resolveInitialFactor(this.factorSource, factor, transfer);\n }\n\n private sessionOf(result: { readonly session: string }): void {\n this.channel.session = result.session;\n this.channel.flushStatus();\n }\n\n readonly vault: VaultApi = {\n unlock: async (factor?: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wire = await resolveFactor(\n this.factorSource,\n factor ?? defaultUnlockFactor(this.factorSource),\n transfer,\n );\n const result = await this.channel.call(\"vault.unlock\", { factor: wire }, transfer);\n this.sessionOf(result);\n }),\n // Host-side lock: immediate, no kernel round trip — fails pending calls, clears the session\n // and respawns the port. Idempotent: re-locking is a no-op.\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n lock: async (): Promise<void> => {\n this.channel.lockNow();\n this.markLocked();\n },\n addFactor: async (factor: InitialFactor, verify: UnlockFactor): Promise<FactorInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const wireFactor = await resolveInitialFactor(this.factorSource, factor, transfer);\n return this.channel.call(\n \"vault.addFactor\",\n { verify: wireVerify, factor: wireFactor },\n transfer,\n );\n }),\n removeFactor: async (id: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"vault.removeFactor\", { verify: wireVerify, id }, transfer);\n }),\n reset: async (): Promise<void> => {\n await this.channel.call(\"vault.reset\", null);\n },\n };\n\n readonly keys: KeysApi = {\n import: async (\n family: \"evm\" | \"solana\" | \"bitcoin\",\n secret: string | Uint8Array,\n ): Promise<KeyInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const decoded = decodeKeySecret(family, secret);\n try {\n return await this.channel.call(\n \"keys.import\",\n { family, secret: wireBytes(decoded, transfer) },\n transfer,\n );\n } finally {\n if (decoded !== secret) {\n decoded.fill(0);\n }\n }\n }),\n list: async (): Promise<ReadonlyArray<KeyInfo>> => this.channel.call(\"keys.list\", null, []),\n remove: async (keyId: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"keys.remove\", { verify: wireVerify, keyId }, transfer);\n }),\n export: async (keyId: string, verify: UnlockFactor): Promise<Uint8Array> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n return this.channel.call(\"keys.export\", { verify: wireVerify, keyId }, transfer);\n }),\n };\n\n readonly wallets: WalletsApi = {\n createWithPasskey: async (options: {\n readonly name: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const name = passkeyName(options.name);\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n // The kernel runs the platform ceremony: nothing secret crosses the channel.\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n rpName: this.passkeyCfg.rpName,\n name,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.create({\n purpose: \"wallet\",\n name,\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0); // the vault factor slot is not needed\n } else {\n factor = await resolveInitialFactor(this.factorSource, options.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.createWithPasskey\", result, factor, transfer);\n }),\n restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n const factor = await this.createFactorParam(options?.factor, transfer);\n const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.assert({\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n // The asserted credential must be a wallet-purpose passkey: a vault-purpose credential\n // would silently derive a different wallet. Rejected assertions never reach the kernel.\n if (result.userHandle?.[0] !== PASSKEY_PURPOSE_WALLET) {\n result.first.fill(0);\n result.second?.fill(0);\n throw new WalletError(\"wrong-passkey\", \"the passkey is not a wallet credential\");\n }\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options?.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0);\n } else {\n factor = await resolveInitialFactor(this.factorSource, options?.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.restoreWithPasskey\", result, factor, transfer);\n }),\n createMnemonic: async (options: {\n readonly words: 12 | 24;\n readonly factor?: InitialFactor;\n }): Promise<MnemonicDraft> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createMnemonic\",\n { words: options.words, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n const draftId = created.draft;\n return {\n words: new SingleUseSecret(created.words),\n quiz: created.quiz,\n confirm: async (\n answers: ReadonlyArray<string>,\n confirmOptions?: { readonly passphrase?: string },\n ): Promise<WalletInfo> => {\n const answerTransfer: ArrayBuffer[] = [];\n const encoded = answers.map((word) => wireSecretText(word, answerTransfer));\n const passphrase = wirePassphrase(confirmOptions?.passphrase, answerTransfer);\n const confirmed = await this.channel.call(\n \"wallet.confirmMnemonic\",\n { draft: draftId, answers: encoded, ...passphrase },\n answerTransfer,\n );\n this.sessionOf(confirmed);\n return confirmed.wallet;\n },\n discard: async (): Promise<void> => {\n await this.channel.call(\"wallet.discardMnemonic\", { draft: draftId });\n },\n };\n },\n importMnemonic: async (options: {\n readonly mnemonic: string;\n readonly passphrase?: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const mnemonic = wireSecretText(options.mnemonic, transfer);\n const passphrase = wirePassphrase(options.passphrase, transfer);\n const created = await this.channel.call(\n \"wallet.importMnemonic\",\n { mnemonic, ...passphrase, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n },\n exportMnemonic: async (walletId: string, verify: UnlockFactor): Promise<ExportedMnemonic> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const exported = await this.channel.call(\n \"wallet.exportMnemonic\",\n { verify: wireVerify, walletId },\n transfer,\n );\n return {\n mnemonic: new SingleUseSecret(exported.mnemonic),\n ...(exported.passphrase === undefined\n ? {}\n : { passphrase: new SingleUseSecret(exported.passphrase) }),\n };\n }),\n delete: async (walletId: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"wallet.delete\", { verify: wireVerify, walletId }, transfer);\n }),\n };\n\n readonly dataKeys: DataKeyApi = {\n get: async (purpose: string): Promise<Uint8Array> =>\n this.channel.call(\"dataKeys.get\", { purpose }),\n };\n\n readonly backup: BackupApi = {\n enable: async (options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, options.verify, transfer);\n const wireFactors = await Promise.all(\n options.factors.map(async (factor) =>\n resolveBackupFactor(this.factorSource, factor, transfer),\n ),\n );\n await this.channel.call(\n \"backup.enable\",\n { verify: wireVerify, factors: wireFactors },\n transfer,\n );\n }),\n update: async (): Promise<string> => {\n const result = await this.channel.call(\"backup.update\", null);\n return result.envelope;\n },\n disable: async (): Promise<void> => {\n await this.channel.call(\"backup.disable\", null);\n },\n restore: async (options: {\n readonly envelope: string;\n readonly backupFactor: UnlockFactor;\n readonly passphrases?: ReadonlyArray<{\n readonly walletId: string;\n readonly passphrase: string;\n }>;\n readonly factor?: InitialFactor;\n }): Promise<{\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly passphraseRequired: ReadonlyArray<string>;\n }> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const backupFactor = await resolveBackupUnlockFactor(\n this.factorSource,\n options.backupFactor,\n transfer,\n );\n const factor = await this.createFactorParam(options.factor, transfer);\n const passphrases = options.passphrases?.map(({ walletId, passphrase }) => ({\n walletId,\n passphrase: wireSecretText(passphrase, transfer),\n }));\n const result = await this.channel.call(\n \"backup.restore\",\n {\n envelope: options.envelope,\n backupFactor,\n ...(passphrases === undefined ? {} : { passphrases }),\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(result);\n return { wallets: result.wallets, passphraseRequired: result.passphraseRequired };\n }),\n };\n\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unsubscribePresence?.();\n this.cancelCooldown?.();\n this.onDestroy?.();\n this.channel.destroy();\n }\n}\n\n/**\n * `keys.import`'s `secret` in bytes: a string is the family's canonical text encoding — `0x` hex\n * for EVM, base58 for Solana — while a Uint8Array passes straight through to the kernel's checks.\n */\nfunction decodeKeySecret(\n family: \"evm\" | \"solana\" | \"bitcoin\",\n secret: string | Uint8Array,\n): Uint8Array {\n if (secret instanceof Uint8Array) {\n return secret;\n }\n if (family === \"evm\") {\n if (!/^0x[0-9a-fA-F]{64}$/.test(secret)) {\n throw new WalletError(\"invalid-input\", \"an EVM private key is 0x-prefixed 64-hex\");\n }\n return hex.decode(secret.slice(2));\n }\n if (family === \"solana\") {\n try {\n return base58.decode(secret);\n } catch {\n throw new WalletError(\"invalid-input\", \"a Solana private key is base58\");\n }\n }\n throw new WalletError(\"invalid-input\", `keys are not supported on ${family}`);\n}\n\n/**\n * Validates the passkey configuration: the RP identity and both PRF salts are permanent\n * identifiers, so an empty or colliding value is rejected here rather than producing unrecoverable\n * credentials later.\n */\nfunction checkPasskeyConfig(passkey: PasskeyConfig): void {\n const { rpId, rpName, walletSalt, vaultSalt, backupSalt } = passkey;\n if (\n rpId.length === 0 ||\n rpName.length === 0 ||\n walletSalt.length === 0 ||\n vaultSalt.length === 0 ||\n backupSalt.length === 0 ||\n walletSalt === vaultSalt ||\n backupSalt === vaultSalt ||\n backupSalt === walletSalt\n ) {\n throw new WalletError(\n \"invalid-input\",\n \"passkey config requires a non-empty rpId, rpName and two different salts\",\n );\n }\n}\n\n/**\n * Connects a kernel spawned by the host package and returns the host-facing `Wallet`. The first\n * spawn must deliver a status event before this resolves.\n */\nexport async function connectKernel(options: ConnectOptions): Promise<Wallet> {\n checkPasskeyConfig(options.passkey);\n return KernelWallet.connect(options);\n}\n"],"mappings":";;;;;;;;;;;;;;AAuEA,MAAa,6BAA6B;;AAG1C,SAAS,UAAU,GAAY,GAAqB;CAClD,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAO,MAAM,YAAY,MAAM,MACxE,OAAO;CAET,IAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAA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C;CACnC;CACA,IAAI,WAAW,UACb,IAAI;EACF,OAAO,OAAO,OAAO,MAAM;CAC7B,QAAQ;EACN,MAAM,IAAI,YAAY,iBAAiB,gCAAgC;CACzE;CAEF,MAAM,IAAI,YAAY,iBAAiB,6BAA6B,QAAQ;AAC9E;;;;;;AAOA,SAAS,mBAAmB,SAA8B;CACxD,MAAM,EAAE,MAAM,QAAQ,YAAY,WAAW,eAAe;CAC5D,IACE,KAAK,WAAW,KAChB,OAAO,WAAW,KAClB,WAAW,WAAW,KACtB,UAAU,WAAW,KACrB,WAAW,WAAW,KACtB,eAAe,aACf,eAAe,aACf,eAAe,YAEf,MAAM,IAAI,YACR,iBACA,0EACF;AAEJ;;;;;AAMA,eAAsB,cAAc,SAA0C;CAC5E,mBAAmB,QAAQ,OAAO;CAClC,OAAO,aAAa,QAAQ,OAAO;AACrC"}
1
+ {"version":3,"file":"host.mjs","names":[],"sources":["../src/factors.ts","../src/wallet.ts"],"sourcesContent":["/**\n * Factor plumbing for the host connector: public `UnlockFactor`/`InitialFactor` inputs become wire\n * `Factor` material, passkey material comes from the host's WebAuthn ceremony, and every secret\n * byte travels in a fresh exact-size buffer on the transfer list.\n */\nimport { base64urlnopad } from \"@scure/base\";\n\nimport type {\n BackupFactor,\n BackupUnlockFactor,\n Factor,\n MethodName,\n ParamsOf,\n ProtocolValue,\n SECRET_FIELDS,\n VerifyFactor as WireVerifyFactor,\n} from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupFactorInput,\n FactorInfo,\n InitialFactor,\n PasskeyConfig,\n UnlockFactor,\n VerifyFactor,\n} from \"./types.ts\";\n\nexport type PrfSalts = { readonly first: Uint8Array; readonly second?: Uint8Array };\n\n/** Purpose bytes stamped into the first byte of a credential's WebAuthn user handle. */\nexport const PASSKEY_PURPOSE_WALLET = 0x01;\nexport const PASSKEY_PURPOSE_VAULT = 0x02;\n\nexport type PrfResult = {\n readonly credentialId: Uint8Array;\n readonly first: Uint8Array;\n readonly second?: Uint8Array;\n /** The assertion's `userHandle` — its first byte declares the credential's purpose. */\n readonly userHandle?: Uint8Array;\n /** The credential survives this device: the authenticator data's BE and BS flags are both set. */\n readonly synced: boolean;\n};\n\n/**\n * The WebAuthn ceremony the host performs. Implementations throw `WalletError` — \"cancelled\" when\n * the user aborts, \"passkey-prf-unsupported\" when the credential cannot produce a PRF. `name` is\n * the new credential's display name, validated by the host before the call (1–64 characters).\n */\nexport type PasskeyCeremony = {\n readonly create: (input: {\n readonly purpose: \"wallet\" | \"vault\";\n readonly name: string;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n readonly assert: (input: {\n readonly credentialIds?: ReadonlyArray<Uint8Array>;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n};\n\n/**\n * Which vault factors a host offers: `hardware` (React Native — the platform keystore factors,\n * device and hardware, and omitted factors mean the silent device one) or `software` (web/node —\n * passkey and password). The kernel enforces the same rule; resolving here keeps a doomed request\n * from firing a ceremony.\n */\nexport type FactorMode = \"hardware\" | \"software\";\n\n/** What factor resolution needs from the wallet: config, the ceremony, live factor records. */\nexport type FactorSource = {\n readonly mode: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly ceremony: PasskeyCeremony | undefined;\n readonly factors: () => ReadonlyArray<FactorInfo>;\n /** Whether the vault currently requires a verifying unlock (no device factor). */\n readonly appLock: () => boolean;\n};\n\nfunction hardwareOnly(): WalletError {\n return new WalletError(\"unsupported\", \"this host unlocks only with the keystore factors\");\n}\n\nexport function noHardware(): WalletError {\n return new WalletError(\"unsupported\", \"keystore factors exist only on React Native\");\n}\n\n/** The factor `vault.unlock()` uses when the caller passes none. */\nexport function defaultUnlockFactor(source: FactorSource): UnlockFactor {\n if (source.mode === \"hardware\") {\n // Under app lock there is no device factor — the silent default would just report not-found.\n return source.appLock() ? { kind: \"hardware\" } : { kind: \"device\" };\n }\n return { kind: \"passkey\" };\n}\n\nexport function vaultSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.vaultSalt);\n}\n\nexport function walletSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.walletSalt);\n}\n\nexport function backupSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.backupSalt);\n}\n\n/**\n * The host-run backup passkey ceremony (web): the PRF is evaluated over `backupSalt`, producing\n * `prfBackup` instead of the vault `prf`. `credentialIds` scopes the assertion — sealing uses the\n * vault's own credentials; opening uses the envelope's.\n */\nasync function hostBackupPasskey(\n source: FactorSource,\n wire: SecretWire,\n credentialIds?: ReadonlyArray<Uint8Array>,\n): Promise<Extract<BackupFactor, { ceremony: \"host\" }>> {\n const ceremony = requireCeremony(source);\n const result = await ceremony.assert({\n credentialIds: credentialIds ?? passkeyCredentialIds(source),\n salts: { first: backupSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n ceremony: \"host\",\n credentialId: wire.bytes(result.credentialId),\n prfBackup: wire.bytes(result.first, true),\n };\n}\n\n/**\n * Resolves a public `BackupFactorInput` password arm. On a hardware host (React Native) the kernel\n * collects the password through its secure input — a supplied string is refused so the main runtime\n * never holds it, an absent one resolves to the `kernel` ceremony arm. On a software host the wire\n * carries the bytes and the string is required.\n */\nfunction backupPassword(\n source: FactorSource,\n factor: Extract<BackupFactorInput, { readonly kind: \"password\" }>,\n wire: SecretWire,\n):\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | { readonly kind: \"password\"; readonly ceremony: \"kernel\" } {\n if (source.mode === \"hardware\") {\n if (factor.password !== undefined) {\n throw new WalletError(\n \"unsupported\",\n \"on React Native the kernel collects the backup password itself\",\n );\n }\n return { kind: \"password\", ceremony: \"kernel\" };\n }\n if (factor.password === undefined) {\n throw new WalletError(\"invalid-input\", \"backup password factors need a password\");\n }\n return { kind: \"password\", password: wire.text(factor.password) };\n}\n\n/**\n * Resolves a public `BackupFactorInput` to a factor that seals a new backup key. A hardware host\n * lets the kernel register the protection credential itself; nothing secret crosses the channel.\n */\nexport async function resolveBackupFactor(\n source: FactorSource,\n factor: BackupFactorInput,\n wire: SecretWire,\n): Promise<BackupFactor> {\n if (factor.kind === \"password\") {\n return backupPassword(source, factor, wire);\n }\n if (source.mode === \"hardware\") {\n return {\n kind: \"passkey\",\n ceremony: \"kernel\",\n rpId: source.passkey.rpId,\n rpName: source.passkey.rpName,\n backupSalt: source.passkey.backupSalt,\n };\n }\n return hostBackupPasskey(source, wire);\n}\n\n/**\n * Resolves a public `UnlockFactor` to a factor that opens a backup envelope. `credentialIds` is the\n * envelope's own allow-list — a restored vault's passkey credentials are a different set (a fresh\n * vault has none).\n */\nexport async function resolveBackupUnlockFactor(\n source: FactorSource,\n factor: BackupFactorInput,\n wire: SecretWire,\n credentialIds?: ReadonlyArray<Uint8Array>,\n): Promise<BackupUnlockFactor> {\n if (factor.kind === \"password\") {\n return backupPassword(source, factor, wire);\n }\n if (source.mode === \"hardware\") {\n return {\n kind: \"passkey\",\n ceremony: \"kernel\",\n rpId: source.passkey.rpId,\n backupSalt: source.passkey.backupSalt,\n };\n }\n return hostBackupPasskey(source, wire, credentialIds);\n}\n\n/** Passkey credential ids of the current vault factors, for `assert`'s allowCredentials. */\nfunction passkeyCredentialIds(source: FactorSource): Uint8Array[] {\n return source\n .factors()\n .flatMap((factor) =>\n factor.kind === \"passkey\" ? [base64urlnopad.decode(factor.credentialId)] : [],\n );\n}\n\n/**\n * The secret buffers of one request. Every byte array that carries a secret to the kernel is placed\n * here in a fresh exact-size buffer (transferring must never detach caller-owned memory, and a\n * secret source is zeroed once copied); the channel either moves the whole set on the post's\n * transfer list or calls `wipe()`. A wire is never half-detached and never left resident.\n */\nexport class SecretWire {\n private readonly buffers: ArrayBuffer[] = [];\n private wiped = false;\n\n /**\n * A wire copy of `source`; `wipeSource` zeroes a secret original after copying. Once the wire is\n * wiped its request is over, so a late copy (a ceremony that settled after the build failed) is\n * zeroed at once instead of staying resident with nothing left to wipe it.\n */\n bytes(source: Uint8Array, wipeSource = false): Uint8Array {\n const wire = new Uint8Array(source);\n if (wipeSource) {\n source.fill(0);\n }\n if (this.wiped) {\n wire.fill(0);\n return wire;\n }\n this.buffers.push(wire.buffer);\n return wire;\n }\n\n /** A wire copy of a secret string (passwords, mnemonics, passphrases). */\n text(text: string): Uint8Array {\n return this.bytes(new TextEncoder().encode(text));\n }\n\n /** The `passphrase` wire field for a BIP-39 passphrase: absent for none (undefined or \"\"). */\n passphrase(text: string | undefined): { readonly passphrase?: Uint8Array } {\n return text === undefined || text === \"\" ? {} : { passphrase: this.text(text) };\n }\n\n /** Every buffer this wire recorded — the post's transfer list. */\n get transfer(): ArrayBuffer[] {\n return this.buffers;\n }\n\n /** Zeroes every recorded buffer still attached — already-transferred ones are gone. */\n wipe(): void {\n this.wiped = true;\n for (const buffer of this.buffers) {\n if (buffer.byteLength > 0) {\n new Uint8Array(buffer).fill(0);\n }\n }\n }\n}\n\n/**\n * Param field names whose bytes are secrets. Everything else on the wire — credential ids, public\n * keys, unsigned payloads, ciphertexts — is public material.\n */\nexport type SecretField = (typeof SECRET_FIELDS)[number];\n\n/* True when any field reachable through T's objects, arrays or union members is a SecretField. The\n `ProtocolValue extends T` stop keeps the walk out of the recursive wire type — a pass-through\n `params` field is its method's own validation domain, so the classifier treats it as public. */\ntype CarriesSecret<T> = ProtocolValue extends T\n ? false\n : T extends Uint8Array\n ? false\n : T extends ReadonlyArray<infer E>\n ? CarriesSecret<E>\n : T extends Readonly<Record<PropertyKey, unknown>>\n ? true extends {\n [K in keyof T]: K extends SecretField ? true : CarriesSecret<T[K]>;\n }[keyof T]\n ? true\n : false\n : false;\n\n/** Methods whose params can carry secret bytes — they may only be sent through callWithSecrets. */\nexport type SecretMethod = {\n [M in MethodName]: true extends CarriesSecret<ParamsOf<M>> ? M : never;\n}[MethodName];\n\n/** Methods whose params never carry secret bytes. */\nexport type PlainMethod = Exclude<MethodName, SecretMethod>;\n\n/** The raw byte shapes a wire value can carry: a byte view or a bare buffer. */\ntype BytesLike = Uint8Array | ArrayBufferLike;\n\n/**\n * Whether a value of `T` — null and undefined already removed — can hold raw bytes: T is bytes\n * itself, or a container (array, map, set) whose values can hold bytes through the same containers.\n * Object members are not walked here: they are named fields, which {@link BytesFieldOf} reports\n * instead.\n */\ntype HoldsBytes<T> =\n Extract<T, BytesLike> extends never\n ? T extends ReadonlyArray<infer E>\n ? HoldsBytes<NonNullable<E>>\n : T extends ReadonlyMap<unknown, infer V>\n ? HoldsBytes<NonNullable<V>>\n : T extends ReadonlySet<infer E>\n ? HoldsBytes<NonNullable<E>>\n : false\n : true;\n\n/**\n * Every field name under which T's values hold bytes, reached through objects, arrays, maps, sets,\n * union members and optional fields. A field counts when its own type holds bytes — a `Uint8Array`,\n * an `ArrayBuffer`, or a container of them — so a `ReadonlyMap<string, Uint8Array>` field names its\n * field, while a `ReadonlyArray<{ seed: Uint8Array }>` field names `seed`.\n */\nexport type BytesFieldOf<T> = T extends BytesLike\n ? never\n : T extends ReadonlyArray<infer E>\n ? BytesFieldOf<NonNullable<E>>\n : T extends ReadonlyMap<unknown, infer V>\n ? BytesFieldOf<NonNullable<V>>\n : T extends ReadonlySet<infer E>\n ? BytesFieldOf<NonNullable<E>>\n : T extends Readonly<Record<PropertyKey, unknown>>\n ? {\n [K in keyof T]-?: true extends HoldsBytes<NonNullable<T[K]>>\n ? K\n : BytesFieldOf<NonNullable<T[K]>>;\n }[keyof T]\n : never;\n\n/**\n * Param byte fields that are public material: credential ids, public keys, ciphertexts, unsigned\n * payloads, hashes and signature shares.\n */\nexport type PublicBytesField =\n | \"adaptorPublicKey\"\n | \"binding\"\n | \"challenge\"\n | \"ciphertext\"\n | \"ciphertexts\"\n | \"cbor\"\n | \"connectorTx\"\n | \"credentialId\"\n | \"data\"\n | \"exitTx\"\n | \"hashLockPublicKey\"\n | \"hiding\"\n | \"identityPublicKey\"\n | \"invoice\"\n | \"limits\"\n | \"message\"\n | \"ownerPublicKey\"\n | \"package\"\n | \"params\"\n | \"partialTransaction\"\n | \"paymentHash\"\n | \"psbt\"\n | \"rawData\"\n | \"publicKey\"\n | \"receiverIdentityPublicKey\"\n | \"script\"\n | \"secretCipher\"\n | \"signatureShare\"\n | \"sspSignature\"\n | \"tokenIdentifier\"\n | \"transaction\"\n | \"txid\"\n | \"verifyingKey\";\n\n/**\n * `never` while every params byte field is classified. A new `Uint8Array` params field lands here,\n * failing the type test until it joins {@link SecretField} (secret bytes) or {@link PublicBytesField}\n * (public material).\n */\nexport type UnclassifiedBytesField = Exclude<\n { [M in MethodName]: BytesFieldOf<ParamsOf<M>> }[MethodName],\n SecretField | PublicBytesField\n>;\n\nexport function requireCeremony(source: FactorSource): PasskeyCeremony {\n if (source.ceremony === undefined) {\n throw new WalletError(\"unsupported\", \"no passkey ceremony is configured\");\n }\n return source.ceremony;\n}\n\n/** A passkey credential's display name: trimmed, 1–64 UTF-16 code units, else invalid-input. */\nexport function passkeyName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > 64) {\n throw new WalletError(\"invalid-input\", \"the passkey name must be 1–64 characters\");\n }\n return trimmed;\n}\n\n/**\n * Resolves a public `UnlockFactor` to wire factor material. `wire` collects every buffer the port\n * must move. Ceremony errors surface as they are (cancelled / passkey-prf-unsupported).\n */\nexport async function resolveFactor(\n source: FactorSource,\n factor: UnlockFactor,\n wire: SecretWire,\n): Promise<Factor> {\n if (source.mode === \"hardware\") {\n if (factor.kind !== \"device\" && factor.kind !== \"hardware\") {\n throw hardwareOnly();\n }\n return { kind: factor.kind };\n }\n if (factor.kind === \"hardware\" || factor.kind === \"device\") {\n throw noHardware();\n }\n if (factor.kind === \"password\") {\n return { kind: \"password\", password: wire.text(factor.password) };\n }\n const ceremony = requireCeremony(source);\n const result = await ceremony.assert({\n credentialIds: passkeyCredentialIds(source),\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wire.bytes(result.credentialId),\n prf: wire.bytes(result.first, true),\n };\n}\n\n/**\n * The fail-closed gate on every verify parameter: a `device` factor proves no presence, so it can\n * never verify — rejected here before any ceremony, and again by the wire validator and the\n * kernel's `verifyFactor`.\n */\nexport async function resolveVerifyFactor(\n source: FactorSource,\n factor: VerifyFactor,\n wire: SecretWire,\n): Promise<WireVerifyFactor> {\n if ((factor as UnlockFactor).kind === \"device\") {\n throw new WalletError(\"invalid-input\", \"the device factor cannot verify\");\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- device was rejected above\n return (await resolveFactor(source, factor, wire)) as WireVerifyFactor;\n}\n\n/**\n * Resolves a public `InitialFactor` (a factor being created). For `create/restoreWithPasskey` the\n * default passkey factor reuses the wallet ceremony's own credential and `second` PRF output; a\n * hardware host chooses its own vault factors (the wire `device` marker lets the kernel build the\n * device + hardware set) and drops that output.\n */\nexport async function resolveInitialFactor(\n source: FactorSource,\n factor: InitialFactor | undefined,\n wire: SecretWire,\n walletCeremony?: PrfResult,\n): Promise<Factor> {\n if (source.mode === \"hardware\") {\n walletCeremony?.second?.fill(0);\n if (factor !== undefined) {\n throw new WalletError(\"unsupported\", \"this host chooses its own vault factors\");\n }\n return { kind: \"device\" };\n }\n if (factor === undefined || factor.kind === \"passkey\") {\n const name = factor === undefined ? undefined : passkeyName(factor.name);\n if (walletCeremony !== undefined) {\n const { second } = walletCeremony;\n if (second === undefined) {\n throw new WalletError(\n \"passkey-prf-unsupported\",\n \"the ceremony returned no vault PRF output\",\n );\n }\n return {\n kind: \"passkey\",\n credentialId: wire.bytes(walletCeremony.credentialId),\n prf: wire.bytes(second, true),\n };\n }\n if (name === undefined) {\n // No caller reaches this today (createFactorParam requires a factor), but the ceremony\n // contract needs a name — fail closed rather than inventing one.\n throw new WalletError(\"invalid-input\", \"a passkey factor requires a name\");\n }\n const result = await requireCeremony(source).create({\n purpose: \"vault\",\n name,\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wire.bytes(result.credentialId),\n prf: wire.bytes(result.first, true),\n };\n }\n if (factor.kind === \"password\") {\n walletCeremony?.second?.fill(0); // the passkey vault factor is not needed\n return { kind: \"password\", password: wire.text(factor.password) };\n }\n throw noHardware();\n}\n","/**\n * The host-facing `Wallet` (design/entry.mdx \"API\"): snapshot state, the core API groups, and the\n * glue between the kernel `Channel` and factor resolution. `connectKernel` is exported under the\n * `./host` subpath — reserved for host packages; applications must not use it. Protocol modules\n * (@qntx/wallet/nostr and future siblings) reach this wallet's channel through the registered\n * internals in internal.ts — never through the public type.\n */\n\nimport { base58, hex } from \"@scure/base\";\n\nimport { backupPasskeyCredentialIds } from \"./backup.ts\";\nimport { Channel } from \"./channel.ts\";\nimport type { MainPort, SetTimer } from \"./channel.ts\";\nimport {\n defaultUnlockFactor,\n noHardware,\n PASSKEY_PURPOSE_WALLET,\n passkeyName,\n requireCeremony,\n resolveBackupFactor,\n resolveBackupUnlockFactor,\n resolveFactor,\n resolveInitialFactor,\n resolveVerifyFactor,\n SecretWire,\n vaultSaltBytes,\n walletSaltBytes,\n} from \"./factors.ts\";\nimport type {\n FactorMode,\n FactorSource,\n PasskeyCeremony,\n PrfResult,\n SecretMethod,\n} from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor, ParamsOf, ResultOf, SignedEvent } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupFactorInput,\n BackupApi,\n DataKeyApi,\n ExportedMnemonic,\n FactorInfo,\n InitialFactor,\n KeyInfo,\n KeysApi,\n LockReason,\n MnemonicDraft,\n PasskeyConfig,\n StatusPayload,\n UnlockFactor,\n VaultApi,\n VaultWalletInfo,\n VerifyFactor,\n Wallet,\n WalletSnapshot,\n WalletsApi,\n} from \"./types.ts\";\n\nexport type ConnectOptions = {\n readonly spawn: () => MainPort;\n /** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */\n readonly factors: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly verifyEvent: (event: SignedEvent) => boolean;\n readonly ceremony: PasskeyCeremony | undefined;\n /** Timer source injected by the host package (globalThis timers on web/node). */\n readonly setTimer: SetTimer;\n /**\n * User-presence source: subscribes to activity signals and returns an unsubscribe the wallet\n * owns. Absent means the host has no presence signals (the kernel policy decides what counts).\n */\n readonly presence?: (onActivity: () => void) => () => void;\n /** Runs once inside `destroy()` — host-side cleanup (page listeners, timers). */\n readonly onDestroy?: () => void;\n};\n\n/** One `session.touch` at most per interval — the idle deadline slips at most this much early. */\nexport const PRESENCE_TOUCH_INTERVAL_MS = 30_000;\n\n/** Structural equality over plain snapshot data (validated protocol payloads only). */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((item, index) => deepEqual(item, b[index]))\n );\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every(\n (key) =>\n key in b &&\n deepEqual(\n (a as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n (b as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n ),\n )\n );\n}\n\nexport class KernelWallet implements Wallet {\n private readonly channel: Channel;\n private readonly factorMode: FactorMode;\n private readonly passkeyCfg: PasskeyConfig;\n private readonly ceremony: PasskeyCeremony | undefined;\n private readonly setTimer: SetTimer;\n private readonly onDestroy: (() => void) | undefined;\n private readonly unsubscribePresence: (() => void) | undefined;\n private presenceCooling = false;\n private cancelCooldown: (() => void) | undefined;\n private destroyed = false;\n\n private status: StatusPayload | undefined;\n private lockReason: LockReason | undefined;\n private verifying = 0;\n private snapshotValue: WalletSnapshot;\n private readonly listeners = new Set<() => void>();\n\n private constructor(options: ConnectOptions) {\n this.factorMode = options.factors;\n this.passkeyCfg = options.passkey;\n this.ceremony = options.ceremony;\n this.setTimer = options.setTimer;\n this.onDestroy = options.onDestroy;\n this.snapshotValue = {\n vault: \"uninitialized\",\n lockReason: undefined,\n verifying: false,\n appLock: false,\n verification: \"unavailable\",\n factors: [],\n wallets: [],\n nostr: { keys: [] },\n importedKeys: [],\n backup: null,\n blindSigning: false,\n };\n this.channel = new Channel(\n options.spawn,\n {\n onStatus: (status) => {\n this.onStatus(status);\n },\n onLocked: (reason) => {\n this.lockReason = reason;\n this.markLocked();\n },\n onCrashed: () => {\n this.lockReason = \"crashed\";\n this.markLocked();\n },\n },\n options.setTimer,\n );\n // The wallet owns the subscription it creates: destroy() unsubscribes — no second owner.\n this.unsubscribePresence = options.presence?.(() => {\n this.onPresence();\n });\n registerInternals(this, {\n call: async (method, params) => this.channel.call(method, params),\n secretCall: async (method, build) => this.secretCall(method, build),\n ready: async () => this.channel.ready,\n snapshot: () => this.snapshotValue,\n verifyEvent: options.verifyEvent,\n withVerifying: async (fn) => this.withVerifying(fn),\n resolveVerifyFactor: async (factor, wire) =>\n resolveVerifyFactor(this.factorSource, factor, wire),\n });\n }\n\n static async connect(options: ConnectOptions): Promise<KernelWallet> {\n const wallet = new KernelWallet(options);\n await wallet.channel.start();\n return wallet;\n }\n\n /**\n * One request whose params carry secret bytes: `build` places them on a fresh wire, a build\n * failure wipes it, and the channel either transfers it or wipes it from there.\n */\n private async secretCall<M extends SecretMethod>(\n method: M,\n build: (wire: SecretWire) => ParamsOf<M> | Promise<ParamsOf<M>>,\n ): Promise<ResultOf<M>> {\n const wire = new SecretWire();\n let params: ParamsOf<M>;\n try {\n params = await build(wire);\n } catch (error) {\n wire.wipe();\n throw error;\n }\n return this.channel.callWithSecrets(method, params, wire);\n }\n\n /** The host-ceremony arm of a create/restoreWithPasskey request, with `result` on the wire. */\n private hostPasskeyParams(\n wire: SecretWire,\n result: PrfResult,\n factor: Factor | undefined,\n ): {\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfWallet: Uint8Array;\n readonly synced: boolean;\n readonly factor?: Factor;\n } {\n return {\n ceremony: \"host\",\n credentialId: wire.bytes(result.credentialId),\n prfWallet: wire.bytes(result.first, true),\n synced: result.synced,\n ...(factor === undefined ? {} : { factor }),\n };\n }\n\n /**\n * Presence refresh, throttled to one touch per interval: once a touch fires, signals are ignored\n * until the cooldown elapses — no clock reads, just the injected timer. Touches only go out while\n * a session is held; failures are silent (a lock or respawn needs no handling).\n */\n private onPresence(): void {\n if (this.presenceCooling || this.destroyed || this.channel.session === undefined) {\n return;\n }\n this.presenceCooling = true;\n this.cancelCooldown = this.setTimer(PRESENCE_TOUCH_INTERVAL_MS, () => {\n this.presenceCooling = false;\n this.cancelCooldown = undefined;\n });\n void this.touchSession();\n }\n\n private async touchSession(): Promise<void> {\n try {\n await this.channel.call(\"session.touch\", null);\n } catch {\n // A racing lock or respawn needs no handling.\n }\n }\n\n /**\n * The worker is dead or replaced — no status will arrive from it, yet an unlocked vault is locked\n * now. Reflect that in the snapshot without waiting for the respawned kernel; other states\n * (uninitialized, corrupted, …) are the kernel's truth and stay untouched.\n */\n private markLocked(): void {\n if (this.status !== undefined && this.status.vault === \"unlocked\") {\n this.status = { ...this.status, vault: \"locked\" };\n }\n this.emit();\n }\n\n private onStatus(status: StatusPayload): void {\n if (this.lockReason === undefined && status.vault === \"locked\") {\n this.lockReason = \"cold-start\"; // locked at first sight, not by an action of ours\n }\n this.status = status;\n this.emit();\n }\n\n /**\n * Rebuilds the immutable snapshot and notifies subscribers — only when the content actually\n * changed (identical status events produce no new reference and no notification).\n */\n private emit(): void {\n const { status } = this;\n const next: WalletSnapshot = {\n vault: status === undefined ? \"uninitialized\" : status.vault,\n lockReason: this.lockReason,\n verifying: this.verifying > 0,\n appLock: status === undefined ? false : status.appLock,\n verification: status === undefined ? \"unavailable\" : status.verification,\n factors: status === undefined ? [] : status.factors,\n wallets: status === undefined ? [] : status.wallets,\n nostr: { keys: status === undefined ? [] : status.nostr.keys },\n importedKeys: status === undefined ? [] : status.importedKeys,\n backup: status === undefined ? null : status.backup,\n blindSigning: status === undefined ? false : status.blindSigning,\n };\n const current = this.snapshotValue;\n if (\n current.vault === next.vault &&\n current.lockReason === next.lockReason &&\n current.verifying === next.verifying &&\n current.appLock === next.appLock &&\n current.verification === next.verification &&\n deepEqual(current.factors, next.factors) &&\n deepEqual(current.wallets, next.wallets) &&\n deepEqual(current.nostr, next.nostr) &&\n deepEqual(current.importedKeys, next.importedKeys) &&\n deepEqual(current.backup, next.backup) &&\n current.blindSigning === next.blindSigning\n ) {\n return;\n }\n this.snapshotValue = next;\n for (const listener of this.listeners) {\n listener();\n }\n }\n\n // Arrow properties: safe unbound, e.g. useSyncExternalStore(wallet.subscribe, wallet.getSnapshot).\n readonly getSnapshot = (): WalletSnapshot => this.snapshotValue;\n\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n private get factorSource(): FactorSource {\n return {\n mode: this.factorMode,\n passkey: this.passkeyCfg,\n ceremony: this.ceremony,\n factors: () => this.snapshotValue.factors,\n appLock: () => this.snapshotValue.appLock,\n };\n }\n\n /** True while a ceremony or a factor-bearing request is in flight; drives `verifying`. */\n private async withVerifying<T>(fn: () => Promise<T>): Promise<T> {\n this.verifying++;\n this.emit();\n try {\n return await fn();\n } finally {\n this.verifying--;\n this.emit();\n }\n }\n\n private initialized(): boolean {\n return this.snapshotValue.vault !== \"uninitialized\";\n }\n\n /**\n * Locally decidable rejections for a software host's create/restore factor. Runs before the\n * WebAuthn ceremony so a doomed call never prompts — and again inside the request build, because\n * the vault may have initialized while the ceremony was pending.\n */\n private checkSoftwareFactor(factor: InitialFactor | undefined): void {\n if (factor === undefined) {\n return;\n }\n if (this.initialized()) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n if (factor.kind !== \"passkey\" && factor.kind !== \"password\") {\n // An untyped caller can still hand a keystore factor to a software host.\n throw noHardware();\n }\n if (factor.kind === \"passkey\") {\n passkeyName(factor.name);\n }\n }\n\n /** The factor gate on create/import commands; keeps useless ceremonies from firing. */\n private async createFactorParam(\n factor: InitialFactor | undefined,\n wire: SecretWire,\n ): Promise<Factor | undefined> {\n if (this.initialized()) {\n if (factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n return undefined;\n }\n if (factor === undefined && this.factorMode === \"software\") {\n throw new WalletError(\"invalid-input\", \"an initial factor is required\");\n }\n return resolveInitialFactor(this.factorSource, factor, wire);\n }\n\n private sessionOf(result: { readonly session: string }): void {\n this.channel.session = result.session;\n this.channel.flushStatus();\n }\n\n readonly vault: VaultApi = {\n unlock: async (factor?: UnlockFactor): Promise<void> => {\n const resolved = factor ?? defaultUnlockFactor(this.factorSource);\n const run = async (): Promise<void> => {\n const result = await this.secretCall(\"vault.unlock\", async (wire) => ({\n factor: await resolveFactor(this.factorSource, resolved, wire),\n }));\n this.sessionOf(result);\n };\n // A device unlock shows no UI — the snapshot never marks it verifying.\n await (resolved.kind === \"device\" ? run() : this.withVerifying(run));\n },\n // Host-side lock: immediate, no kernel round trip — fails pending calls, clears the session\n // and respawns the port. Idempotent: re-locking is a no-op.\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n lock: async (): Promise<void> => {\n this.channel.lockNow();\n this.markLocked();\n },\n addFactor: async (factor: InitialFactor, verify: VerifyFactor): Promise<FactorInfo> =>\n this.withVerifying(async () =>\n this.secretCall(\"vault.addFactor\", async (wire) => ({\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n factor: await resolveInitialFactor(this.factorSource, factor, wire),\n })),\n ),\n removeFactor: async (id: string, verify: VerifyFactor): Promise<void> =>\n this.withVerifying(async () => {\n await this.secretCall(\"vault.removeFactor\", async (wire) => ({\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n id,\n }));\n }),\n enrolVerification: async (): Promise<void> =>\n this.withVerifying(async () => {\n await this.channel.call(\"vault.enrolVerification\", null);\n }),\n setAppLock: async (enabled: boolean, verify: VerifyFactor): Promise<void> =>\n this.withVerifying(async () => {\n await this.secretCall(\"vault.setAppLock\", async (wire) => ({\n enabled,\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n }));\n }),\n setBlindSigning: async (enabled: boolean, verify: VerifyFactor): Promise<void> =>\n this.withVerifying(async () => {\n await this.secretCall(\"vault.setBlindSigning\", async (wire) => ({\n enabled,\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n }));\n }),\n reset: async (): Promise<void> => {\n await this.channel.call(\"vault.reset\", null);\n },\n };\n\n readonly keys: KeysApi = {\n import: async (\n family: \"evm\" | \"solana\" | \"bitcoin\" | \"tron\",\n secret: string | Uint8Array,\n ): Promise<KeyInfo> =>\n this.withVerifying(async () => {\n const decoded = decodeKeySecret(family, secret);\n try {\n return await this.secretCall(\"keys.import\", (wire) => ({\n family,\n secret: wire.bytes(decoded),\n }));\n } finally {\n if (decoded !== secret) {\n decoded.fill(0);\n }\n }\n }),\n list: async (): Promise<ReadonlyArray<KeyInfo>> => this.channel.call(\"keys.list\", null),\n remove: async (keyId: string, verify: VerifyFactor): Promise<void> =>\n this.withVerifying(async () => {\n await this.secretCall(\"keys.remove\", async (wire) => ({\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n keyId,\n }));\n }),\n export: async (keyId: string, verify: VerifyFactor): Promise<Uint8Array> =>\n this.withVerifying(async () =>\n this.secretCall(\"keys.export\", async (wire) => ({\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n keyId,\n })),\n ),\n };\n\n readonly wallets: WalletsApi = {\n createWithPasskey: async (options: {\n readonly name: string;\n readonly factor?: InitialFactor;\n }): Promise<VaultWalletInfo> =>\n this.withVerifying(async () => {\n const name = passkeyName(options.name);\n if (this.factorMode === \"hardware\") {\n // The kernel runs the platform ceremony: nothing secret crosses the channel.\n const created = await this.secretCall(\"wallet.createWithPasskey\", async (wire) => {\n const factor = await this.createFactorParam(options.factor, wire);\n return {\n ceremony: \"kernel\" as const,\n rpId: this.passkeyCfg.rpId,\n rpName: this.passkeyCfg.rpName,\n name,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n };\n });\n this.sessionOf(created);\n return created.wallet;\n }\n this.checkSoftwareFactor(options.factor);\n const ceremony = requireCeremony(this.factorSource);\n const created = await this.secretCall(\"wallet.createWithPasskey\", async (wire) => {\n const result = await ceremony.create({\n purpose: \"wallet\",\n name,\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n try {\n this.checkSoftwareFactor(options.factor);\n const factor = this.initialized()\n ? undefined\n : await resolveInitialFactor(this.factorSource, options.factor, wire, result);\n return this.hostPasskeyParams(wire, result, factor);\n } finally {\n result.first.fill(0);\n result.second?.fill(0);\n }\n });\n this.sessionOf(created);\n return created.wallet;\n }),\n restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<VaultWalletInfo> =>\n this.withVerifying(async () => {\n if (this.factorMode === \"hardware\") {\n const created = await this.secretCall(\"wallet.restoreWithPasskey\", async (wire) => {\n const factor = await this.createFactorParam(options?.factor, wire);\n return {\n ceremony: \"kernel\" as const,\n rpId: this.passkeyCfg.rpId,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n };\n });\n this.sessionOf(created);\n return created.wallet;\n }\n this.checkSoftwareFactor(options?.factor);\n const ceremony = requireCeremony(this.factorSource);\n const created = await this.secretCall(\"wallet.restoreWithPasskey\", async (wire) => {\n const result = await ceremony.assert({\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n try {\n // The asserted credential must be a wallet-purpose passkey: a vault-purpose\n // credential would silently derive a different wallet. Rejected assertions\n // never reach the kernel.\n if (result.userHandle?.[0] !== PASSKEY_PURPOSE_WALLET) {\n throw new WalletError(\"wrong-passkey\", \"the passkey is not a wallet credential\");\n }\n this.checkSoftwareFactor(options?.factor);\n const factor = this.initialized()\n ? undefined\n : await resolveInitialFactor(this.factorSource, options?.factor, wire, result);\n return this.hostPasskeyParams(wire, result, factor);\n } finally {\n result.first.fill(0);\n result.second?.fill(0);\n }\n });\n this.sessionOf(created);\n return created.wallet;\n }),\n createMnemonic: async (options: {\n readonly words: 12 | 24;\n readonly factor?: InitialFactor;\n }): Promise<MnemonicDraft> => {\n const created = await this.secretCall(\"wallet.createMnemonic\", async (wire) => {\n const factor = await this.createFactorParam(options.factor, wire);\n return { words: options.words, ...(factor === undefined ? {} : { factor }) };\n });\n const draftId = created.draft;\n return {\n words: new SingleUseSecret(created.words),\n quiz: created.quiz,\n confirm: async (\n answers: ReadonlyArray<string>,\n confirmOptions?: { readonly passphrase?: string },\n ): Promise<VaultWalletInfo> => {\n const confirmed = await this.secretCall(\"wallet.confirmMnemonic\", (wire) => ({\n draft: draftId,\n answers: answers.map((word) => wire.text(word)),\n ...wire.passphrase(confirmOptions?.passphrase),\n }));\n this.sessionOf(confirmed);\n return confirmed.wallet;\n },\n discard: async (): Promise<void> => {\n await this.channel.call(\"wallet.discardMnemonic\", { draft: draftId });\n },\n };\n },\n importMnemonic: async (options: {\n readonly mnemonic: string;\n readonly passphrase?: string;\n readonly factor?: InitialFactor;\n }): Promise<VaultWalletInfo> => {\n const created = await this.secretCall(\"wallet.importMnemonic\", async (wire) => {\n const factor = await this.createFactorParam(options.factor, wire);\n return {\n mnemonic: wire.text(options.mnemonic),\n ...wire.passphrase(options.passphrase),\n ...(factor === undefined ? {} : { factor }),\n };\n });\n this.sessionOf(created);\n return created.wallet;\n },\n exportMnemonic: async (walletId: string, verify: VerifyFactor): Promise<ExportedMnemonic> =>\n this.withVerifying(async () => {\n const exported = await this.secretCall(\"wallet.exportMnemonic\", async (wire) => ({\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n walletId,\n }));\n return {\n mnemonic: new SingleUseSecret(exported.mnemonic),\n ...(exported.passphrase === undefined\n ? {}\n : { passphrase: new SingleUseSecret(exported.passphrase) }),\n };\n }),\n delete: async (walletId: string, verify: VerifyFactor): Promise<void> =>\n this.withVerifying(async () => {\n await this.secretCall(\"wallet.delete\", async (wire) => ({\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n walletId,\n }));\n }),\n };\n\n readonly dataKeys: DataKeyApi = {\n get: async (purpose: string): Promise<Uint8Array> =>\n this.channel.call(\"dataKeys.get\", { purpose }),\n };\n\n readonly backup: BackupApi = {\n enable: async (options: {\n readonly verify: VerifyFactor;\n readonly factors: ReadonlyArray<BackupFactorInput>;\n }): Promise<void> =>\n this.withVerifying(async () => {\n await this.secretCall(\"backup.enable\", async (wire) => {\n const verify = await resolveVerifyFactor(this.factorSource, options.verify, wire);\n // One ceremony at a time: a browser runs one WebAuthn request at once, and a failed\n // factor must not leave another ceremony still writing secrets to the wire.\n const factors: Array<Awaited<ReturnType<typeof resolveBackupFactor>>> = [];\n for (const factor of options.factors) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- ceremonies run one after another\n factors.push(await resolveBackupFactor(this.factorSource, factor, wire));\n }\n return { verify, factors };\n });\n }),\n update: async (): Promise<string> => {\n const result = await this.channel.call(\"backup.update\", null);\n return result.envelope;\n },\n disable: async (verify: VerifyFactor): Promise<void> =>\n this.withVerifying(async () => {\n await this.secretCall(\"backup.disable\", async (wire) => ({\n verify: await resolveVerifyFactor(this.factorSource, verify, wire),\n }));\n }),\n restore: async (options: {\n readonly envelope: string;\n readonly backupFactor: BackupFactorInput;\n readonly passphrases?: ReadonlyArray<{\n readonly walletId: string;\n readonly passphrase: string;\n }>;\n readonly factor?: InitialFactor;\n }): Promise<{\n readonly wallets: ReadonlyArray<VaultWalletInfo>;\n readonly passphraseRequired: ReadonlyArray<string>;\n }> =>\n this.withVerifying(async () => {\n const result = await this.secretCall(\"backup.restore\", async (wire) => {\n const backupFactor = await resolveBackupUnlockFactor(\n this.factorSource,\n options.backupFactor,\n wire,\n options.backupFactor.kind === \"passkey\"\n ? backupPasskeyCredentialIds(options.envelope)\n : undefined,\n );\n const factor = await this.createFactorParam(options.factor, wire);\n const passphrases = options.passphrases?.map(({ walletId, passphrase }) => ({\n walletId,\n passphrase: wire.text(passphrase),\n }));\n return {\n envelope: options.envelope,\n backupFactor,\n ...(passphrases === undefined ? {} : { passphrases }),\n ...(factor === undefined ? {} : { factor }),\n };\n });\n this.sessionOf(result);\n return { wallets: result.wallets, passphraseRequired: result.passphraseRequired };\n }),\n };\n\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unsubscribePresence?.();\n this.cancelCooldown?.();\n this.onDestroy?.();\n this.channel.destroy();\n }\n}\n\n/**\n * `keys.import`'s `secret` in bytes: a string is the family's canonical text encoding — `0x` hex\n * for EVM, base58 for Solana, bare hex for TRON — while a Uint8Array passes straight through to the\n * kernel's checks.\n */\nfunction decodeKeySecret(\n family: \"evm\" | \"solana\" | \"bitcoin\" | \"tron\",\n secret: string | Uint8Array,\n): Uint8Array {\n if (secret instanceof Uint8Array) {\n return secret;\n }\n if (family === \"evm\") {\n if (!/^0x[0-9a-fA-F]{64}$/.test(secret)) {\n throw new WalletError(\"invalid-input\", \"an EVM private key is 0x-prefixed 64-hex\");\n }\n return hex.decode(secret.slice(2));\n }\n if (family === \"solana\") {\n try {\n return base58.decode(secret);\n } catch {\n throw new WalletError(\"invalid-input\", \"a Solana private key is base58\");\n }\n }\n if (family === \"tron\") {\n if (!/^[0-9a-fA-F]{64}$/.test(secret)) {\n throw new WalletError(\"invalid-input\", \"a TRON private key is 64-hex without 0x\");\n }\n return hex.decode(secret);\n }\n throw new WalletError(\"invalid-input\", `keys are not supported on ${family}`);\n}\n\n/**\n * Validates the passkey configuration: the RP identity and both PRF salts are permanent\n * identifiers, so an empty or colliding value is rejected here rather than producing unrecoverable\n * credentials later.\n */\nfunction checkPasskeyConfig(passkey: PasskeyConfig): void {\n const { rpId, rpName, walletSalt, vaultSalt, backupSalt } = passkey;\n if (\n rpId.length === 0 ||\n rpName.length === 0 ||\n walletSalt.length === 0 ||\n vaultSalt.length === 0 ||\n backupSalt.length === 0 ||\n walletSalt === vaultSalt ||\n backupSalt === vaultSalt ||\n backupSalt === walletSalt\n ) {\n throw new WalletError(\n \"invalid-input\",\n \"passkey config requires a non-empty rpId, rpName and two different salts\",\n );\n }\n}\n\n/**\n * Connects a kernel spawned by the host package and returns the host-facing `Wallet`. The first\n * spawn must deliver a status event before this resolves.\n */\nexport async function connectKernel(options: ConnectOptions): Promise<Wallet> {\n checkPasskeyConfig(options.passkey);\n return KernelWallet.connect(options);\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,MAAa,yBAAyB;AACtC,MAAa,wBAAwB;AA+CrC,SAAS,eAA4B;CACnC,OAAO,IAAI,YAAY,eAAe,kDAAkD;AAC1F;AAEA,SAAgB,aAA0B;CACxC,OAAO,IAAI,YAAY,eAAe,6CAA6C;AACrF;;AAGA,SAAgB,oBAAoB,QAAoC;CACtE,IAAI,OAAO,SAAS,YAElB,OAAO,OAAO,QAAQ,IAAI,EAAE,MAAM,WAAW,IAAI,EAAE,MAAM,SAAS;CAEpE,OAAO,EAAE,MAAM,UAAU;AAC3B;AAEA,SAAgB,eAAe,QAAkC;CAC/D,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,QAAQ,SAAS;AAC1D;AAEA,SAAgB,gBAAgB,QAAkC;CAChE,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,QAAQ,UAAU;AAC3D;AAEA,SAAgB,gBAAgB,QAAkC;CAChE,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,QAAQ,UAAU;AAC3D;;;;;;AAOA,eAAe,kBACb,QACA,MACA,eACsD;CAEtD,MAAM,SAAS,MADE,gBAAgB,MACL,CAAC,CAAC,OAAO;EACnC,eAAe,iBAAiB,qBAAqB,MAAM;EAC3D,OAAO,EAAE,OAAO,gBAAgB,MAAM,EAAE;CAC1C,C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,YACpB,OAAO;CAET,IAAI,WAAW,OAAO;EACpB,IAAI,CAAC,sBAAsB,KAAK,MAAM,GACpC,MAAM,IAAI,YAAY,iBAAiB,0CAA0C;EAEnF,OAAO,IAAI,OAAO,OAAO,MAAM,CAAC,CAAC;CACnC;CACA,IAAI,WAAW,UACb,IAAI;EACF,OAAO,OAAO,OAAO,MAAM;CAC7B,QAAQ;EACN,MAAM,IAAI,YAAY,iBAAiB,gCAAgC;CACzE;CAEF,IAAI,WAAW,QAAQ;EACrB,IAAI,CAAC,oBAAoB,KAAK,MAAM,GAClC,MAAM,IAAI,YAAY,iBAAiB,yCAAyC;EAElF,OAAO,IAAI,OAAO,MAAM;CAC1B;CACA,MAAM,IAAI,YAAY,iBAAiB,6BAA6B,QAAQ;AAC9E;;;;;;AAOA,SAAS,mBAAmB,SAA8B;CACxD,MAAM,EAAE,MAAM,QAAQ,YAAY,WAAW,eAAe;CAC5D,IACE,KAAK,WAAW,KAChB,OAAO,WAAW,KAClB,WAAW,WAAW,KACtB,UAAU,WAAW,KACrB,WAAW,WAAW,KACtB,eAAe,aACf,eAAe,aACf,eAAe,YAEf,MAAM,IAAI,YACR,iBACA,0EACF;AAEJ;;;;;AAMA,eAAsB,cAAc,SAA0C;CAC5E,mBAAmB,QAAQ,OAAO;CAClC,OAAO,aAAa,QAAQ,OAAO;AACrC"}
@@ -1,5 +1,129 @@
1
- import { C as WalletErrorCode, _ as StatusPayload, a as DerivedNostrKey, f as LockReason, m as NostrKeyInfo } from "./types-cAQAJBLi.mjs";
2
- import { f as Factor, g as NullValue, l as CORE_METHODS, p as MethodSpec, t as CHAINS_METHODS, v as Validator } from "./chains-B-FmFmuV.mjs";
1
+ import { N as WalletErrorCode, T as StatusPayload, c as DerivedNostrKey, v as LockReason, x as NostrKeyInfo } from "./types-CRnacSqJ.mjs";
2
+ import { C as ProtocolValue, S as NullValue, T as Validator, _ as MethodSpec, c as ChainSignRequest, l as ChainSignResult, n as ChainAccount, p as CORE_METHODS, t as CHAINS_METHODS, u as ChainTemplate, y as VerifyFactor } from "./chains-u1M0CWkT.mjs";
3
+ import { a as HARDWARE_METHODS } from "./hardware-BL6zvhQh.mjs";
4
+ import { HyperliquidL1Action, HyperliquidL1Order, HyperliquidL1Params, HyperliquidL1Params as HyperliquidL1Params$1, HyperliquidNetwork, HyperliquidNetwork as HyperliquidNetwork$1 } from "@qntx/wallet-chains/evm";
5
+ type CardInputPurpose = "access-code" | "new-access-code" | "confirm-access-code" | "short-id";
6
+ type CardTapReason = "any" | "source" | "target" | "member" | "retry";
7
+ /** The next thing the host must do for the operation to advance; `done` ends the poll loop. */
8
+ type CardStep = {
9
+ readonly kind: "input";
10
+ readonly purpose: CardInputPurpose;
11
+ /** Short id (`XXXX-XXXX`) of the card the input belongs to, when the op knows it. */
12
+ readonly card?: string;
13
+ /** Access-code tries left, when the card just reported a failure. */
14
+ readonly remaining?: number;
15
+ } | {
16
+ readonly kind: "tap";
17
+ readonly reason: CardTapReason;
18
+ /** Short id (`XXXX-XXXX`) of the card to tap, when the op knows it. */
19
+ readonly card?: string;
20
+ /** The response takes seconds; the host must keep the card on the reader. */
21
+ readonly hold?: true;
22
+ } | {
23
+ readonly kind: "done";
24
+ readonly result: CardOpResult;
25
+ };
26
+ type CardOperation = {
27
+ readonly kind: "status";
28
+ } | {
29
+ readonly kind: "add";
30
+ readonly groups?: number;
31
+ } | {
32
+ readonly kind: "accounts";
33
+ readonly walletId: string;
34
+ readonly groupIndex: number;
35
+ readonly templates: ReadonlyArray<ChainTemplate>;
36
+ readonly network: string;
37
+ } | {
38
+ readonly kind: "health";
39
+ readonly walletId: string;
40
+ } | {
41
+ readonly kind: "change-access";
42
+ readonly walletId: string;
43
+ readonly remember?: true;
44
+ } | {
45
+ readonly kind: "erase";
46
+ readonly walletId: string;
47
+ readonly card: string;
48
+ readonly last?: true;
49
+ } | {
50
+ readonly kind: "create";
51
+ readonly cards: number;
52
+ readonly source: {
53
+ readonly kind: "generate";
54
+ } | {
55
+ readonly kind: "wallet";
56
+ readonly walletId: string;
57
+ };
58
+ readonly groups?: number;
59
+ readonly remember?: true;
60
+ } | {
61
+ readonly kind: "transfer";
62
+ readonly walletId: string;
63
+ } | {
64
+ readonly kind: "reseal";
65
+ readonly walletId: string;
66
+ readonly card: string;
67
+ readonly member?: string;
68
+ } | {
69
+ readonly kind: "sign";
70
+ readonly request: ChainSignRequest;
71
+ readonly remember?: true;
72
+ } | {
73
+ readonly kind: "forget-access";
74
+ readonly walletId: string;
75
+ };
76
+ type CardOpResult = {
77
+ readonly kind: "status";
78
+ readonly life: "blank" | "loaded";
79
+ readonly tries: number;
80
+ readonly walletId?: string;
81
+ } | {
82
+ readonly kind: "sign";
83
+ readonly result: ChainSignResult;
84
+ } | {
85
+ readonly kind: "accounts";
86
+ readonly accounts: ReadonlyArray<ChainAccount>;
87
+ } | {
88
+ readonly kind: "add";
89
+ readonly walletId: string;
90
+ } | {
91
+ readonly kind: "health";
92
+ readonly walletId: string;
93
+ } | {
94
+ readonly kind: "change-access";
95
+ readonly walletId: string;
96
+ } | {
97
+ readonly kind: "erase";
98
+ readonly walletId: string;
99
+ } | {
100
+ readonly kind: "create";
101
+ readonly walletId: string;
102
+ } | {
103
+ readonly kind: "transfer";
104
+ readonly walletId: string;
105
+ } | {
106
+ readonly kind: "reseal";
107
+ readonly walletId: string;
108
+ } | {
109
+ readonly kind: "forget-access";
110
+ readonly walletId: string;
111
+ };
112
+ type CardBeginParams = {
113
+ readonly op: CardOperation;
114
+ readonly verify?: VerifyFactor;
115
+ };
116
+ type CardStepParams = {
117
+ readonly opId: string;
118
+ };
119
+ declare const CARD_METHODS: {
120
+ readonly "card.begin": MethodSpec<CardBeginParams, {
121
+ opId: string;
122
+ step: CardStep;
123
+ }>;
124
+ readonly "card.step": MethodSpec<CardStepParams, CardStep>;
125
+ readonly "card.cancel": MethodSpec<CardStepParams, NullValue>;
126
+ };
3
127
  /**
4
128
  * The unsigned event input the kernel signs. `pubkey` is optional: callers may omit it and the
5
129
  * kernel fills the signing key's own. Structurally compatible with @qntx/nostr's UnsignedEvent.
@@ -57,7 +181,7 @@ declare const NOSTR_METHODS: {
57
181
  readonly publicKey: string;
58
182
  }, NullValue>;
59
183
  readonly "nostr.exportKey": MethodSpec<{
60
- readonly verify: Factor;
184
+ readonly verify: VerifyFactor;
61
185
  readonly publicKey: string;
62
186
  readonly format: NostrExportFormat;
63
187
  }, Uint8Array>;
@@ -109,6 +233,111 @@ declare const NOSTR_METHODS: {
109
233
  readonly results: ReadonlyArray<UnwrapResult>;
110
234
  }>;
111
235
  };
236
+ /** One asset's cumulative size cap inside `HyperliquidAgentLimits.assets`. */
237
+ type HyperliquidAssetLimit = {
238
+ readonly asset: number;
239
+ /** Canonical positive decimal — the size buys and sells on `asset` may charge in total. */
240
+ readonly size: string;
241
+ };
242
+ /**
243
+ * The limits a `hyperliquid-l1-agent` session is approved under — `notional` is the quote budget
244
+ * BUY orders charge (Σ max(price, triggerPx) × size, in each market's quote currency: perp ids are
245
+ * quoted in USDC, spot ids in each pair's own quote token), `maxLeverage` caps `updateLeverage`,
246
+ * and `assets` lists 1..16 entries strictly ascending by asset id (0..99999 — builder-deployed
247
+ * HIP-3 perps start at 100000 and stay out of scope), each with the cumulative size cap buys and
248
+ * sells share. The kernel strictly validates them at create and charges every signed order into
249
+ * `spent`; past a budget it answers `limit-exceeded`. The kernel cannot know a market price, so a
250
+ * sell is bounded by its asset's `size`, never by a self-declared `p`.
251
+ */
252
+ type HyperliquidAgentLimits = {
253
+ /** Canonical positive decimal (the scheme's `positive` grammar), at most 1e15. */
254
+ readonly notional: string;
255
+ readonly maxLeverage: number;
256
+ readonly assets: ReadonlyArray<HyperliquidAssetLimit>;
257
+ };
258
+ /**
259
+ * What a `hyperliquid-l1-agent` record has charged: `notional` is the buy-charged quote total and
260
+ * `size[i]` the cumulative size charged against `limits.assets[i]` — buys and sells, reduce-only or
261
+ * not.
262
+ */
263
+ type HyperliquidAgentSpent = {
264
+ /** Canonical decimal (≤ 16 fractional digits) — always ≤ `limits.notional`. */
265
+ readonly notional: string;
266
+ readonly size: ReadonlyArray<string>;
267
+ };
268
+ /**
269
+ * The session schemes this kernel knows — its key set equals the kernel's `SESSION_SCHEMES` table:
270
+ * a missing or extra entry fails the table's mapped-type emit.
271
+ */
272
+ type SessionSchemes = {
273
+ readonly "hyperliquid-l1-agent": {
274
+ readonly scope: HyperliquidNetwork;
275
+ readonly params: HyperliquidL1Params;
276
+ readonly limits: HyperliquidAgentLimits;
277
+ readonly spent: HyperliquidAgentSpent;
278
+ };
279
+ };
280
+ type SessionSchemeId = keyof SessionSchemes;
281
+ type SessionInfo = {
282
+ /** EIP-55 address of the session key. */
283
+ readonly address: string;
284
+ /** The record's scheme — possibly one this build does not know. */
285
+ readonly scheme: string;
286
+ /** Whether this build's kernel can sign with the record's scheme. */
287
+ readonly supported: boolean;
288
+ readonly walletId: string;
289
+ readonly groupIndex: number;
290
+ /** EIP-55 address of the HD account at m/44'/60'/0'/0/groupIndex the session signs for. */
291
+ readonly owner: string;
292
+ /** The scheme's opaque scope (a `HyperliquidNetwork` for hyperliquid-l1-agent). */
293
+ readonly scope: string;
294
+ readonly name: string;
295
+ /** Wall-clock ms after which the kernel refuses to sign; the platform enforces it too. */
296
+ readonly validUntil: number;
297
+ readonly createdAt: number;
298
+ /**
299
+ * The limits the session was approved under — the scheme's canonical JSON object for metered
300
+ * schemes, `null` when the record carries none (a scheme this build does not know, or one that
301
+ * declares no metering).
302
+ */
303
+ readonly limits: ProtocolValue;
304
+ /**
305
+ * The charged metering — the scheme's canonical JSON object, `null` when the record carries none
306
+ * (a scheme this build does not know, or one that declares no metering).
307
+ */
308
+ readonly spent: ProtocolValue;
309
+ };
310
+ declare const SESSIONS_METHODS: {
311
+ readonly "sessions.create": MethodSpec<{
312
+ readonly scheme: string;
313
+ readonly owner: {
314
+ readonly walletId: string;
315
+ readonly groupIndex: number;
316
+ };
317
+ readonly scope: string;
318
+ readonly name: string;
319
+ readonly validUntil: number;
320
+ readonly limits: ProtocolValue;
321
+ readonly verify: VerifyFactor;
322
+ }, {
323
+ readonly address: string;
324
+ }>;
325
+ readonly "sessions.list": MethodSpec<NullValue, ReadonlyArray<SessionInfo>>;
326
+ readonly "sessions.delete": MethodSpec<{
327
+ readonly address: string;
328
+ }, NullValue>;
329
+ readonly "sessions.open": MethodSpec<{
330
+ readonly address: string;
331
+ readonly verify: VerifyFactor;
332
+ }, NullValue>;
333
+ readonly "sessions.sign": MethodSpec<{
334
+ readonly scheme: string;
335
+ readonly address: string;
336
+ readonly params: ProtocolValue;
337
+ }, {
338
+ readonly signature: Uint8Array;
339
+ }>;
340
+ };
112
341
  /** The Spark network the account's signer runs on — identical to @qntx/spark's SparkNetwork. */
113
342
  type SparkNetwork = "mainnet" | "regtest";
114
343
  /** The wallet+group+network triple every spark.* request addresses a pooled signer by. */
@@ -376,7 +605,7 @@ declare const SPARK_METHODS: {
376
605
  readonly "spark.approve": MethodSpec<{
377
606
  readonly account: SparkAccountRef;
378
607
  readonly intent: SparkApproveIntent;
379
- readonly verify: Factor;
608
+ readonly verify: VerifyFactor;
380
609
  }, SparkApprovalSummary>;
381
610
  };
382
611
  type BackupEnvelopeFactor = {
@@ -385,12 +614,19 @@ type BackupEnvelopeFactor = {
385
614
  readonly sealedBek: string;
386
615
  } | {
387
616
  readonly kind: "password";
388
- readonly iterations: 600_000;
617
+ /**
618
+ * Argon2id, RFC 9106 second recommended option; fixed, recorded so the file says how to open
619
+ * it.
620
+ */
621
+ readonly kdf: "argon2id";
622
+ readonly memoryKiB: 65_536;
623
+ readonly passes: 3;
624
+ readonly lanes: 4;
389
625
  readonly salt: string;
390
626
  readonly sealedBek: string;
391
627
  };
392
628
  type BackupEnvelopeWire = {
393
- readonly version: 1;
629
+ readonly version: 3;
394
630
  readonly createdAt: number;
395
631
  /** Raw JSON text — authenticated by the payload tag before it is parsed. */
396
632
  readonly header: string;
@@ -409,7 +645,7 @@ type BackupHeaderWallet = {
409
645
  };
410
646
  type BackupHeaderKey = {
411
647
  readonly keyId: string;
412
- readonly family: "evm" | "solana" | "bitcoin";
648
+ readonly family: "evm" | "solana" | "bitcoin" | "tron";
413
649
  };
414
650
  type BackupHeaderWire = {
415
651
  readonly wallets: ReadonlyArray<BackupHeaderWallet>;
@@ -426,15 +662,17 @@ type BackupInfo = {
426
662
  readonly createdAt: number;
427
663
  };
428
664
  declare const backupInfo: Validator<BackupInfo>;
429
- declare const PROTOCOL_VERSION = 2;
665
+ declare const PROTOCOL_VERSION = 3;
430
666
  /**
431
667
  * Responses to requests whose `id` cannot be parsed (malformed envelope) carry id 0. Main-side
432
668
  * request ids start at 1, so a `0` is never a real pending request.
433
669
  */
434
670
  declare const UNATTRIBUTED_ID = 0;
435
- type ProtocolValue = NullValue | boolean | number | string | Uint8Array | ReadonlyArray<ProtocolValue> | {
436
- readonly [key: string]: ProtocolValue;
437
- };
671
+ /**
672
+ * Param field names whose bytes are secrets: the kernel consumes and wipes them, so each must own
673
+ * its memory.
674
+ */
675
+ declare const SECRET_FIELDS: readonly ["password", "prf", "prfWallet", "prfBackup", "mnemonic", "passphrase", "secret", "answers"];
438
676
  type Request = {
439
677
  readonly v: typeof PROTOCOL_VERSION;
440
678
  readonly id: number;
@@ -465,6 +703,11 @@ type KernelEvent = {
465
703
  readonly v: typeof PROTOCOL_VERSION;
466
704
  readonly event: "locked";
467
705
  readonly reason: LockReason;
706
+ } | {
707
+ /** The kernel is (true) / is no longer (false) waiting on a system verification prompt. */
708
+ readonly v: typeof PROTOCOL_VERSION;
709
+ readonly event: "ceremony";
710
+ readonly active: boolean;
468
711
  };
469
712
  /**
470
713
  * The worst-case encoded size of one request, enforced by both sides: the host refuses to post a
@@ -475,21 +718,28 @@ declare const MAX_REQUEST_BYTES = 1048576;
475
718
  /**
476
719
  * Upper-bound byte weight of a protocol value: a string costs `length * 3` (worst-case UTF-8), a
477
720
  * Uint8Array its `byteLength`, every scalar and every array element 8, and every object key
478
- * `key.length * 3 + 8` plus its value. Iterative — a deeply nested value cannot overflow the
479
- * stack.
721
+ * `key.length * 3 + 8` plus its value. Iterative — a deeply nested value cannot overflow the stack
722
+ * — and stops once the running total passes MAX_REQUEST_BYTES, the only comparison callers make, so
723
+ * oversized values are rejected without walking the whole value.
480
724
  */
481
725
  declare function requestBytes(value: ProtocolValue): number;
482
- /** Deep check that a structured-cloned value is a strict ProtocolValue (no cycles detected). */
726
+ /**
727
+ * Deep check that a structured-cloned value is a strict ProtocolValue. Structured clone keeps
728
+ * shared references, so the value may be a graph: every object and array is checked once however
729
+ * often it is referenced — a shared reference serializes once and must not expand on every walk —
730
+ * and one that contains itself (a cycle, which can never be a protocol value) is rejected.
731
+ * Iterative — a deeply nested value cannot overflow the stack.
732
+ */
483
733
  declare function isProtocolValue(value: unknown): value is ProtocolValue;
484
734
  declare const METHODS: {
485
735
  readonly status: MethodSpec<NullValue, StatusPayload>;
486
- } & typeof CORE_METHODS & typeof NOSTR_METHODS & typeof CHAINS_METHODS & typeof SPARK_METHODS;
736
+ } & typeof CORE_METHODS & typeof CARD_METHODS & typeof NOSTR_METHODS & typeof CHAINS_METHODS & typeof SPARK_METHODS & typeof SESSIONS_METHODS & typeof HARDWARE_METHODS;
487
737
  type AssertNever<T extends never> = T;
488
- type MethodTablesDisjoint = [AssertNever<keyof typeof CORE_METHODS & keyof typeof NOSTR_METHODS>, AssertNever<keyof typeof CORE_METHODS & keyof typeof SPARK_METHODS>, AssertNever<keyof typeof NOSTR_METHODS & keyof typeof SPARK_METHODS>];
738
+ type MethodTablesDisjoint = [AssertNever<keyof typeof CORE_METHODS & keyof typeof CARD_METHODS>, AssertNever<keyof typeof CORE_METHODS & keyof typeof NOSTR_METHODS>, AssertNever<keyof typeof CORE_METHODS & keyof typeof SPARK_METHODS>, AssertNever<keyof typeof CARD_METHODS & keyof typeof NOSTR_METHODS>, AssertNever<keyof typeof CARD_METHODS & keyof typeof CHAINS_METHODS>, AssertNever<keyof typeof CARD_METHODS & keyof typeof SPARK_METHODS>, AssertNever<keyof typeof CARD_METHODS & keyof typeof SESSIONS_METHODS>, AssertNever<keyof typeof NOSTR_METHODS & keyof typeof SPARK_METHODS>, AssertNever<keyof typeof SESSIONS_METHODS & keyof typeof CORE_METHODS>, AssertNever<keyof typeof SESSIONS_METHODS & keyof typeof NOSTR_METHODS>, AssertNever<keyof typeof SESSIONS_METHODS & keyof typeof CHAINS_METHODS>, AssertNever<keyof typeof SESSIONS_METHODS & keyof typeof SPARK_METHODS>, AssertNever<keyof typeof HARDWARE_METHODS & keyof typeof CORE_METHODS>, AssertNever<keyof typeof HARDWARE_METHODS & keyof typeof NOSTR_METHODS>, AssertNever<keyof typeof HARDWARE_METHODS & keyof typeof CHAINS_METHODS>, AssertNever<keyof typeof HARDWARE_METHODS & keyof typeof SPARK_METHODS>, AssertNever<keyof typeof HARDWARE_METHODS & keyof typeof SESSIONS_METHODS>, AssertNever<keyof typeof HARDWARE_METHODS & keyof typeof CARD_METHODS>];
489
739
  type MethodName = keyof typeof METHODS;
490
740
  type ParamsOf<M extends MethodName> = ReturnType<(typeof METHODS)[M]["params"]>;
491
741
  type ResultOf<M extends MethodName> = ReturnType<(typeof METHODS)[M]["result"]>;
492
- /** Host-side validators: `kernelEvent` covers the two push messages. */
742
+ /** Host-side validators: `kernelEvent` covers the push messages. */
493
743
  declare const kernelEvent: Validator<KernelEvent>;
494
744
  /** Validates the `err` payload of a response; `ok` is checked against `METHODS[m].result`. */
495
745
  declare const responseError: Validator<{
@@ -497,5 +747,5 @@ declare const responseError: Validator<{
497
747
  retryAt?: number | undefined;
498
748
  detail?: string | undefined;
499
749
  }>;
500
- export { Rumor as $, HtlcTimeoutSignRequest as A, SigningCommitment as B, backupEnvelope as C, backupInfo as D, backupHeader as E, PreparedClaim as F, SparkKey as G, SparkAccountRef as H, PreparedLightningReceive as I, StaticDepositClaimRequest as J, SparkLeafKey as K, PreparedTransfer as L, OperatorCommitment as M, PrepareClaimRequest as N, FrostAggregateJob as O, PrepareTransferRequest as P, NostrExportFormat as Q, PreparedTransferLeaf as R, BackupInfo as S, backupEnvelopeText as T, SparkApprovalSummary as U, SigningTarget as V, SparkApproveIntent as W, StaticDepositClaimStatement as X, StaticDepositClaimResult as Y, NOSTR_METHODS as Z, responseError as _, MethodName as a, BackupHeaderWallet as b, ParamsOf as c, Response as d, SignedEvent as et, ResultOf as f, requestBytes as g, kernelEvent as h, METHODS as i, IdentityStatement as j, FrostSignJob as k, ProtocolValue as l, isProtocolValue as m, KernelEvent as n, UnwrapResult as nt, MethodTablesDisjoint as o, UNATTRIBUTED_ID as p, SparkNetwork as q, MAX_REQUEST_BYTES as r, PROTOCOL_VERSION as s, ErrorPayload as t, UnsignedEventInput as tt, Request as u, BackupEnvelopeFactor as v, backupEnvelopeFactor as w, BackupHeaderWire as x, BackupEnvelopeWire as y, SPARK_METHODS as z };
501
- //# sourceMappingURL=index-CEhrd0Pl.d.mts.map
750
+ export { HyperliquidAgentSpent as $, FrostSignJob as A, SPARK_METHODS as B, BackupInfo as C, backupHeader as D, backupEnvelopeText as E, PrepareTransferRequest as F, SparkApproveIntent as G, SigningTarget as H, PreparedClaim as I, SparkNetwork as J, SparkKey as K, PreparedLightningReceive as L, IdentityStatement as M, OperatorCommitment as N, backupInfo as O, PrepareClaimRequest as P, HyperliquidAgentLimits as Q, PreparedTransfer as R, BackupHeaderWire as S, CardTapReason as St, backupEnvelopeFactor as T, SparkAccountRef as U, SigningCommitment as V, SparkApprovalSummary as W, StaticDepositClaimResult as X, StaticDepositClaimRequest as Y, StaticDepositClaimStatement as Z, responseError as _, CardInputPurpose as _t, MethodName as a, SESSIONS_METHODS as at, BackupHeaderKey as b, CardStep as bt, ParamsOf as c, SessionSchemes as ct, ResultOf as d, Rumor as dt, HyperliquidAssetLimit as et, SECRET_FIELDS as f, SignedEvent as ft, requestBytes as g, CardBeginParams as gt, kernelEvent as h, CARD_METHODS as ht, METHODS as i, HyperliquidNetwork$1 as it, HtlcTimeoutSignRequest as j, FrostAggregateJob as k, Request as l, NOSTR_METHODS as lt, isProtocolValue as m, UnwrapResult as mt, KernelEvent as n, HyperliquidL1Order as nt, MethodTablesDisjoint as o, SessionInfo as ot, UNATTRIBUTED_ID as p, UnsignedEventInput as pt, SparkLeafKey as q, MAX_REQUEST_BYTES as r, HyperliquidL1Params$1 as rt, PROTOCOL_VERSION as s, SessionSchemeId as st, ErrorPayload as t, HyperliquidL1Action as tt, Response as u, NostrExportFormat as ut, BackupEnvelopeFactor as v, CardOpResult as vt, backupEnvelope as w, BackupHeaderWallet as x, CardStepParams as xt, BackupEnvelopeWire as y, CardOperation as yt, PreparedTransferLeaf as z };
751
+ //# sourceMappingURL=index-UclKfprm.d.mts.map