@qntx/wallet 0.9.0 → 0.11.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-Dub5eUl3.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-Dkmqwe-8.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-Dub5eUl3.mjs";
2
+ import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-Dkmqwe-8.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-D6u0HBfy.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-DDfzuSIa.mjs";
2
+ import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-DqBfdhN5.mjs";
3
3
  import { WalletError } from "./types.mjs";
4
4
  // src/channel.ts
5
5
  /**
@@ -241,7 +241,7 @@ var Channel = class {
241
241
  try {
242
242
  const err = responseError(message["err"]);
243
243
  this.settle(id, (p) => {
244
- p.reject(new WalletError(err.code, `kernel returned ${err.code}`, typeof err.retryAt === "number" ? err.retryAt : void 0));
244
+ p.reject(new WalletError(err.code, `kernel returned ${err.code}`, typeof err.retryAt === "number" ? err.retryAt : void 0, err.detail));
245
245
  });
246
246
  } catch (error) {
247
247
  if (!(error instanceof ValidationError)) throw error;
@@ -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-D6u0HBfy.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,IAAq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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 err.detail,\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,MAAM,QAAuB;EAC3B,KAAK,QAAQ;EACb,OAAO,KAAK;CACd;;CAGA,IAAI,QAAuB;EACzB,OAAO,KAAK;CACd;;;;;CAMA,UAAgB;EACd,IAAI,KAAK,aAAa,KAAK,WAAW,KAAA,GACpC;EAEF,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,UAAU,OAAO;EACtB,KAAK,WAAW,KAAA;EAChB,KAAK,YAAY;EAEjB,MAAM,aAAa,EAAE,KAAK;EAI1B,KAAU,aAAa,YAAY,KAAA,CAAS;EAC5C,KAAK,cAAc,IAAI,YAAY,UAAU,sBAAsB,CAAC;EACpE,KAAK,eAA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AAW;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"}
@@ -209,9 +209,12 @@ 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
  });
214
- 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
+ /** A BIP-39 passphrase on the wire: raw UTF-8 bytes, never empty (the host omits "none"). */
216
+ const passphraseBytes = bytes(1, 1024);
217
+ const walletErrorCode = union(literal("locked"), literal("cancelled"), literal("factor-invalidated"), literal("no-device-credential"), literal("passkey-not-configured"), literal("passkey-prf-unsupported"), 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,
217
220
  session: sessionId
@@ -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-DDfzuSIa.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"core-Cq5h9X0X.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 createdAt: safeTime,\n});\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 { readonly draft: string; readonly answers: ReadonlyArray<Uint8Array> },\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 factor?: Factor;\n },\n { readonly wallets: ReadonlyArray<WalletInfo>; readonly session: string }\n >;\n readonly \"wallet.importMnemonic\": MethodSpec<\n { readonly mnemonic: Uint8Array; readonly factor?: Factor },\n CreatedResult\n >;\n readonly \"wallet.exportMnemonic\": MethodSpec<\n { readonly verify: Factor; readonly walletId: string },\n 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({ draft: draftId, answers: arr(bytes(1, 64), 3, 3) }),\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 factor: opt(factor),\n }),\n result: obj({ wallets: arr(walletInfo, 1000), session: sessionId }),\n },\n \"wallet.importMnemonic\": {\n session: false,\n presence: true,\n params: obj({ mnemonic: bytes(1, 1024), factor: opt(factor) }),\n result: createdResult,\n },\n \"wallet.exportMnemonic\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, walletId }),\n result: bytes(16, 1024),\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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;EACV,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,QAAQ,IAAI,MAAM;EACpB,CAAC;EACD,QAAQ,IAAI;GAAE,SAAS,IAAI,YAAY,GAAI;GAAG,SAAS;EAAU,CAAC;CACpE;CACA,yBAAyB;EACvB,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GAAE,UAAU,MAAM,GAAG,IAAI;GAAG,QAAQ,IAAI,MAAM;EAAE,CAAC;EAC7D,QAAQ;CACV;CACA,yBAAyB;EACvB,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GAAE,QAAQ;GAAQ;EAAS,CAAC;EACxC,QAAQ,MAAM,IAAI,IAAI;CACxB;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"}
1
+ {"version":3,"file":"core-DDfzuSIa.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-invalidated\"),\n literal(\"no-device-credential\"),\n literal(\"passkey-not-configured\"),\n literal(\"passkey-prf-unsupported\"),\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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C,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-Dub5eUl3.mjs";
2
+ import { et as SignedEvent, l as ProtocolValue } from "./index-HWtJPkvq.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).
@@ -32,8 +32,8 @@ type PrfResult = {
32
32
  };
33
33
  /**
34
34
  * The WebAuthn ceremony the host performs. Implementations throw `WalletError` — "cancelled" when
35
- * the user aborts, "factor-unavailable" when the credential cannot produce a PRF. `name` is the new
36
- * credential's display name, validated by the host before the call (1–64 characters).
35
+ * the user aborts, "passkey-prf-unsupported" when the credential cannot produce a PRF. `name` is
36
+ * the new credential's display name, validated by the host before the call (1–64 characters).
37
37
  */
38
38
  type PasskeyCeremony = {
39
39
  readonly create: (input: {
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-D6u0HBfy.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-CcjyF8D3.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() {