@qntx/wallet 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-Dhf6wGjQ.d.mts → chains-D_jfwTPT.d.mts} +299 -117
- package/dist/chains.d.mts +14 -0
- package/dist/chains.mjs +70 -0
- package/dist/chains.mjs.map +1 -0
- package/dist/{secret-IcTjjaX0.mjs → channel-ChYtMklb.mjs} +19 -155
- package/dist/channel-ChYtMklb.mjs.map +1 -0
- package/dist/{core-QJ66nLLG.mjs → core-Dmz5SbyJ.mjs} +55 -23
- package/dist/core-Dmz5SbyJ.mjs.map +1 -0
- package/dist/host.d.mts +17 -4
- package/dist/host.mjs +37 -9
- package/dist/host.mjs.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/nostr.d.mts +1 -1
- package/dist/nostr.mjs +2 -1
- package/dist/nostr.mjs.map +1 -1
- package/dist/{protocol-D9xBuMzq.mjs → protocol-DvzlUKB8.mjs} +147 -3
- package/dist/protocol-DvzlUKB8.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -3
- package/dist/protocol.mjs +3 -3
- package/dist/secret-BiyX0Hus.mjs +203 -0
- package/dist/secret-BiyX0Hus.mjs.map +1 -0
- package/dist/spark.d.mts +2 -2
- package/dist/{types-D4OUjGVS.d.mts → types-BD9fuAUj.d.mts} +9 -2
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +19 -7
- package/dist/core-QJ66nLLG.mjs.map +0 -1
- package/dist/protocol-D9xBuMzq.mjs.map +0 -1
- package/dist/secret-IcTjjaX0.mjs.map +0 -1
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 */\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 wireSecretText,\n resolveBackupFactor,\n} from \"./factors.ts\";\nimport type { FactorSource, PasskeyCeremony } from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupApi,\n DataKeyApi,\n ExportedSecret,\n FactorInfo,\n InitialFactor,\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 readonly passkey: PasskeyConfig;\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 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.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 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.emit();\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 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 /**\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 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.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 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) {\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 ?? { kind: \"passkey\" },\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 wallets: WalletsApi = {\n createWithPasskey: async (options: {\n readonly name: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const ceremony = requireCeremony(this.factorSource);\n const name = passkeyName(options.name);\n const transfer: ArrayBuffer[] = [];\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 const created = await this.channel.call(\n \"wallet.createWithPasskey\",\n {\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 restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const ceremony = requireCeremony(this.factorSource);\n const transfer: ArrayBuffer[] = [];\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 const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\n {\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 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 (answers: ReadonlyArray<string>): Promise<WalletInfo> => {\n const answerTransfer: ArrayBuffer[] = [];\n const encoded = answers.map((word) => wireSecretText(word, answerTransfer));\n const confirmed = await this.channel.call(\n \"wallet.confirmMnemonic\",\n { draft: draftId, answers: encoded },\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 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 created = await this.channel.call(\n \"wallet.importMnemonic\",\n { mnemonic, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n },\n exportMnemonic: async (walletId: string, verify: UnlockFactor): Promise<ExportedSecret> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const bytes = await this.channel.call(\n \"wallet.exportMnemonic\",\n { verify: wireVerify, walletId },\n transfer,\n );\n return new SingleUseSecret(bytes);\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 factor?: InitialFactor;\n }): Promise<ReadonlyArray<WalletInfo>> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const backupFactor = await resolveBackupFactor(\n this.factorSource,\n options.backupFactor,\n transfer,\n );\n const factor = await this.createFactorParam(options.factor, transfer);\n const result = await this.channel.call(\n \"backup.restore\",\n {\n envelope: options.envelope,\n backupFactor,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(result);\n return result.wallets;\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 * 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":";;;;;;;;;;;;AA4DA,MAAa,6BA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ACzB,KAAK,cACL,QAAQ,cACR,QACF;GACA,MAAM,SAAS,MAAM,KAAK,kBAAkB,QAAQ,QAAQ,QAAQ;GACpE,MAAM,SAAS,MAAM,KAAK,QAAQ,KAChC,kBACA;IACE,UAAU,QAAQ;IAClB;IACA,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;GAC3C,GACA,QACF;GACA,KAAK,UAAU,MAAM;GACrB,OAAO,OAAO;EAChB,CAAC;CACL;CAGA,MAAM,UAAyB;EAC7B,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,sBAAsB;EAC3B,KAAK,iBAAiB;EACtB,KAAK,YAAY;EACjB,KAAK,QAAQ,QAAQ;CACvB;AACF;;;;;;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/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 */\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 wireSecretText,\n resolveBackupFactor,\n resolveBackupUnlockFactor,\n defaultUnlockFactor,\n} from \"./factors.ts\";\nimport type { FactorMode, FactorSource, PasskeyCeremony } from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupApi,\n DataKeyApi,\n ExportedSecret,\n FactorInfo,\n InitialFactor,\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 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 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 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 /**\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 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.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 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 const created = await this.channel.call(\n \"wallet.createWithPasskey\",\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 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 const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\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 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 (answers: ReadonlyArray<string>): Promise<WalletInfo> => {\n const answerTransfer: ArrayBuffer[] = [];\n const encoded = answers.map((word) => wireSecretText(word, answerTransfer));\n const confirmed = await this.channel.call(\n \"wallet.confirmMnemonic\",\n { draft: draftId, answers: encoded },\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 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 created = await this.channel.call(\n \"wallet.importMnemonic\",\n { mnemonic, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n },\n exportMnemonic: async (walletId: string, verify: UnlockFactor): Promise<ExportedSecret> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const bytes = await this.channel.call(\n \"wallet.exportMnemonic\",\n { verify: wireVerify, walletId },\n transfer,\n );\n return new SingleUseSecret(bytes);\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 factor?: InitialFactor;\n }): Promise<ReadonlyArray<WalletInfo>> =>\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 result = await this.channel.call(\n \"backup.restore\",\n {\n envelope: options.envelope,\n backupFactor,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(result);\n return result.wallets;\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 * 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":";;;;;;;;;;;;;AAgEA,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,QAAQ,CAAC,GACrC,OACE,MAAM,QAAQ,CAAC,KACf,MAAM,QAAQ,CAAC,KACf,EAAE,WAAW,EAAE,UACf,EAAE,OAAO,MAAM,UAAU,UAAU,MAAM,EAAE,MAAM,CAAC;CAGtD,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,OACE,MAAM,WAAW,MAAM,UACvB,MAAM,OACH,QACC,OAAO,KACP,UACG,EAA8B,MAC9B,EAA8B,IACjC,CACJ;AAEJ;AAEA,IAAa,eAAb,MAAa,aAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA,kBAA0B;CAC1B;CACA,YAAoB;CAEpB;CACA;CACA,YAAoB;CACpB;CACA,4BAA6B,IAAI,IAAgB;CAEjD,YAAoB,SAAyB;EAC3C,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ;EAC1B,KAAK,WAA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,SAAS,MAAM,KAAK,kBAAkB,QAAQ,QAAQ,QAAQ;GACpE,MAAM,SAAS,MAAM,KAAK,QAAQ,KAChC,kBACA;IACE,UAAU,QAAQ;IAClB;IACA,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;GAC3C,GACA,QACF;GACA,KAAK,UAAU,MAAM;GACrB,OAAO,OAAO;EAChB,CAAC;CACL;CAGA,MAAM,UAAyB;EAC7B,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,sBAAsB;EAC3B,KAAK,iBAAiB;EACtB,KAAK,YAAY;EACjB,KAAK,QAAQ,QAAQ;CACvB;AACF;;;;;;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"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as WalletSnapshot, S as WalletOptions, _ as VaultState, a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, g as VaultApi, h as UnlockFactor, i as DataKeyApi, l as LockReason, m as StatusPayload, n as BackupApi, o as ExportedSecret, p as PasskeyConfig, r as BackupInfo, s as FactorInfo, t as AutoLockPolicy, u as MnemonicDraft, v as Wallet, w as WalletsApi, x as WalletInfo, y as WalletError } from "./types-
|
|
2
|
-
import {
|
|
1
|
+
import { C as WalletSnapshot, S as WalletOptions, _ as VaultState, a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, g as VaultApi, h as UnlockFactor, i as DataKeyApi, l as LockReason, m as StatusPayload, n as BackupApi, o as ExportedSecret, p as PasskeyConfig, r as BackupInfo, s as FactorInfo, t as AutoLockPolicy, u as MnemonicDraft, v as Wallet, w as WalletsApi, x as WalletInfo, y as WalletError } from "./types-BD9fuAUj.mjs";
|
|
2
|
+
import { L as BackupHeaderWire } from "./chains-D_jfwTPT.mjs";
|
|
3
3
|
//#region src/backup.d.ts
|
|
4
4
|
type BackupHeaderWallet = BackupHeaderWire["wallets"][number];
|
|
5
5
|
type BackupHeader = {
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as validate } from "./core-
|
|
2
|
-
import {
|
|
1
|
+
import { D as validate } from "./core-Dmz5SbyJ.mjs";
|
|
2
|
+
import { f as backupEnvelope, h as backupHeader } from "./protocol-DvzlUKB8.mjs";
|
|
3
3
|
import { WalletError } from "./types.mjs";
|
|
4
4
|
//#region src/backup.ts
|
|
5
5
|
function integrity(msg) {
|
package/dist/nostr.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, h as UnlockFactor, o as ExportedSecret, v as Wallet } from "./types-
|
|
1
|
+
import { a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, h as UnlockFactor, o as ExportedSecret, v as Wallet } from "./types-BD9fuAUj.mjs";
|
|
2
2
|
import { Event, NostrSigner } from "@qntx/nostr";
|
|
3
3
|
import { Rumor } from "@qntx/nostr/nips/nip59";
|
|
4
4
|
//#region src/nostr/types.d.ts
|
package/dist/nostr.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { WalletError } from "./types.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { n as integrity } from "./channel-ChYtMklb.mjs";
|
|
3
3
|
import { t as internalsOf } from "./internal-LBHal13j.mjs";
|
|
4
|
+
import { m as wireSecretText, t as SingleUseSecret } from "./secret-BiyX0Hus.mjs";
|
|
4
5
|
import { signedMatchesUnsigned, verifyEvent } from "@qntx/nostr";
|
|
5
6
|
//#region src/nostr/signer.ts
|
|
6
7
|
/**
|
package/dist/nostr.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nostr.mjs","names":[],"sources":["../src/nostr/signer.ts","../src/nostr/index.ts"],"sourcesContent":["/**\n * The proxy NostrSigner: the ref resolves against the CURRENT snapshot at every call, so the same\n * signer object keeps working across lock/unlock and worker respawns. Returned events are checked\n * against the request — a compromised kernel cannot make a valid signature over different content\n * pass as the requested event.\n */\nimport { signedMatchesUnsigned, verifyEvent } from \"@qntx/nostr\";\nimport type { UnsignedEvent } from \"@qntx/nostr\";\nimport type { Rumor } from \"@qntx/nostr/nips/nip59\";\n\nimport { integrity } from \"../channel.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { MAX_BATCH } from \"../protocol/core.ts\";\nimport type { UnsignedEventInput } from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { NostrKeyInfo, NostrKeyRef } from \"../types.ts\";\nimport type { WalletSigner } from \"./types.ts\";\n\n/** Resolves a public ref to its stored key record; missing refs are `not-found`. */\nexport function keyInfoOf(internals: WalletInternals, ref: NostrKeyRef): NostrKeyInfo {\n const info = internals.snapshot().nostr.keys.find((key) => {\n const k = key.ref;\n return (\n (ref.kind === \"derived\" &&\n k.kind === \"derived\" &&\n k.walletId === ref.walletId &&\n k.groupIndex === ref.groupIndex) ||\n (ref.kind === \"nip46-client\" && k.kind === \"nip46-client\" && k.id === ref.id) ||\n (ref.kind === \"standalone\" && k.kind === \"standalone\" && k.id === ref.id)\n );\n });\n if (info === undefined) {\n throw new WalletError(\"not-found\", \"no such nostr key\");\n }\n return info;\n}\n\nexport function proxySigner(ref: NostrKeyRef, internals: WalletInternals): WalletSigner {\n const resolvePublicKey = (): string => keyInfoOf(internals, ref).publicKey;\n return {\n getPublicKey: async () => {\n await internals.ready();\n return resolvePublicKey();\n },\n signEvent: async (unsigned) => {\n const publicKey = resolvePublicKey();\n // An absent pubkey must stay absent: `pubkey: undefined` is not a ProtocolValue and the\n // kernel would reject the params outright.\n const event: UnsignedEventInput =\n unsigned.pubkey === undefined\n ? {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n }\n : {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: unsigned.pubkey,\n };\n const signed = await internals.call(\"nostr.signEvent\", { publicKey, event });\n // The kernel output must be the requested event, signed by the expected key.\n const requested: UnsignedEvent = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: publicKey,\n };\n if (\n signed.pubkey !== publicKey ||\n !signedMatchesUnsigned(signed, requested) ||\n !verifyEvent(signed)\n ) {\n throw integrity(\"the kernel returned a forged event\");\n }\n return signed;\n },\n nip04Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip04Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip04Decrypt: async (peer, ciphertext) =>\n internals.call(\"nostr.nip04Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: ciphertext,\n }),\n nip44Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip44Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip44Decrypt: async (peer, payload) =>\n internals.call(\"nostr.nip44Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: payload,\n }),\n unwrapGiftWraps: async (events) => {\n if (events.length === 0) {\n return [];\n }\n const publicKey = resolvePublicKey();\n const results: Array<Rumor | Error> = [];\n // The wire caps one batch at MAX_BATCH; chunk sequentially and concatenate in order —\n // other requests can interleave between chunks.\n for (let start = 0; start < events.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"nostr.unwrapGiftWraps\", {\n publicKey,\n events: events.slice(start, start + MAX_BATCH),\n });\n for (const r of batch.results) {\n results.push(\"ok\" in r ? r.ok : new Error(r.err));\n }\n }\n return results;\n },\n };\n}\n","/**\n * The nostr module of @qntx/wallet: `nostr(wallet)` returns the wallet's Nostr API — signer\n * proxies, key discovery/derivation/import/generation, guarded export and removal. The API is\n * memoized per wallet so repeated calls return the same object (stable React identity); a foreign\n * object is rejected because only a Wallet from this package holds a registered channel.\n */\nimport { wireSecretText } from \"../factors.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { SingleUseSecret } from \"../secret.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type {\n DerivedNostrKey,\n ExportedSecret,\n InitialFactor,\n NostrKeyInfo,\n NostrKeyRef,\n UnlockFactor,\n Wallet,\n} from \"../types.ts\";\nimport { keyInfoOf, proxySigner } from \"./signer.ts\";\nimport type { NostrApi, NostrExportKeyFormat, NostrImportKeyInput, WalletSigner } from \"./types.ts\";\n\nexport type {\n DerivedNostrKey,\n NostrApi,\n NostrExportKeyFormat,\n NostrImportKeyInput,\n NostrKeyInfo,\n NostrKeyRef,\n NostrUnwrapResult,\n WalletSigner,\n} from \"./types.ts\";\n\nfunction createNostrApi(internals: WalletInternals): NostrApi {\n return {\n signer: (ref: NostrKeyRef): WalletSigner => proxySigner(ref, internals),\n\n discover: async (\n walletId: string,\n from: number,\n count: number,\n ): Promise<ReadonlyArray<DerivedNostrKey>> => {\n const result = await internals.call(\"nostr.discover\", { walletId, from, count });\n return result.keys;\n },\n\n deriveKey: async (walletId: string, groupIndex: number): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.deriveKey\", { walletId, groupIndex }),\n\n importKey: async (\n input: NostrImportKeyInput,\n options?: { readonly factor?: InitialFactor },\n ): Promise<NostrKeyInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await internals.createFactorParam(options?.factor, transfer);\n const wireInput =\n \"nsec\" in input\n ? { kind: \"nsec\" as const, nsec: wireSecretText(input.nsec, transfer) }\n : {\n kind: \"ncryptsec\" as const,\n ncryptsec: input.ncryptsec,\n password: wireSecretText(input.password, transfer),\n };\n const result = await internals.call(\n \"nostr.importKey\",\n { input: wireInput, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n internals.sessionOf(result);\n return result.key;\n },\n\n generateKey: async (options?: { readonly factor?: InitialFactor }): Promise<NostrKeyInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await internals.createFactorParam(options?.factor, transfer);\n const result = await internals.call(\n \"nostr.generateKey\",\n factor === undefined ? {} : { factor },\n transfer,\n );\n internals.sessionOf(result);\n return result.key;\n },\n\n createNip46ClientKey: async (): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.createNip46ClientKey\", null),\n\n removeKey: async (ref: NostrKeyRef, verify?: UnlockFactor): Promise<void> =>\n internals.withVerifying(async () => {\n const info = keyInfoOf(internals, ref); // resolves ref → publicKey + origin\n const transfer: ArrayBuffer[] = [];\n let wireVerify;\n if (info.origin !== \"nip46-client\") {\n if (verify === undefined) {\n throw new WalletError(\"invalid-input\", \"factor verification is required\");\n }\n wireVerify = await internals.resolveFactor(verify, transfer);\n }\n await internals.call(\n \"nostr.removeKey\",\n {\n publicKey: info.publicKey,\n ...(wireVerify === undefined ? {} : { verify: wireVerify }),\n },\n transfer,\n );\n }),\n\n exportKey: async (\n ref: NostrKeyRef,\n format: NostrExportKeyFormat,\n verify: UnlockFactor,\n ): Promise<ExportedSecret> =>\n internals.withVerifying(async () => {\n const { publicKey } = keyInfoOf(internals, ref);\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await internals.resolveFactor(verify, transfer);\n const wireFormat =\n format.kind === \"nsec\"\n ? { kind: \"nsec\" as const }\n : {\n kind: \"ncryptsec\" as const,\n password: wireSecretText(format.password, transfer),\n };\n const bytes = await internals.call(\n \"nostr.exportKey\",\n { verify: wireVerify, publicKey, format: wireFormat },\n transfer,\n );\n return new SingleUseSecret(bytes);\n }),\n };\n}\n\nconst apis = new WeakMap<Wallet, NostrApi>();\n\nexport function nostr(wallet: Wallet): NostrApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createNostrApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,UAAU,WAA4B,KAAgC;CACpF,MAAM,OAAO,UAAU,SAAS,CAAC,CAAC,MAAM,KAAK,MAAM,QAAQ;EACzD,MAAM,IAAI,IAAI;EACd,OACG,IAAI,SAAS,aACZ,EAAE,SAAS,aACX,EAAE,aAAa,IAAI,YACnB,EAAE,eAAe,IAAI,cACtB,IAAI,SAAS,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,OAAO,IAAI,MACzE,IAAI,SAAS,gBAAgB,EAAE,SAAS,gBAAgB,EAAE,OAAO,IAAI;CAE1E,CAAC;CACD,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,YAAY,aAAa,mBAAmB;CAExD,OAAO;AACT;AAEA,SAAgB,YAAY,KAAkB,WAA0C;CACtF,MAAM,yBAAiC,UAAU,WAAW,GAAG,CAAC,CAAC;CACjE,OAAO;EACL,cAAc,YAAY;GACxB,MAAM,UAAU,MAAM;GACtB,OAAO,iBAAiB;EAC1B;EACA,WAAW,OAAO,aAAa;GAC7B,MAAM,YAAY,iBAAiB;GAGnC,MAAM,QACJ,SAAS,WAAW,KAAA,IAChB;IACE,MAAM,SAAS;IACf,YAAY,SAAS;IACrB,MAAM,SAAS;IACf,SAAS,SAAS;GACpB,IACA;IACE,MAAM,SAAS;IACf,YAAY,SAAS;IACrB,MAAM,SAAS;IACf,SAAS,SAAS;IAClB,QAAQ,SAAS;GACnB;GACN,MAAM,SAAS,MAAM,UAAU,KAAK,mBAAmB;IAAE;IAAW;GAAM,CAAC;GAE3E,MA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AAW;GAC3D,GACA,QACF;EACF,CAAC;EAEH,WAAW,OACT,KACA,QACA,WAEA,UAAU,cAAc,YAAY;GAClC,MAAM,EAAE,cAAc,UAAU,WAAW,GAAG;GAC9C,MAAM,WAA0B,CAAC;GACjC,MAAM,aAAa,MAAM,UAAU,cAAc,QAAQ,QAAQ;GACjE,MAAM,aACJ,OAAO,SAAS,SACZ,EAAE,MAAM,OAAgB,IACxB;IACE,MAAM;IACN,UAAU,eAAe,OAAO,UAAU,QAAQ;GACpD;GACN,MAAM,QAAQ,MAAM,UAAU,KAC5B,mBACA;IAAE,QAAQ;IAAY;IAAW,QAAQ;GAAW,GACpD,QACF;GACA,OAAO,IAAI,gBAAgB,KAAK;EAClC,CAAC;CACL;AACF;AAEA,MAAM,uBAAO,IAAI,QAA0B;AAE3C,SAAgB,MAAM,QAA0B;CAC9C,MAAM,YAAY,YAAY,MAAM;CACpC,IAAI,MAAM,KAAK,IAAI,MAAM;CACzB,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,eAAe,SAAS;EAC9B,KAAK,IAAI,QAAQ,GAAG;CACtB;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"nostr.mjs","names":[],"sources":["../src/nostr/signer.ts","../src/nostr/index.ts"],"sourcesContent":["/**\n * The proxy NostrSigner: the ref resolves against the CURRENT snapshot at every call, so the same\n * signer object keeps working across lock/unlock and worker respawns. Returned events are checked\n * against the request — a compromised kernel cannot make a valid signature over different content\n * pass as the requested event.\n */\nimport { signedMatchesUnsigned, verifyEvent } from \"@qntx/nostr\";\nimport type { UnsignedEvent } from \"@qntx/nostr\";\nimport type { Rumor } from \"@qntx/nostr/nips/nip59\";\n\nimport { integrity } from \"../channel.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { MAX_BATCH } from \"../protocol/core.ts\";\nimport type { UnsignedEventInput } from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { NostrKeyInfo, NostrKeyRef } from \"../types.ts\";\nimport type { WalletSigner } from \"./types.ts\";\n\n/** Resolves a public ref to its stored key record; missing refs are `not-found`. */\nexport function keyInfoOf(internals: WalletInternals, ref: NostrKeyRef): NostrKeyInfo {\n const info = internals.snapshot().nostr.keys.find((key) => {\n const k = key.ref;\n return (\n (ref.kind === \"derived\" &&\n k.kind === \"derived\" &&\n k.walletId === ref.walletId &&\n k.groupIndex === ref.groupIndex) ||\n (ref.kind === \"nip46-client\" && k.kind === \"nip46-client\" && k.id === ref.id) ||\n (ref.kind === \"standalone\" && k.kind === \"standalone\" && k.id === ref.id)\n );\n });\n if (info === undefined) {\n throw new WalletError(\"not-found\", \"no such nostr key\");\n }\n return info;\n}\n\nexport function proxySigner(ref: NostrKeyRef, internals: WalletInternals): WalletSigner {\n const resolvePublicKey = (): string => keyInfoOf(internals, ref).publicKey;\n return {\n getPublicKey: async () => {\n await internals.ready();\n return resolvePublicKey();\n },\n signEvent: async (unsigned) => {\n const publicKey = resolvePublicKey();\n // An absent pubkey must stay absent: `pubkey: undefined` is not a ProtocolValue and the\n // kernel would reject the params outright.\n const event: UnsignedEventInput =\n unsigned.pubkey === undefined\n ? {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n }\n : {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: unsigned.pubkey,\n };\n const signed = await internals.call(\"nostr.signEvent\", { publicKey, event });\n // The kernel output must be the requested event, signed by the expected key.\n const requested: UnsignedEvent = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: publicKey,\n };\n if (\n signed.pubkey !== publicKey ||\n !signedMatchesUnsigned(signed, requested) ||\n !verifyEvent(signed)\n ) {\n throw integrity(\"the kernel returned a forged event\");\n }\n return signed;\n },\n nip04Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip04Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip04Decrypt: async (peer, ciphertext) =>\n internals.call(\"nostr.nip04Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: ciphertext,\n }),\n nip44Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip44Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip44Decrypt: async (peer, payload) =>\n internals.call(\"nostr.nip44Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: payload,\n }),\n unwrapGiftWraps: async (events) => {\n if (events.length === 0) {\n return [];\n }\n const publicKey = resolvePublicKey();\n const results: Array<Rumor | Error> = [];\n // The wire caps one batch at MAX_BATCH; chunk sequentially and concatenate in order —\n // other requests can interleave between chunks.\n for (let start = 0; start < events.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"nostr.unwrapGiftWraps\", {\n publicKey,\n events: events.slice(start, start + MAX_BATCH),\n });\n for (const r of batch.results) {\n results.push(\"ok\" in r ? r.ok : new Error(r.err));\n }\n }\n return results;\n },\n };\n}\n","/**\n * The nostr module of @qntx/wallet: `nostr(wallet)` returns the wallet's Nostr API — signer\n * proxies, key discovery/derivation/import/generation, guarded export and removal. The API is\n * memoized per wallet so repeated calls return the same object (stable React identity); a foreign\n * object is rejected because only a Wallet from this package holds a registered channel.\n */\nimport { wireSecretText } from \"../factors.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { SingleUseSecret } from \"../secret.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type {\n DerivedNostrKey,\n ExportedSecret,\n InitialFactor,\n NostrKeyInfo,\n NostrKeyRef,\n UnlockFactor,\n Wallet,\n} from \"../types.ts\";\nimport { keyInfoOf, proxySigner } from \"./signer.ts\";\nimport type { NostrApi, NostrExportKeyFormat, NostrImportKeyInput, WalletSigner } from \"./types.ts\";\n\nexport type {\n DerivedNostrKey,\n NostrApi,\n NostrExportKeyFormat,\n NostrImportKeyInput,\n NostrKeyInfo,\n NostrKeyRef,\n NostrUnwrapResult,\n WalletSigner,\n} from \"./types.ts\";\n\nfunction createNostrApi(internals: WalletInternals): NostrApi {\n return {\n signer: (ref: NostrKeyRef): WalletSigner => proxySigner(ref, internals),\n\n discover: async (\n walletId: string,\n from: number,\n count: number,\n ): Promise<ReadonlyArray<DerivedNostrKey>> => {\n const result = await internals.call(\"nostr.discover\", { walletId, from, count });\n return result.keys;\n },\n\n deriveKey: async (walletId: string, groupIndex: number): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.deriveKey\", { walletId, groupIndex }),\n\n importKey: async (\n input: NostrImportKeyInput,\n options?: { readonly factor?: InitialFactor },\n ): Promise<NostrKeyInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await internals.createFactorParam(options?.factor, transfer);\n const wireInput =\n \"nsec\" in input\n ? { kind: \"nsec\" as const, nsec: wireSecretText(input.nsec, transfer) }\n : {\n kind: \"ncryptsec\" as const,\n ncryptsec: input.ncryptsec,\n password: wireSecretText(input.password, transfer),\n };\n const result = await internals.call(\n \"nostr.importKey\",\n { input: wireInput, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n internals.sessionOf(result);\n return result.key;\n },\n\n generateKey: async (options?: { readonly factor?: InitialFactor }): Promise<NostrKeyInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await internals.createFactorParam(options?.factor, transfer);\n const result = await internals.call(\n \"nostr.generateKey\",\n factor === undefined ? {} : { factor },\n transfer,\n );\n internals.sessionOf(result);\n return result.key;\n },\n\n createNip46ClientKey: async (): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.createNip46ClientKey\", null),\n\n removeKey: async (ref: NostrKeyRef, verify?: UnlockFactor): Promise<void> =>\n internals.withVerifying(async () => {\n const info = keyInfoOf(internals, ref); // resolves ref → publicKey + origin\n const transfer: ArrayBuffer[] = [];\n let wireVerify;\n if (info.origin !== \"nip46-client\") {\n if (verify === undefined) {\n throw new WalletError(\"invalid-input\", \"factor verification is required\");\n }\n wireVerify = await internals.resolveFactor(verify, transfer);\n }\n await internals.call(\n \"nostr.removeKey\",\n {\n publicKey: info.publicKey,\n ...(wireVerify === undefined ? {} : { verify: wireVerify }),\n },\n transfer,\n );\n }),\n\n exportKey: async (\n ref: NostrKeyRef,\n format: NostrExportKeyFormat,\n verify: UnlockFactor,\n ): Promise<ExportedSecret> =>\n internals.withVerifying(async () => {\n const { publicKey } = keyInfoOf(internals, ref);\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await internals.resolveFactor(verify, transfer);\n const wireFormat =\n format.kind === \"nsec\"\n ? { kind: \"nsec\" as const }\n : {\n kind: \"ncryptsec\" as const,\n password: wireSecretText(format.password, transfer),\n };\n const bytes = await internals.call(\n \"nostr.exportKey\",\n { verify: wireVerify, publicKey, format: wireFormat },\n transfer,\n );\n return new SingleUseSecret(bytes);\n }),\n };\n}\n\nconst apis = new WeakMap<Wallet, NostrApi>();\n\nexport function nostr(wallet: Wallet): NostrApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createNostrApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,SAAgB,UAAU,WAA4B,KAAgC;CACpF,MAAM,OAAO,UAAU,SAAS,CAAC,CAAC,MAAM,KAAK,MAAM,QAAQ;EACzD,MAAM,IAAI,IAAI;EACd,OACG,IAAI,SAAS,aACZ,EAAE,SAAS,aACX,EAAE,aAAa,IAAI,YACnB,EAAE,eAAe,IAAI,cACtB,IAAI,SAAS,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,OAAO,IAAI,MACzE,IAAI,SAAS,gBAAgB,EAAE,SAAS,gBAAgB,EAAE,OAAO,IAAI;CAE1E,CAAC;CACD,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,YAAY,aAAa,mBAAmB;CAExD,OAAO;AACT;AAEA,SAAgB,YAAY,KAAkB,WA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, S as obj, T as str, _ as bool, a as MAX_TEXT, b as literal, c as groupIndex, d as sessionId, f as walletErrorCode, g as arr, h as ValidationError, i as MAX_TAG_ITEM, l as publicKey, m as walletInfo, n as MAX_SNAPSHOT_ITEMS, o as factor, p as walletId, r as MAX_TAGS, s as factorInfo, t as CORE_METHODS, u as safeTime, v as bytes, w as record, x as nullValue, y as int } from "./core-
|
|
1
|
+
import { C as opt, E as union, S as obj, T as str, _ as bool, a as MAX_TEXT, b as literal, c as groupIndex, d as sessionId, f as walletErrorCode, g as arr, h as ValidationError, i as MAX_TAG_ITEM, l as publicKey, m as walletInfo, n as MAX_SNAPSHOT_ITEMS, o as factor, p as walletId, r as MAX_TAGS, s as factorInfo, t as CORE_METHODS, u as safeTime, v as bytes, w as record, x as nullValue, y as int } from "./core-Dmz5SbyJ.mjs";
|
|
2
2
|
//#region src/protocol/backup.ts
|
|
3
3
|
/**
|
|
4
4
|
* Backup-envelope wire validators (design/backup.mdx): the strict structural shape the kernel and
|
|
@@ -45,6 +45,149 @@ const backupInfo = obj({
|
|
|
45
45
|
createdAt: safeTime
|
|
46
46
|
});
|
|
47
47
|
//#endregion
|
|
48
|
+
//#region src/protocol/chains.ts
|
|
49
|
+
const template = union(literal("evm.bip44"), literal("solana.bip44-change"), union(literal("btc.bip44"), literal("btc.bip49"), literal("btc.bip84")), literal("btc.bip86"));
|
|
50
|
+
const caip2 = str(200, /^[a-z0-9-]{3,64}:[0-9a-zA-Z-]{1,128}$/);
|
|
51
|
+
const addressResult = (t) => obj({
|
|
52
|
+
template: literal(t),
|
|
53
|
+
network: caip2,
|
|
54
|
+
address: str(128, /^[0-9a-zA-Z-]{20,128}$/)
|
|
55
|
+
});
|
|
56
|
+
const accountRef = union(obj({
|
|
57
|
+
kind: literal("hd"),
|
|
58
|
+
walletId,
|
|
59
|
+
groupIndex,
|
|
60
|
+
template
|
|
61
|
+
}), obj({
|
|
62
|
+
kind: literal("imported"),
|
|
63
|
+
keyId: str(64, /^[0-9a-f]{8,64}$/),
|
|
64
|
+
family: union(literal("evm"), literal("solana"), literal("bitcoin"))
|
|
65
|
+
}));
|
|
66
|
+
const hexQuantity = str(66, /^0x[0-9a-fA-F]+$/);
|
|
67
|
+
const hexData = str(4e4, /^0x[0-9a-fA-F]*$/);
|
|
68
|
+
const evmAddress = str(42, /^0x[0-9a-fA-F]{40}$/);
|
|
69
|
+
const solanaAddress = str(44, /^[1-9A-HJ-NP-Za-km-z]{32,44}$/);
|
|
70
|
+
const bitcoinAddress = str(90, /^(bc1|tb1|bcrt1|[13mn2])[a-zA-Z0-9]{4,87}$/);
|
|
71
|
+
const safeInt = int(0, 9007199254740991);
|
|
72
|
+
const accessList = arr(obj({
|
|
73
|
+
address: evmAddress,
|
|
74
|
+
storageKeys: arr(str(66, /^0x[0-9a-fA-F]{64}$/), 256)
|
|
75
|
+
}), 256);
|
|
76
|
+
const txBase = {
|
|
77
|
+
chainId: safeInt,
|
|
78
|
+
nonce: safeInt,
|
|
79
|
+
gas: hexQuantity,
|
|
80
|
+
value: hexQuantity,
|
|
81
|
+
data: hexData,
|
|
82
|
+
to: opt(evmAddress)
|
|
83
|
+
};
|
|
84
|
+
const evmTx = union(obj({
|
|
85
|
+
...txBase,
|
|
86
|
+
type: literal("legacy"),
|
|
87
|
+
gasPrice: hexQuantity
|
|
88
|
+
}), obj({
|
|
89
|
+
...txBase,
|
|
90
|
+
type: literal("eip2930"),
|
|
91
|
+
gasPrice: hexQuantity,
|
|
92
|
+
accessList
|
|
93
|
+
}), obj({
|
|
94
|
+
...txBase,
|
|
95
|
+
type: literal("eip1559"),
|
|
96
|
+
maxFeePerGas: hexQuantity,
|
|
97
|
+
maxPriorityFeePerGas: hexQuantity,
|
|
98
|
+
accessList
|
|
99
|
+
}));
|
|
100
|
+
const signRequest = union(obj({
|
|
101
|
+
kind: literal("evm.transaction"),
|
|
102
|
+
network: caip2,
|
|
103
|
+
account: accountRef,
|
|
104
|
+
tx: evmTx
|
|
105
|
+
}), obj({
|
|
106
|
+
kind: literal("evm.personal-message"),
|
|
107
|
+
network: caip2,
|
|
108
|
+
account: accountRef,
|
|
109
|
+
message: bytes(0, 65536)
|
|
110
|
+
}), obj({
|
|
111
|
+
kind: literal("evm.typed-data"),
|
|
112
|
+
network: caip2,
|
|
113
|
+
account: accountRef,
|
|
114
|
+
typedData: str(1048576)
|
|
115
|
+
}), obj({
|
|
116
|
+
kind: literal("solana.transaction"),
|
|
117
|
+
network: caip2,
|
|
118
|
+
account: accountRef,
|
|
119
|
+
message: bytes(1, 1232),
|
|
120
|
+
lookupTables: opt(arr(obj({
|
|
121
|
+
address: solanaAddress,
|
|
122
|
+
addresses: arr(solanaAddress, 256)
|
|
123
|
+
}), 64))
|
|
124
|
+
}), obj({
|
|
125
|
+
kind: literal("solana.message"),
|
|
126
|
+
network: caip2,
|
|
127
|
+
account: accountRef,
|
|
128
|
+
message: bytes(1, 65536),
|
|
129
|
+
format: literal("raw")
|
|
130
|
+
}), obj({
|
|
131
|
+
kind: literal("bitcoin.psbt"),
|
|
132
|
+
network: caip2,
|
|
133
|
+
account: accountRef,
|
|
134
|
+
psbt: bytes(1, 131072),
|
|
135
|
+
sign: arr(int(0, 1024), 1024)
|
|
136
|
+
}), obj({
|
|
137
|
+
kind: literal("bitcoin.message"),
|
|
138
|
+
network: caip2,
|
|
139
|
+
account: accountRef,
|
|
140
|
+
address: bitcoinAddress,
|
|
141
|
+
message: str(1048576),
|
|
142
|
+
format: union(literal("bip322-simple"), literal("legacy")),
|
|
143
|
+
change: union(literal(0), literal(1)),
|
|
144
|
+
index: int(0, 2147483647)
|
|
145
|
+
}));
|
|
146
|
+
const signResult = union(obj({
|
|
147
|
+
kind: literal("evm.transaction"),
|
|
148
|
+
signedTransaction: bytes(1, 65536)
|
|
149
|
+
}), obj({
|
|
150
|
+
kind: union(literal("evm.personal-message"), literal("evm.typed-data")),
|
|
151
|
+
signature: bytes(65, 65)
|
|
152
|
+
}), obj({
|
|
153
|
+
kind: union(literal("solana.transaction"), literal("solana.message")),
|
|
154
|
+
signature: bytes(64, 64)
|
|
155
|
+
}), obj({
|
|
156
|
+
kind: literal("bitcoin.psbt"),
|
|
157
|
+
signedPsbt: bytes(1, 131072)
|
|
158
|
+
}), obj({
|
|
159
|
+
kind: literal("bitcoin.message"),
|
|
160
|
+
signature: str(512)
|
|
161
|
+
}));
|
|
162
|
+
const CHAINS_METHODS = {
|
|
163
|
+
"wallet.accounts": {
|
|
164
|
+
session: true,
|
|
165
|
+
presence: false,
|
|
166
|
+
params: obj({
|
|
167
|
+
walletId,
|
|
168
|
+
groupIndex,
|
|
169
|
+
template,
|
|
170
|
+
network: caip2
|
|
171
|
+
}),
|
|
172
|
+
result: union(addressResult("evm.bip44"), addressResult("solana.bip44-change"), obj({
|
|
173
|
+
template: union(literal("btc.bip44"), literal("btc.bip49"), literal("btc.bip84"), literal("btc.bip86")),
|
|
174
|
+
network: caip2,
|
|
175
|
+
xpub: str(111, /^[a-zA-Z0-9]{111}$/),
|
|
176
|
+
fingerprint: str(8, /^[0-9a-f]{8}$/),
|
|
177
|
+
path: str(11, /^m\/[0-9'/]+$/)
|
|
178
|
+
}))
|
|
179
|
+
},
|
|
180
|
+
"chain.sign": {
|
|
181
|
+
session: true,
|
|
182
|
+
presence: true,
|
|
183
|
+
params: obj({
|
|
184
|
+
request: signRequest,
|
|
185
|
+
verify: factor
|
|
186
|
+
}),
|
|
187
|
+
result: signResult
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
//#endregion
|
|
48
191
|
//#region src/protocol/nostr.ts
|
|
49
192
|
const hex128 = str(128, /^[0-9a-f]{128}$/);
|
|
50
193
|
const nostrKeyRef = union(obj({
|
|
@@ -671,6 +814,7 @@ const METHODS = {
|
|
|
671
814
|
result: statusPayload
|
|
672
815
|
},
|
|
673
816
|
...CORE_METHODS,
|
|
817
|
+
...CHAINS_METHODS,
|
|
674
818
|
...NOSTR_METHODS,
|
|
675
819
|
...SPARK_METHODS
|
|
676
820
|
};
|
|
@@ -692,6 +836,6 @@ const kernelEvent = union(obj({
|
|
|
692
836
|
/** Validates the `err` payload of a response; `ok` is checked against `METHODS[m].result`. */
|
|
693
837
|
const responseError = errorPayload;
|
|
694
838
|
//#endregion
|
|
695
|
-
export { isProtocolValue as a, responseError as c,
|
|
839
|
+
export { isProtocolValue as a, responseError as c, CHAINS_METHODS as d, backupEnvelope as f, backupInfo as g, backupHeader as h, UNATTRIBUTED_ID as i, SPARK_METHODS as l, backupEnvelopeText as m, METHODS as n, kernelEvent as o, backupEnvelopeFactor as p, PROTOCOL_VERSION as r, requestBytes as s, MAX_REQUEST_BYTES as t, NOSTR_METHODS as u };
|
|
696
840
|
|
|
697
|
-
//# sourceMappingURL=protocol-
|
|
841
|
+
//# sourceMappingURL=protocol-DvzlUKB8.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protocol-DvzlUKB8.mjs","names":[],"sources":["../src/protocol/backup.ts","../src/protocol/chains.ts","../src/protocol/nostr.ts","../src/protocol/spark.ts","../src/protocol/index.ts"],"sourcesContent":["/**\n * Backup-envelope wire validators (design/backup.mdx): the strict structural shape the kernel and\n * the host-side `parseBackupHeader` share — version 1, bounded fields, `obj` rejects unknown keys.\n * Cryptographic checks (the payload tag, factor unwrap) stay in the kernel; these rules only shape\n * the JSON.\n */\nimport { safeTime } from \"./core.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport { arr, int, literal, obj, str, union } from \"./validate.ts\";\n\nconst MAX_FACTOR_CHARS = 512;\nconst MAX_STRING_BYTES = 64_000;\nconst MAX_PAYLOAD_CHARS = 1_400_000; // ~1 MiB of sealed bytes in base64url\nconst MAX_ENVELOPE_CHARS = 4_000_000;\n\nexport type BackupEnvelopeFactor =\n | { readonly kind: \"passkey\"; readonly credentialId: string; readonly sealedBek: string }\n | {\n readonly kind: \"password\";\n readonly iterations: 600_000;\n readonly salt: string;\n readonly sealedBek: string;\n };\n\nexport type BackupEnvelopeWire = {\n readonly version: 1;\n readonly createdAt: number;\n /** Raw JSON text — authenticated by the payload tag before it is parsed. */\n readonly header: string;\n readonly factors: ReadonlyArray<BackupEnvelopeFactor>;\n readonly payload: string;\n};\n\n/** One public factor entry — shared by the envelope and the retained `backup-key` header. */\nexport const backupEnvelopeFactor: Validator<BackupEnvelopeFactor> = union(\n obj({\n kind: literal(\"passkey\"),\n credentialId: str(MAX_FACTOR_CHARS),\n sealedBek: str(MAX_FACTOR_CHARS),\n }),\n obj({\n kind: literal(\"password\"),\n iterations: literal(600_000),\n salt: str(128),\n sealedBek: str(MAX_FACTOR_CHARS),\n }),\n);\n\nexport const backupEnvelope: Validator<BackupEnvelopeWire> = obj({\n version: literal(1),\n createdAt: int(0, Number.MAX_SAFE_INTEGER),\n header: str(MAX_STRING_BYTES),\n factors: arr(backupEnvelopeFactor, 5, 1),\n payload: str(MAX_PAYLOAD_CHARS),\n});\n\nexport type BackupHeaderWallet = {\n readonly walletId: string;\n readonly origin: \"mnemonic\" | \"passkey\";\n readonly words: 12 | 15 | 18 | 21 | 24;\n};\n\nexport type BackupHeaderWire = {\n readonly wallets: ReadonlyArray<BackupHeaderWallet>;\n readonly importedNostrKeyCount: number;\n readonly importedChainKeyCount: number;\n};\n\nexport const backupHeader: Validator<BackupHeaderWire> = obj({\n wallets: arr(\n obj({\n walletId: str(128),\n origin: union(literal(\"mnemonic\"), literal(\"passkey\")),\n words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),\n }),\n 1000,\n ),\n importedNostrKeyCount: int(0, 10_000),\n importedChainKeyCount: int(0, 10_000),\n});\n\n/** The whole-envelope text bound — `backup.update` results and `backup.restore` params use it. */\nexport const backupEnvelopeText: Validator<string> = str(MAX_ENVELOPE_CHARS);\n\n/** The status/snapshot summary of a retained backup key — public data only. */\nexport type BackupInfo = {\n readonly id: string; // 32 lowercase hex, HKDF over the BEK\n readonly factors: ReadonlyArray<\"passkey\" | \"password\">;\n readonly createdAt: number;\n};\n\nexport const backupInfo: Validator<BackupInfo> = obj({\n id: str(32, /^[0-9a-f]{32}$/),\n factors: arr(union(literal(\"passkey\"), literal(\"password\")), 5, 1),\n createdAt: safeTime,\n});\n","/**\n * The chains module's method table and wire validators. `wallet.accounts` derives the public\n * account for a template at the wallet's group index — the EVM/Solana arm returns the address; the\n * Bitcoin arm returns the account-level extended public key plus the master fingerprint and account\n * path (both needed to build the PSBT `bip32Derivation` entries later). The protocol is free of\n *\n * @qntx/wallet-chains imports; template names and path shapes are declared here.\n */\nimport type { Factor } from \"./core.ts\";\nimport { factor, groupIndex, walletId } from \"./core.ts\";\nimport type { MethodSpec } from \"./index.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport { arr, bytes, int, literal, obj, opt, str, union } from \"./validate.ts\";\n\nexport type ChainTemplate =\n | \"evm.bip44\"\n | \"solana.bip44-change\"\n | \"btc.bip44\"\n | \"btc.bip49\"\n | \"btc.bip84\"\n | \"btc.bip86\";\n\nexport type ChainAccountsParams = {\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: ChainTemplate;\n readonly network: string;\n};\n\nexport type ChainAccount =\n | {\n readonly template: \"evm.bip44\";\n readonly network: string;\n readonly address: string;\n }\n | {\n readonly template: \"solana.bip44-change\";\n readonly network: string;\n readonly address: string;\n }\n | {\n readonly template: \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n readonly network: string;\n readonly xpub: string;\n /** Master-key fingerprint as 8 lowercase hex chars (PSBT bip32Derivation). */\n readonly fingerprint: string;\n /** Account derivation path, e.g. \"m/84'/0'/0'\". */\n readonly path: string;\n };\n\nconst template: Validator<ChainTemplate> = union(\n literal(\"evm.bip44\"),\n literal(\"solana.bip44-change\"),\n union(literal(\"btc.bip44\"), literal(\"btc.bip49\"), literal(\"btc.bip84\")),\n literal(\"btc.bip86\"),\n);\n\nconst caip2: Validator<string> = str(200, /^[a-z0-9-]{3,64}:[0-9a-zA-Z-]{1,128}$/);\nconst addressResult = (t: \"evm.bip44\" | \"solana.bip44-change\"): Validator<ChainAccount> =>\n obj({\n template: literal(t),\n network: caip2,\n address: str(128, /^[0-9a-zA-Z-]{20,128}$/),\n });\n\nexport type AccountRef =\n | {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: ChainTemplate;\n }\n | {\n readonly kind: \"imported\";\n readonly keyId: string;\n readonly family: \"evm\" | \"solana\" | \"bitcoin\";\n };\n\nexport type EvmAccessListEntryWire = {\n readonly address: string;\n readonly storageKeys: ReadonlyArray<string>;\n};\n\ntype EvmTransactionBase = {\n readonly chainId: number;\n readonly nonce: number;\n readonly gas: string;\n readonly value: string;\n readonly data: string;\n readonly to?: string;\n};\n\nexport type EvmTransactionWire =\n | (EvmTransactionBase & { readonly type: \"legacy\"; readonly gasPrice: string })\n | (EvmTransactionBase & {\n readonly type: \"eip2930\";\n readonly gasPrice: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;\n })\n | (EvmTransactionBase & {\n readonly type: \"eip1559\";\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;\n });\n\n/** `chain.sign`'s request — the wire mirror of @qntx/wallet-chains `SignRequest`. */\nexport type ChainSignRequest =\n | {\n readonly kind: \"evm.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly tx: EvmTransactionWire;\n }\n | {\n readonly kind: \"evm.personal-message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n }\n | {\n readonly kind: \"evm.typed-data\";\n readonly network: string;\n readonly account: AccountRef;\n readonly typedData: string;\n }\n | {\n readonly kind: \"solana.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n readonly lookupTables?: ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>;\n }\n | {\n readonly kind: \"solana.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n readonly format: \"raw\";\n }\n | {\n readonly kind: \"bitcoin.psbt\";\n readonly network: string;\n readonly account: AccountRef;\n readonly psbt: Uint8Array;\n readonly sign: ReadonlyArray<number>;\n }\n | {\n readonly kind: \"bitcoin.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly address: string;\n readonly message: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly change: 0 | 1;\n readonly index: number;\n };\n\nexport type ChainSignResult =\n | { readonly kind: \"evm.transaction\"; readonly signedTransaction: Uint8Array }\n | { readonly kind: \"evm.personal-message\" | \"evm.typed-data\"; readonly signature: Uint8Array }\n | { readonly kind: \"solana.transaction\" | \"solana.message\"; readonly signature: Uint8Array }\n | { readonly kind: \"bitcoin.psbt\"; readonly signedPsbt: Uint8Array }\n | { readonly kind: \"bitcoin.message\"; readonly signature: string };\n\nexport type ChainSignParams = { readonly request: ChainSignRequest; readonly verify: Factor };\n\nconst accountRef: Validator<AccountRef> = union(\n obj({ kind: literal(\"hd\"), walletId, groupIndex, template }),\n obj({\n kind: literal(\"imported\"),\n keyId: str(64, /^[0-9a-f]{8,64}$/),\n family: union(literal(\"evm\"), literal(\"solana\"), literal(\"bitcoin\")),\n }),\n);\n\nconst hexQuantity = str(66, /^0x[0-9a-fA-F]+$/);\nconst hexData = str(40000, /^0x[0-9a-fA-F]*$/);\nconst evmAddress = str(42, /^0x[0-9a-fA-F]{40}$/);\nconst solanaAddress = str(44, /^[1-9A-HJ-NP-Za-km-z]{32,44}$/);\nconst bitcoinAddress = str(90, /^(bc1|tb1|bcrt1|[13mn2])[a-zA-Z0-9]{4,87}$/);\nconst safeInt = int(0, 9007199254740991);\nconst accessList = arr(\n obj({ address: evmAddress, storageKeys: arr(str(66, /^0x[0-9a-fA-F]{64}$/), 256) }),\n 256,\n);\nconst txBase = {\n chainId: safeInt,\n nonce: safeInt,\n gas: hexQuantity,\n value: hexQuantity,\n data: hexData,\n to: opt(evmAddress),\n};\nconst evmTx: Validator<EvmTransactionWire> = union(\n obj({ ...txBase, type: literal(\"legacy\"), gasPrice: hexQuantity }),\n obj({ ...txBase, type: literal(\"eip2930\"), gasPrice: hexQuantity, accessList }),\n obj({\n ...txBase,\n type: literal(\"eip1559\"),\n maxFeePerGas: hexQuantity,\n maxPriorityFeePerGas: hexQuantity,\n accessList,\n }),\n);\n\nconst signRequest: Validator<ChainSignRequest> = union(\n obj({ kind: literal(\"evm.transaction\"), network: caip2, account: accountRef, tx: evmTx }),\n obj({\n kind: literal(\"evm.personal-message\"),\n network: caip2,\n account: accountRef,\n message: bytes(0, 65536),\n }),\n obj({\n kind: literal(\"evm.typed-data\"),\n network: caip2,\n account: accountRef,\n typedData: str(1048576),\n }),\n obj({\n kind: literal(\"solana.transaction\"),\n network: caip2,\n account: accountRef,\n message: bytes(1, 1232),\n lookupTables: opt(arr(obj({ address: solanaAddress, addresses: arr(solanaAddress, 256) }), 64)),\n }),\n obj({\n kind: literal(\"solana.message\"),\n network: caip2,\n account: accountRef,\n message: bytes(1, 65536),\n format: literal(\"raw\"),\n }),\n obj({\n kind: literal(\"bitcoin.psbt\"),\n network: caip2,\n account: accountRef,\n psbt: bytes(1, 131072),\n sign: arr(int(0, 1024), 1024),\n }),\n obj({\n kind: literal(\"bitcoin.message\"),\n network: caip2,\n account: accountRef,\n address: bitcoinAddress,\n message: str(1048576),\n format: union(literal(\"bip322-simple\"), literal(\"legacy\")),\n change: union(literal(0), literal(1)),\n index: int(0, 2147483647),\n }),\n);\n\nconst signResult: Validator<ChainSignResult> = union(\n obj({ kind: literal(\"evm.transaction\"), signedTransaction: bytes(1, 65536) }),\n obj({\n kind: union(literal(\"evm.personal-message\"), literal(\"evm.typed-data\")),\n signature: bytes(65, 65),\n }),\n obj({\n kind: union(literal(\"solana.transaction\"), literal(\"solana.message\")),\n signature: bytes(64, 64),\n }),\n obj({ kind: literal(\"bitcoin.psbt\"), signedPsbt: bytes(1, 131072) }),\n obj({ kind: literal(\"bitcoin.message\"), signature: str(512) }),\n);\n\nexport const CHAINS_METHODS: {\n readonly \"wallet.accounts\": MethodSpec<ChainAccountsParams, ChainAccount>;\n readonly \"chain.sign\": MethodSpec<ChainSignParams, ChainSignResult>;\n} = {\n \"wallet.accounts\": {\n session: true,\n presence: false,\n params: obj({ walletId, groupIndex, template, network: caip2 }),\n result: union(\n addressResult(\"evm.bip44\"),\n addressResult(\"solana.bip44-change\"),\n obj({\n template: union(\n literal(\"btc.bip44\"),\n literal(\"btc.bip49\"),\n literal(\"btc.bip84\"),\n literal(\"btc.bip86\"),\n ),\n network: caip2,\n xpub: str(111, /^[a-zA-Z0-9]{111}$/),\n fingerprint: str(8, /^[0-9a-f]{8}$/),\n path: str(11, /^m\\/[0-9'/]+$/),\n }),\n ),\n },\n \"chain.sign\": {\n session: true,\n presence: true,\n params: obj({ request: signRequest, verify: factor }),\n result: signResult,\n },\n};\n","/**\n * The nostr module's method table and wire validators. The protocol stays free of @qntx/nostr\n * imports — even types — so the event shapes it validates are declared here structurally; a\n * type-level test in packages/wallet/tests pins them assignable to and from @qntx/nostr's\n * Event/UnsignedEvent/Rumor.\n */\nimport type { DerivedNostrKey, NostrKeyInfo, WalletErrorCode } from \"../types.ts\";\nimport {\n factor,\n groupIndex,\n MAX_BATCH,\n MAX_SNAPSHOT_ITEMS,\n MAX_TAG_ITEM,\n MAX_TAG_ITEMS,\n MAX_TAGS,\n MAX_TEXT,\n publicKey,\n safeTime,\n sessionId,\n walletErrorCode,\n walletId,\n} from \"./core.ts\";\nimport type { Factor } from \"./core.ts\";\nimport type { MethodSpec, NullValue } from \"./index.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport { arr, bool, bytes, int, literal, nullValue, obj, opt, str, union } from \"./validate.ts\";\n\n/**\n * The unsigned event input the kernel signs. `pubkey` is optional: callers may omit it and the\n * kernel fills the signing key's own. Structurally compatible with @qntx/nostr's UnsignedEvent.\n */\nexport type UnsignedEventInput = {\n readonly kind: number;\n readonly created_at: number;\n readonly tags: ReadonlyArray<ReadonlyArray<string>>;\n readonly content: string;\n readonly pubkey?: string;\n};\n\n/** The signed event the kernel returns — the Nostr event minus `id`-less forms. */\nexport type SignedEvent = {\n readonly id: string;\n readonly pubkey: string;\n readonly sig: string;\n readonly kind: number;\n readonly created_at: number;\n readonly tags: ReadonlyArray<ReadonlyArray<string>>;\n readonly content: string;\n};\n\n/** A NIP-59 rumor: an unsigned event carrying a computed `id` but no `sig`. */\nexport type Rumor = {\n readonly id: string;\n readonly pubkey: string;\n readonly kind: number;\n readonly created_at: number;\n readonly tags: ReadonlyArray<ReadonlyArray<string>>;\n readonly content: string;\n};\n\nexport type NostrImportInput =\n | { readonly kind: \"nsec\"; readonly nsec: Uint8Array }\n | { readonly kind: \"ncryptsec\"; readonly ncryptsec: string; readonly password: Uint8Array };\n\nexport type NostrExportFormat =\n | { readonly kind: \"nsec\" }\n | { readonly kind: \"ncryptsec\"; readonly password: Uint8Array };\n\n/** One \"import/generate a key\" result: the key's public info plus the session it may have opened. */\nexport type KeyResult = { readonly key: NostrKeyInfo; readonly session: string };\n\nexport type UnwrapResult = { readonly ok: Rumor } | { readonly err: WalletErrorCode };\n\nconst hex128: Validator<string> = str(128, /^[0-9a-f]{128}$/);\n\nconst nostrKeyRef = union(\n obj({ kind: literal(\"derived\"), walletId, groupIndex }),\n obj({ kind: literal(\"standalone\"), id: publicKey }),\n obj({ kind: literal(\"nip46-client\"), id: publicKey }),\n);\n\n// `backedUp` exists only on the standalone origins — the kernel never emits it for derived or\n// nip46-client keys, and a peer that does is untrustworthy.\nexport const nostrKeyInfo: Validator<NostrKeyInfo> = union(\n obj({\n ref: nostrKeyRef,\n publicKey,\n origin: union(literal(\"nsec\"), literal(\"ncryptsec\"), literal(\"generated\")),\n backedUp: bool,\n createdAt: safeTime,\n }),\n obj({\n ref: nostrKeyRef,\n publicKey,\n origin: union(literal(\"derived\"), literal(\"nip46-client\")),\n createdAt: safeTime,\n }),\n);\n\n/** The nostr section of the status payload, composed by protocol/index.ts. */\nexport const nostrStatus: Validator<{ readonly keys: ReadonlyArray<NostrKeyInfo> }> = obj({\n keys: arr(nostrKeyInfo, MAX_SNAPSHOT_ITEMS),\n});\n\nconst keyResult: Validator<KeyResult> = obj({ key: nostrKeyInfo, session: sessionId });\n\nconst derivedNostrKey: Validator<DerivedNostrKey> = obj({ groupIndex, publicKey });\n\nconst tags: Validator<ReadonlyArray<ReadonlyArray<string>>> = arr(\n arr(str(MAX_TAG_ITEM), MAX_TAG_ITEMS),\n MAX_TAGS,\n);\n\nconst signEventInput: Validator<UnsignedEventInput> = obj({\n kind: int(0, 65535),\n created_at: safeTime,\n tags,\n content: str(MAX_TEXT),\n pubkey: opt(publicKey),\n});\n\nconst signedEvent: Validator<SignedEvent> = obj({\n id: publicKey,\n pubkey: publicKey,\n sig: hex128,\n kind: int(0, 65535),\n created_at: safeTime,\n tags,\n content: str(MAX_TEXT),\n});\n\nconst rumor: Validator<Rumor> = obj({\n id: publicKey,\n pubkey: publicKey,\n kind: int(0, 65535),\n created_at: safeTime,\n tags,\n content: str(MAX_TEXT),\n});\n\nconst nostrImportInput: Validator<NostrImportInput> = union(\n obj({ kind: literal(\"nsec\"), nsec: bytes(1, 256) }),\n obj({ kind: literal(\"ncryptsec\"), ncryptsec: str(512, /^ncryptsec1/), password: bytes(1, 1024) }),\n);\n\nconst nostrExportFormat: Validator<NostrExportFormat> = union(\n obj({ kind: literal(\"nsec\") }),\n obj({ kind: literal(\"ncryptsec\"), password: bytes(1, 1024) }),\n);\n\nconst textParams = obj({ publicKey, peer: publicKey, text: str(MAX_TEXT) });\nconst textResult = str(MAX_TEXT * 4);\n\nexport const NOSTR_METHODS: {\n readonly \"nostr.discover\": MethodSpec<\n { readonly walletId: string; readonly from: number; readonly count: number },\n { readonly keys: ReadonlyArray<DerivedNostrKey> }\n >;\n readonly \"nostr.deriveKey\": MethodSpec<\n { readonly walletId: string; readonly groupIndex: number },\n NostrKeyInfo\n >;\n readonly \"nostr.importKey\": MethodSpec<\n { readonly input: NostrImportInput; readonly factor?: Factor },\n KeyResult\n >;\n readonly \"nostr.generateKey\": MethodSpec<{ readonly factor?: Factor }, KeyResult>;\n readonly \"nostr.createNip46ClientKey\": MethodSpec<NullValue, NostrKeyInfo>;\n readonly \"nostr.removeKey\": MethodSpec<\n { readonly publicKey: string; readonly verify?: Factor },\n NullValue\n >;\n readonly \"nostr.exportKey\": MethodSpec<\n { readonly verify: Factor; readonly publicKey: string; readonly format: NostrExportFormat },\n Uint8Array\n >;\n readonly \"nostr.signEvent\": MethodSpec<\n { readonly publicKey: string; readonly event: UnsignedEventInput },\n SignedEvent\n >;\n readonly \"nostr.nip04Encrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.nip04Decrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.nip44Encrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.nip44Decrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.unwrapGiftWraps\": MethodSpec<\n { readonly publicKey: string; readonly events: ReadonlyArray<SignedEvent> },\n { readonly results: ReadonlyArray<UnwrapResult> }\n >;\n} = {\n \"nostr.discover\": {\n session: true,\n presence: false,\n params: obj({ walletId, from: groupIndex, count: int(1, 20) }),\n result: obj({ keys: arr(derivedNostrKey, 20) }),\n },\n \"nostr.deriveKey\": {\n session: true,\n presence: false,\n params: obj({ walletId, groupIndex }),\n result: nostrKeyInfo,\n },\n \"nostr.importKey\": {\n session: false,\n presence: true,\n params: obj({ input: nostrImportInput, factor: opt(factor) }),\n result: keyResult,\n },\n \"nostr.generateKey\": {\n session: false,\n presence: true,\n params: obj({ factor: opt(factor) }),\n result: keyResult,\n },\n \"nostr.createNip46ClientKey\": {\n session: true,\n presence: false,\n params: nullValue,\n result: nostrKeyInfo,\n },\n \"nostr.removeKey\": {\n session: true,\n presence: true,\n params: obj({ publicKey, verify: opt(factor) }),\n result: nullValue,\n },\n \"nostr.exportKey\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, publicKey, format: nostrExportFormat }),\n result: bytes(16, 4096),\n },\n \"nostr.signEvent\": {\n session: true,\n presence: false,\n params: obj({ publicKey, event: signEventInput }),\n result: signedEvent,\n },\n \"nostr.nip04Encrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.nip04Decrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.nip44Encrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.nip44Decrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.unwrapGiftWraps\": {\n session: true,\n presence: false,\n params: obj({ publicKey, events: arr(signedEvent, MAX_BATCH) }),\n result: obj({\n results: arr(union(obj({ ok: rumor }), obj({ err: walletErrorCode })), MAX_BATCH),\n }),\n },\n};\n","/**\n * The spark module's method table and wire validators. The protocol stays free of @qntx/spark\n * imports — even types — so the signer shapes it validates are declared here structurally; a\n * type-level test in packages/wallet/tests pins them assignable to and from @qntx/spark/signer's\n * types.\n *\n * Every method carries `account` — walletId/groupIndex/network — and is session-gated but not\n * presence-bearing (signer work must not hold a session open). List params are capped at MAX_BATCH;\n * the leaf lists of prepareTransfer/prepareClaim are capped at the signer's own 256.\n */\nimport { factor, groupIndex, MAX_BATCH, safeTime, walletId } from \"./core.ts\";\nimport type { Factor } from \"./core.ts\";\nimport type { MethodSpec } from \"./index.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport {\n arr,\n bytes,\n int,\n literal,\n obj,\n opt,\n record,\n str,\n union,\n ValidationError,\n} from \"./validate.ts\";\n\n/** The Spark network the account's signer runs on — identical to @qntx/spark's SparkNetwork. */\nexport type SparkNetwork = \"mainnet\" | \"regtest\";\n\n/** The wallet+group+network triple every spark.* request addresses a pooled signer by. */\nexport type SparkAccountRef = {\n readonly walletId: string;\n readonly groupIndex: number;\n readonly network: SparkNetwork;\n};\n\nexport type SparkLeafKey =\n | { readonly type: \"leaf\"; readonly leafId: string }\n | { readonly type: \"static-deposit\"; readonly index: number };\n\nexport type SparkKey =\n | SparkLeafKey\n | { readonly type: \"received\"; readonly ciphertext: Uint8Array };\n\nexport type SigningCommitment = {\n readonly hiding: Uint8Array;\n readonly binding: Uint8Array;\n};\n\nexport type OperatorCommitment = {\n readonly identifier: string;\n readonly commitment: SigningCommitment;\n};\n\nexport type SigningTarget = {\n readonly transaction: Uint8Array;\n readonly inputIndex: number;\n readonly prevouts: ReadonlyArray<{\n script: Uint8Array;\n amount: number;\n }>;\n};\n\nexport type FrostSignJob = {\n readonly key: SparkKey;\n readonly target: SigningTarget;\n readonly verifyingKey: Uint8Array;\n readonly commitment: SigningCommitment;\n readonly operatorCommitments: ReadonlyArray<OperatorCommitment>;\n readonly adaptorPublicKey?: Uint8Array;\n /** Connector-refund proof pair — see `FrostSignJob.exit` in @qntx/spark/signer. */\n readonly exit?: {\n readonly connectorTx: Uint8Array;\n readonly exitTx: Uint8Array;\n };\n};\n\nexport type FrostAggregateJob = {\n readonly key: SparkKey;\n readonly target: SigningTarget;\n readonly verifyingKey: Uint8Array;\n readonly commitment: SigningCommitment;\n readonly signatureShare: Uint8Array;\n readonly operators: ReadonlyArray<{\n readonly identifier: string;\n readonly commitment: SigningCommitment;\n readonly signatureShare: Uint8Array;\n readonly publicKey: Uint8Array;\n }>;\n readonly adaptorPublicKey?: Uint8Array;\n};\n\nexport type StaticDepositClaimStatement = {\n readonly kind: \"static-deposit-claim\";\n readonly network: SparkNetwork;\n readonly txid: Uint8Array;\n readonly vout: number;\n readonly creditAmountSats: number;\n readonly sspSignature: Uint8Array;\n};\n\nexport type IdentityStatement =\n | { readonly kind: \"so-challenge\"; readonly challenge: Uint8Array }\n | { readonly kind: \"ssp-challenge\"; readonly protectedChallenge: string }\n | { readonly kind: \"transfer-package\"; readonly transferId: string; readonly package: Uint8Array }\n | { readonly kind: \"claim-package\"; readonly transferId: string; readonly package: Uint8Array }\n | StaticDepositClaimStatement\n | {\n readonly kind: \"static-deposit-refund\";\n readonly network: SparkNetwork;\n readonly txid: Uint8Array;\n readonly vout: number;\n readonly amount: number;\n readonly target: SigningTarget;\n }\n | {\n readonly kind: \"watchtower-recovery\";\n readonly network: SparkNetwork;\n readonly leafId: string;\n readonly target: SigningTarget;\n }\n | { readonly kind: \"spark-invoice\"; readonly invoice: Uint8Array }\n | { readonly kind: \"token-transaction\"; readonly partialTransaction: Uint8Array }\n | {\n readonly kind: \"lightning-address\";\n readonly action: \"register\";\n readonly domain: string;\n readonly username: string;\n readonly description: string;\n readonly timestamp: number;\n }\n | {\n readonly kind: \"lightning-address\";\n readonly action: \"unregister\";\n readonly domain: string;\n readonly username: string;\n readonly timestamp: number;\n };\n\nexport type PrepareTransferRequest = {\n readonly transferId: string;\n readonly leaves: ReadonlyArray<{\n readonly leafId: string;\n readonly key: SparkLeafKey;\n readonly receiverIdentityPublicKey: Uint8Array;\n }>;\n};\n\nexport type PreparedTransferLeaf = {\n readonly leafId: string;\n readonly newPublicKey: Uint8Array;\n readonly secretCipher: Uint8Array;\n readonly signature: Uint8Array;\n};\n\nexport type PreparedTransfer = {\n readonly operatorPackages: Record<string, Uint8Array>;\n readonly leaves: ReadonlyArray<PreparedTransferLeaf>;\n};\n\nexport type PrepareClaimRequest = {\n readonly transferId: string;\n readonly leaves: ReadonlyArray<{\n readonly leafId: string;\n readonly secretCipher: Uint8Array;\n }>;\n};\n\nexport type PreparedClaim = {\n readonly operatorPackages: Record<string, Uint8Array>;\n};\n\nexport type PreparedLightningReceive = {\n readonly paymentHash: Uint8Array;\n readonly operatorPackages: Record<string, Uint8Array>;\n};\n\nexport type HtlcTimeoutSignRequest = {\n readonly transaction: Uint8Array;\n readonly inputIndex: number;\n readonly prevoutAmountSats: number;\n readonly paymentHash: Uint8Array;\n readonly hashLockPublicKey: Uint8Array;\n};\n\nexport type StaticDepositClaimRequest = {\n readonly index: number;\n readonly statement: StaticDepositClaimStatement;\n};\n\nexport type StaticDepositClaimResult = {\n readonly encryptedSecretKey: Uint8Array;\n readonly signature: Uint8Array;\n};\n\n// Field bounds. Where @qntx/spark/signer constrains a value the same rule is mirrored (64-hex\n// identifiers, 32/33/64-byte keys and signatures, 1..MAX_BATCH counts); where it leaves a value\n// unbounded (leafId/transferId are hashed as UTF-8, ciphertexts and protobuf blobs are bytes) the\n// protocol still needs a size — the MAX_REQUEST_BYTES envelope cap makes these generous bounds\n// sufficient rather than security-critical.\nconst MAX_LEAVES = 256;\nconst MAX_OPERATORS = 16;\nconst MAX_PACKAGE_BYTES = 1_048_576;\nconst MAX_TX_BYTES = 1_048_576;\nconst MAX_PREVOUTS = 1024;\nconst MAX_SCRIPT_BYTES = 16_384;\nconst MAX_CIPHERTEXT_BYTES = 4096;\nconst MAX_SATS = 2_100_000_000_000_000; // 21M BTC in sats\n\nconst network: Validator<SparkNetwork> = union(literal(\"mainnet\"), literal(\"regtest\"));\nconst account: Validator<SparkAccountRef> = obj({ walletId, groupIndex, network });\n\nconst identifier: Validator<string> = str(64, /^[0-9a-f]{64}$/);\nconst leafId: Validator<string> = str(64);\nconst transferId: Validator<string> = str(64);\nconst bytes32: Validator<Uint8Array> = bytes(32);\nconst bytes33: Validator<Uint8Array> = bytes(33);\nconst bytes64: Validator<Uint8Array> = bytes(64);\nconst ciphertext: Validator<Uint8Array> = bytes(1, MAX_CIPHERTEXT_BYTES);\nconst sats: Validator<number> = int(0, MAX_SATS);\n\nconst sparkLeafKey: Validator<SparkLeafKey> = union(\n obj({ type: literal(\"leaf\"), leafId }),\n obj({ type: literal(\"static-deposit\"), index: int(0, 0x7fffffff) }),\n);\n\nconst sparkKey: Validator<SparkKey> = union(\n obj({ type: literal(\"leaf\"), leafId }),\n obj({ type: literal(\"static-deposit\"), index: int(0, 0x7fffffff) }),\n obj({ type: literal(\"received\"), ciphertext }),\n);\n\nconst signingCommitment: Validator<SigningCommitment> = obj({\n hiding: bytes33,\n binding: bytes33,\n});\n\nconst operatorCommitment: Validator<OperatorCommitment> = obj({\n identifier,\n commitment: signingCommitment,\n});\n\nconst signingTarget: Validator<SigningTarget> = obj({\n transaction: bytes(1, MAX_TX_BYTES),\n inputIndex: int(0, 0x7fffffff),\n prevouts: arr(obj({ script: bytes(0, MAX_SCRIPT_BYTES), amount: sats }), MAX_PREVOUTS),\n});\n\nconst adaptorPublicKey = opt(union(bytes(0), bytes(33)));\n\nconst frostSignJob: Validator<FrostSignJob> = obj({\n key: sparkKey,\n target: signingTarget,\n verifyingKey: bytes33,\n commitment: signingCommitment,\n operatorCommitments: arr(operatorCommitment, MAX_OPERATORS),\n adaptorPublicKey,\n});\n\nconst frostAggregateJob: Validator<FrostAggregateJob> = obj({\n key: sparkKey,\n target: signingTarget,\n verifyingKey: bytes33,\n commitment: signingCommitment,\n signatureShare: bytes32,\n operators: arr(\n obj({\n identifier,\n commitment: signingCommitment,\n signatureShare: bytes32,\n publicKey: bytes33,\n }),\n MAX_OPERATORS,\n ),\n adaptorPublicKey,\n});\n\nconst staticDepositClaimStatement: Validator<StaticDepositClaimStatement> = obj({\n kind: literal(\"static-deposit-claim\"),\n network,\n txid: bytes32,\n vout: int(0, 0x7fffffff),\n creditAmountSats: sats,\n sspSignature: bytes(1, 1024),\n});\n\nconst identityStatement: Validator<IdentityStatement> = union(\n obj({ kind: literal(\"so-challenge\"), challenge: bytes(1, 4096) }),\n obj({ kind: literal(\"ssp-challenge\"), protectedChallenge: str(8192) }),\n obj({\n kind: literal(\"transfer-package\"),\n transferId,\n package: bytes(1, MAX_PACKAGE_BYTES),\n }),\n obj({\n kind: literal(\"claim-package\"),\n transferId,\n package: bytes(1, MAX_PACKAGE_BYTES),\n }),\n staticDepositClaimStatement,\n obj({\n kind: literal(\"static-deposit-refund\"),\n network,\n txid: bytes32,\n vout: int(0, 0x7fffffff),\n amount: sats,\n target: signingTarget,\n }),\n obj({\n kind: literal(\"watchtower-recovery\"),\n network,\n leafId,\n target: signingTarget,\n }),\n obj({ kind: literal(\"spark-invoice\"), invoice: bytes(1, 65_536) }),\n obj({ kind: literal(\"token-transaction\"), partialTransaction: bytes(1, MAX_PACKAGE_BYTES) }),\n obj({\n kind: literal(\"lightning-address\"),\n action: literal(\"register\"),\n domain: str(253),\n username: str(64, /^[a-z0-9\\-_.+]{1,64}$/u),\n description: str(512),\n timestamp: safeTime,\n }),\n obj({\n kind: literal(\"lightning-address\"),\n action: literal(\"unregister\"),\n domain: str(253),\n username: str(64, /^[a-z0-9\\-_.+]{1,64}$/u),\n timestamp: safeTime,\n }),\n);\n\nconst htlcTimeoutRequest: Validator<HtlcTimeoutSignRequest> = obj({\n transaction: bytes(1, MAX_TX_BYTES),\n inputIndex: int(0, 0x7fffffff),\n prevoutAmountSats: sats,\n paymentHash: bytes32,\n hashLockPublicKey: bytes33,\n});\n\nconst prepareTransferRequest: Validator<PrepareTransferRequest> = obj({\n transferId,\n leaves: arr(\n obj({ leafId, key: sparkLeafKey, receiverIdentityPublicKey: bytes33 }),\n MAX_LEAVES,\n 1,\n ),\n});\n\nconst preparedTransfer: Validator<PreparedTransfer> = obj({\n operatorPackages: record(identifier, bytes(1, MAX_PACKAGE_BYTES), MAX_OPERATORS),\n leaves: arr(\n obj({\n leafId,\n newPublicKey: bytes33,\n secretCipher: ciphertext,\n signature: bytes64,\n }),\n MAX_LEAVES,\n ),\n});\n\nconst prepareClaimRequest: Validator<PrepareClaimRequest> = obj({\n transferId,\n leaves: arr(obj({ leafId, secretCipher: ciphertext }), MAX_LEAVES, 1),\n});\n\nconst preparedClaim: Validator<PreparedClaim> = obj({\n operatorPackages: record(identifier, bytes(1, MAX_PACKAGE_BYTES), MAX_OPERATORS),\n});\n\nconst preparedLightningReceive: Validator<PreparedLightningReceive> = obj({\n paymentHash: bytes32,\n operatorPackages: record(identifier, bytes(1, MAX_PACKAGE_BYTES), MAX_OPERATORS),\n});\n\nconst staticDepositClaimRequest: Validator<StaticDepositClaimRequest> = obj({\n index: int(0, 0x7fffffff),\n statement: staticDepositClaimStatement,\n});\n\nconst staticDepositClaimResult: Validator<StaticDepositClaimResult> = obj({\n encryptedSecretKey: bytes(1, MAX_CIPHERTEXT_BYTES),\n signature: bytes(64, 128),\n});\n\n/**\n * The intent a `spark.approve` registers — kernel-decoded before the host ever displays it. `token`\n * receivers' amounts are canonical decimal strings in the u128 range.\n */\nexport type SparkApproveIntent =\n | {\n readonly kind: \"transfer\";\n readonly receivers: ReadonlyArray<{\n readonly identityPublicKey: Uint8Array;\n readonly amountSats: number;\n }>;\n }\n | {\n readonly kind: \"lightning\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"exit\";\n readonly address: string;\n readonly amountSats: number;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"onchain\";\n readonly address: string;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"token\";\n readonly tokenIdentifier: Uint8Array;\n readonly receivers: ReadonlyArray<{\n readonly ownerPublicKey: Uint8Array;\n readonly amount: string;\n }>;\n };\n\n/**\n * What `spark.approve` returns: the kernel's own decode of the intent — receivers and amounts, the\n * invoice's payment hash and amount, or the exit/onchain destination — never host-provided text.\n */\nexport type SparkApprovalSummary =\n | {\n readonly kind: \"transfer\";\n readonly receivers: ReadonlyArray<{\n readonly identityPublicKey: Uint8Array;\n readonly amountSats: number;\n }>;\n }\n | {\n readonly kind: \"lightning\";\n readonly paymentHash: Uint8Array;\n readonly invoiceAmountSats?: number;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"exit\";\n readonly address: string;\n readonly amountSats: number;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"onchain\";\n readonly address: string;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"token\";\n readonly tokenIdentifier: Uint8Array;\n readonly receivers: ReadonlyArray<{\n readonly ownerPublicKey: Uint8Array;\n readonly amount: string;\n }>;\n };\n\n// sats amounts are bounded by the protocol's safe-integer contract; u128 token amounts\n// travel as canonical decimal strings.\nconst satsAmount = (): Validator<number> => int(0, Number.MAX_SAFE_INTEGER);\nconst U128_MAX = 340282366920938463463374607431768211455n;\n// Canonical decimal u128: \"0\" or no leading zeros, at most 2^128 − 1.\nconst decimalU128: Validator<string> = (value) => {\n if (\n typeof value !== \"string\" ||\n value.length > 39 ||\n !/^(?:0|[1-9][0-9]*)$/.test(value) ||\n BigInt(value) > U128_MAX\n ) {\n throw new ValidationError();\n }\n return value;\n};\nconst approveIntent: Validator<SparkApproveIntent> = union(\n obj({\n kind: literal(\"transfer\"),\n receivers: arr(obj({ identityPublicKey: bytes(33), amountSats: satsAmount() }), 256, 1),\n }),\n obj({\n kind: literal(\"lightning\"),\n invoice: str(4096),\n amountSats: opt(satsAmount()),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"exit\"),\n address: str(128),\n amountSats: satsAmount(),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"onchain\"),\n address: str(128),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"token\"),\n tokenIdentifier: bytes(32),\n receivers: arr(obj({ ownerPublicKey: bytes(33), amount: decimalU128 }), 256, 1),\n }),\n);\n\nconst approvalSummary: Validator<SparkApprovalSummary> = union(\n obj({\n kind: literal(\"transfer\"),\n receivers: arr(obj({ identityPublicKey: bytes(33), amountSats: satsAmount() }), 256, 1),\n }),\n obj({\n kind: literal(\"lightning\"),\n paymentHash: bytes(32),\n invoiceAmountSats: opt(satsAmount()),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"exit\"),\n address: str(128),\n amountSats: satsAmount(),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"onchain\"),\n address: str(128),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"token\"),\n tokenIdentifier: bytes(32),\n receivers: arr(obj({ ownerPublicKey: bytes(33), amount: decimalU128 }), 256, 1),\n }),\n);\n\nexport const SPARK_METHODS: {\n readonly \"spark.identityPublicKey\": MethodSpec<{ readonly account: SparkAccountRef }, Uint8Array>;\n readonly \"spark.publicKeys\": MethodSpec<\n { readonly account: SparkAccountRef; readonly keys: ReadonlyArray<SparkLeafKey> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.receivedPublicKeys\": MethodSpec<\n { readonly account: SparkAccountRef; readonly ciphertexts: ReadonlyArray<Uint8Array> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.newCommitments\": MethodSpec<\n { readonly account: SparkAccountRef; readonly count: number },\n ReadonlyArray<SigningCommitment>\n >;\n readonly \"spark.signFrost\": MethodSpec<\n { readonly account: SparkAccountRef; readonly jobs: ReadonlyArray<FrostSignJob> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.aggregateFrost\": MethodSpec<\n { readonly account: SparkAccountRef; readonly jobs: ReadonlyArray<FrostAggregateJob> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.signIdentity\": MethodSpec<\n { readonly account: SparkAccountRef; readonly statement: IdentityStatement },\n Uint8Array\n >;\n readonly \"spark.signKeySpend\": MethodSpec<\n {\n readonly account: SparkAccountRef;\n readonly key: SparkKey;\n readonly target: SigningTarget;\n },\n Uint8Array\n >;\n readonly \"spark.signHtlcTimeout\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: HtlcTimeoutSignRequest },\n Uint8Array\n >;\n readonly \"spark.prepareTransfer\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: PrepareTransferRequest },\n PreparedTransfer\n >;\n readonly \"spark.prepareClaim\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: PrepareClaimRequest },\n PreparedClaim\n >;\n readonly \"spark.prepareLightningReceive\": MethodSpec<\n { readonly account: SparkAccountRef },\n PreparedLightningReceive\n >;\n readonly \"spark.claimStaticDeposit\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: StaticDepositClaimRequest },\n StaticDepositClaimResult\n >;\n readonly \"spark.approve\": MethodSpec<\n {\n readonly account: SparkAccountRef;\n readonly intent: SparkApproveIntent;\n readonly verify: Factor;\n },\n SparkApprovalSummary\n >;\n} = {\n \"spark.identityPublicKey\": {\n session: true,\n presence: false,\n params: obj({ account }),\n result: bytes33,\n },\n \"spark.publicKeys\": {\n session: true,\n presence: false,\n params: obj({ account, keys: arr(sparkLeafKey, MAX_BATCH) }),\n result: arr(bytes33, MAX_BATCH),\n },\n \"spark.receivedPublicKeys\": {\n session: true,\n presence: false,\n params: obj({ account, ciphertexts: arr(ciphertext, MAX_BATCH) }),\n result: arr(bytes33, MAX_BATCH),\n },\n \"spark.newCommitments\": {\n session: true,\n presence: false,\n params: obj({ account, count: int(1, MAX_BATCH) }),\n result: arr(signingCommitment, MAX_BATCH),\n },\n \"spark.signFrost\": {\n session: true,\n presence: false,\n params: obj({ account, jobs: arr(frostSignJob, MAX_BATCH) }),\n result: arr(bytes32, MAX_BATCH),\n },\n \"spark.aggregateFrost\": {\n session: true,\n presence: false,\n params: obj({ account, jobs: arr(frostAggregateJob, MAX_BATCH) }),\n result: arr(bytes64, MAX_BATCH),\n },\n \"spark.signIdentity\": {\n session: true,\n presence: false,\n params: obj({ account, statement: identityStatement }),\n result: bytes(64, 128),\n },\n \"spark.signKeySpend\": {\n session: true,\n presence: false,\n params: obj({ account, key: sparkKey, target: signingTarget }),\n result: bytes64,\n },\n \"spark.signHtlcTimeout\": {\n session: true,\n presence: false,\n params: obj({ account, request: htlcTimeoutRequest }),\n result: bytes64,\n },\n \"spark.prepareTransfer\": {\n session: true,\n presence: false,\n params: obj({ account, request: prepareTransferRequest }),\n result: preparedTransfer,\n },\n \"spark.prepareClaim\": {\n session: true,\n presence: false,\n params: obj({ account, request: prepareClaimRequest }),\n result: preparedClaim,\n },\n \"spark.prepareLightningReceive\": {\n session: true,\n presence: false,\n params: obj({ account }),\n result: preparedLightningReceive,\n },\n \"spark.claimStaticDeposit\": {\n session: true,\n presence: false,\n params: obj({ account, request: staticDepositClaimRequest }),\n result: staticDepositClaimResult,\n },\n \"spark.approve\": {\n session: true,\n presence: true,\n params: obj({ account, intent: approveIntent, verify: factor }),\n result: approvalSummary,\n },\n};\n","/**\n * Secret-area wire protocol (design/impl/wallet-e0.mdx \"协议与传输\"). Shared by the kernel and the main\n * runtime: the kernel validates every request, the host validates every response. Web/Node carry\n * ProtocolValue via structured clone; the RN host encodes the same values as CBOR.\n *\n * This file is the method-table composition point: `METHODS` spreads the core table\n * (protocol/core.ts) and the nostr module's table (protocol/nostr.ts), and the status result\n * validator composes the core sections with each module's status section.\n */\nimport type { LockReason, StatusPayload, WalletErrorCode } from \"../types.ts\";\nimport { backupInfo } from \"./backup.ts\";\nimport { CHAINS_METHODS } from \"./chains.ts\";\nimport {\n CORE_METHODS,\n factorInfo,\n MAX_SNAPSHOT_ITEMS,\n safeTime,\n walletErrorCode,\n walletInfo,\n} from \"./core.ts\";\nimport type { MethodSpec } from \"./core.ts\";\n// oxlint-disable-next-line unicorn/prefer-export-from -- the table is composed locally AND re-exported\nimport { NOSTR_METHODS, nostrStatus } from \"./nostr.ts\";\n// oxlint-disable-next-line unicorn/prefer-export-from -- the table is composed locally AND re-exported\nimport { SPARK_METHODS } from \"./spark.ts\";\nimport { arr, literal, nullValue, obj, opt, union } from \"./validate.ts\";\nimport type { Validator } from \"./validate.ts\";\n\nexport type { WalletErrorCode } from \"../types.ts\";\n\nexport const PROTOCOL_VERSION = 1;\n\n/**\n * Responses to requests whose `id` cannot be parsed (malformed envelope) carry id 0. Main-side\n * request ids start at 1, so a `0` is never a real pending request.\n */\nexport const UNATTRIBUTED_ID = 0;\n\n// oxlint-disable-next-line typescript/no-restricted-types -- JSON null is a protocol value\nexport type NullValue = null;\n\nexport type ProtocolValue =\n | NullValue\n | boolean\n | number // safe integer\n | string\n | Uint8Array\n | ReadonlyArray<ProtocolValue>\n | { readonly [key: string]: ProtocolValue };\n\nexport type Request = {\n readonly v: 1;\n readonly id: number;\n readonly method: string;\n readonly session?: string;\n readonly params: ProtocolValue;\n};\n\nexport type ErrorPayload = {\n readonly code: WalletErrorCode;\n readonly retryAt?: number; // only for \"rate-limited\"\n};\n\nexport type Response =\n | { readonly v: 1; readonly id: number; readonly ok: ProtocolValue }\n | { readonly v: 1; readonly id: number; readonly err: ErrorPayload };\n\nexport type KernelEvent =\n | { readonly v: 1; readonly event: \"status\"; readonly status: StatusPayload }\n | { readonly v: 1; readonly event: \"locked\"; readonly reason: LockReason };\n\n/**\n * The worst-case encoded size of one request, enforced by both sides: the host refuses to post a\n * request over the cap and the kernel answers an oversized raw request with `invalid-input`.\n * Responses are not capped.\n */\nexport const MAX_REQUEST_BYTES = 1_048_576;\n\n/**\n * Upper-bound byte weight of a protocol value: a string costs `length * 3` (worst-case UTF-8), a\n * Uint8Array its `byteLength`, every scalar and every array element 8, and every object key\n * `key.length * 3 + 8` plus its value. Iterative — a deeply nested value cannot overflow the\n * stack.\n */\nexport function requestBytes(value: ProtocolValue): number {\n let total = 0;\n const stack: ProtocolValue[] = [value];\n while (stack.length > 0) {\n const item = stack.pop();\n if (item === undefined) {\n continue;\n }\n if (typeof item === \"string\") {\n total += item.length * 3;\n } else if (item instanceof Uint8Array) {\n total += item.byteLength;\n } else if (item === null || typeof item === \"boolean\" || typeof item === \"number\") {\n total += 8;\n } else if (Array.isArray(item)) {\n // Array.isArray widens the readonly member to any[] — re-annotate the element domain.\n const elements: ReadonlyArray<ProtocolValue> = item;\n total += elements.length * 8;\n for (const element of elements) {\n stack.push(element);\n }\n } else {\n for (const [key, child] of Object.entries(item)) {\n total += key.length * 3 + 8;\n stack.push(child);\n }\n }\n }\n return total;\n}\n\n/** Deep check that a structured-cloned value is a strict ProtocolValue (no cycles detected). */\nexport function isProtocolValue(value: unknown): value is ProtocolValue {\n switch (typeof value) {\n case \"boolean\":\n case \"string\":\n return true;\n case \"number\":\n return Number.isSafeInteger(value);\n case \"object\":\n break;\n default:\n return false;\n }\n if (value === null || value instanceof Uint8Array) {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isProtocolValue);\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return false;\n }\n return Object.values(value).every(isProtocolValue);\n}\n\n/** The status payload: core sections plus one object section per protocol module. */\nconst statusPayload: Validator<StatusPayload> = obj({\n protocol: literal(1),\n vault: union(\n literal(\"uninitialized\"),\n literal(\"locked\"),\n literal(\"unlocked\"),\n literal(\"corrupted\"),\n literal(\"unsupported\"),\n literal(\"unavailable\"),\n ),\n factors: arr(factorInfo, MAX_SNAPSHOT_ITEMS),\n wallets: arr(walletInfo, MAX_SNAPSHOT_ITEMS),\n nostr: nostrStatus,\n backup: union(backupInfo, nullValue),\n});\n\n// The explicit annotation is the composition contract: a key missing from either table fails\n// declaration emit, and a duplicated key fails assignability (the spread's type for that key\n// cannot satisfy the intersection).\nexport const METHODS: {\n readonly status: MethodSpec<NullValue, StatusPayload>;\n} & typeof CORE_METHODS &\n typeof NOSTR_METHODS &\n typeof CHAINS_METHODS &\n typeof SPARK_METHODS = {\n status: {\n session: false,\n presence: false,\n params: nullValue,\n result: statusPayload,\n },\n ...CORE_METHODS,\n ...CHAINS_METHODS,\n ...NOSTR_METHODS,\n ...SPARK_METHODS,\n};\n\n// A method name must live in exactly one table: an overlap violates the never constraint.\ntype AssertNever<T extends never> = T;\nexport type MethodTablesDisjoint = [\n AssertNever<keyof typeof CORE_METHODS & keyof typeof NOSTR_METHODS>,\n AssertNever<keyof typeof CORE_METHODS & keyof typeof SPARK_METHODS>,\n AssertNever<keyof typeof NOSTR_METHODS & keyof typeof SPARK_METHODS>,\n];\n\nexport type MethodName = keyof typeof METHODS;\nexport type ParamsOf<M extends MethodName> = ReturnType<(typeof METHODS)[M][\"params\"]>;\nexport type ResultOf<M extends MethodName> = ReturnType<(typeof METHODS)[M][\"result\"]>;\n\nconst lockReason: Validator<LockReason> = union(\n literal(\"cold-start\"),\n literal(\"user\"),\n literal(\"idle\"),\n literal(\"background\"),\n literal(\"expired\"),\n literal(\"crashed\"),\n literal(\"invalidated\"),\n);\n\nconst errorPayload = obj({ code: walletErrorCode, retryAt: opt(safeTime) });\n\n/** Host-side validators: `kernelEvent` covers the two push messages. */\nexport const kernelEvent: Validator<KernelEvent> = union(\n obj({ v: literal(1), event: literal(\"status\"), status: statusPayload }),\n obj({ v: literal(1), event: literal(\"locked\"), reason: lockReason }),\n);\n\n/** Validates the `err` payload of a response; `ok` is checked against `METHODS[m].result`. */\nexport const responseError: Validator<{ code: WalletErrorCode; retryAt?: number | undefined }> =\n errorPayload;\n\nexport { NOSTR_METHODS, SPARK_METHODS };\nexport { CHAINS_METHODS } from \"./chains.ts\";\nexport type {\n ChainAccount,\n ChainAccountsParams,\n ChainSignResult,\n ChainTemplate,\n} from \"./chains.ts\";\nexport { CORE_METHODS, walletErrorCode } from \"./core.ts\";\nexport type { MethodSpec } from \"./core.ts\";\nexport {\n backupEnvelope,\n backupEnvelopeFactor,\n backupEnvelopeText,\n backupHeader,\n backupInfo,\n} from \"./backup.ts\";\nexport type {\n BackupFactor,\n BackupUnlockFactor,\n CreatedResult,\n CreateWithPasskeyParams,\n Factor,\n RestoreWithPasskeyParams,\n} from \"./core.ts\";\nexport type {\n BackupEnvelopeFactor,\n BackupEnvelopeWire,\n BackupHeaderWallet,\n BackupHeaderWire,\n BackupInfo,\n} from \"./backup.ts\";\nexport type {\n KeyResult,\n NostrExportFormat,\n NostrImportInput,\n Rumor,\n SignedEvent,\n UnsignedEventInput,\n UnwrapResult,\n} from \"./nostr.ts\";\nexport type {\n FrostAggregateJob,\n SparkApprovalSummary,\n SparkApproveIntent,\n FrostSignJob,\n HtlcTimeoutSignRequest,\n IdentityStatement,\n OperatorCommitment,\n PrepareClaimRequest,\n PreparedClaim,\n PreparedLightningReceive,\n PreparedTransfer,\n PreparedTransferLeaf,\n PrepareTransferRequest,\n SigningCommitment,\n SigningTarget,\n SparkAccountRef,\n SparkKey,\n SparkLeafKey,\n SparkNetwork,\n StaticDepositClaimRequest,\n StaticDepositClaimResult,\n StaticDepositClaimStatement,\n} from \"./spark.ts\";\nexport {\n ValidationError,\n arr,\n bool,\n bytes,\n int,\n literal,\n nullValue,\n obj,\n opt,\n record,\n str,\n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