@qntx/wallet 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { b as WalletErrorCode, s as FactorInfo, x as WalletInfo } from "./types-CIYT5uFj.mjs";
1
+ import { S as WalletInfo, c as FactorInfo, x as WalletErrorCode } from "./types-Jsz2m1ib.mjs";
2
2
  /**
3
3
  * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel
4
4
  * validates every request, the host validates every response. Anything that does not match is a
@@ -163,6 +163,7 @@ declare const CORE_METHODS: {
163
163
  readonly "wallet.confirmMnemonic": MethodSpec<{
164
164
  readonly draft: string;
165
165
  readonly answers: ReadonlyArray<Uint8Array>;
166
+ readonly passphrase?: Uint8Array;
166
167
  }, CreatedResult>;
167
168
  readonly "wallet.discardMnemonic": MethodSpec<{
168
169
  readonly draft: string;
@@ -178,19 +179,28 @@ declare const CORE_METHODS: {
178
179
  readonly "backup.restore": MethodSpec<{
179
180
  readonly envelope: string;
180
181
  readonly backupFactor: BackupUnlockFactor;
182
+ readonly passphrases?: ReadonlyArray<{
183
+ readonly walletId: string;
184
+ readonly passphrase: Uint8Array;
185
+ }>;
181
186
  readonly factor?: Factor;
182
187
  }, {
183
188
  readonly wallets: ReadonlyArray<WalletInfo>;
189
+ readonly passphraseRequired: ReadonlyArray<string>;
184
190
  readonly session: string;
185
191
  }>;
186
192
  readonly "wallet.importMnemonic": MethodSpec<{
187
193
  readonly mnemonic: Uint8Array;
194
+ readonly passphrase?: Uint8Array;
188
195
  readonly factor?: Factor;
189
196
  }, CreatedResult>;
190
197
  readonly "wallet.exportMnemonic": MethodSpec<{
191
198
  readonly verify: Factor;
192
199
  readonly walletId: string;
193
- }, Uint8Array>;
200
+ }, {
201
+ readonly mnemonic: Uint8Array;
202
+ readonly passphrase?: Uint8Array;
203
+ }>;
194
204
  readonly "wallet.delete": MethodSpec<{
195
205
  readonly verify: Factor;
196
206
  readonly walletId: string;
@@ -330,4 +340,4 @@ declare const CHAINS_METHODS: {
330
340
  readonly "chain.sign": MethodSpec<ChainSignParams, ChainSignResult>;
331
341
  };
332
342
  export { validate as A, literal as C, record as D, opt as E, str as O, int as S, obj as T, ValidationError as _, ChainSignResult as a, bool as b, BackupUnlockFactor as c, CreatedResult as d, Factor as f, NullValue as g, walletErrorCode as h, ChainSignRequest as i, union as k, CORE_METHODS as l, RestoreWithPasskeyParams as m, ChainAccount as n, ChainTemplate as o, MethodSpec as p, ChainAccountsParams as r, BackupFactor as s, CHAINS_METHODS as t, CreateWithPasskeyParams as u, Validator as v, nullValue as w, bytes as x, arr as y };
333
- //# sourceMappingURL=chains-BdcH4YnJ.d.mts.map
343
+ //# sourceMappingURL=chains-CoZhm-Y1.d.mts.map
package/dist/chains.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { h as UnlockFactor, v as Wallet } from "./types-CIYT5uFj.mjs";
2
- import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-BdcH4YnJ.mjs";
1
+ import { g as UnlockFactor, y as Wallet } from "./types-Jsz2m1ib.mjs";
2
+ import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-CoZhm-Y1.mjs";
3
3
  export type ChainsApi = {
4
4
  readonly account: (params: ChainAccountsParams) => Promise<ChainAccount>;
5
5
  readonly sign: (params: {
package/dist/chains.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as integrity } from "./channel-Iiz28m-e.mjs";
1
+ import { n as integrity } from "./channel-DcIolCZs.mjs";
2
2
  import { t as internalsOf } from "./internal-CAKfHjIg.mjs";
3
3
  import { bitcoinAddressFromXpub, verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from "@qntx/wallet-chains/bitcoin";
4
4
  import { recoverEvmSigner } from "@qntx/wallet-chains/evm";
@@ -1,5 +1,5 @@
1
- import { h as ValidationError } from "./core-Cq5h9X0X.mjs";
2
- import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-DbpLncEB.mjs";
1
+ import { h as ValidationError } from "./core-D-NCx1CQ.mjs";
2
+ import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-DDz4nlYK.mjs";
3
3
  import { WalletError } from "./types.mjs";
4
4
  // src/channel.ts
5
5
  /**
@@ -317,4 +317,4 @@ var Channel = class {
317
317
  };
318
318
  export { integrity as n, Channel as t };
319
319
 
320
- //# sourceMappingURL=channel-Iiz28m-e.mjs.map
320
+ //# sourceMappingURL=channel-DcIolCZs.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"channel-Iiz28m-e.mjs","names":[],"sources":["../src/channel.ts"],"sourcesContent":["/**\n * The host side of the kernel channel (design/enclave.mdx \"协议与传输\"): port lifecycle, respawn,\n * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for\n * host packages (wallet-worker, wallet-native); applications must not use it.\n */\nimport {\n isProtocolValue,\n kernelEvent,\n MAX_REQUEST_BYTES,\n METHODS,\n PROTOCOL_VERSION,\n requestBytes,\n responseError,\n ValidationError,\n} from \"./protocol/index.ts\";\nimport type { MethodName, ParamsOf, ProtocolValue, ResultOf } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { LockReason, StatusPayload } from \"./types.ts\";\n\n/**\n * Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock\n * triggered by the platform (native background expiry — W7).\n */\nexport type PortExit = \"crashed\" | \"background\";\n\n/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */\nexport type MainPort = {\n readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n readonly onExit: (handler: (reason: PortExit) => void) => () => void;\n readonly terminate: () => void;\n};\n\nexport function integrity(message: string): WalletError {\n return new WalletError(\"integrity\", message);\n}\n\n/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */\nexport type SetTimer = (delayMs: number, fn: () => void) => () => void;\n\n/**\n * A silent kernel is a wedged kernel: the request at the head of the kernel's serial queue gets\n * this long before the port is replaced. Requests still queued behind it are not timed — the kernel\n * answers in order, so only the head can wedge.\n */\nconst CALL_TIMEOUT_MS = 60_000;\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/**\n * State callbacks: the channel owns the port lifecycle and message ordering; the wallet owns the\n * snapshot state these events describe. `onLocked`/`onCrashed` fire before the port is replaced so\n * the wallet can stamp the lock reason.\n */\nexport type ChannelHandlers = {\n readonly onStatus: (status: StatusPayload) => void;\n readonly onLocked: (reason: LockReason) => void;\n readonly onCrashed: () => void;\n};\n\nexport class Channel {\n /** The live kernel session; attached to every request and cleared whenever it is gone. */\n session: string | undefined;\n\n private port: MainPort | undefined;\n private unlisten: (() => void) | undefined;\n private unlistenExit: (() => void) | undefined;\n private generation = 0;\n\n private readonly pending = new Map<number, Pending>();\n /** Times the earliest pending request — the one the kernel is working on. */\n private watchdog: { readonly id: number; readonly cancel: () => void } | undefined;\n private nextId = 1;\n private destroyed = false;\n /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */\n private broken: WalletError | undefined;\n /** An unlocked status held back until the session it belongs to is installed. */\n private deferredStatus: StatusPayload | undefined;\n /** Whether the current port has delivered its first valid status event. */\n private portReady = false;\n private readyPromise: Promise<void>;\n private resolveReady: (() => void) | undefined;\n private rejectReady: ((error: WalletError) => void) | undefined;\n\n private readonly spawn: () => MainPort;\n private readonly handlers: ChannelHandlers;\n private readonly setTimer: SetTimer;\n\n constructor(spawn: () => MainPort, handlers: ChannelHandlers, setTimer: SetTimer) {\n this.spawn = spawn;\n this.handlers = handlers;\n this.setTimer = setTimer;\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n }\n\n /** Spawns the first kernel and resolves once its initial status event arrives. */\n async start(): Promise<void> {\n this.respawn();\n return this.readyPromise;\n }\n\n /** Resolves when the current port has delivered its first status event. */\n get ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the\n * host-side store survives the worker). \"Lock destroys the enclave.\"\n */\n respawn(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.watchdog?.cancel();\n this.watchdog = undefined;\n this.portReady = false;\n\n const generation = ++this.generation;\n // Settle the previous gate: a call still awaiting it must not hang — the kernel it was\n // waiting for is gone, so \"locked\" (session destroyed) applies.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the stale gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n this.rejectReady?.(new WalletError(\"locked\", \"the kernel restarted\"));\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A rejected gate with nobody awaiting it (e.g. destroy() mid-boot) must not surface as\n // an unhandled rejection; callers that do await still observe the rejection.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n try {\n const port = this.spawn();\n this.unlisten = port.listen((message) => {\n this.onMessage(message, generation);\n });\n this.unlistenExit = port.onExit((reason) => {\n this.onExit(reason, generation);\n });\n this.port = port;\n } catch (error) {\n // A host that cannot spawn has no kernel to talk to — fail closed like a dead peer.\n const spawnError = integrity(\"could not spawn the kernel port\");\n spawnError.cause = error;\n this.breakChannel(spawnError);\n }\n }\n\n private onExit(reason: PortExit, generation: number): void {\n if (generation !== this.generation || this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n if (!this.portReady) {\n // Death before the first valid status means the runtime never ran honestly (worker\n // blocked by CSP, a script that fails to load, protocol skew): no respawn — a fresh\n // spawn would face the same broken peer. Initial connect rejects with integrity;\n // a respawned port dying this way breaks the wallet.\n this.breakChannel(integrity(\"the kernel port died before its first status\"));\n return;\n }\n if (reason === \"background\") {\n // The platform backgrounded the app past autoLock.backgroundSeconds and locked the\n // enclave: not a crash — take the lock path so the user sees the real reason.\n this.lockWith(\"background\");\n return;\n }\n // A proven port dying is a crash: fail everything in flight, mark it, respawn.\n this.failPending(new WalletError(\"crashed\", \"the kernel port exited\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n /**\n * Immediate host-side lock: no kernel round trip. Fails everything in flight with `locked`, drops\n * the session, reports the user lock, and replaces the port — the old worker can never answer\n * again. Safe mid-commit: IndexedDB transactions are atomic.\n */\n lockNow(): void {\n this.lockWith(\"user\");\n }\n\n private lockWith(reason: \"user\" | \"background\"): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.handlers.onLocked(reason);\n this.respawn();\n }\n\n private onCallTimeout(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.failPending(new WalletError(\"crashed\", \"the kernel did not answer in time\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n private failPending(error: WalletError): void {\n this.watchdog?.cancel();\n this.watchdog = undefined;\n for (const [, pending] of this.pending) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n /** (Re)arms the watchdog on `pending`'s insertion-ordered head, or clears it when empty. */\n private armWatchdog(): void {\n this.watchdog?.cancel();\n const head = this.pending.keys().next().value;\n this.watchdog =\n head === undefined\n ? undefined\n : {\n id: head,\n cancel: this.setTimer(CALL_TIMEOUT_MS, () => {\n this.onCallTimeout();\n }),\n };\n }\n\n /** Removes the pending entry, re-timing the watchdog when the head settled, then runs `fn`. */\n private settle(id: number, fn: (pending: Pending) => void): void {\n const pending = this.pending.get(id);\n if (pending !== undefined) {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n fn(pending);\n }\n }\n\n /**\n * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every\n * later call rejects with the same error. The snapshot is left untouched.\n */\n private breakChannel(error: WalletError): void {\n this.broken = error;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(error);\n this.rejectReady?.(error);\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.generation++; // anything the dead port still emits is stale\n }\n\n /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */\n private poison(reason: string): void {\n this.breakChannel(integrity(reason));\n }\n\n private onMessage(raw: unknown, generation: number): void {\n if (generation !== this.generation) {\n return; // a dead port must not steer the wallet\n }\n if (\n !isProtocolValue(raw) ||\n typeof raw !== \"object\" ||\n raw === null ||\n raw instanceof Uint8Array ||\n Array.isArray(raw)\n ) {\n this.poison(\"malformed kernel message\");\n return;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain record above\n const message = raw as Readonly<Record<string, ProtocolValue>>;\n if (\"id\" in message) {\n this.onResponse(message);\n return;\n }\n if (\"event\" in message) {\n let event;\n try {\n event = kernelEvent(message);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed kernel event\");\n return;\n }\n if (event.event === \"status\") {\n if (event.status.vault !== \"unlocked\") {\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onStatus(event.status);\n } else if (this.session === undefined) {\n // The unlock/create response has not delivered the session yet — subscribers must\n // never see \"unlocked\" while requests would go out sessionless.\n this.deferredStatus = event.status;\n } else {\n this.handlers.onStatus(event.status);\n }\n this.portReady = true;\n this.resolveReady?.();\n } else {\n // A locked event destroys the enclave: drop the session, tear down the port, respawn.\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onLocked(event.reason);\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.respawn();\n }\n return;\n }\n this.poison(\"unrecognised kernel message\");\n }\n\n private onResponse(message: Readonly<Record<string, ProtocolValue>>): void {\n const { id } = message;\n if (typeof id !== \"number\" || !Number.isSafeInteger(id) || message[\"v\"] !== PROTOCOL_VERSION) {\n this.poison(\"malformed response envelope\");\n return;\n }\n const pending = this.pending.get(id);\n if (pending === undefined) {\n // Includes UNATTRIBUTED_ID 0 — never a live request.\n this.poison(\"response for an unknown request\");\n return;\n }\n const hasOk = \"ok\" in message;\n const hasErr = \"err\" in message;\n if (hasOk === hasErr) {\n // Keep the entry so poison's failPending rejects this caller too.\n this.poison(\"malformed response body\");\n return;\n }\n if (hasErr) {\n try {\n const err = responseError(message[\"err\"]);\n this.settle(id, (p) => {\n p.reject(\n new WalletError(\n err.code,\n `kernel returned ${err.code}`,\n typeof err.retryAt === \"number\" ? err.retryAt : undefined,\n ),\n );\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed error payload\");\n }\n return;\n }\n try {\n const result = METHODS[pending.method].result(message[\"ok\"]);\n this.settle(id, (p) => {\n p.resolve(result);\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"invalid result from the kernel\");\n }\n }\n\n /**\n * Sends one request and resolves with the validated result. The kernel answers with status →\n * response → locked, so the snapshot is already current when this promise settles.\n */\n async call<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer: ArrayBuffer[] = [],\n ): Promise<ResultOf<M>> {\n await this.readyPromise;\n if (this.broken !== undefined) {\n throw this.broken;\n }\n const { port } = this;\n if (this.destroyed || port === undefined) {\n throw new WalletError(\"locked\", \"wallet is destroyed\");\n }\n const id = this.nextId++;\n const message: Record<string, ProtocolValue> = { v: PROTOCOL_VERSION, id, method, params };\n // Attach the session whenever we hold one: the create/import methods are session:false\n // in the table because the rule is dynamic (required exactly when the vault is initialized).\n if (this.session !== undefined) {\n message[\"session\"] = this.session;\n }\n // The whole envelope counts against the cap — an oversized request never reaches the port.\n if (requestBytes(message) > MAX_REQUEST_BYTES) {\n throw new WalletError(\"invalid-input\", \"request exceeds the size limit\");\n }\n const result = await new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n if (this.watchdog === undefined) {\n // Pending went empty → non-empty: this request is the head the kernel works on next.\n this.armWatchdog();\n }\n try {\n port.post(message, transfer);\n } catch {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n reject(integrity(\"the kernel port refused the message\"));\n }\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n }\n\n /** Fires the deferred unlocked status, if any, once the session is installed. */\n flushStatus(): void {\n const status = this.deferredStatus;\n if (status !== undefined && this.session !== undefined) {\n this.deferredStatus = undefined;\n this.handlers.onStatus(status);\n }\n }\n\n /** Terminates the port without respawn; later calls fail \"locked\". */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.rejectReady?.(new WalletError(\"locked\", \"wallet is destroyed\"));\n this.failPending(new WalletError(\"locked\", \"wallet is destroyed\"));\n }\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,UAAU,SAA8B;CACtD,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;;;;;;AAUA,MAAM,kBAAkB;AAmBxB,IAAa,UAAb,MAAqB;;CAEnB;CAEA;CACA;CACA;CACA,aAAqB;CAErB,0BAA2B,IAAI,IAAqB;;CAEpD;CACA,SAAiB;CACjB,YAAoB;;CAEpB;;CAEA;;CAEA,YAAoB;CACpB;CACA;CACA;CAEA;CACA;CACA;CAEA,YAAY,OAAuB,UAA2B,UAAoB;EAChF,KAAK,QAAQ;EACb,KAAK,WAAW;EAChB,KAAK,WAAW;EAChB,KAAK,eAAe,IAAI,SAAS,SAAS,WAAW;GACnD,KAAK,eAAe;GACpB,KAAK,cAAc;EACrB,CAAC;CACH;;CAGA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O,IAAA,SACtB,MAAM,IAAI,YAAY,iBAAiB,gCAAgC;EAmBzE,OAAO,MAjBc,IAAI,SAAkB,SAAS,WAAW;GAC7D,KAAK,QAAQ,IAAI,IAAI;IAAE;IAAQ;IAAS;GAAO,CAAC;GAChD,IAAI,KAAK,aAAa,KAAA,GAEpB,KAAK,YAAY;GAEnB,IAAI;IACF,KAAK,KAAK,SAAS,QAAQ;GAC7B,QAAQ;IACN,KAAK,QAAQ,OAAO,EAAE;IACtB,IAAI,KAAK,UAAU,OAAO,IACxB,KAAK,YAAY;IAEnB,OAAO,UAAU,qCAAqC,CAAC;GACzD;EACF,CAAC;CAGH;;CAGA,cAAoB;EAClB,MAAM,SAAS,KAAK;EACpB,IAAI,WAAW,KAAA,KAAa,KAAK,YAAY,KAAA,GAAW;GACtD,KAAK,iBAAiB,KAAA;GACtB,KAAK,SAAS,SAAS,MAAM;EAC/B;CACF;;CAGA,UAAgB;EACd,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,cAAc,IAAI,YAAY,UAAU,qBAAqB,CAAC;EACnE,KAAK,YAAY,IAAI,YAAY,UAAU,qBAAqB,CAAC;CACnE;AACF"}
1
+ {"version":3,"file":"channel-DcIolCZs.mjs","names":[],"sources":["../src/channel.ts"],"sourcesContent":["/**\n * The host side of the kernel channel (design/enclave.mdx \"协议与传输\"): port lifecycle, respawn,\n * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for\n * host packages (wallet-worker, wallet-native); applications must not use it.\n */\nimport {\n isProtocolValue,\n kernelEvent,\n MAX_REQUEST_BYTES,\n METHODS,\n PROTOCOL_VERSION,\n requestBytes,\n responseError,\n ValidationError,\n} from \"./protocol/index.ts\";\nimport type { MethodName, ParamsOf, ProtocolValue, ResultOf } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { LockReason, StatusPayload } from \"./types.ts\";\n\n/**\n * Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock\n * triggered by the platform (native background expiry — W7).\n */\nexport type PortExit = \"crashed\" | \"background\";\n\n/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */\nexport type MainPort = {\n readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n readonly onExit: (handler: (reason: PortExit) => void) => () => void;\n readonly terminate: () => void;\n};\n\nexport function integrity(message: string): WalletError {\n return new WalletError(\"integrity\", message);\n}\n\n/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */\nexport type SetTimer = (delayMs: number, fn: () => void) => () => void;\n\n/**\n * A silent kernel is a wedged kernel: the request at the head of the kernel's serial queue gets\n * this long before the port is replaced. Requests still queued behind it are not timed — the kernel\n * answers in order, so only the head can wedge.\n */\nconst CALL_TIMEOUT_MS = 60_000;\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/**\n * State callbacks: the channel owns the port lifecycle and message ordering; the wallet owns the\n * snapshot state these events describe. `onLocked`/`onCrashed` fire before the port is replaced so\n * the wallet can stamp the lock reason.\n */\nexport type ChannelHandlers = {\n readonly onStatus: (status: StatusPayload) => void;\n readonly onLocked: (reason: LockReason) => void;\n readonly onCrashed: () => void;\n};\n\nexport class Channel {\n /** The live kernel session; attached to every request and cleared whenever it is gone. */\n session: string | undefined;\n\n private port: MainPort | undefined;\n private unlisten: (() => void) | undefined;\n private unlistenExit: (() => void) | undefined;\n private generation = 0;\n\n private readonly pending = new Map<number, Pending>();\n /** Times the earliest pending request — the one the kernel is working on. */\n private watchdog: { readonly id: number; readonly cancel: () => void } | undefined;\n private nextId = 1;\n private destroyed = false;\n /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */\n private broken: WalletError | undefined;\n /** An unlocked status held back until the session it belongs to is installed. */\n private deferredStatus: StatusPayload | undefined;\n /** Whether the current port has delivered its first valid status event. */\n private portReady = false;\n private readyPromise: Promise<void>;\n private resolveReady: (() => void) | undefined;\n private rejectReady: ((error: WalletError) => void) | undefined;\n\n private readonly spawn: () => MainPort;\n private readonly handlers: ChannelHandlers;\n private readonly setTimer: SetTimer;\n\n constructor(spawn: () => MainPort, handlers: ChannelHandlers, setTimer: SetTimer) {\n this.spawn = spawn;\n this.handlers = handlers;\n this.setTimer = setTimer;\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n }\n\n /** Spawns the first kernel and resolves once its initial status event arrives. */\n async start(): Promise<void> {\n this.respawn();\n return this.readyPromise;\n }\n\n /** Resolves when the current port has delivered its first status event. */\n get ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the\n * host-side store survives the worker). \"Lock destroys the enclave.\"\n */\n respawn(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.watchdog?.cancel();\n this.watchdog = undefined;\n this.portReady = false;\n\n const generation = ++this.generation;\n // Settle the previous gate: a call still awaiting it must not hang — the kernel it was\n // waiting for is gone, so \"locked\" (session destroyed) applies.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the stale gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n this.rejectReady?.(new WalletError(\"locked\", \"the kernel restarted\"));\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A rejected gate with nobody awaiting it (e.g. destroy() mid-boot) must not surface as\n // an unhandled rejection; callers that do await still observe the rejection.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n try {\n const port = this.spawn();\n this.unlisten = port.listen((message) => {\n this.onMessage(message, generation);\n });\n this.unlistenExit = port.onExit((reason) => {\n this.onExit(reason, generation);\n });\n this.port = port;\n } catch (error) {\n // A host that cannot spawn has no kernel to talk to — fail closed like a dead peer.\n const spawnError = integrity(\"could not spawn the kernel port\");\n spawnError.cause = error;\n this.breakChannel(spawnError);\n }\n }\n\n private onExit(reason: PortExit, generation: number): void {\n if (generation !== this.generation || this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n if (!this.portReady) {\n // Death before the first valid status means the runtime never ran honestly (worker\n // blocked by CSP, a script that fails to load, protocol skew): no respawn — a fresh\n // spawn would face the same broken peer. Initial connect rejects with integrity;\n // a respawned port dying this way breaks the wallet.\n this.breakChannel(integrity(\"the kernel port died before its first status\"));\n return;\n }\n if (reason === \"background\") {\n // The platform backgrounded the app past autoLock.backgroundSeconds and locked the\n // enclave: not a crash — take the lock path so the user sees the real reason.\n this.lockWith(\"background\");\n return;\n }\n // A proven port dying is a crash: fail everything in flight, mark it, respawn.\n this.failPending(new WalletError(\"crashed\", \"the kernel port exited\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n /**\n * Immediate host-side lock: no kernel round trip. Fails everything in flight with `locked`, drops\n * the session, reports the user lock, and replaces the port — the old worker can never answer\n * again. Safe mid-commit: IndexedDB transactions are atomic.\n */\n lockNow(): void {\n this.lockWith(\"user\");\n }\n\n private lockWith(reason: \"user\" | \"background\"): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.handlers.onLocked(reason);\n this.respawn();\n }\n\n private onCallTimeout(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.failPending(new WalletError(\"crashed\", \"the kernel did not answer in time\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n private failPending(error: WalletError): void {\n this.watchdog?.cancel();\n this.watchdog = undefined;\n for (const [, pending] of this.pending) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n /** (Re)arms the watchdog on `pending`'s insertion-ordered head, or clears it when empty. */\n private armWatchdog(): void {\n this.watchdog?.cancel();\n const head = this.pending.keys().next().value;\n this.watchdog =\n head === undefined\n ? undefined\n : {\n id: head,\n cancel: this.setTimer(CALL_TIMEOUT_MS, () => {\n this.onCallTimeout();\n }),\n };\n }\n\n /** Removes the pending entry, re-timing the watchdog when the head settled, then runs `fn`. */\n private settle(id: number, fn: (pending: Pending) => void): void {\n const pending = this.pending.get(id);\n if (pending !== undefined) {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n fn(pending);\n }\n }\n\n /**\n * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every\n * later call rejects with the same error. The snapshot is left untouched.\n */\n private breakChannel(error: WalletError): void {\n this.broken = error;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(error);\n this.rejectReady?.(error);\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.generation++; // anything the dead port still emits is stale\n }\n\n /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */\n private poison(reason: string): void {\n this.breakChannel(integrity(reason));\n }\n\n private onMessage(raw: unknown, generation: number): void {\n if (generation !== this.generation) {\n return; // a dead port must not steer the wallet\n }\n if (\n !isProtocolValue(raw) ||\n typeof raw !== \"object\" ||\n raw === null ||\n raw instanceof Uint8Array ||\n Array.isArray(raw)\n ) {\n this.poison(\"malformed kernel message\");\n return;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain record above\n const message = raw as Readonly<Record<string, ProtocolValue>>;\n if (\"id\" in message) {\n this.onResponse(message);\n return;\n }\n if (\"event\" in message) {\n let event;\n try {\n event = kernelEvent(message);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed kernel event\");\n return;\n }\n if (event.event === \"status\") {\n if (event.status.vault !== \"unlocked\") {\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onStatus(event.status);\n } else if (this.session === undefined) {\n // The unlock/create response has not delivered the session yet — subscribers must\n // never see \"unlocked\" while requests would go out sessionless.\n this.deferredStatus = event.status;\n } else {\n this.handlers.onStatus(event.status);\n }\n this.portReady = true;\n this.resolveReady?.();\n } else {\n // A locked event destroys the enclave: drop the session, tear down the port, respawn.\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onLocked(event.reason);\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.respawn();\n }\n return;\n }\n this.poison(\"unrecognised kernel message\");\n }\n\n private onResponse(message: Readonly<Record<string, ProtocolValue>>): void {\n const { id } = message;\n if (typeof id !== \"number\" || !Number.isSafeInteger(id) || message[\"v\"] !== PROTOCOL_VERSION) {\n this.poison(\"malformed response envelope\");\n return;\n }\n const pending = this.pending.get(id);\n if (pending === undefined) {\n // Includes UNATTRIBUTED_ID 0 — never a live request.\n this.poison(\"response for an unknown request\");\n return;\n }\n const hasOk = \"ok\" in message;\n const hasErr = \"err\" in message;\n if (hasOk === hasErr) {\n // Keep the entry so poison's failPending rejects this caller too.\n this.poison(\"malformed response body\");\n return;\n }\n if (hasErr) {\n try {\n const err = responseError(message[\"err\"]);\n this.settle(id, (p) => {\n p.reject(\n new WalletError(\n err.code,\n `kernel returned ${err.code}`,\n typeof err.retryAt === \"number\" ? err.retryAt : undefined,\n ),\n );\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed error payload\");\n }\n return;\n }\n try {\n const result = METHODS[pending.method].result(message[\"ok\"]);\n this.settle(id, (p) => {\n p.resolve(result);\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"invalid result from the kernel\");\n }\n }\n\n /**\n * Sends one request and resolves with the validated result. The kernel answers with status →\n * response → locked, so the snapshot is already current when this promise settles.\n */\n async call<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer: ArrayBuffer[] = [],\n ): Promise<ResultOf<M>> {\n await this.readyPromise;\n if (this.broken !== undefined) {\n throw this.broken;\n }\n const { port } = this;\n if (this.destroyed || port === undefined) {\n throw new WalletError(\"locked\", \"wallet is destroyed\");\n }\n const id = this.nextId++;\n const message: Record<string, ProtocolValue> = { v: PROTOCOL_VERSION, id, method, params };\n // Attach the session whenever we hold one: the create/import methods are session:false\n // in the table because the rule is dynamic (required exactly when the vault is initialized).\n if (this.session !== undefined) {\n message[\"session\"] = this.session;\n }\n // The whole envelope counts against the cap — an oversized request never reaches the port.\n if (requestBytes(message) > MAX_REQUEST_BYTES) {\n throw new WalletError(\"invalid-input\", \"request exceeds the size limit\");\n }\n const result = await new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n if (this.watchdog === undefined) {\n // Pending went empty → non-empty: this request is the head the kernel works on next.\n this.armWatchdog();\n }\n try {\n port.post(message, transfer);\n } catch {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n reject(integrity(\"the kernel port refused the message\"));\n }\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n }\n\n /** Fires the deferred unlocked status, if any, once the session is installed. */\n flushStatus(): void {\n const status = this.deferredStatus;\n if (status !== undefined && this.session !== undefined) {\n this.deferredStatus = undefined;\n this.handlers.onStatus(status);\n }\n }\n\n /** Terminates the port without respawn; later calls fail \"locked\". */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.rejectReady?.(new WalletError(\"locked\", \"wallet is destroyed\"));\n this.failPending(new WalletError(\"locked\", \"wallet is destroyed\"));\n }\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,UAAU,SAA8B;CACtD,OAA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AAC;EACnE,KAAK,YAAY,IAAI,YAAY,UAAU,qBAAqB,CAAC;CACnE;AACF"}
@@ -209,8 +209,11 @@ const walletInfo = obj({
209
209
  origin: union(literal("passkey"), literal("mnemonic")),
210
210
  words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),
211
211
  backup: union(literal("none"), literal("passkey"), literal("mnemonic")),
212
+ passphrase: bool,
212
213
  createdAt: safeTime
213
214
  });
215
+ /** A BIP-39 passphrase on the wire: raw UTF-8 bytes, never empty (the host omits "none"). */
216
+ const passphraseBytes = bytes(1, 1024);
214
217
  const walletErrorCode = union(literal("locked"), literal("cancelled"), literal("factor-unavailable"), literal("factor-invalidated"), literal("wrong-password"), literal("wrong-passkey"), literal("rate-limited"), literal("invalid-input"), literal("not-found"), literal("already-exists"), literal("conflict"), literal("unsupported"), literal("unavailable"), literal("integrity"), literal("approval-required"), literal("crashed"));
215
218
  const createdResult = obj({
216
219
  wallet: walletInfo,
@@ -283,7 +286,8 @@ const CORE_METHODS = {
283
286
  presence: true,
284
287
  params: obj({
285
288
  draft: draftId,
286
- answers: arr(bytes(1, 64), 3, 3)
289
+ answers: arr(bytes(1, 64), 3, 3),
290
+ passphrase: opt(passphraseBytes)
287
291
  }),
288
292
  result: createdResult
289
293
  },
@@ -320,10 +324,15 @@ const CORE_METHODS = {
320
324
  params: obj({
321
325
  envelope: str(4e6),
322
326
  backupFactor: backupUnlockFactor,
327
+ passphrases: opt(arr(obj({
328
+ walletId,
329
+ passphrase: passphraseBytes
330
+ }), 1e3)),
323
331
  factor: opt(factor)
324
332
  }),
325
333
  result: obj({
326
334
  wallets: arr(walletInfo, 1e3),
335
+ passphraseRequired: arr(str(128), 1e3),
327
336
  session: sessionId
328
337
  })
329
338
  },
@@ -332,6 +341,7 @@ const CORE_METHODS = {
332
341
  presence: true,
333
342
  params: obj({
334
343
  mnemonic: bytes(1, 1024),
344
+ passphrase: opt(passphraseBytes),
335
345
  factor: opt(factor)
336
346
  }),
337
347
  result: createdResult
@@ -343,7 +353,10 @@ const CORE_METHODS = {
343
353
  verify: factor,
344
354
  walletId
345
355
  }),
346
- result: bytes(16, 1024)
356
+ result: obj({
357
+ mnemonic: bytes(16, 1024),
358
+ passphrase: opt(passphraseBytes)
359
+ })
347
360
  },
348
361
  "wallet.delete": {
349
362
  session: true,
@@ -363,4 +376,4 @@ const CORE_METHODS = {
363
376
  };
364
377
  export { opt as C, validate as D, union as E, obj as S, str as T, bool as _, MAX_TEXT as a, literal as b, groupIndex as c, safeTime as d, walletErrorCode as f, arr as g, ValidationError as h, MAX_TAG_ITEM as i, identityIndex as l, walletInfo as m, MAX_SNAPSHOT_ITEMS as n, factor as o, walletId as p, MAX_TAGS as r, factorInfo as s, CORE_METHODS as t, publicKey as u, bytes as v, record as w, nullValue as x, int as y };
365
378
 
366
- //# sourceMappingURL=core-Cq5h9X0X.mjs.map
379
+ //# sourceMappingURL=core-D-NCx1CQ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-D-NCx1CQ.mjs","names":[],"sources":["../src/protocol/validate.ts","../src/protocol/core.ts"],"sourcesContent":["/**\n * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel\n * validates every request, the host validates every response. Anything that does not match is a\n * `ValidationError` — never a partially-accepted value.\n */\n\nexport class ValidationError extends Error {\n override name = \"ValidationError\";\n}\n\nexport type Validator<T> = (value: unknown) => T;\n\nfunction fail(): never {\n throw new ValidationError();\n}\n\n// oxlint-disable-next-line typescript/no-restricted-types -- JSON null is a protocol value\nexport type NullValue = null;\n\nexport function literal<T extends NullValue | boolean | number | string>(\n expected: T,\n): Validator<T> {\n return (value) => {\n if (value !== expected) {\n fail();\n }\n return expected;\n };\n}\n\nexport const nullValue: Validator<NullValue> = literal(null);\nexport const bool: Validator<boolean> = (value) => {\n if (typeof value !== \"boolean\") {\n fail();\n }\n return value;\n};\n\nexport function int(min: number, max: number): Validator<number> {\n return (value) => {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < min || value > max) {\n fail();\n }\n return value;\n };\n}\n\nexport function str(max: number, pattern?: RegExp): Validator<string> {\n return (value) => {\n if (\n typeof value !== \"string\" ||\n value.length > max ||\n (pattern !== undefined && !pattern.test(value))\n ) {\n fail();\n }\n return value;\n };\n}\n\nexport function bytes(min: number, max?: number): Validator<Uint8Array> {\n const high = max ?? min;\n return (value) => {\n if (!(value instanceof Uint8Array) || value.length < min || value.length > high) {\n fail();\n }\n return value;\n };\n}\n\nexport function arr<T>(item: Validator<T>, max: number, min = 0): Validator<ReadonlyArray<T>> {\n return (value) => {\n if (!Array.isArray(value) || value.length < min || value.length > max) {\n fail();\n }\n const out: T[] = [];\n for (const element of value) {\n out.push(item(element));\n }\n return out;\n };\n}\n\nclass Opt<T> {\n readonly validator: Validator<T>;\n\n constructor(validator: Validator<T>) {\n this.validator = validator;\n }\n}\n\nexport function opt<T>(validator: Validator<T>): Opt<T> {\n return new Opt(validator);\n}\n\ntype Field = Validator<unknown> | Opt<unknown>;\ntype Shape = Record<string, Field>;\n\ntype RequiredKeys<S extends Shape> = {\n readonly [K in keyof S as S[K] extends Opt<unknown> ? never : K]: S[K] extends Validator<infer T>\n ? T\n : never;\n};\ntype OptionalKeys<S extends Shape> = {\n readonly [K in keyof S as S[K] extends Opt<unknown> ? K : never]?: S[K] extends Opt<infer T>\n ? T\n : never;\n};\ntype ShapeResult<S extends Shape> = RequiredKeys<S> & OptionalKeys<S>;\n\n/** Exact key set: required keys present, optional keys allowed, nothing else. */\nexport function obj<S extends Shape>(shape: S): Validator<ShapeResult<S>> {\n const keys = Object.keys(shape);\n return (value) => {\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Uint8Array\n ) {\n fail();\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain object above\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!Object.hasOwn(shape, key)) {\n fail();\n }\n }\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n const field = shape[key];\n if (field === undefined) {\n fail();\n }\n const raw = record[key];\n if (field instanceof Opt) {\n if (raw !== undefined) {\n out[key] = field.validator(raw);\n }\n } else {\n if (!Object.hasOwn(record, key)) {\n fail();\n }\n out[key] = field(raw);\n }\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the shape guarantees the keys\n return out as ShapeResult<S>;\n };\n}\n\nconst FORBIDDEN_RECORD_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * A `Record<K, V>` wire value: plain objects only, every key checked by `key`, every value by\n * `value`, at most `max` entries. Prototype-polluting keys are rejected outright — a validated\n * record must be safe to copy key-by-key.\n */\nexport function record<K extends string, V>(\n key: Validator<K>,\n value: Validator<V>,\n max: number,\n): Validator<Record<K, V>> {\n return (input) => {\n if (\n typeof input !== \"object\" ||\n input === null ||\n Array.isArray(input) ||\n input instanceof Uint8Array ||\n Object.getPrototypeOf(input) !== Object.prototype\n ) {\n fail();\n }\n const out: Record<string, V> = {};\n const entries = Object.entries(input);\n if (entries.length > max) {\n fail();\n }\n for (const [name, item] of entries) {\n if (FORBIDDEN_RECORD_KEYS.has(name)) {\n fail();\n }\n out[key(name)] = value(item);\n }\n return out;\n };\n}\n\n/** Tries each branch in order; the first match wins. */\nexport function union<Vs extends ReadonlyArray<Validator<unknown>>>(\n ...branches: Vs\n): Validator<ReturnType<Vs[number]>> {\n return (value) => {\n for (const branch of branches) {\n try {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ReturnType of the branch union\n return branch(value) as ReturnType<Vs[number]>;\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n }\n }\n return fail();\n };\n}\n\n/** Validates a value and returns it, or undefined on a shape mismatch. */\nexport function validate<T>(validator: Validator<T>, value: unknown): T | undefined {\n try {\n return validator(value);\n } catch (error) {\n if (error instanceof ValidationError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * The core method table: vault, wallet and data-key commands — nothing protocol-specific. \"Create\n * or import\" commands (createWithPasskey/restoreWithPasskey/createMnemonic/importMnemonic) are\n * `session: false` here because the rule is dynamic: with an uninitialized vault they carry\n * `factor` and establish the vault in one commit; with an established vault `factor` must be absent\n * and a valid session is required.\n *\n * The shared wire validators (factor, wallet info, ids) live here too so the nostr module's table\n * can reuse them — `protocol/nostr.ts` imports only from this file.\n */\nimport type { FactorInfo, WalletErrorCode, WalletInfo } from \"../types.ts\";\nimport type { NullValue, Validator } from \"./validate.ts\";\nimport { arr, bool, bytes, int, literal, nullValue, obj, opt, str, union } from \"./validate.ts\";\n\nexport type MethodSpec<P, R> = {\n readonly session: boolean;\n /** Whether a successful call refreshes the idle timer — presence-bearing methods only. */\n readonly presence: boolean;\n readonly params: Validator<P>;\n readonly result: Validator<R>;\n};\n\n// Size caps (UTF-16 units for strings, bytes for Uint8Array). These bound individual fields; the\n// whole-request cap MAX_REQUEST_BYTES (protocol/index.ts) is enforced by host and kernel.\nexport const MAX_TEXT = 262_144;\nexport const MAX_TAGS = 1024;\nexport const MAX_TAG_ITEMS = 64;\nexport const MAX_TAG_ITEM = 4096;\nexport const MAX_BATCH = 64;\nexport const MAX_SNAPSHOT_ITEMS = 4096;\n\nexport const sessionId: Validator<string> = str(32, /^[0-9a-f]{32}$/);\nexport const draftId: Validator<string> = str(32, /^[0-9a-f]{32}$/);\nexport const walletId: Validator<string> = str(16, /^[0-9a-f]{16}$/);\nexport const publicKey: Validator<string> = str(64, /^[0-9a-f]{64}$/);\nexport const credentialId: Validator<string> = str(1364, /^[A-Za-z0-9_-]+$/);\nexport const safeTime: Validator<number> = int(0, Number.MAX_SAFE_INTEGER);\nexport const groupIndex: Validator<number> = int(0, 0x7fffffff);\n/** Identity indices stop below 2^31 - 1 — the top segment derives the wallet sync key. */\nexport const identityIndex: Validator<number> = int(0, 0x7ffffffe);\n\n/**\n * Vault factor material on the wire. `hardware` carries nothing: the kernel runs the platform\n * keystore ceremony itself, so the main runtime never touches the KEK.\n */\nexport type Factor =\n | { readonly kind: \"hardware\" }\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | { readonly kind: \"passkey\"; readonly credentialId: Uint8Array; readonly prf: Uint8Array };\n\nexport const factor: Validator<Factor> = union(\n obj({ kind: literal(\"hardware\") }),\n obj({ kind: literal(\"password\"), password: bytes(1, 1024) }),\n obj({ kind: literal(\"passkey\"), credentialId: bytes(1, 1023), prf: bytes(32) }),\n);\n\n/** A host-run backup passkey ceremony's evidence: the PRF over `backupSalt` (web). */\ntype HostBackupPasskey = {\n readonly kind: \"passkey\";\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfBackup: Uint8Array;\n};\n\n/**\n * A factor that seals a new backup key. On React Native the kernel registers a protection\n * credential (`kernel`) itself and names it; on the web the host hands over its ceremony's\n * evidence.\n */\nexport type BackupFactor =\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | HostBackupPasskey\n | {\n readonly kind: \"passkey\";\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly rpName: string;\n readonly backupSalt: string;\n };\n\n/**\n * A factor that opens a backup envelope. The `kernel` passkey arm asserts one of the envelope's own\n * credentials.\n */\nexport type BackupUnlockFactor =\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | HostBackupPasskey\n | {\n readonly kind: \"passkey\";\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly backupSalt: string;\n };\n\nexport const factorInfo: Validator<FactorInfo> = union(\n obj({ kind: literal(\"hardware\"), id: sessionId, createdAt: safeTime }),\n obj({\n kind: literal(\"passkey\"),\n id: sessionId,\n credentialId,\n createdAt: safeTime,\n }),\n obj({ kind: literal(\"password\"), id: sessionId, createdAt: safeTime }),\n);\n\n/**\n * Passkey wallet creation. `host`: the host ran the WebAuthn ceremony and hands over the PRF\n * evidence (web). `kernel`: the kernel runs the platform ceremony itself and nothing secret crosses\n * the channel (React Native). The kernel accepts exactly the shape its platform supports.\n */\nexport type CreateWithPasskeyParams =\n | {\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfWallet: Uint8Array;\n readonly synced: boolean;\n readonly factor?: Factor;\n }\n | {\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly rpName: string;\n readonly name: string;\n readonly walletSalt: string;\n readonly factor?: Factor;\n };\n\nexport type RestoreWithPasskeyParams =\n | {\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfWallet: Uint8Array;\n readonly synced: boolean;\n readonly factor?: Factor;\n }\n | {\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly walletSalt: string;\n readonly factor?: Factor;\n };\n\n// An RP id is a lowercase DNS name; the platform rejects anything its associated domains do not\n// list, so this only bounds the shape.\nconst RP_ID =\n /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;\nconst label = (max: number): Validator<string> => str(max, /^\\S(?:.*\\S)?$/su);\n\nconst hostEvidence = {\n ceremony: literal(\"host\"),\n credentialId: bytes(1, 1023),\n prfWallet: bytes(32),\n synced: bool,\n factor: opt(factor),\n};\n\nconst createWithPasskeyParams: Validator<CreateWithPasskeyParams> = union(\n obj(hostEvidence),\n obj({\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n rpName: label(64),\n name: label(64),\n walletSalt: label(64),\n factor: opt(factor),\n }),\n);\n\nconst restoreWithPasskeyParams: Validator<RestoreWithPasskeyParams> = union(\n obj(hostEvidence),\n obj({\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n walletSalt: label(64),\n factor: opt(factor),\n }),\n);\n\nconst hostBackupPasskey = obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"host\"),\n credentialId: bytes(1, 1023),\n prfBackup: bytes(32),\n});\nconst backupPassword = obj({ kind: literal(\"password\"), password: bytes(1, 1024) });\n\nexport const backupFactor: Validator<BackupFactor> = union(\n backupPassword,\n hostBackupPasskey,\n obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n rpName: label(64),\n backupSalt: label(64),\n }),\n);\n\nexport const backupUnlockFactor: Validator<BackupUnlockFactor> = union(\n backupPassword,\n hostBackupPasskey,\n obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n backupSalt: label(64),\n }),\n);\n\nexport const walletInfo: Validator<WalletInfo> = obj({\n walletId,\n origin: union(literal(\"passkey\"), literal(\"mnemonic\")),\n words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),\n backup: union(literal(\"none\"), literal(\"passkey\"), literal(\"mnemonic\")),\n passphrase: bool,\n createdAt: safeTime,\n});\n\n/** A BIP-39 passphrase on the wire: raw UTF-8 bytes, never empty (the host omits \"none\"). */\nconst passphraseBytes: Validator<Uint8Array> = bytes(1, 1024);\n\nexport const walletErrorCode: Validator<WalletErrorCode> = union(\n literal(\"locked\"),\n literal(\"cancelled\"),\n literal(\"factor-unavailable\"),\n literal(\"factor-invalidated\"),\n literal(\"wrong-password\"),\n literal(\"wrong-passkey\"),\n literal(\"rate-limited\"),\n literal(\"invalid-input\"),\n literal(\"not-found\"),\n literal(\"already-exists\"),\n literal(\"conflict\"),\n literal(\"unsupported\"),\n literal(\"unavailable\"),\n literal(\"integrity\"),\n literal(\"approval-required\"),\n literal(\"crashed\"),\n);\n\n/**\n * The result of every \"create or import\" wallet command: the new wallet's public info plus the\n * session it opened. Creating a wallet derives no protocol keys — modules add keys separately.\n */\nexport type CreatedResult = {\n readonly wallet: WalletInfo;\n readonly session: string;\n};\n\nconst createdResult: Validator<CreatedResult> = obj({ wallet: walletInfo, session: sessionId });\n\n// `status` itself is a core method, but its result validator composes every module's status\n// section — it is wired in protocol/index.ts, not here.\nexport const CORE_METHODS: {\n readonly \"vault.unlock\": MethodSpec<{ readonly factor: Factor }, { readonly session: string }>;\n readonly \"vault.reset\": MethodSpec<NullValue, NullValue>;\n readonly \"vault.addFactor\": MethodSpec<\n { readonly verify: Factor; readonly factor: Factor },\n FactorInfo\n >;\n readonly \"vault.removeFactor\": MethodSpec<\n { readonly verify: Factor; readonly id: string },\n NullValue\n >;\n readonly \"session.touch\": MethodSpec<NullValue, NullValue>;\n readonly \"wallet.createWithPasskey\": MethodSpec<CreateWithPasskeyParams, CreatedResult>;\n readonly \"wallet.restoreWithPasskey\": MethodSpec<RestoreWithPasskeyParams, CreatedResult>;\n readonly \"wallet.createMnemonic\": MethodSpec<\n { readonly words: 12 | 24; readonly factor?: Factor },\n { readonly draft: string; readonly words: Uint8Array; readonly quiz: ReadonlyArray<number> }\n >;\n readonly \"wallet.confirmMnemonic\": MethodSpec<\n {\n readonly draft: string;\n readonly answers: ReadonlyArray<Uint8Array>;\n readonly passphrase?: Uint8Array;\n },\n CreatedResult\n >;\n readonly \"wallet.discardMnemonic\": MethodSpec<{ readonly draft: string }, NullValue>;\n readonly \"backup.enable\": MethodSpec<\n {\n readonly verify: Factor;\n readonly factors: ReadonlyArray<BackupFactor>;\n },\n NullValue\n >;\n readonly \"backup.update\": MethodSpec<NullValue, { readonly envelope: string }>;\n readonly \"backup.disable\": MethodSpec<NullValue, NullValue>;\n readonly \"backup.restore\": MethodSpec<\n {\n readonly envelope: string;\n readonly backupFactor: BackupUnlockFactor;\n readonly passphrases?: ReadonlyArray<{\n readonly walletId: string;\n readonly passphrase: Uint8Array;\n }>;\n readonly factor?: Factor;\n },\n {\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly passphraseRequired: ReadonlyArray<string>;\n readonly session: string;\n }\n >;\n readonly \"wallet.importMnemonic\": MethodSpec<\n { readonly mnemonic: Uint8Array; readonly passphrase?: Uint8Array; readonly factor?: Factor },\n CreatedResult\n >;\n readonly \"wallet.exportMnemonic\": MethodSpec<\n { readonly verify: Factor; readonly walletId: string },\n { readonly mnemonic: Uint8Array; readonly passphrase?: Uint8Array }\n >;\n readonly \"wallet.delete\": MethodSpec<\n { readonly verify: Factor; readonly walletId: string },\n NullValue\n >;\n readonly \"dataKeys.get\": MethodSpec<{ readonly purpose: string }, Uint8Array>;\n} = {\n \"session.touch\": {\n session: true,\n presence: true,\n params: nullValue,\n result: nullValue,\n },\n \"vault.unlock\": {\n session: false,\n presence: true,\n params: obj({ factor }),\n result: obj({ session: sessionId }),\n },\n \"vault.reset\": { session: false, presence: false, params: nullValue, result: nullValue },\n \"vault.addFactor\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, factor }),\n result: factorInfo,\n },\n \"vault.removeFactor\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, id: sessionId }),\n result: nullValue,\n },\n \"wallet.createWithPasskey\": {\n session: false,\n presence: true,\n params: createWithPasskeyParams,\n result: createdResult,\n },\n \"wallet.restoreWithPasskey\": {\n session: false,\n presence: true,\n params: restoreWithPasskeyParams,\n result: createdResult,\n },\n \"wallet.createMnemonic\": {\n session: false,\n presence: true,\n params: obj({ words: union(literal(12), literal(24)), factor: opt(factor) }),\n result: obj({\n draft: draftId,\n words: bytes(16, 1024),\n quiz: arr(int(0, 23), 3, 3),\n }),\n },\n \"wallet.confirmMnemonic\": {\n session: false,\n presence: true,\n params: obj({\n draft: draftId,\n answers: arr(bytes(1, 64), 3, 3),\n passphrase: opt(passphraseBytes),\n }),\n result: createdResult,\n },\n \"wallet.discardMnemonic\": {\n session: false,\n presence: false,\n params: obj({ draft: draftId }),\n result: nullValue,\n },\n \"backup.enable\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, factors: arr(backupFactor, 5, 1) }),\n result: nullValue,\n },\n \"backup.update\": {\n session: true,\n presence: false,\n params: nullValue,\n result: obj({ envelope: str(4_000_000) }),\n },\n \"backup.disable\": {\n session: true,\n presence: true,\n params: nullValue,\n result: nullValue,\n },\n \"backup.restore\": {\n session: false,\n presence: true,\n params: obj({\n envelope: str(4_000_000),\n backupFactor: backupUnlockFactor,\n passphrases: opt(arr(obj({ walletId, passphrase: passphraseBytes }), 1000)),\n factor: opt(factor),\n }),\n result: obj({\n wallets: arr(walletInfo, 1000),\n passphraseRequired: arr(str(128), 1000),\n session: sessionId,\n }),\n },\n \"wallet.importMnemonic\": {\n session: false,\n presence: true,\n params: obj({\n mnemonic: bytes(1, 1024),\n passphrase: opt(passphraseBytes),\n factor: opt(factor),\n }),\n result: createdResult,\n },\n \"wallet.exportMnemonic\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, walletId }),\n result: obj({ mnemonic: bytes(16, 1024), passphrase: opt(passphraseBytes) }),\n },\n \"wallet.delete\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, walletId }),\n result: nullValue,\n },\n \"dataKeys.get\": {\n session: true,\n presence: false,\n params: obj({ purpose: str(32, /^[a-z0-9-]{1,32}$/) }),\n result: bytes(32),\n },\n};\n"],"mappings":";;;;;;AAMA,IAAa,kBAAb,cAAqC,MAAM;CACzC,OAAgB;AAClB;AAIA,SAAS,OAAc;CACrB,MAAM,IAAI,gBAAgB;AAC5B;AAKA,SAAgB,QACd,UACc;CACd,QAAQ,UAAU;EAChB,IAAI,UAAU,UACZ,KAAK;EAEP,OAAO;CACT;AACF;AAEA,MAAa,YAAkC,QAAQ,IAAI;AAC3D,MAAa,QAA4B,UAAU;CACjD,IAAI,OAAO,UAAU,WACnB,KAAK;CAEP,OAAO;AACT;AAEA,SAAgB,IAAI,KAAa,KAAgC;CAC/D,QAAQ,UAAU;EAChB,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,OAAO,QAAQ,KACtF,KAAK;EAEP,OAAO;CACT;AACF;AAEA,SAAgB,IAAI,KAAa,SAAqC;CACpE,QAAQ,UAAU;EAChB,IACE,OAAO,UAAU,YACjB,MAAM,SAAS,OACd,YAAY,KAAA,KAAa,CAAC,QAAQ,KAAK,KAAK,GAE7C,KAAK;EAEP,OAAO;CACT;AACF;AAEA,SAAgB,MAAM,KAAa,KAAqC;CACtE,MAAM,OAAO,OAAO;CACpB,QAAQ,UAAU;EAChB,IAAI,EAAE,iBAAiB,eAAe,MAA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QAAQ;EACR,QAAQ,IAAI,EAAE,UAAU,IAAI,GAAS,EAAE,CAAC;CAC1C;CACA,kBAAkB;EAChB,SAAS;EACT,UAAU;EACV,QAAQ;EACR,QAAQ;CACV;CACA,kBAAkB;EAChB,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GACV,UAAU,IAAI,GAAS;GACvB,cAAc;GACd,aAAa,IAAI,IAAI,IAAI;IAAE;IAAU,YAAY;GAAgB,CAAC,GAAG,GAAI,CAAC;GAC1E,QAAQ,IAAI,MAAM;EACpB,CAAC;EACD,QAAQ,IAAI;GACV,SAAS,IAAI,YAAY,GAAI;GAC7B,oBAAoB,IAAI,IAAI,GAAG,GAAG,GAAI;GACtC,SAAS;EACX,CAAC;CACH;CACA,yBAAyB;EACvB,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GACV,UAAU,MAAM,GAAG,IAAI;GACvB,YAAY,IAAI,eAAe;GAC/B,QAAQ,IAAI,MAAM;EACpB,CAAC;EACD,QAAQ;CACV;CACA,yBAAyB;EACvB,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GAAE,QAAQ;GAAQ;EAAS,CAAC;EACxC,QAAQ,IAAI;GAAE,UAAU,MAAM,IAAI,IAAI;GAAG,YAAY,IAAI,eAAe;EAAE,CAAC;CAC7E;CACA,iBAAiB;EACf,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GAAE,QAAQ;GAAQ;EAAS,CAAC;EACxC,QAAQ;CACV;CACA,gBAAgB;EACd,SAAS;EACT,UAAU;EACV,QAAQ,IAAI,EAAE,SAAS,IAAI,IAAI,mBAAmB,EAAE,CAAC;EACrD,QAAQ,MAAM,EAAE;CAClB;AACF"}
package/dist/host.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { p as PasskeyConfig, v as Wallet } from "./types-CIYT5uFj.mjs";
2
- import { et as SignedEvent, l as ProtocolValue } from "./index-BXnQtz55.mjs";
1
+ import { m as PasskeyConfig, y as Wallet } from "./types-Jsz2m1ib.mjs";
2
+ import { et as SignedEvent, l as ProtocolValue } from "./index-Cxt3caTG.mjs";
3
3
  /**
4
4
  * Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock
5
5
  * triggered by the platform (native background expiry — W7).
package/dist/host.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { WalletError } from "./types.mjs";
2
- import { t as Channel } from "./channel-Iiz28m-e.mjs";
2
+ import { t as Channel } from "./channel-DcIolCZs.mjs";
3
3
  import { n as registerInternals } from "./internal-CAKfHjIg.mjs";
4
- import { a as passkeyName, c as resolveBackupUnlockFactor, d as vaultSaltBytes, f as walletSaltBytes, i as defaultUnlockFactor, l as resolveFactor, m as wireSecretText, n as PASSKEY_PURPOSE_VAULT, o as requireCeremony, p as wireBytes, r as PASSKEY_PURPOSE_WALLET, s as resolveBackupFactor, t as SingleUseSecret, u as resolveInitialFactor } from "./secret-Dz_ItVt6.mjs";
4
+ import { a as passkeyName, c as resolveBackupUnlockFactor, d as vaultSaltBytes, f as walletSaltBytes, h as wireSecretText, i as defaultUnlockFactor, l as resolveFactor, m as wirePassphrase, n as PASSKEY_PURPOSE_VAULT, o as requireCeremony, p as wireBytes, r as PASSKEY_PURPOSE_WALLET, s as resolveBackupFactor, t as SingleUseSecret, u as resolveInitialFactor } from "./secret-D1_CwVQD.mjs";
5
5
  // src/wallet.ts
6
6
  /**
7
7
  * The host-facing `Wallet` (design/entry.mdx "API"): snapshot state, the core API groups, and the
@@ -300,12 +300,14 @@ var KernelWallet = class KernelWallet {
300
300
  return {
301
301
  words: new SingleUseSecret(created.words),
302
302
  quiz: created.quiz,
303
- confirm: async (answers) => {
303
+ confirm: async (answers, confirmOptions) => {
304
304
  const answerTransfer = [];
305
305
  const encoded = answers.map((word) => wireSecretText(word, answerTransfer));
306
+ const passphrase = wirePassphrase(confirmOptions?.passphrase, answerTransfer);
306
307
  const confirmed = await this.channel.call("wallet.confirmMnemonic", {
307
308
  draft: draftId,
308
- answers: encoded
309
+ answers: encoded,
310
+ ...passphrase
309
311
  }, answerTransfer);
310
312
  this.sessionOf(confirmed);
311
313
  return confirmed.wallet;
@@ -319,8 +321,10 @@ var KernelWallet = class KernelWallet {
319
321
  const transfer = [];
320
322
  const factor = await this.createFactorParam(options.factor, transfer);
321
323
  const mnemonic = wireSecretText(options.mnemonic, transfer);
324
+ const passphrase = wirePassphrase(options.passphrase, transfer);
322
325
  const created = await this.channel.call("wallet.importMnemonic", {
323
326
  mnemonic,
327
+ ...passphrase,
324
328
  ...factor === void 0 ? {} : { factor }
325
329
  }, transfer);
326
330
  this.sessionOf(created);
@@ -329,11 +333,14 @@ var KernelWallet = class KernelWallet {
329
333
  exportMnemonic: async (walletId, verify) => this.withVerifying(async () => {
330
334
  const transfer = [];
331
335
  const wireVerify = await resolveFactor(this.factorSource, verify, transfer);
332
- const bytes = await this.channel.call("wallet.exportMnemonic", {
336
+ const exported = await this.channel.call("wallet.exportMnemonic", {
333
337
  verify: wireVerify,
334
338
  walletId
335
339
  }, transfer);
336
- return new SingleUseSecret(bytes);
340
+ return {
341
+ mnemonic: new SingleUseSecret(exported.mnemonic),
342
+ ...exported.passphrase === void 0 ? {} : { passphrase: new SingleUseSecret(exported.passphrase) }
343
+ };
337
344
  }),
338
345
  delete: async (walletId, verify) => this.withVerifying(async () => {
339
346
  const transfer = [];
@@ -365,13 +372,21 @@ var KernelWallet = class KernelWallet {
365
372
  const transfer = [];
366
373
  const backupFactor = await resolveBackupUnlockFactor(this.factorSource, options.backupFactor, transfer);
367
374
  const factor = await this.createFactorParam(options.factor, transfer);
375
+ const passphrases = options.passphrases?.map(({ walletId, passphrase }) => ({
376
+ walletId,
377
+ passphrase: wireSecretText(passphrase, transfer)
378
+ }));
368
379
  const result = await this.channel.call("backup.restore", {
369
380
  envelope: options.envelope,
370
381
  backupFactor,
382
+ ...passphrases === void 0 ? {} : { passphrases },
371
383
  ...factor === void 0 ? {} : { factor }
372
384
  }, transfer);
373
385
  this.sessionOf(result);
374
- return result.wallets;
386
+ return {
387
+ wallets: result.wallets,
388
+ passphraseRequired: result.passphraseRequired
389
+ };
375
390
  })
376
391
  };
377
392
  async destroy() {
package/dist/host.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.mjs","names":[],"sources":["../src/wallet.ts"],"sourcesContent":["/**\n * The host-facing `Wallet` (design/entry.mdx \"API\"): snapshot state, the core API groups, and the\n * glue between the kernel `Channel` and factor resolution. `connectKernel` is exported under the\n * `./host` subpath — reserved for host packages; applications must not use it. Protocol modules\n * (@qntx/wallet/nostr and future siblings) reach this wallet's channel through the registered\n * internals in internal.ts — never through the public type.\n */\n\nimport { 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, PrfResult } from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor, SignedEvent } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupApi,\n DataKeyApi,\n 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 verifyEvent: (event: SignedEvent) => boolean;\n readonly ceremony: PasskeyCeremony | undefined;\n /** Timer source injected by the host package (globalThis timers on web/node). */\n readonly setTimer: SetTimer;\n /**\n * User-presence source: subscribes to activity signals and returns an unsubscribe the wallet\n * owns. Absent means the host has no presence signals (the kernel policy decides what counts).\n */\n readonly presence?: (onActivity: () => void) => () => void;\n /** Runs once inside `destroy()` — host-side cleanup (page listeners, timers). */\n readonly onDestroy?: () => void;\n};\n\n/** One `session.touch` at most per interval — the idle deadline slips at most this much early. */\nexport const PRESENCE_TOUCH_INTERVAL_MS = 30_000;\n\n/** Structural equality over plain snapshot data (validated protocol payloads only). */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((item, index) => deepEqual(item, b[index]))\n );\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every(\n (key) =>\n key in b &&\n deepEqual(\n (a as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n (b as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n ),\n )\n );\n}\n\nexport class KernelWallet implements Wallet {\n private readonly channel: Channel;\n private readonly factorMode: FactorMode;\n private readonly passkeyCfg: PasskeyConfig;\n private readonly ceremony: PasskeyCeremony | undefined;\n private readonly setTimer: SetTimer;\n private readonly onDestroy: (() => void) | undefined;\n private readonly unsubscribePresence: (() => void) | undefined;\n private presenceCooling = false;\n private cancelCooldown: (() => void) | undefined;\n private destroyed = false;\n\n private status: StatusPayload | undefined;\n private lockReason: LockReason | undefined;\n private verifying = 0;\n private snapshotValue: WalletSnapshot;\n private readonly listeners = new Set<() => void>();\n\n private constructor(options: ConnectOptions) {\n this.factorMode = options.factors;\n this.passkeyCfg = options.passkey;\n this.ceremony = options.ceremony;\n this.setTimer = options.setTimer;\n this.onDestroy = options.onDestroy;\n this.snapshotValue = {\n vault: \"uninitialized\",\n lockReason: undefined,\n verifying: false,\n factors: [],\n wallets: [],\n nostr: { keys: [] },\n backup: null,\n };\n this.channel = new Channel(\n options.spawn,\n {\n onStatus: (status) => {\n this.onStatus(status);\n },\n onLocked: (reason) => {\n this.lockReason = reason;\n this.markLocked();\n },\n onCrashed: () => {\n this.lockReason = \"crashed\";\n this.markLocked();\n },\n },\n options.setTimer,\n );\n // The wallet owns the subscription it creates: destroy() unsubscribes — no second owner.\n this.unsubscribePresence = options.presence?.(() => {\n this.onPresence();\n });\n registerInternals(this, {\n call: async (method, params, transfer) => this.channel.call(method, params, transfer),\n ready: async () => this.channel.ready,\n snapshot: () => this.snapshotValue,\n verifyEvent: options.verifyEvent,\n withVerifying: async (fn) => this.withVerifying(fn),\n resolveFactor: async (factor, transfer) => resolveFactor(this.factorSource, factor, transfer),\n createFactorParam: async (factor, transfer) => this.createFactorParam(factor, transfer),\n sessionOf: (result) => {\n this.sessionOf(result);\n },\n });\n }\n\n static async connect(options: ConnectOptions): Promise<KernelWallet> {\n const wallet = new KernelWallet(options);\n await wallet.channel.start();\n return wallet;\n }\n\n /** Runs a host-ceremony passkey call and adopts the returned session and wallet info. */\n private async hostPasskeyWallet(\n method: \"wallet.createWithPasskey\" | \"wallet.restoreWithPasskey\",\n result: PrfResult,\n factor: Factor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<WalletInfo> {\n const created = await this.channel.call(\n method,\n {\n ceremony: \"host\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfWallet: wireBytes(result.first, transfer, true),\n synced: result.synced,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n\n /**\n * Presence refresh, throttled to one touch per interval: once a touch fires, signals are ignored\n * until the cooldown elapses — no clock reads, just the injected timer. Touches only go out while\n * a session is held; failures are silent (a lock or respawn needs no handling).\n */\n private onPresence(): void {\n if (this.presenceCooling || this.destroyed || this.channel.session === undefined) {\n return;\n }\n this.presenceCooling = true;\n this.cancelCooldown = this.setTimer(PRESENCE_TOUCH_INTERVAL_MS, () => {\n this.presenceCooling = false;\n this.cancelCooldown = undefined;\n });\n void this.touchSession();\n }\n\n private async touchSession(): Promise<void> {\n try {\n await this.channel.call(\"session.touch\", null);\n } catch {\n // A racing lock or respawn needs no handling.\n }\n }\n\n /**\n * The worker is dead or replaced — no status will arrive from it, yet an unlocked vault is locked\n * now. Reflect that in the snapshot without waiting for the respawned kernel; other states\n * (uninitialized, corrupted, …) are the kernel's truth and stay untouched.\n */\n private markLocked(): void {\n if (this.status !== undefined && this.status.vault === \"unlocked\") {\n this.status = { ...this.status, vault: \"locked\" };\n }\n this.emit();\n }\n\n private onStatus(status: StatusPayload): void {\n if (this.lockReason === undefined && status.vault === \"locked\") {\n this.lockReason = \"cold-start\"; // locked at first sight, not by an action of ours\n }\n this.status = status;\n this.emit();\n }\n\n /**\n * Rebuilds the immutable snapshot and notifies subscribers — only when the content actually\n * changed (identical status events produce no new reference and no notification).\n */\n private emit(): void {\n const { status } = this;\n const next: WalletSnapshot = {\n vault: status === undefined ? \"uninitialized\" : status.vault,\n lockReason: this.lockReason,\n verifying: this.verifying > 0,\n factors: status === undefined ? [] : status.factors,\n wallets: status === undefined ? [] : status.wallets,\n nostr: { keys: status === undefined ? [] : status.nostr.keys },\n 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 return this.hostPasskeyWallet(\"wallet.createWithPasskey\", result, factor, transfer);\n }),\n restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n const factor = await this.createFactorParam(options?.factor, transfer);\n const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.assert({\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n // The asserted credential must be a wallet-purpose passkey: a vault-purpose credential\n // would silently derive a different wallet. Rejected assertions never reach the kernel.\n if (result.userHandle?.[0] !== PASSKEY_PURPOSE_WALLET) {\n result.first.fill(0);\n result.second?.fill(0);\n throw new WalletError(\"wrong-passkey\", \"the passkey is not a wallet credential\");\n }\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options?.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0);\n } else {\n factor = await resolveInitialFactor(this.factorSource, options?.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.restoreWithPasskey\", result, factor, transfer);\n }),\n createMnemonic: async (options: {\n readonly words: 12 | 24;\n readonly factor?: InitialFactor;\n }): Promise<MnemonicDraft> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createMnemonic\",\n { words: options.words, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n const draftId = created.draft;\n return {\n words: new SingleUseSecret(created.words),\n quiz: created.quiz,\n confirm: async (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":";;;;;;;;;;;;;AAkEA,MAAa,6BAA6B;;AAG1C,SAAS,UAAU,GAAY,GAAqB;CAClD,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,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,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 */\n\nimport { Channel } from \"./channel.ts\";\nimport type { MainPort, SetTimer } from \"./channel.ts\";\nimport {\n PASSKEY_PURPOSE_WALLET,\n passkeyName,\n requireCeremony,\n resolveFactor,\n resolveInitialFactor,\n vaultSaltBytes,\n walletSaltBytes,\n wireBytes,\n wirePassphrase,\n wireSecretText,\n resolveBackupFactor,\n resolveBackupUnlockFactor,\n defaultUnlockFactor,\n} from \"./factors.ts\";\nimport type { FactorMode, FactorSource, PasskeyCeremony, PrfResult } from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor, SignedEvent } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupApi,\n DataKeyApi,\n ExportedMnemonic,\n FactorInfo,\n InitialFactor,\n LockReason,\n MnemonicDraft,\n PasskeyConfig,\n StatusPayload,\n UnlockFactor,\n VaultApi,\n Wallet,\n WalletInfo,\n WalletSnapshot,\n WalletsApi,\n} from \"./types.ts\";\n\nexport type ConnectOptions = {\n readonly spawn: () => MainPort;\n /** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */\n readonly factors: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly verifyEvent: (event: SignedEvent) => boolean;\n readonly ceremony: PasskeyCeremony | undefined;\n /** Timer source injected by the host package (globalThis timers on web/node). */\n readonly setTimer: SetTimer;\n /**\n * User-presence source: subscribes to activity signals and returns an unsubscribe the wallet\n * owns. Absent means the host has no presence signals (the kernel policy decides what counts).\n */\n readonly presence?: (onActivity: () => void) => () => void;\n /** Runs once inside `destroy()` — host-side cleanup (page listeners, timers). */\n readonly onDestroy?: () => void;\n};\n\n/** One `session.touch` at most per interval — the idle deadline slips at most this much early. */\nexport const PRESENCE_TOUCH_INTERVAL_MS = 30_000;\n\n/** Structural equality over plain snapshot data (validated protocol payloads only). */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((item, index) => deepEqual(item, b[index]))\n );\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every(\n (key) =>\n key in b &&\n deepEqual(\n (a as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n (b as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n ),\n )\n );\n}\n\nexport class KernelWallet implements Wallet {\n private readonly channel: Channel;\n private readonly factorMode: FactorMode;\n private readonly passkeyCfg: PasskeyConfig;\n private readonly ceremony: PasskeyCeremony | undefined;\n private readonly setTimer: SetTimer;\n private readonly onDestroy: (() => void) | undefined;\n private readonly unsubscribePresence: (() => void) | undefined;\n private presenceCooling = false;\n private cancelCooldown: (() => void) | undefined;\n private destroyed = false;\n\n private status: StatusPayload | undefined;\n private lockReason: LockReason | undefined;\n private verifying = 0;\n private snapshotValue: WalletSnapshot;\n private readonly listeners = new Set<() => void>();\n\n private constructor(options: ConnectOptions) {\n this.factorMode = options.factors;\n this.passkeyCfg = options.passkey;\n this.ceremony = options.ceremony;\n this.setTimer = options.setTimer;\n this.onDestroy = options.onDestroy;\n this.snapshotValue = {\n vault: \"uninitialized\",\n lockReason: undefined,\n verifying: false,\n factors: [],\n wallets: [],\n nostr: { keys: [] },\n backup: null,\n };\n this.channel = new Channel(\n options.spawn,\n {\n onStatus: (status) => {\n this.onStatus(status);\n },\n onLocked: (reason) => {\n this.lockReason = reason;\n this.markLocked();\n },\n onCrashed: () => {\n this.lockReason = \"crashed\";\n this.markLocked();\n },\n },\n options.setTimer,\n );\n // The wallet owns the subscription it creates: destroy() unsubscribes — no second owner.\n this.unsubscribePresence = options.presence?.(() => {\n this.onPresence();\n });\n registerInternals(this, {\n call: async (method, params, transfer) => this.channel.call(method, params, transfer),\n ready: async () => this.channel.ready,\n snapshot: () => this.snapshotValue,\n verifyEvent: options.verifyEvent,\n withVerifying: async (fn) => this.withVerifying(fn),\n resolveFactor: async (factor, transfer) => resolveFactor(this.factorSource, factor, transfer),\n createFactorParam: async (factor, transfer) => this.createFactorParam(factor, transfer),\n sessionOf: (result) => {\n this.sessionOf(result);\n },\n });\n }\n\n static async connect(options: ConnectOptions): Promise<KernelWallet> {\n const wallet = new KernelWallet(options);\n await wallet.channel.start();\n return wallet;\n }\n\n /** Runs a host-ceremony passkey call and adopts the returned session and wallet info. */\n private async hostPasskeyWallet(\n method: \"wallet.createWithPasskey\" | \"wallet.restoreWithPasskey\",\n result: PrfResult,\n factor: Factor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<WalletInfo> {\n const created = await this.channel.call(\n method,\n {\n ceremony: \"host\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfWallet: wireBytes(result.first, transfer, true),\n synced: result.synced,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n\n /**\n * Presence refresh, throttled to one touch per interval: once a touch fires, signals are ignored\n * until the cooldown elapses — no clock reads, just the injected timer. Touches only go out while\n * a session is held; failures are silent (a lock or respawn needs no handling).\n */\n private onPresence(): void {\n if (this.presenceCooling || this.destroyed || this.channel.session === undefined) {\n return;\n }\n this.presenceCooling = true;\n this.cancelCooldown = this.setTimer(PRESENCE_TOUCH_INTERVAL_MS, () => {\n this.presenceCooling = false;\n this.cancelCooldown = undefined;\n });\n void this.touchSession();\n }\n\n private async touchSession(): Promise<void> {\n try {\n await this.channel.call(\"session.touch\", null);\n } catch {\n // A racing lock or respawn needs no handling.\n }\n }\n\n /**\n * The worker is dead or replaced — no status will arrive from it, yet an unlocked vault is locked\n * now. Reflect that in the snapshot without waiting for the respawned kernel; other states\n * (uninitialized, corrupted, …) are the kernel's truth and stay untouched.\n */\n private markLocked(): void {\n if (this.status !== undefined && this.status.vault === \"unlocked\") {\n this.status = { ...this.status, vault: \"locked\" };\n }\n this.emit();\n }\n\n private onStatus(status: StatusPayload): void {\n if (this.lockReason === undefined && status.vault === \"locked\") {\n this.lockReason = \"cold-start\"; // locked at first sight, not by an action of ours\n }\n this.status = status;\n this.emit();\n }\n\n /**\n * Rebuilds the immutable snapshot and notifies subscribers — only when the content actually\n * changed (identical status events produce no new reference and no notification).\n */\n private emit(): void {\n const { status } = this;\n const next: WalletSnapshot = {\n vault: status === undefined ? \"uninitialized\" : status.vault,\n lockReason: this.lockReason,\n verifying: this.verifying > 0,\n factors: status === undefined ? [] : status.factors,\n wallets: status === undefined ? [] : status.wallets,\n nostr: { keys: status === undefined ? [] : status.nostr.keys },\n 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 return this.hostPasskeyWallet(\"wallet.createWithPasskey\", result, factor, transfer);\n }),\n restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n const factor = await this.createFactorParam(options?.factor, transfer);\n const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.assert({\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n // The asserted credential must be a wallet-purpose passkey: a vault-purpose credential\n // would silently derive a different wallet. Rejected assertions never reach the kernel.\n if (result.userHandle?.[0] !== PASSKEY_PURPOSE_WALLET) {\n result.first.fill(0);\n result.second?.fill(0);\n throw new WalletError(\"wrong-passkey\", \"the passkey is not a wallet credential\");\n }\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options?.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0);\n } else {\n factor = await resolveInitialFactor(this.factorSource, options?.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.restoreWithPasskey\", result, factor, transfer);\n }),\n createMnemonic: async (options: {\n readonly words: 12 | 24;\n readonly factor?: InitialFactor;\n }): Promise<MnemonicDraft> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createMnemonic\",\n { words: options.words, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n const draftId = created.draft;\n return {\n words: new SingleUseSecret(created.words),\n quiz: created.quiz,\n confirm: async (\n answers: ReadonlyArray<string>,\n confirmOptions?: { readonly passphrase?: string },\n ): Promise<WalletInfo> => {\n const answerTransfer: ArrayBuffer[] = [];\n const encoded = answers.map((word) => wireSecretText(word, answerTransfer));\n const passphrase = wirePassphrase(confirmOptions?.passphrase, answerTransfer);\n const confirmed = await this.channel.call(\n \"wallet.confirmMnemonic\",\n { draft: draftId, answers: encoded, ...passphrase },\n answerTransfer,\n );\n this.sessionOf(confirmed);\n return confirmed.wallet;\n },\n discard: async (): Promise<void> => {\n await this.channel.call(\"wallet.discardMnemonic\", { draft: draftId });\n },\n };\n },\n importMnemonic: async (options: {\n readonly mnemonic: string;\n readonly passphrase?: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const mnemonic = wireSecretText(options.mnemonic, transfer);\n const passphrase = wirePassphrase(options.passphrase, transfer);\n const created = await this.channel.call(\n \"wallet.importMnemonic\",\n { mnemonic, ...passphrase, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n },\n exportMnemonic: async (walletId: string, verify: UnlockFactor): Promise<ExportedMnemonic> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const exported = await this.channel.call(\n \"wallet.exportMnemonic\",\n { verify: wireVerify, walletId },\n transfer,\n );\n return {\n mnemonic: new SingleUseSecret(exported.mnemonic),\n ...(exported.passphrase === undefined\n ? {}\n : { passphrase: new SingleUseSecret(exported.passphrase) }),\n };\n }),\n delete: async (walletId: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"wallet.delete\", { verify: wireVerify, walletId }, transfer);\n }),\n };\n\n readonly dataKeys: DataKeyApi = {\n get: async (purpose: string): Promise<Uint8Array> =>\n this.channel.call(\"dataKeys.get\", { purpose }),\n };\n\n readonly backup: BackupApi = {\n enable: async (options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, options.verify, transfer);\n const wireFactors = await Promise.all(\n options.factors.map(async (factor) =>\n resolveBackupFactor(this.factorSource, factor, transfer),\n ),\n );\n await this.channel.call(\n \"backup.enable\",\n { verify: wireVerify, factors: wireFactors },\n transfer,\n );\n }),\n update: async (): Promise<string> => {\n const result = await this.channel.call(\"backup.update\", null);\n return result.envelope;\n },\n disable: async (): Promise<void> => {\n await this.channel.call(\"backup.disable\", null);\n },\n restore: async (options: {\n readonly envelope: string;\n readonly backupFactor: UnlockFactor;\n readonly passphrases?: ReadonlyArray<{\n readonly walletId: string;\n readonly passphrase: string;\n }>;\n readonly factor?: InitialFactor;\n }): Promise<{\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly passphraseRequired: ReadonlyArray<string>;\n }> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const backupFactor = await resolveBackupUnlockFactor(\n this.factorSource,\n options.backupFactor,\n transfer,\n );\n const factor = await this.createFactorParam(options.factor, transfer);\n const passphrases = options.passphrases?.map(({ walletId, passphrase }) => ({\n walletId,\n passphrase: wireSecretText(passphrase, transfer),\n }));\n const result = await this.channel.call(\n \"backup.restore\",\n {\n envelope: options.envelope,\n backupFactor,\n ...(passphrases === undefined ? {} : { passphrases }),\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(result);\n return { wallets: result.wallets, passphraseRequired: result.passphraseRequired };\n }),\n };\n\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unsubscribePresence?.();\n this.cancelCooldown?.();\n this.onDestroy?.();\n this.channel.destroy();\n }\n}\n\n/**\n * 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":";;;;;;;;;;;;;AAmEA,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,WAAW,QAAQ;EACxB,KAAK,WAAW,QAAQ;EACxB,KAAK,YAAY,QAAQ;EACzB,KAAK,gBAAg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AAM,eAAe,MAAM,0BACzB,KAAK,cACL,QAAQ,cACR,QACF;GACA,MAAM,SAAS,MAAM,KAAK,kBAAkB,QAAQ,QAAQ,QAAQ;GACpE,MAAM,cAAc,QAAQ,aAAa,KAAK,EAAE,UAAU,kBAAkB;IAC1E;IACA,YAAY,eAAe,YAAY,QAAQ;GACjD,EAAE;GACF,MAAM,SAAS,MAAM,KAAK,QAAQ,KAChC,kBACA;IACE,UAAU,QAAQ;IAClB;IACA,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;IACnD,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;GAC3C,GACA,QACF;GACA,KAAK,UAAU,MAAM;GACrB,OAAO;IAAE,SAAS,OAAO;IAAS,oBAAoB,OAAO;GAAmB;EAClF,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,5 +1,5 @@
1
- import { a as DerivedNostrKey, b as WalletErrorCode, d as NostrKeyInfo, l as LockReason, m as StatusPayload } from "./types-CIYT5uFj.mjs";
2
- import { f as Factor, g as NullValue, l as CORE_METHODS, p as MethodSpec, t as CHAINS_METHODS, v as Validator } from "./chains-BdcH4YnJ.mjs";
1
+ import { a as DerivedNostrKey, f as NostrKeyInfo, h as StatusPayload, u as LockReason, x as WalletErrorCode } from "./types-Jsz2m1ib.mjs";
2
+ import { f as Factor, g as NullValue, l as CORE_METHODS, p as MethodSpec, t as CHAINS_METHODS, v as Validator } from "./chains-CoZhm-Y1.mjs";
3
3
  /**
4
4
  * The unsigned event input the kernel signs. `pubkey` is optional: callers may omit it and the
5
5
  * kernel fills the signing key's own. Structurally compatible with @qntx/nostr's UnsignedEvent.
@@ -404,6 +404,8 @@ type BackupHeaderWallet = {
404
404
  readonly walletId: string;
405
405
  readonly origin: "mnemonic" | "passkey";
406
406
  readonly words: 12 | 15 | 18 | 21 | 24;
407
+ /** The wallet has a BIP-39 passphrase; it is never part of the payload. */
408
+ readonly passphrase?: true;
407
409
  };
408
410
  type BackupHeaderWire = {
409
411
  readonly wallets: ReadonlyArray<BackupHeaderWallet>;
@@ -487,4 +489,4 @@ declare const responseError: Validator<{
487
489
  retryAt?: number | undefined;
488
490
  }>;
489
491
  export { Rumor as $, HtlcTimeoutSignRequest as A, SigningCommitment as B, backupEnvelope as C, backupInfo as D, backupHeader as E, PreparedClaim as F, SparkKey as G, SparkAccountRef as H, PreparedLightningReceive as I, StaticDepositClaimRequest as J, SparkLeafKey as K, PreparedTransfer as L, OperatorCommitment as M, PrepareClaimRequest as N, FrostAggregateJob as O, PrepareTransferRequest as P, NostrExportFormat as Q, PreparedTransferLeaf as R, BackupInfo as S, backupEnvelopeText as T, SparkApprovalSummary as U, SigningTarget as V, SparkApproveIntent as W, StaticDepositClaimStatement as X, StaticDepositClaimResult as Y, NOSTR_METHODS as Z, responseError as _, MethodName as a, BackupHeaderWallet as b, ParamsOf as c, Response as d, SignedEvent as et, ResultOf as f, requestBytes as g, kernelEvent as h, METHODS as i, IdentityStatement as j, FrostSignJob as k, ProtocolValue as l, isProtocolValue as m, KernelEvent as n, UnwrapResult as nt, MethodTablesDisjoint as o, UNATTRIBUTED_ID as p, SparkNetwork as q, MAX_REQUEST_BYTES as r, PROTOCOL_VERSION as s, ErrorPayload as t, UnsignedEventInput as tt, Request as u, BackupEnvelopeFactor as v, backupEnvelopeFactor as w, BackupHeaderWire as x, BackupEnvelopeWire as y, SPARK_METHODS as z };
490
- //# sourceMappingURL=index-BXnQtz55.d.mts.map
492
+ //# sourceMappingURL=index-Cxt3caTG.d.mts.map