@qntx/wallet-worker 0.10.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.
package/dist/browser.mjs CHANGED
@@ -9,8 +9,11 @@ import { PASSKEY_PURPOSE_VAULT, PASSKEY_PURPOSE_WALLET, connectKernel } from "@q
9
9
  * never reaches the kernel.
10
10
  */
11
11
  const UV_FLAG = 4;
12
- function factorUnavailable(message) {
13
- return new WalletError("factor-unavailable", message);
12
+ function unavailable(message) {
13
+ return new WalletError("unavailable", message);
14
+ }
15
+ function prfUnsupported(message) {
16
+ return new WalletError("passkey-prf-unsupported", message);
14
17
  }
15
18
  function cancelled(message) {
16
19
  return new WalletError("cancelled", message);
@@ -18,7 +21,7 @@ function cancelled(message) {
18
21
  function mapCeremonyError(error) {
19
22
  if (error instanceof DOMException && (error.name === "NotAllowedError" || error.name === "AbortError")) throw cancelled("the passkey ceremony was cancelled");
20
23
  if (error instanceof WalletError) throw error;
21
- throw factorUnavailable("the passkey ceremony failed");
24
+ throw unavailable("the passkey ceremony failed");
22
25
  }
23
26
  /** The UV bit of an authenticator-data blob (flags byte at offset 32, bit 0x04). */
24
27
  function userVerified(authenticatorData) {
@@ -45,7 +48,7 @@ function copyBufferSource(source) {
45
48
  function readPrfResult(credential, results, wantSecond, synced, userHandle) {
46
49
  const first = results?.first;
47
50
  const second = results?.second;
48
- if (first === void 0 || wantSecond && second === void 0) throw factorUnavailable("the passkey produced no PRF output");
51
+ if (first === void 0 || wantSecond && second === void 0) throw prfUnsupported("the passkey produced no PRF output");
49
52
  return {
50
53
  credentialId: copyBufferSource(credential.rawId),
51
54
  first: copyBufferSource(first),
@@ -55,7 +58,7 @@ function readPrfResult(credential, results, wantSecond, synced, userHandle) {
55
58
  };
56
59
  }
57
60
  function checkCredential(credential) {
58
- if (!(credential instanceof PublicKeyCredential)) throw factorUnavailable("the authenticator returned no public-key credential");
61
+ if (!(credential instanceof PublicKeyCredential)) throw unavailable("the authenticator returned no public-key credential");
59
62
  return credential;
60
63
  }
61
64
  /**
@@ -81,8 +84,8 @@ function createWebAuthnPasskey(rp) {
81
84
  mapCeremonyError(error);
82
85
  }
83
86
  const { response } = credential;
84
- if (!(response instanceof AuthenticatorAssertionResponse)) throw factorUnavailable("the authenticator returned no assertion response");
85
- if (!userVerified(response.authenticatorData)) throw factorUnavailable("the passkey assertion was not user-verified");
87
+ if (!(response instanceof AuthenticatorAssertionResponse)) throw unavailable("the authenticator returned no assertion response");
88
+ if (!userVerified(response.authenticatorData)) throw unavailable("the passkey assertion was not user-verified");
86
89
  return readPrfResult(credential, credential.getClientExtensionResults().prf?.results, input.salts.second !== void 0, credentialSynced(response.authenticatorData), response.userHandle ?? void 0);
87
90
  }
88
91
  return {
@@ -120,15 +123,15 @@ function createWebAuthnPasskey(rp) {
120
123
  mapCeremonyError(error);
121
124
  }
122
125
  const { response } = credential;
123
- if (!(response instanceof AuthenticatorAttestationResponse)) throw factorUnavailable("the authenticator returned no attestation response");
126
+ if (!(response instanceof AuthenticatorAttestationResponse)) throw unavailable("the authenticator returned no attestation response");
124
127
  const extensions = credential.getClientExtensionResults();
125
- if (extensions.prf?.enabled !== true) throw factorUnavailable("the authenticator does not support the PRF extension");
128
+ if (extensions.prf?.enabled !== true) throw prfUnsupported("the authenticator does not support the PRF extension");
126
129
  if (extensions.prf.results === void 0) return assert({
127
130
  credentialIds: [copyBufferSource(credential.rawId)],
128
131
  salts: input.salts
129
132
  });
130
133
  const authenticatorData = response.getAuthenticatorData();
131
- if (!userVerified(authenticatorData)) throw factorUnavailable("the passkey creation was not user-verified");
134
+ if (!userVerified(authenticatorData)) throw unavailable("the passkey creation was not user-verified");
132
135
  return readPrfResult(credential, extensions.prf.results, input.salts.second !== void 0, credentialSynced(authenticatorData));
133
136
  },
134
137
  assert
@@ -1 +1 @@
1
- {"version":3,"file":"browser.mjs","names":[],"sources":["../src/browser/passkey.ts","../src/browser/index.ts"],"sourcesContent":["/**\n * The WebAuthn passkey ceremony (main thread only): `navigator.credentials` with the PRF extension.\n * A wallet passkey derives the wallet seed from `PRF(walletSalt)`; the vault factor derives the\n * vault KEK from `PRF(vaultSalt)` on the same credential. Every ceremony output is checked for\n * `prf.enabled`, PRF results and the user-verification flag — a credential that cannot prove UV\n * never reaches the kernel.\n */\nimport { WalletError } from \"@qntx/wallet\";\nimport { PASSKEY_PURPOSE_VAULT, PASSKEY_PURPOSE_WALLET } from \"@qntx/wallet/host\";\nimport type { PasskeyCeremony, PrfResult, PrfSalts } from \"@qntx/wallet/host\";\n\nexport type WebAuthnRp = {\n /** RP id — the origin's effective domain, e.g. `location.hostname`. */\n readonly id: string;\n readonly name: string;\n};\n\nconst UV_FLAG = 0x04; // authenticator-data flags byte (offset 32), bit 2 = user verified\nconst BE_FLAG = 0x08; // bit 3 = credential is backup-eligible (multi-device capable)\nconst BS_FLAG = 0x10; // bit 4 = credential is currently backed up (synced)\n\nfunction factorUnavailable(message: string): WalletError {\n return new WalletError(\"factor-unavailable\", message);\n}\n\nfunction cancelled(message: string): WalletError {\n return new WalletError(\"cancelled\", message);\n}\n\nfunction mapCeremonyError(error: unknown): never {\n if (\n error instanceof DOMException &&\n (error.name === \"NotAllowedError\" || error.name === \"AbortError\")\n ) {\n throw cancelled(\"the passkey ceremony was cancelled\");\n }\n if (error instanceof WalletError) {\n throw error;\n }\n throw factorUnavailable(\"the passkey ceremony failed\");\n}\n\n/** The UV bit of an authenticator-data blob (flags byte at offset 32, bit 0x04). */\nfunction userVerified(authenticatorData: ArrayBuffer): boolean {\n return (\n authenticatorData.byteLength > 32 &&\n // oxlint-disable-next-line eslint/no-bitwise -- flags bit test\n (new DataView(authenticatorData).getUint8(32) & UV_FLAG) !== 0\n );\n}\n\n/**\n * Whether the credential is backed up off-device (flags byte at offset 32): synced requires both BE\n * (the credential is eligible for backup) and BS (the authenticator actually backs it up).\n */\nfunction credentialSynced(authenticatorData: ArrayBuffer): boolean {\n return (\n authenticatorData.byteLength > 32 &&\n // oxlint-disable-next-line eslint/no-bitwise -- flags bit test\n (new DataView(authenticatorData).getUint8(32) & (BE_FLAG | BS_FLAG)) === (BE_FLAG | BS_FLAG)\n );\n}\n\nfunction prfEval(salts: PrfSalts): AuthenticationExtensionsPRFValues {\n // The constructor copy narrows Uint8Array<ArrayBufferLike> to Uint8Array<ArrayBuffer> —\n // the DOM BufferSource does not admit shared-array-buffer views.\n return salts.second === undefined\n ? { first: new Uint8Array(salts.first) }\n : { first: new Uint8Array(salts.first), second: new Uint8Array(salts.second) };\n}\n\n/** A detached copy of a BufferSource — the returned Uint8Array owns its own fresh buffer. */\nfunction copyBufferSource(source: BufferSource): Uint8Array {\n const view =\n source instanceof ArrayBuffer\n ? new Uint8Array(source)\n : new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n return new Uint8Array(view);\n}\n\nfunction readPrfResult(\n credential: PublicKeyCredential,\n results: AuthenticationExtensionsPRFValues | undefined,\n wantSecond: boolean,\n synced: boolean,\n userHandle?: ArrayBuffer,\n): PrfResult {\n const first = results?.first;\n const second = results?.second;\n if (first === undefined || (wantSecond && second === undefined)) {\n throw factorUnavailable(\"the passkey produced no PRF output\");\n }\n // Copy into fresh Uint8Arrays and drop every reference to the extension's ArrayBuffers.\n return {\n credentialId: copyBufferSource(credential.rawId),\n first: copyBufferSource(first),\n ...(second === undefined ? {} : { second: copyBufferSource(second) }),\n ...(userHandle === undefined ? {} : { userHandle: copyBufferSource(userHandle) }),\n synced,\n };\n}\n\nfunction checkCredential(credential: unknown): PublicKeyCredential {\n if (!(credential instanceof PublicKeyCredential)) {\n throw factorUnavailable(\"the authenticator returned no public-key credential\");\n }\n return credential;\n}\n\n/**\n * The WebAuthn ceremony. `create` registers a resident credential with `prf.eval` over the salts;\n * when the extension returns no results a single assertion over the new credential produces them.\n * `assert` runs a discoverable (or allowCredentials-scoped) get with the same eval shape.\n */\nexport function createWebAuthnPasskey(rp: WebAuthnRp): PasskeyCeremony {\n async function assert(input: {\n readonly credentialIds?: ReadonlyArray<Uint8Array>;\n readonly salts: PrfSalts;\n }): Promise<PrfResult> {\n let credential: PublicKeyCredential;\n try {\n credential = checkCredential(\n await navigator.credentials.get({\n publicKey: {\n rpId: rp.id,\n challenge: crypto.getRandomValues(new Uint8Array(32)),\n userVerification: \"required\",\n ...(input.credentialIds === undefined\n ? {}\n : {\n allowCredentials: input.credentialIds.map((id) => ({\n type: \"public-key\" as const,\n id: new Uint8Array(id),\n })),\n }),\n extensions: { prf: { eval: prfEval(input.salts) } },\n },\n }),\n );\n } catch (error) {\n mapCeremonyError(error);\n }\n const { response } = credential;\n if (!(response instanceof AuthenticatorAssertionResponse)) {\n throw factorUnavailable(\"the authenticator returned no assertion response\");\n }\n if (!userVerified(response.authenticatorData)) {\n throw factorUnavailable(\"the passkey assertion was not user-verified\");\n }\n return readPrfResult(\n credential,\n credential.getClientExtensionResults().prf?.results,\n input.salts.second !== undefined,\n credentialSynced(response.authenticatorData),\n response.userHandle ?? undefined,\n );\n }\n\n return {\n create: async (input) => {\n const userId = new Uint8Array(16);\n userId[0] = input.purpose === \"wallet\" ? PASSKEY_PURPOSE_WALLET : PASSKEY_PURPOSE_VAULT;\n crypto.getRandomValues(userId.subarray(1));\n let credential: PublicKeyCredential;\n try {\n credential = checkCredential(\n await navigator.credentials.create({\n publicKey: {\n rp: { id: rp.id, name: rp.name },\n user: {\n id: userId,\n name: input.name,\n displayName: input.name,\n },\n challenge: crypto.getRandomValues(new Uint8Array(32)),\n pubKeyCredParams: [\n { type: \"public-key\", alg: -7 },\n { type: \"public-key\", alg: -257 },\n ],\n authenticatorSelection: {\n residentKey: \"required\",\n userVerification: \"required\",\n },\n extensions: { prf: { eval: prfEval(input.salts) } },\n },\n }),\n );\n } catch (error) {\n mapCeremonyError(error);\n }\n const { response } = credential;\n if (!(response instanceof AuthenticatorAttestationResponse)) {\n throw factorUnavailable(\"the authenticator returned no attestation response\");\n }\n const extensions = credential.getClientExtensionResults();\n if (extensions.prf?.enabled !== true) {\n throw factorUnavailable(\"the authenticator does not support the PRF extension\");\n }\n if (extensions.prf.results === undefined) {\n // Some authenticators omit creation-time PRF outputs: one assertion over the new\n // credential produces them (it is that response whose UV and BE/BS flags get read).\n return assert({\n credentialIds: [copyBufferSource(credential.rawId)],\n salts: input.salts,\n });\n }\n const authenticatorData = response.getAuthenticatorData();\n if (!userVerified(authenticatorData)) {\n throw factorUnavailable(\"the passkey creation was not user-verified\");\n }\n return readPrfResult(\n credential,\n extensions.prf.results,\n input.salts.second !== undefined,\n credentialSynced(authenticatorData),\n );\n },\n assert,\n };\n}\n","/**\n * The Web host: `createWebWallet` spawns the bundled kernel worker (dist/kernel.worker.js) whose\n * vault lives in the worker's own IndexedDB. Lock destroys the worker; the vault survives in\n * IndexedDB, so the respawned worker reloads it. `pagehide` locks immediately; the idle timer is\n * refreshed by user-presence signals, not request traffic. The WebAuthn ceremony runs on the main\n * thread.\n */\nimport { WalletError } from \"@qntx/wallet\";\nimport type { Wallet, WalletOptions } from \"@qntx/wallet\";\nimport { connectKernel } from \"@qntx/wallet/host\";\nimport type { MainPort } from \"@qntx/wallet/host\";\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nimport type { BrowserWorkerInit } from \"../shared.ts\";\nimport { createWebAuthnPasskey } from \"./passkey.ts\";\n\nconst LISTENER_OPTIONS = { capture: true, passive: true };\nconst ACTIVITY_EVENTS = [\"pointerdown\", \"pointermove\", \"keydown\", \"wheel\", \"touchstart\"];\n\n/**\n * The browser's user-presence source: direct input on the page, or returning to a visible tab.\n * Capture-phase passive listeners do a single boolean check per event — high-frequency signals\n * (scroll, pointermove) cost nothing. Returns the unsubscribe the wallet owns.\n */\nfunction subscribePresence(onActivity: () => void): () => void {\n for (const type of ACTIVITY_EVENTS) {\n globalThis.addEventListener(type, onActivity, LISTENER_OPTIONS);\n }\n const onVisible = (): void => {\n if (document.visibilityState === \"visible\") {\n onActivity();\n }\n };\n document.addEventListener(\"visibilitychange\", onVisible);\n return () => {\n for (const type of ACTIVITY_EVENTS) {\n globalThis.removeEventListener(type, onActivity, LISTENER_OPTIONS);\n }\n document.removeEventListener(\"visibilitychange\", onVisible);\n };\n}\n\nasync function bestEffort(task: () => Promise<unknown>): Promise<void> {\n try {\n await task();\n } catch {\n // Lifecycle hooks and persistence hints must never surface failures.\n }\n}\n\nexport async function createWebWallet(options: WalletOptions): Promise<Wallet> {\n const { autoLock } = options;\n if (autoLock.platform !== \"web\") {\n throw new WalletError(\"invalid-input\", \"createWebWallet accepts only the web autoLock policy\");\n }\n // The page sends only the idle choice; the worker owns the maximum session duration.\n const init: BrowserWorkerInit = { t: \"init\", idleMinutes: autoLock.idleMinutes };\n const ceremony = createWebAuthnPasskey({\n id: options.passkey.rpId,\n name: options.passkey.rpName,\n });\n\n const spawn = (): MainPort => {\n // Keep this exact `new Worker(new URL(\"…\", import.meta.url))` shape: bundlers (Vite,\n // webpack, Parcel, esbuild-based tools) recognize only this literal form as a worker entry and\n // bundle the kernel with its chunks and spark.wasm. A precomputed URL is copied as one opaque\n // asset, and the worker then dies loading its first chunk.\n const worker = new Worker(new URL(\"kernel.worker.js\", import.meta.url), {\n type: \"module\",\n name: \"qntx-wallet\",\n });\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Worker.postMessage takes a transfer list, not an origin\n worker.postMessage(init); // the kernel validates it strictly before startKernel\n return {\n post: (message: ProtocolValue, transfer: ArrayBuffer[]) => {\n worker.postMessage(message, transfer);\n },\n listen: (handler) => {\n const listener = (event: MessageEvent): void => {\n handler(event.data);\n };\n worker.addEventListener(\"message\", listener);\n return () => {\n worker.removeEventListener(\"message\", listener);\n };\n },\n onExit: (handler) => {\n // Web Workers have no exit event; error/messageerror are the only death signals.\n const listener = (): void => {\n handler(\"crashed\");\n };\n worker.addEventListener(\"error\", listener);\n worker.addEventListener(\"messageerror\", listener);\n return () => {\n worker.removeEventListener(\"error\", listener);\n worker.removeEventListener(\"messageerror\", listener);\n };\n },\n terminate: () => {\n worker.terminate();\n },\n };\n };\n\n const wallet = await connectKernel({\n factors: \"software\",\n spawn,\n passkey: options.passkey,\n verifyEvent: options.verifyEvent,\n ceremony,\n setTimer: (delayMs, fn) => {\n const timer = globalThis.setTimeout(fn, delayMs);\n return () => {\n globalThis.clearTimeout(timer);\n };\n },\n presence: subscribePresence,\n onDestroy: () => {\n globalThis.removeEventListener(\"pagehide\", onPageHide);\n },\n });\n\n // Page lifecycle: lock on pagehide. A BFCache-frozen page still runs the queued locked-event\n // handler on restore, so the wallet respawns then — terminating the worker directly would\n // leave the wallet pointing at a dead port.\n const onPageHide = (): void => {\n void bestEffort(async () => wallet.vault.lock());\n };\n globalThis.addEventListener(\"pagehide\", onPageHide);\n\n // Ask the browser to persist the vault once it exists — a denied request is fine.\n let persisted = false;\n const unsubscribe = wallet.subscribe(() => {\n if (!persisted && wallet.getSnapshot().vault !== \"uninitialized\") {\n persisted = true;\n unsubscribe();\n void bestEffort(async () => navigator.storage.persist());\n }\n });\n\n return wallet;\n}\n\nexport { createWebAuthnPasskey } from \"./passkey.ts\";\nexport type { WebAuthnRp } from \"./passkey.ts\";\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,UAAU;AAIhB,SAAS,kBAAkB,SAA8B;CACvD,OAAO,IAAI,YAAY,sBAAsB,OAAO;AACtD;AAEA,SAAS,UAAU,SAA8B;CAC/C,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;AAEA,SAAS,iBAAiB,OAAuB;CAC/C,IACE,iBAAiB,iBAChB,MAAM,SAAS,qBAAqB,MAAM,SAAS,eAEpD,MAAM,UAAU,oCAAoC;CAEtD,IAAI,iBAAiB,aACnB,MAAM;CAER,MAAM,kBAAkB,6BAA6B;AACvD;;AAGA,SAAS,aAAa,mBAAyC;CAC7D,OACE,kBAAkB,aAAa,OAE9B,IAAI,SAAS,iBAAiB,CAAC,CAAC,SAAS,EAAE,IAAI,aAAa;AAEjE;;;;;AAMA,SAAS,iBAAiB,mBAAyC;CACjE,OACE,kBAAkB,aAAa,OAE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AQ,QAAQ,CAAC;EACzD;CACF,CAAC;CAED,OAAO;AACT"}
1
+ {"version":3,"file":"browser.mjs","names":[],"sources":["../src/browser/passkey.ts","../src/browser/index.ts"],"sourcesContent":["/**\n * The WebAuthn passkey ceremony (main thread only): `navigator.credentials` with the PRF extension.\n * A wallet passkey derives the wallet seed from `PRF(walletSalt)`; the vault factor derives the\n * vault KEK from `PRF(vaultSalt)` on the same credential. Every ceremony output is checked for\n * `prf.enabled`, PRF results and the user-verification flag — a credential that cannot prove UV\n * never reaches the kernel.\n */\nimport { WalletError } from \"@qntx/wallet\";\nimport { PASSKEY_PURPOSE_VAULT, PASSKEY_PURPOSE_WALLET } from \"@qntx/wallet/host\";\nimport type { PasskeyCeremony, PrfResult, PrfSalts } from \"@qntx/wallet/host\";\n\nexport type WebAuthnRp = {\n /** RP id — the origin's effective domain, e.g. `location.hostname`. */\n readonly id: string;\n readonly name: string;\n};\n\nconst UV_FLAG = 0x04; // authenticator-data flags byte (offset 32), bit 2 = user verified\nconst BE_FLAG = 0x08; // bit 3 = credential is backup-eligible (multi-device capable)\nconst BS_FLAG = 0x10; // bit 4 = credential is currently backed up (synced)\n\nfunction unavailable(message: string): WalletError {\n return new WalletError(\"unavailable\", message);\n}\n\nfunction prfUnsupported(message: string): WalletError {\n return new WalletError(\"passkey-prf-unsupported\", message);\n}\n\nfunction cancelled(message: string): WalletError {\n return new WalletError(\"cancelled\", message);\n}\n\nfunction mapCeremonyError(error: unknown): never {\n if (\n error instanceof DOMException &&\n (error.name === \"NotAllowedError\" || error.name === \"AbortError\")\n ) {\n throw cancelled(\"the passkey ceremony was cancelled\");\n }\n if (error instanceof WalletError) {\n throw error;\n }\n throw unavailable(\"the passkey ceremony failed\");\n}\n\n/** The UV bit of an authenticator-data blob (flags byte at offset 32, bit 0x04). */\nfunction userVerified(authenticatorData: ArrayBuffer): boolean {\n return (\n authenticatorData.byteLength > 32 &&\n // oxlint-disable-next-line eslint/no-bitwise -- flags bit test\n (new DataView(authenticatorData).getUint8(32) & UV_FLAG) !== 0\n );\n}\n\n/**\n * Whether the credential is backed up off-device (flags byte at offset 32): synced requires both BE\n * (the credential is eligible for backup) and BS (the authenticator actually backs it up).\n */\nfunction credentialSynced(authenticatorData: ArrayBuffer): boolean {\n return (\n authenticatorData.byteLength > 32 &&\n // oxlint-disable-next-line eslint/no-bitwise -- flags bit test\n (new DataView(authenticatorData).getUint8(32) & (BE_FLAG | BS_FLAG)) === (BE_FLAG | BS_FLAG)\n );\n}\n\nfunction prfEval(salts: PrfSalts): AuthenticationExtensionsPRFValues {\n // The constructor copy narrows Uint8Array<ArrayBufferLike> to Uint8Array<ArrayBuffer> —\n // the DOM BufferSource does not admit shared-array-buffer views.\n return salts.second === undefined\n ? { first: new Uint8Array(salts.first) }\n : { first: new Uint8Array(salts.first), second: new Uint8Array(salts.second) };\n}\n\n/** A detached copy of a BufferSource — the returned Uint8Array owns its own fresh buffer. */\nfunction copyBufferSource(source: BufferSource): Uint8Array {\n const view =\n source instanceof ArrayBuffer\n ? new Uint8Array(source)\n : new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n return new Uint8Array(view);\n}\n\nfunction readPrfResult(\n credential: PublicKeyCredential,\n results: AuthenticationExtensionsPRFValues | undefined,\n wantSecond: boolean,\n synced: boolean,\n userHandle?: ArrayBuffer,\n): PrfResult {\n const first = results?.first;\n const second = results?.second;\n if (first === undefined || (wantSecond && second === undefined)) {\n throw prfUnsupported(\"the passkey produced no PRF output\");\n }\n // Copy into fresh Uint8Arrays and drop every reference to the extension's ArrayBuffers.\n return {\n credentialId: copyBufferSource(credential.rawId),\n first: copyBufferSource(first),\n ...(second === undefined ? {} : { second: copyBufferSource(second) }),\n ...(userHandle === undefined ? {} : { userHandle: copyBufferSource(userHandle) }),\n synced,\n };\n}\n\nfunction checkCredential(credential: unknown): PublicKeyCredential {\n if (!(credential instanceof PublicKeyCredential)) {\n throw unavailable(\"the authenticator returned no public-key credential\");\n }\n return credential;\n}\n\n/**\n * The WebAuthn ceremony. `create` registers a resident credential with `prf.eval` over the salts;\n * when the extension returns no results a single assertion over the new credential produces them.\n * `assert` runs a discoverable (or allowCredentials-scoped) get with the same eval shape.\n */\nexport function createWebAuthnPasskey(rp: WebAuthnRp): PasskeyCeremony {\n async function assert(input: {\n readonly credentialIds?: ReadonlyArray<Uint8Array>;\n readonly salts: PrfSalts;\n }): Promise<PrfResult> {\n let credential: PublicKeyCredential;\n try {\n credential = checkCredential(\n await navigator.credentials.get({\n publicKey: {\n rpId: rp.id,\n challenge: crypto.getRandomValues(new Uint8Array(32)),\n userVerification: \"required\",\n ...(input.credentialIds === undefined\n ? {}\n : {\n allowCredentials: input.credentialIds.map((id) => ({\n type: \"public-key\" as const,\n id: new Uint8Array(id),\n })),\n }),\n extensions: { prf: { eval: prfEval(input.salts) } },\n },\n }),\n );\n } catch (error) {\n mapCeremonyError(error);\n }\n const { response } = credential;\n if (!(response instanceof AuthenticatorAssertionResponse)) {\n throw unavailable(\"the authenticator returned no assertion response\");\n }\n if (!userVerified(response.authenticatorData)) {\n throw unavailable(\"the passkey assertion was not user-verified\");\n }\n return readPrfResult(\n credential,\n credential.getClientExtensionResults().prf?.results,\n input.salts.second !== undefined,\n credentialSynced(response.authenticatorData),\n response.userHandle ?? undefined,\n );\n }\n\n return {\n create: async (input) => {\n const userId = new Uint8Array(16);\n userId[0] = input.purpose === \"wallet\" ? PASSKEY_PURPOSE_WALLET : PASSKEY_PURPOSE_VAULT;\n crypto.getRandomValues(userId.subarray(1));\n let credential: PublicKeyCredential;\n try {\n credential = checkCredential(\n await navigator.credentials.create({\n publicKey: {\n rp: { id: rp.id, name: rp.name },\n user: {\n id: userId,\n name: input.name,\n displayName: input.name,\n },\n challenge: crypto.getRandomValues(new Uint8Array(32)),\n pubKeyCredParams: [\n { type: \"public-key\", alg: -7 },\n { type: \"public-key\", alg: -257 },\n ],\n authenticatorSelection: {\n residentKey: \"required\",\n userVerification: \"required\",\n },\n extensions: { prf: { eval: prfEval(input.salts) } },\n },\n }),\n );\n } catch (error) {\n mapCeremonyError(error);\n }\n const { response } = credential;\n if (!(response instanceof AuthenticatorAttestationResponse)) {\n throw unavailable(\"the authenticator returned no attestation response\");\n }\n const extensions = credential.getClientExtensionResults();\n if (extensions.prf?.enabled !== true) {\n throw prfUnsupported(\"the authenticator does not support the PRF extension\");\n }\n if (extensions.prf.results === undefined) {\n // Some authenticators omit creation-time PRF outputs: one assertion over the new\n // credential produces them (it is that response whose UV and BE/BS flags get read).\n return assert({\n credentialIds: [copyBufferSource(credential.rawId)],\n salts: input.salts,\n });\n }\n const authenticatorData = response.getAuthenticatorData();\n if (!userVerified(authenticatorData)) {\n throw unavailable(\"the passkey creation was not user-verified\");\n }\n return readPrfResult(\n credential,\n extensions.prf.results,\n input.salts.second !== undefined,\n credentialSynced(authenticatorData),\n );\n },\n assert,\n };\n}\n","/**\n * The Web host: `createWebWallet` spawns the bundled kernel worker (dist/kernel.worker.js) whose\n * vault lives in the worker's own IndexedDB. Lock destroys the worker; the vault survives in\n * IndexedDB, so the respawned worker reloads it. `pagehide` locks immediately; the idle timer is\n * refreshed by user-presence signals, not request traffic. The WebAuthn ceremony runs on the main\n * thread.\n */\nimport { WalletError } from \"@qntx/wallet\";\nimport type { Wallet, WalletOptions } from \"@qntx/wallet\";\nimport { connectKernel } from \"@qntx/wallet/host\";\nimport type { MainPort } from \"@qntx/wallet/host\";\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nimport type { BrowserWorkerInit } from \"../shared.ts\";\nimport { createWebAuthnPasskey } from \"./passkey.ts\";\n\nconst LISTENER_OPTIONS = { capture: true, passive: true };\nconst ACTIVITY_EVENTS = [\"pointerdown\", \"pointermove\", \"keydown\", \"wheel\", \"touchstart\"];\n\n/**\n * The browser's user-presence source: direct input on the page, or returning to a visible tab.\n * Capture-phase passive listeners do a single boolean check per event — high-frequency signals\n * (scroll, pointermove) cost nothing. Returns the unsubscribe the wallet owns.\n */\nfunction subscribePresence(onActivity: () => void): () => void {\n for (const type of ACTIVITY_EVENTS) {\n globalThis.addEventListener(type, onActivity, LISTENER_OPTIONS);\n }\n const onVisible = (): void => {\n if (document.visibilityState === \"visible\") {\n onActivity();\n }\n };\n document.addEventListener(\"visibilitychange\", onVisible);\n return () => {\n for (const type of ACTIVITY_EVENTS) {\n globalThis.removeEventListener(type, onActivity, LISTENER_OPTIONS);\n }\n document.removeEventListener(\"visibilitychange\", onVisible);\n };\n}\n\nasync function bestEffort(task: () => Promise<unknown>): Promise<void> {\n try {\n await task();\n } catch {\n // Lifecycle hooks and persistence hints must never surface failures.\n }\n}\n\nexport async function createWebWallet(options: WalletOptions): Promise<Wallet> {\n const { autoLock } = options;\n if (autoLock.platform !== \"web\") {\n throw new WalletError(\"invalid-input\", \"createWebWallet accepts only the web autoLock policy\");\n }\n // The page sends only the idle choice; the worker owns the maximum session duration.\n const init: BrowserWorkerInit = { t: \"init\", idleMinutes: autoLock.idleMinutes };\n const ceremony = createWebAuthnPasskey({\n id: options.passkey.rpId,\n name: options.passkey.rpName,\n });\n\n const spawn = (): MainPort => {\n // Keep this exact `new Worker(new URL(\"…\", import.meta.url))` shape: bundlers (Vite,\n // webpack, Parcel, esbuild-based tools) recognize only this literal form as a worker entry and\n // bundle the kernel with its chunks and spark.wasm. A precomputed URL is copied as one opaque\n // asset, and the worker then dies loading its first chunk.\n const worker = new Worker(new URL(\"kernel.worker.js\", import.meta.url), {\n type: \"module\",\n name: \"qntx-wallet\",\n });\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Worker.postMessage takes a transfer list, not an origin\n worker.postMessage(init); // the kernel validates it strictly before startKernel\n return {\n post: (message: ProtocolValue, transfer: ArrayBuffer[]) => {\n worker.postMessage(message, transfer);\n },\n listen: (handler) => {\n const listener = (event: MessageEvent): void => {\n handler(event.data);\n };\n worker.addEventListener(\"message\", listener);\n return () => {\n worker.removeEventListener(\"message\", listener);\n };\n },\n onExit: (handler) => {\n // Web Workers have no exit event; error/messageerror are the only death signals.\n const listener = (): void => {\n handler(\"crashed\");\n };\n worker.addEventListener(\"error\", listener);\n worker.addEventListener(\"messageerror\", listener);\n return () => {\n worker.removeEventListener(\"error\", listener);\n worker.removeEventListener(\"messageerror\", listener);\n };\n },\n terminate: () => {\n worker.terminate();\n },\n };\n };\n\n const wallet = await connectKernel({\n factors: \"software\",\n spawn,\n passkey: options.passkey,\n verifyEvent: options.verifyEvent,\n ceremony,\n setTimer: (delayMs, fn) => {\n const timer = globalThis.setTimeout(fn, delayMs);\n return () => {\n globalThis.clearTimeout(timer);\n };\n },\n presence: subscribePresence,\n onDestroy: () => {\n globalThis.removeEventListener(\"pagehide\", onPageHide);\n },\n });\n\n // Page lifecycle: lock on pagehide. A BFCache-frozen page still runs the queued locked-event\n // handler on restore, so the wallet respawns then — terminating the worker directly would\n // leave the wallet pointing at a dead port.\n const onPageHide = (): void => {\n void bestEffort(async () => wallet.vault.lock());\n };\n globalThis.addEventListener(\"pagehide\", onPageHide);\n\n // Ask the browser to persist the vault once it exists — a denied request is fine.\n let persisted = false;\n const unsubscribe = wallet.subscribe(() => {\n if (!persisted && wallet.getSnapshot().vault !== \"uninitialized\") {\n persisted = true;\n unsubscribe();\n void bestEffort(async () => navigator.storage.persist());\n }\n });\n\n return wallet;\n}\n\nexport { createWebAuthnPasskey } from \"./passkey.ts\";\nexport type { WebAuthnRp } from \"./passkey.ts\";\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,UAAU;AAIhB,SAAS,YAAY,SAA8B;CACjD,OAAO,IAAI,YAAY,eAAe,OAAO;AAC/C;AAEA,SAAS,eAAe,SAA8B;CACpD,OAAO,IAAI,YAAY,2BAA2B,OAAO;AAC3D;AAEA,SAAS,UAAU,SAA8B;CAC/C,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;AAEA,SAAS,iBAAiB,OAAuB;CAC/C,IACE,iBAAiB,iBAChB,MAAM,SAAS,qBAAqB,MAAM,SAAS,eAEpD,MAAM,UAAU,oCAAoC;CAEtD,IAA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O,MAAM,KAAK,CAAC;CACjD;CACA,WAAW,iBAAiB,YAAY,UAAU;CAGlD,IAAI,YAAY;CAChB,MAAM,cAAc,OAAO,gBAAgB;EACzC,IAAI,CAAC,aAAa,OAAO,YAAY,CAAC,CAAC,UAAU,iBAAiB;GAChE,YAAY;GACZ,YAAY;GACZ,WAAgB,YAAY,UAAU,QAAQ,QAAQ,CAAC;EACzD;CACF,CAAC;CAED,OAAO;AACT"}
@@ -76,7 +76,7 @@
76
76
  },
77
77
  {
78
78
  "file": "kernel.node.js",
79
- "sha256": "c2c7b7c3ae893d495f633ae7a3dc96dd59ce921c3c928fa2ca98f4eea1abbfe1"
79
+ "sha256": "3e9912ec823015b718d3a8319ad022130d13a52aa4eec4ba64ae486c0d280faa"
80
80
  },
81
81
  {
82
82
  "file": "signer-h69ffzx5.js",
@@ -84,7 +84,7 @@
84
84
  },
85
85
  {
86
86
  "file": "kernel.worker.js",
87
- "sha256": "eb69a624b2111d8d75c0a28ef962f1647a89ce1f07c118b9e8359886cab8efb7"
87
+ "sha256": "9a0202e34595363e39f3f100a5f6afb838292a82e654b6a31b108026c827c262"
88
88
  },
89
89
  {
90
90
  "file": "worker-gsare3mw.js",
@@ -1822,15 +1822,17 @@ class KernelError extends Error {
1822
1822
  code;
1823
1823
  retryAt;
1824
1824
  corrupted;
1825
- constructor(code, message, retryAt, corrupted = false) {
1825
+ detail;
1826
+ constructor(code, message, retryAt, corrupted = false, detail) {
1826
1827
  super(message);
1827
1828
  this.name = "KernelError";
1828
1829
  this.code = code;
1829
1830
  this.retryAt = retryAt;
1830
1831
  this.corrupted = corrupted;
1832
+ this.detail = detail;
1831
1833
  }
1832
1834
  }
1833
- // ../wallet/dist/core-D-NCx1CQ.mjs
1835
+ // ../wallet/dist/core-DDfzuSIa.mjs
1834
1836
  var ValidationError = class extends Error {
1835
1837
  name = "ValidationError";
1836
1838
  };
@@ -2049,7 +2051,7 @@ var walletInfo = obj({
2049
2051
  createdAt: safeTime
2050
2052
  });
2051
2053
  var passphraseBytes = bytes(1, 1024);
2052
- var 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"));
2054
+ var 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"));
2053
2055
  var createdResult = obj({
2054
2056
  wallet: walletInfo,
2055
2057
  session: sessionId
@@ -2210,7 +2212,7 @@ var CORE_METHODS = {
2210
2212
  }
2211
2213
  };
2212
2214
 
2213
- // ../wallet/dist/protocol-DDz4nlYK.mjs
2215
+ // ../wallet/dist/protocol-DqBfdhN5.mjs
2214
2216
  var MAX_FACTOR_CHARS = 512;
2215
2217
  var MAX_STRING_BYTES = 64000;
2216
2218
  var MAX_PAYLOAD_CHARS = 1400000;
@@ -2972,7 +2974,8 @@ var METHODS = {
2972
2974
  var lockReason = union(literal("cold-start"), literal("user"), literal("idle"), literal("background"), literal("expired"), literal("crashed"), literal("invalidated"));
2973
2975
  var errorPayload = obj({
2974
2976
  code: walletErrorCode,
2975
- retryAt: opt(safeTime)
2977
+ retryAt: opt(safeTime),
2978
+ detail: opt(str(80, /^[A-Za-z0-9_.:-]+$/))
2976
2979
  });
2977
2980
  var kernelEvent = union(obj({
2978
2981
  v: literal(2),
@@ -2987,7 +2990,7 @@ var kernelEvent = union(obj({
2987
2990
  // ../wallet-kernel/src/platform.ts
2988
2991
  function requirePasskey(platform) {
2989
2992
  if (platform.passkey === undefined) {
2990
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies in the host");
2993
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies in the host");
2991
2994
  }
2992
2995
  return platform.passkey;
2993
2996
  }
@@ -3024,12 +3027,12 @@ function serializeCeremonies(platform) {
3024
3027
  }
3025
3028
  function assertFactorKindAvailable(platform, kind) {
3026
3029
  if (platform.keystore !== undefined !== (kind === "hardware")) {
3027
- throw new KernelError("factor-unavailable", "this factor kind is not available here");
3030
+ throw new KernelError("unsupported", "this factor kind is not available here");
3028
3031
  }
3029
3032
  }
3030
3033
  function requireKeystore(platform) {
3031
3034
  if (platform.keystore === undefined) {
3032
- throw new KernelError("factor-unavailable", "this platform has no hardware keystore");
3035
+ throw new KernelError("unsupported", "this platform has no hardware keystore");
3033
3036
  }
3034
3037
  return platform.keystore;
3035
3038
  }
@@ -4332,7 +4335,7 @@ async function unlock(platform, image, factor, commit) {
4332
4335
  if (factor.kind === "hardware") {
4333
4336
  const stored = image.factors.find((f) => f.kind === "hardware");
4334
4337
  if (stored === undefined) {
4335
- throw new KernelError("factor-unavailable", "no hardware factor exists");
4338
+ throw new KernelError("not-found", "no hardware factor exists");
4336
4339
  }
4337
4340
  const kek = await kekFor(platform, factor, stored, corePromptFor(platform.keystore, "unlock"));
4338
4341
  try {
@@ -4424,7 +4427,7 @@ async function verifyFactor(platform, image, factor, dek, prompt) {
4424
4427
  throw new KernelError(candidates.length > 0 ? "wrong-password" : "invalid-input", "password did not verify");
4425
4428
  }
4426
4429
  if (factor.kind === "hardware") {
4427
- throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", undefined, true) : new KernelError("factor-unavailable", "no hardware factor exists");
4430
+ throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", undefined, true) : new KernelError("not-found", "no hardware factor exists");
4428
4431
  }
4429
4432
  throw new KernelError("wrong-passkey", "passkey did not verify");
4430
4433
  }
@@ -7427,7 +7430,7 @@ function walletPrfOf(result) {
7427
7430
  if (result.first !== undefined) {
7428
7431
  wipe(result.first);
7429
7432
  }
7430
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
7433
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
7431
7434
  }
7432
7435
  return { prfWallet: result.first, synced: result.synced };
7433
7436
  }
@@ -7460,7 +7463,7 @@ async function walletCeremony(ctx, params) {
7460
7463
  }
7461
7464
  async function createWithPasskey(ctx, params, requestSession) {
7462
7465
  if (ctx.platform.passkey !== undefined !== (params.ceremony === "kernel")) {
7463
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
7466
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
7464
7467
  }
7465
7468
  const gated = gate(ctx, params.factor, requestSession);
7466
7469
  let prf;
@@ -7644,7 +7647,7 @@ function backupMaterialOf(result) {
7644
7647
  result.second?.fill(0);
7645
7648
  if (!result.userVerified || result.first?.length !== 32) {
7646
7649
  result.first?.fill(0);
7647
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
7650
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
7648
7651
  }
7649
7652
  return { kind: "passkey", credentialId: result.credentialId, prfBackup: result.first };
7650
7653
  }
@@ -7653,7 +7656,7 @@ async function backupMaterial(ctx, factor, allowCredentials) {
7653
7656
  return factor;
7654
7657
  }
7655
7658
  if (ctx.platform.passkey !== undefined !== (factor.ceremony === "kernel")) {
7656
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
7659
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
7657
7660
  }
7658
7661
  if (factor.ceremony === "host") {
7659
7662
  return factor;
@@ -18718,7 +18721,11 @@ function startKernel(host, port) {
18718
18721
  integrityFailure = true;
18719
18722
  setHealth("corrupted");
18720
18723
  }
18721
- const err = error instanceof KernelError ? error.retryAt === undefined ? { code: error.code } : { code: error.code, retryAt: error.retryAt } : { code: "integrity" };
18724
+ const err = error instanceof KernelError ? {
18725
+ code: error.code,
18726
+ ...error.retryAt === undefined ? {} : { retryAt: error.retryAt },
18727
+ ...error.detail === undefined ? {} : { detail: error.detail }
18728
+ } : { code: "integrity" };
18722
18729
  return { v: PROTOCOL_VERSION, id, err };
18723
18730
  }
18724
18731
  };
@@ -98,7 +98,7 @@ var __chunks = (base, ids, nodes, entry) => {
98
98
  __chunkSeen ||= {};
99
99
  __preload(ids[entry], 1);
100
100
  };
101
- __chunks(import.meta.url,["tbfpcecm","h69ffzx5","1vpxmqwn","k5etevb7","gsare3mw"],[["./kernel.worker.js",3],["./signer-h69ffzx5.js",3,4],["./browser-1vpxmqwn.js",4],["./worker-k5etevb7.js"],["./worker-gsare3mw.js"]],0);
101
+ __chunks(import.meta.url,["ewnv0yfm","h69ffzx5","1vpxmqwn","k5etevb7","gsare3mw"],[["./kernel.worker.js",3],["./signer-h69ffzx5.js",3,4],["./browser-1vpxmqwn.js",4],["./worker-k5etevb7.js"],["./worker-gsare3mw.js"]],0);
102
102
  // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/util-BcRBO6o-.mjs
103
103
  var NostrError = class extends Error {
104
104
  name = "NostrError";
@@ -1849,15 +1849,17 @@ class KernelError extends Error {
1849
1849
  code;
1850
1850
  retryAt;
1851
1851
  corrupted;
1852
- constructor(code, message, retryAt, corrupted = false) {
1852
+ detail;
1853
+ constructor(code, message, retryAt, corrupted = false, detail) {
1853
1854
  super(message);
1854
1855
  this.name = "KernelError";
1855
1856
  this.code = code;
1856
1857
  this.retryAt = retryAt;
1857
1858
  this.corrupted = corrupted;
1859
+ this.detail = detail;
1858
1860
  }
1859
1861
  }
1860
- // ../wallet/dist/core-D-NCx1CQ.mjs
1862
+ // ../wallet/dist/core-DDfzuSIa.mjs
1861
1863
  var ValidationError = class extends Error {
1862
1864
  name = "ValidationError";
1863
1865
  };
@@ -2076,7 +2078,7 @@ var walletInfo = obj({
2076
2078
  createdAt: safeTime
2077
2079
  });
2078
2080
  var passphraseBytes = bytes(1, 1024);
2079
- var 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"));
2081
+ var 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"));
2080
2082
  var createdResult = obj({
2081
2083
  wallet: walletInfo,
2082
2084
  session: sessionId
@@ -2237,7 +2239,7 @@ var CORE_METHODS = {
2237
2239
  }
2238
2240
  };
2239
2241
 
2240
- // ../wallet/dist/protocol-DDz4nlYK.mjs
2242
+ // ../wallet/dist/protocol-DqBfdhN5.mjs
2241
2243
  var MAX_FACTOR_CHARS = 512;
2242
2244
  var MAX_STRING_BYTES = 64000;
2243
2245
  var MAX_PAYLOAD_CHARS = 1400000;
@@ -2999,7 +3001,8 @@ var METHODS = {
2999
3001
  var lockReason = union(literal("cold-start"), literal("user"), literal("idle"), literal("background"), literal("expired"), literal("crashed"), literal("invalidated"));
3000
3002
  var errorPayload = obj({
3001
3003
  code: walletErrorCode,
3002
- retryAt: opt(safeTime)
3004
+ retryAt: opt(safeTime),
3005
+ detail: opt(str(80, /^[A-Za-z0-9_.:-]+$/))
3003
3006
  });
3004
3007
  var kernelEvent = union(obj({
3005
3008
  v: literal(2),
@@ -3014,7 +3017,7 @@ var kernelEvent = union(obj({
3014
3017
  // ../wallet-kernel/src/platform.ts
3015
3018
  function requirePasskey(platform) {
3016
3019
  if (platform.passkey === undefined) {
3017
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies in the host");
3020
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies in the host");
3018
3021
  }
3019
3022
  return platform.passkey;
3020
3023
  }
@@ -3051,12 +3054,12 @@ function serializeCeremonies(platform) {
3051
3054
  }
3052
3055
  function assertFactorKindAvailable(platform, kind) {
3053
3056
  if (platform.keystore !== undefined !== (kind === "hardware")) {
3054
- throw new KernelError("factor-unavailable", "this factor kind is not available here");
3057
+ throw new KernelError("unsupported", "this factor kind is not available here");
3055
3058
  }
3056
3059
  }
3057
3060
  function requireKeystore(platform) {
3058
3061
  if (platform.keystore === undefined) {
3059
- throw new KernelError("factor-unavailable", "this platform has no hardware keystore");
3062
+ throw new KernelError("unsupported", "this platform has no hardware keystore");
3060
3063
  }
3061
3064
  return platform.keystore;
3062
3065
  }
@@ -4359,7 +4362,7 @@ async function unlock(platform, image, factor, commit) {
4359
4362
  if (factor.kind === "hardware") {
4360
4363
  const stored = image.factors.find((f) => f.kind === "hardware");
4361
4364
  if (stored === undefined) {
4362
- throw new KernelError("factor-unavailable", "no hardware factor exists");
4365
+ throw new KernelError("not-found", "no hardware factor exists");
4363
4366
  }
4364
4367
  const kek = await kekFor(platform, factor, stored, corePromptFor(platform.keystore, "unlock"));
4365
4368
  try {
@@ -4451,7 +4454,7 @@ async function verifyFactor(platform, image, factor, dek, prompt) {
4451
4454
  throw new KernelError(candidates.length > 0 ? "wrong-password" : "invalid-input", "password did not verify");
4452
4455
  }
4453
4456
  if (factor.kind === "hardware") {
4454
- throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", undefined, true) : new KernelError("factor-unavailable", "no hardware factor exists");
4457
+ throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", undefined, true) : new KernelError("not-found", "no hardware factor exists");
4455
4458
  }
4456
4459
  throw new KernelError("wrong-passkey", "passkey did not verify");
4457
4460
  }
@@ -7454,7 +7457,7 @@ function walletPrfOf(result) {
7454
7457
  if (result.first !== undefined) {
7455
7458
  wipe(result.first);
7456
7459
  }
7457
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
7460
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
7458
7461
  }
7459
7462
  return { prfWallet: result.first, synced: result.synced };
7460
7463
  }
@@ -7487,7 +7490,7 @@ async function walletCeremony(ctx, params) {
7487
7490
  }
7488
7491
  async function createWithPasskey(ctx, params, requestSession) {
7489
7492
  if (ctx.platform.passkey !== undefined !== (params.ceremony === "kernel")) {
7490
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
7493
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
7491
7494
  }
7492
7495
  const gated = gate(ctx, params.factor, requestSession);
7493
7496
  let prf;
@@ -7671,7 +7674,7 @@ function backupMaterialOf(result) {
7671
7674
  result.second?.fill(0);
7672
7675
  if (!result.userVerified || result.first?.length !== 32) {
7673
7676
  result.first?.fill(0);
7674
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
7677
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
7675
7678
  }
7676
7679
  return { kind: "passkey", credentialId: result.credentialId, prfBackup: result.first };
7677
7680
  }
@@ -7680,7 +7683,7 @@ async function backupMaterial(ctx, factor, allowCredentials) {
7680
7683
  return factor;
7681
7684
  }
7682
7685
  if (ctx.platform.passkey !== undefined !== (factor.ceremony === "kernel")) {
7683
- throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
7686
+ throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
7684
7687
  }
7685
7688
  if (factor.ceremony === "host") {
7686
7689
  return factor;
@@ -18745,7 +18748,11 @@ function startKernel(host, port) {
18745
18748
  integrityFailure = true;
18746
18749
  setHealth("corrupted");
18747
18750
  }
18748
- const err = error instanceof KernelError ? error.retryAt === undefined ? { code: error.code } : { code: error.code, retryAt: error.retryAt } : { code: "integrity" };
18751
+ const err = error instanceof KernelError ? {
18752
+ code: error.code,
18753
+ ...error.retryAt === undefined ? {} : { retryAt: error.retryAt },
18754
+ ...error.detail === undefined ? {} : { detail: error.detail }
18755
+ } : { code: "integrity" };
18749
18756
  return { v: PROTOCOL_VERSION, id, err };
18750
18757
  }
18751
18758
  };
package/dist/node.mjs CHANGED
@@ -18,12 +18,15 @@ var KernelError = class extends Error {
18
18
  * corrupted state on it. Ordinary failures (a wrong factor, a bad param) leave it false.
19
19
  */
20
20
  corrupted;
21
- constructor(code, message, retryAt, corrupted = false) {
21
+ /** Platform diagnostic `"<domain>:<code>"` a backend reported; forwarded to the host verbatim. */
22
+ detail;
23
+ constructor(code, message, retryAt, corrupted = false, detail) {
22
24
  super(message);
23
25
  this.name = "KernelError";
24
26
  this.code = code;
25
27
  this.retryAt = retryAt;
26
28
  this.corrupted = corrupted;
29
+ this.detail = detail;
27
30
  }
28
31
  };
29
32
  // ../wallet-kernel/src/vault/memory.ts
@@ -285,7 +288,7 @@ function createSoftwarePasskey(seed, options) {
285
288
  },
286
289
  assert: async ({ credentialIds, salts }) => {
287
290
  const credentialId = credentialIds === void 0 ? lastCreated : credentialIds.find((id) => known.has(bytesToHex(id)));
288
- if (credentialId === void 0) throw new WalletError("factor-unavailable", credentialIds === void 0 ? "no software credential exists yet" : "unknown software credential");
291
+ if (credentialId === void 0) throw new WalletError("passkey-prf-unsupported", credentialIds === void 0 ? "no software credential exists yet" : "unknown software credential");
289
292
  const entry = known.get(bytesToHex(credentialId));
290
293
  return result(credentialId, salts, entry?.userHandle);
291
294
  }
package/dist/node.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.mjs","names":[],"sources":["../../wallet-kernel/src/errors.ts","../../wallet-kernel/src/vault/memory.ts","../src/shared.ts","../src/node/store-server.ts","../src/node/software-passkey.ts","../src/node/index.ts"],"sourcesContent":["import type { WalletErrorCode } from \"@qntx/wallet/types\";\n\nexport type KernelErrorCode = WalletErrorCode;\n\n/**\n * The only error type kernel code throws. Its code is the public `WalletErrorCode`: the kernel\n * returns it verbatim in the error payload. Messages are static strings: they must never echo user\n * input or secret contents.\n */\nexport class KernelError extends Error {\n readonly code: KernelErrorCode;\n readonly retryAt: number | undefined;\n /**\n * True when the error proves the stored vault itself is corrupt — the kernel latches the\n * corrupted state on it. Ordinary failures (a wrong factor, a bad param) leave it false.\n */\n readonly corrupted: boolean;\n\n constructor(code: KernelErrorCode, message: string, retryAt?: number, corrupted = false) {\n super(message);\n this.name = \"KernelError\";\n this.code = code;\n this.retryAt = retryAt;\n this.corrupted = corrupted;\n }\n}\n","import { KernelError } from \"../errors.ts\";\nimport type {\n RecordStore,\n StoredFactor,\n StoredRecord,\n StoreOp,\n VaultImage,\n VaultMeta,\n} from \"./store.ts\";\n\nfunction cloneRecord(record: StoredRecord): StoredRecord {\n return { ...record, sealed: Uint8Array.from(record.sealed) };\n}\n\nfunction cloneFactor(factor: StoredFactor): StoredFactor {\n return { ...factor, sealed: Uint8Array.from(factor.sealed) };\n}\n\nfunction cloneMeta(meta: VaultMeta): VaultMeta {\n return { ...meta };\n}\n\nexport function cloneImage(image: VaultImage): VaultImage {\n return {\n meta: image.meta === undefined ? undefined : cloneMeta(image.meta),\n records: image.records.map(cloneRecord),\n factors: image.factors.map(cloneFactor),\n };\n}\n\nfunction conflict(message: string): KernelError {\n return new KernelError(\"conflict\", `vault store: ${message}`);\n}\n\nfunction requireMeta(meta: VaultMeta | undefined): VaultMeta {\n if (meta === undefined) {\n throw conflict(\"vault is not initialized\");\n }\n return meta;\n}\n\n/**\n * In-memory RecordStore for the Node host and kernel tests. Loads and commits deep-copy every\n * Uint8Array, so callers can never mutate stored state. `commit` applies ops to a clone and swaps\n * atomically: a failing precondition (`init`, `expect-revision`, a counter op on an empty store)\n * leaves the store untouched. Content ops bump `meta.revision` once per commit; an `init` commit\n * writes its meta verbatim (revision stays as the initializer set it).\n */\n/**\n * Applies a commit's ops to a vault image and returns the next image — the single implementation of\n * record/factor op semantics shared by the memory store and the file-backed store in\n *\n * @qntx/wallet-native.\n */\nexport function applyStoreOps(image: VaultImage, ops: ReadonlyArray<StoreOp>): VaultImage {\n let { meta } = image;\n let { records } = image;\n let { factors } = image;\n let bump = false;\n let initialized = false;\n for (const op of ops) {\n switch (op.op) {\n case \"init\":\n if (meta !== undefined || records.length > 0 || factors.length > 0) {\n throw conflict(\"vault already initialized\");\n }\n meta = cloneMeta(op.meta);\n initialized = true;\n break;\n case \"expect-revision\":\n if (meta === undefined || meta.revision !== op.revision) {\n throw conflict(\"vault changed underneath\");\n }\n break;\n case \"set-key-id\":\n meta = { ...requireMeta(meta), keyId: op.keyId };\n bump = true;\n break;\n case \"record-failure\": {\n const current = requireMeta(meta);\n meta = {\n ...current,\n failedAttempts: current.failedAttempts + 1,\n lastFailureAt: op.at,\n };\n break;\n }\n case \"reset-failures\":\n meta = { ...requireMeta(meta), failedAttempts: 0, lastFailureAt: 0 };\n break;\n case \"put-record\":\n records = [\n ...records.filter(\n (record) => !(record.kind === op.record.kind && record.id === op.record.id),\n ),\n cloneRecord(op.record),\n ];\n bump = true;\n break;\n case \"delete-record\":\n records = records.filter((record) => !(record.kind === op.kind && record.id === op.id));\n bump = true;\n break;\n case \"put-factor\":\n factors = [\n ...factors.filter((factor) => factor.id !== op.factor.id),\n cloneFactor(op.factor),\n ];\n bump = true;\n break;\n case \"delete-factor\":\n factors = factors.filter((factor) => factor.id !== op.id);\n bump = true;\n break;\n case \"clear\":\n meta = undefined;\n records = [];\n factors = [];\n break;\n }\n }\n if (bump && !initialized && meta !== undefined) {\n meta = { ...meta, revision: meta.revision + 1 };\n }\n return { meta, records, factors };\n}\n\nexport function createMemoryStore(): RecordStore {\n let image: VaultImage = { meta: undefined, records: [], factors: [] };\n const listeners = new Set<() => void>();\n\n return {\n async load() {\n return cloneImage(image);\n },\n async commit(ops) {\n const next = applyStoreOps(image, ops);\n image = next;\n for (const listener of listeners) {\n listener();\n }\n },\n watch(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n","/**\n * The store RPC shared by the worker (`src/worker/store-client.ts`) and the main side\n * (`src/node/store-server.ts`). The vault image travels as plain structured-clone data — it is\n * ciphertext plus public headers only, never decrypted secrets. This file stays platform-neutral:\n * the port shape is injected on both sides.\n */\nimport type { KernelErrorCode, StoreOp, VaultImage } from \"@qntx/wallet-kernel\";\n\nexport type StorePort = {\n readonly post: (message: unknown) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n};\n\nexport type StoreRequest =\n | { readonly t: \"load\"; readonly id: number }\n | { readonly t: \"commit\"; readonly id: number; readonly ops: ReadonlyArray<StoreOp> };\n\nexport type StoreReply =\n | { readonly t: \"loaded\"; readonly id: number; readonly image: WireImage }\n | { readonly t: \"committed\"; readonly id: number }\n | { readonly t: \"failed\"; readonly id: number; readonly code: KernelErrorCode }\n | { readonly t: \"changed\" };\n\n/** Structured clone preserves `undefined` properties, so `meta` travels as-is. */\ntype WireImage = VaultImage;\n\nexport function encodeImage(image: VaultImage): WireImage {\n return { meta: image.meta, factors: image.factors, records: image.records };\n}\n\nexport { assertVaultImage } from \"@qntx/wallet-kernel\";\n\nexport type IdleMinutes = 5 | 15 | 60;\n\nexport function isIdleMinutes(value: unknown): value is IdleMinutes {\n return value === 5 || value === 15 || value === 60;\n}\n\nexport function idleMsOf(minutes: IdleMinutes): number {\n return minutes * 60_000;\n}\n\n/** The fixed maximum session duration owned by the worker entries (never a host input). */\nexport const MAX_SESSION_MS: number = 12 * 3_600_000;\n\n/**\n * The first message the Web host posts to `kernel.worker.js`: the session policy. The browser\n * worker's vault lives in IndexedDB inside the worker itself, so unlike Node there is no store port\n * — policy is all the kernel needs before `startKernel` runs.\n */\nexport type BrowserWorkerInit = {\n readonly t: \"init\";\n readonly idleMinutes: IdleMinutes;\n};\n\nfunction plainInitObject(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return undefined;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain object above\n return value as Record<string, unknown>;\n}\n\n/** Strict init-message validation; anything else must not start the kernel. */\nexport function isBrowserWorkerInit(value: unknown): value is BrowserWorkerInit {\n const init = plainInitObject(value);\n return (\n init !== undefined &&\n Object.keys(init).sort().join(\",\") === \"idleMinutes,t\" &&\n init[\"t\"] === \"init\" &&\n isIdleMinutes(init[\"idleMinutes\"])\n );\n}\n\n/**\n * Strict `workerData` validation for the Node kernel worker: `{ idleMinutes, storePort }` and\n * nothing else. `storePort` is checked structurally (the real type lives behind the worker_threads\n * boundary); a wrong shape must not start the kernel.\n */\nexport function isNodeWorkerData(\n value: unknown,\n): value is { readonly idleMinutes: IdleMinutes; readonly storePort: unknown } {\n const data = plainInitObject(value);\n return (\n data !== undefined &&\n Object.keys(data).sort().join(\",\") === \"idleMinutes,storePort\" &&\n isIdleMinutes(data[\"idleMinutes\"]) &&\n typeof data[\"storePort\"] === \"object\" &&\n data[\"storePort\"] !== null\n );\n}\n","/**\n * Main-side half of the store RPC: serves the shared in-memory RecordStore to the worker and pushes\n * \"changed\" notices for commits that did NOT come through this port (the kernel's own commits must\n * not echo back as external changes).\n */\nimport type { MessagePort } from \"node:worker_threads\";\n\nimport { KernelError } from \"@qntx/wallet-kernel\";\nimport type { KernelErrorCode, RecordStore } from \"@qntx/wallet-kernel\";\n\nimport type { StoreReply, StoreRequest } from \"../shared.ts\";\nimport { encodeImage } from \"../shared.ts\";\n\n// Internal wire between this package's two halves — malformed payloads get dropped.\nfunction isStoreRequest(raw: unknown): raw is StoreRequest {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return false;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain object above\n const request = raw as Record<string, unknown>;\n if (typeof request[\"id\"] !== \"number\") {\n return false;\n }\n return request[\"t\"] === \"load\" || (request[\"t\"] === \"commit\" && Array.isArray(request[\"ops\"]));\n}\n\nexport function serveStore(store: RecordStore, port: MessagePort): () => void {\n let ownCommits = 0;\n\n const post = (reply: StoreReply): void => {\n port.postMessage(reply);\n };\n\n // A failed load/commit replies \"failed\" with the KernelError code (or \"unavailable\" for a\n // non-kernel failure) — a request that hangs would deadlock the kernel's sequential queue.\n const failed = (id: number, error: unknown): void => {\n const code: KernelErrorCode = error instanceof KernelError ? error.code : \"unavailable\";\n post({ t: \"failed\", id, code });\n };\n\n const answer = async (request: StoreRequest): Promise<void> => {\n if (request.t === \"load\") {\n try {\n post({ t: \"loaded\", id: request.id, image: encodeImage(await store.load()) });\n } catch (error) {\n failed(request.id, error);\n }\n return;\n }\n ownCommits++;\n try {\n await store.commit(request.ops);\n } catch (error) {\n ownCommits--; // a failed commit fires no watch — do not eat the next external notice\n failed(request.id, error);\n return;\n }\n post({ t: \"committed\", id: request.id });\n };\n\n const onMessage = (raw: unknown): void => {\n if (!isStoreRequest(raw)) {\n return;\n }\n void (async (): Promise<void> => {\n try {\n await answer(raw);\n } catch {\n // A dead worker cannot be answered; the exit path handles it.\n }\n })();\n };\n\n const unwatch = store.watch(() => {\n if (ownCommits > 0) {\n ownCommits--;\n return;\n }\n post({ t: \"changed\" });\n });\n\n port.on(\"message\", onMessage);\n port.start();\n\n return () => {\n unwatch();\n port.off(\"message\", onMessage);\n port.close();\n };\n}\n","/**\n * CreateSoftwarePasskey — a TEST-ONLY PasskeyCeremony. There is no authenticator, no user presence\n * check, no credential store: the \"passkey\" is a deterministic function of `seed`, so anyone\n * holding the seed owns every wallet it ever protects. Use it in tests and demos only.\n *\n * CredentialId = SHA-256(seed ‖ \"credential\" ‖ u32be(n)) (n increments per create) PRF(salt) =\n * HMAC-SHA256(HMAC-SHA256(seed, credentialId), SHA-256(UTF-8(\"WebAuthn PRF\") ‖ 0x00 ‖ salt))\n * UserHandle = purpose byte ‖ SHA-256(seed ‖ \"user-handle\" ‖ credentialId)[0:15] — the same\n * 16-byte, purpose-prefixed shape the browser create path puts in `user.id`.\n */\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, concatBytes, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\nimport { WalletError } from \"@qntx/wallet\";\nimport { PASSKEY_PURPOSE_VAULT, PASSKEY_PURPOSE_WALLET } from \"@qntx/wallet/host\";\nimport type { PasskeyCeremony, PrfResult, PrfSalts } from \"@qntx/wallet/host\";\n\nexport function createSoftwarePasskey(\n seed: Uint8Array,\n options?: { readonly synced?: boolean },\n): PasskeyCeremony {\n const synced = options?.synced ?? true; // software credentials pretend to be synced by default\n let counter = 0;\n let lastCreated: Uint8Array | undefined;\n const known = new Map<string, { credentialId: Uint8Array; userHandle: Uint8Array }>();\n\n const prf = (credentialId: Uint8Array, salt: Uint8Array): Uint8Array => {\n const key = hmac(sha256, seed, credentialId);\n const message = sha256(concatBytes(utf8ToBytes(\"WebAuthn PRF\"), new Uint8Array([0]), salt));\n return hmac(sha256, key, message);\n };\n\n const result = (\n credentialId: Uint8Array,\n salts: PrfSalts,\n userHandle?: Uint8Array,\n ): PrfResult => ({\n credentialId: new Uint8Array(credentialId),\n first: prf(credentialId, salts.first),\n ...(salts.second === undefined ? {} : { second: prf(credentialId, salts.second) }),\n ...(userHandle === undefined ? {} : { userHandle: new Uint8Array(userHandle) }),\n synced,\n });\n\n return {\n // oxlint-disable-next-line typescript/require-await -- the ceremony contract is async; this test double computes synchronously\n create: async ({ purpose, salts }) => {\n const counterBytes = new Uint8Array(4);\n new DataView(counterBytes.buffer).setUint32(0, counter);\n counter++;\n const credentialId = sha256(concatBytes(seed, utf8ToBytes(\"credential\"), counterBytes));\n const purposeByte = purpose === \"wallet\" ? PASSKEY_PURPOSE_WALLET : PASSKEY_PURPOSE_VAULT;\n const userHandle = new Uint8Array(16);\n userHandle[0] = purposeByte;\n userHandle.set(\n sha256(concatBytes(seed, utf8ToBytes(\"user-handle\"), credentialId)).subarray(0, 15),\n 1,\n );\n known.set(bytesToHex(credentialId), { credentialId, userHandle });\n lastCreated = credentialId;\n return result(credentialId, salts);\n },\n // oxlint-disable-next-line typescript/require-await -- the ceremony contract is async; this test double computes synchronously\n assert: async ({ credentialIds, salts }) => {\n const credentialId =\n credentialIds === undefined\n ? lastCreated\n : credentialIds.find((id) => known.has(bytesToHex(id)));\n if (credentialId === undefined) {\n throw new WalletError(\n \"factor-unavailable\",\n credentialIds === undefined\n ? \"no software credential exists yet\"\n : \"unknown software credential\",\n );\n }\n const entry = known.get(bytesToHex(credentialId));\n return result(credentialId, salts, entry?.userHandle);\n },\n };\n}\n","/**\n * The Node host: `createNodeWallet` spawns the bundled kernel worker (dist/kernel.node.js) and\n * keeps the vault image — ciphertext + public headers, never secrets — in the main thread's\n * in-memory store, served to each worker over a MessageChannel. That is what lets a lock destroy\n * the whole worker without losing the vault.\n */\nimport { MessageChannel, Worker } from \"node:worker_threads\";\n\nimport { WalletError } from \"@qntx/wallet\";\nimport type { Wallet, WalletOptions } from \"@qntx/wallet\";\nimport { createMemoryStore } from \"@qntx/wallet-kernel\";\nimport { connectKernel } from \"@qntx/wallet/host\";\nimport type { MainPort, PasskeyCeremony } from \"@qntx/wallet/host\";\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nimport type { NodeWorkerData } from \"../worker/node.ts\";\nimport { serveStore } from \"./store-server.ts\";\n\nexport { createSoftwarePasskey } from \"./software-passkey.ts\";\n\nexport type NodeWalletOptions = WalletOptions & {\n readonly authenticator?: PasskeyCeremony;\n /**\n * Test/debug hook: the worker file location and a spawn observer (count spawns, watch 'exit').\n * Defaults to the bundled dist/kernel.node.js next to this module.\n */\n readonly kernelUrl?: string | URL;\n readonly onSpawn?: (worker: Worker) => void;\n};\n\nexport async function createNodeWallet(options: NodeWalletOptions): Promise<Wallet> {\n const { autoLock } = options;\n if (autoLock.platform !== \"web\") {\n throw new WalletError(\"invalid-input\", \"createNodeWallet accepts only the web autoLock policy\");\n }\n // The host sends only the idle choice; the worker owns the maximum session duration.\n const workerData = { idleMinutes: autoLock.idleMinutes };\n const store = createMemoryStore(); // ciphertext + public headers only — safe in the main thread\n const kernelUrl = options.kernelUrl ?? new URL(\"kernel.node.js\", import.meta.url);\n\n const spawn = (): MainPort => {\n const channel = new MessageChannel();\n const stopStore = serveStore(store, channel.port1);\n const worker = new Worker(kernelUrl, {\n workerData: { ...workerData, storePort: channel.port2 } satisfies NodeWorkerData,\n transferList: [channel.port2],\n });\n options.onSpawn?.(worker);\n return {\n post: (message: ProtocolValue, transfer: ArrayBuffer[]) => {\n worker.postMessage(message, transfer);\n },\n listen: (handler) => {\n const listener = (message: unknown) => {\n handler(message);\n };\n worker.on(\"message\", listener);\n return () => {\n worker.off(\"message\", listener);\n };\n },\n onExit: (handler) => {\n const listener = () => {\n handler(\"crashed\");\n };\n worker.once(\"exit\", listener);\n return () => {\n worker.off(\"exit\", listener);\n };\n },\n terminate: () => {\n stopStore();\n void worker.terminate();\n },\n };\n };\n\n return connectKernel({\n factors: \"software\",\n spawn,\n passkey: options.passkey,\n verifyEvent: options.verifyEvent,\n ceremony: options.authenticator,\n setTimer: (delayMs, fn) => {\n const timer = setTimeout(fn, delayMs);\n return () => {\n clearTimeout(timer);\n };\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;;;;;CAKA;CAEA,YAAY,MAAuB,SAAiB,SAAkB,YAAY,OAAO;EACvF,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;EACf,KAAK,YAAY;CACnB;AACF;;ACfA,SAAS,YAAY,QAAoC;CACvD,OAAO;EAAE,GAAG;EAAQ,QAAQ,WAAW,KAAK,OAAO,MAAM;CAAE;AAC7D;AAEA,SAAS,YAAY,QAAoC;CACvD,OAAO;EAAE,GAAG;EAAQ,QAAQ,WAAW,KAAK,OAAO,MAAM;CAAE;AAC7D;AAEA,SAAS,UAAU,MAA4B;CAC7C,OAAO,EAAE,GAAG,KAAK;AACnB;AAEA,SAAgB,WAAW,OAA+B;CACxD,OAAO;EACL,MAAM,MAAM,S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IACX,aAAa,KAAK;GACpB;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"node.mjs","names":[],"sources":["../../wallet-kernel/src/errors.ts","../../wallet-kernel/src/vault/memory.ts","../src/shared.ts","../src/node/store-server.ts","../src/node/software-passkey.ts","../src/node/index.ts"],"sourcesContent":["import type { WalletErrorCode } from \"@qntx/wallet/types\";\n\nexport type KernelErrorCode = WalletErrorCode;\n\n/**\n * The only error type kernel code throws. Its code is the public `WalletErrorCode`: the kernel\n * returns it verbatim in the error payload. Messages are static strings: they must never echo user\n * input or secret contents.\n */\nexport class KernelError extends Error {\n readonly code: KernelErrorCode;\n readonly retryAt: number | undefined;\n /**\n * True when the error proves the stored vault itself is corrupt — the kernel latches the\n * corrupted state on it. Ordinary failures (a wrong factor, a bad param) leave it false.\n */\n readonly corrupted: boolean;\n /** Platform diagnostic `\"<domain>:<code>\"` a backend reported; forwarded to the host verbatim. */\n readonly detail: string | undefined;\n\n constructor(\n code: KernelErrorCode,\n message: string,\n retryAt?: number,\n corrupted = false,\n detail?: string,\n ) {\n super(message);\n this.name = \"KernelError\";\n this.code = code;\n this.retryAt = retryAt;\n this.corrupted = corrupted;\n this.detail = detail;\n }\n}\n","import { KernelError } from \"../errors.ts\";\nimport type {\n RecordStore,\n StoredFactor,\n StoredRecord,\n StoreOp,\n VaultImage,\n VaultMeta,\n} from \"./store.ts\";\n\nfunction cloneRecord(record: StoredRecord): StoredRecord {\n return { ...record, sealed: Uint8Array.from(record.sealed) };\n}\n\nfunction cloneFactor(factor: StoredFactor): StoredFactor {\n return { ...factor, sealed: Uint8Array.from(factor.sealed) };\n}\n\nfunction cloneMeta(meta: VaultMeta): VaultMeta {\n return { ...meta };\n}\n\nexport function cloneImage(image: VaultImage): VaultImage {\n return {\n meta: image.meta === undefined ? undefined : cloneMeta(image.meta),\n records: image.records.map(cloneRecord),\n factors: image.factors.map(cloneFactor),\n };\n}\n\nfunction conflict(message: string): KernelError {\n return new KernelError(\"conflict\", `vault store: ${message}`);\n}\n\nfunction requireMeta(meta: VaultMeta | undefined): VaultMeta {\n if (meta === undefined) {\n throw conflict(\"vault is not initialized\");\n }\n return meta;\n}\n\n/**\n * In-memory RecordStore for the Node host and kernel tests. Loads and commits deep-copy every\n * Uint8Array, so callers can never mutate stored state. `commit` applies ops to a clone and swaps\n * atomically: a failing precondition (`init`, `expect-revision`, a counter op on an empty store)\n * leaves the store untouched. Content ops bump `meta.revision` once per commit; an `init` commit\n * writes its meta verbatim (revision stays as the initializer set it).\n */\n/**\n * Applies a commit's ops to a vault image and returns the next image — the single implementation of\n * record/factor op semantics shared by the memory store and the file-backed store in\n *\n * @qntx/wallet-native.\n */\nexport function applyStoreOps(image: VaultImage, ops: ReadonlyArray<StoreOp>): VaultImage {\n let { meta } = image;\n let { records } = image;\n let { factors } = image;\n let bump = false;\n let initialized = false;\n for (const op of ops) {\n switch (op.op) {\n case \"init\":\n if (meta !== undefined || records.length > 0 || factors.length > 0) {\n throw conflict(\"vault already initialized\");\n }\n meta = cloneMeta(op.meta);\n initialized = true;\n break;\n case \"expect-revision\":\n if (meta === undefined || meta.revision !== op.revision) {\n throw conflict(\"vault changed underneath\");\n }\n break;\n case \"set-key-id\":\n meta = { ...requireMeta(meta), keyId: op.keyId };\n bump = true;\n break;\n case \"record-failure\": {\n const current = requireMeta(meta);\n meta = {\n ...current,\n failedAttempts: current.failedAttempts + 1,\n lastFailureAt: op.at,\n };\n break;\n }\n case \"reset-failures\":\n meta = { ...requireMeta(meta), failedAttempts: 0, lastFailureAt: 0 };\n break;\n case \"put-record\":\n records = [\n ...records.filter(\n (record) => !(record.kind === op.record.kind && record.id === op.record.id),\n ),\n cloneRecord(op.record),\n ];\n bump = true;\n break;\n case \"delete-record\":\n records = records.filter((record) => !(record.kind === op.kind && record.id === op.id));\n bump = true;\n break;\n case \"put-factor\":\n factors = [\n ...factors.filter((factor) => factor.id !== op.factor.id),\n cloneFactor(op.factor),\n ];\n bump = true;\n break;\n case \"delete-factor\":\n factors = factors.filter((factor) => factor.id !== op.id);\n bump = true;\n break;\n case \"clear\":\n meta = undefined;\n records = [];\n factors = [];\n break;\n }\n }\n if (bump && !initialized && meta !== undefined) {\n meta = { ...meta, revision: meta.revision + 1 };\n }\n return { meta, records, factors };\n}\n\nexport function createMemoryStore(): RecordStore {\n let image: VaultImage = { meta: undefined, records: [], factors: [] };\n const listeners = new Set<() => void>();\n\n return {\n async load() {\n return cloneImage(image);\n },\n async commit(ops) {\n const next = applyStoreOps(image, ops);\n image = next;\n for (const listener of listeners) {\n listener();\n }\n },\n watch(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n","/**\n * The store RPC shared by the worker (`src/worker/store-client.ts`) and the main side\n * (`src/node/store-server.ts`). The vault image travels as plain structured-clone data — it is\n * ciphertext plus public headers only, never decrypted secrets. This file stays platform-neutral:\n * the port shape is injected on both sides.\n */\nimport type { KernelErrorCode, StoreOp, VaultImage } from \"@qntx/wallet-kernel\";\n\nexport type StorePort = {\n readonly post: (message: unknown) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n};\n\nexport type StoreRequest =\n | { readonly t: \"load\"; readonly id: number }\n | { readonly t: \"commit\"; readonly id: number; readonly ops: ReadonlyArray<StoreOp> };\n\nexport type StoreReply =\n | { readonly t: \"loaded\"; readonly id: number; readonly image: WireImage }\n | { readonly t: \"committed\"; readonly id: number }\n | { readonly t: \"failed\"; readonly id: number; readonly code: KernelErrorCode }\n | { readonly t: \"changed\" };\n\n/** Structured clone preserves `undefined` properties, so `meta` travels as-is. */\ntype WireImage = VaultImage;\n\nexport function encodeImage(image: VaultImage): WireImage {\n return { meta: image.meta, factors: image.factors, records: image.records };\n}\n\nexport { assertVaultImage } from \"@qntx/wallet-kernel\";\n\nexport type IdleMinutes = 5 | 15 | 60;\n\nexport function isIdleMinutes(value: unknown): value is IdleMinutes {\n return value === 5 || value === 15 || value === 60;\n}\n\nexport function idleMsOf(minutes: IdleMinutes): number {\n return minutes * 60_000;\n}\n\n/** The fixed maximum session duration owned by the worker entries (never a host input). */\nexport const MAX_SESSION_MS: number = 12 * 3_600_000;\n\n/**\n * The first message the Web host posts to `kernel.worker.js`: the session policy. The browser\n * worker's vault lives in IndexedDB inside the worker itself, so unlike Node there is no store port\n * — policy is all the kernel needs before `startKernel` runs.\n */\nexport type BrowserWorkerInit = {\n readonly t: \"init\";\n readonly idleMinutes: IdleMinutes;\n};\n\nfunction plainInitObject(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return undefined;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain object above\n return value as Record<string, unknown>;\n}\n\n/** Strict init-message validation; anything else must not start the kernel. */\nexport function isBrowserWorkerInit(value: unknown): value is BrowserWorkerInit {\n const init = plainInitObject(value);\n return (\n init !== undefined &&\n Object.keys(init).sort().join(\",\") === \"idleMinutes,t\" &&\n init[\"t\"] === \"init\" &&\n isIdleMinutes(init[\"idleMinutes\"])\n );\n}\n\n/**\n * Strict `workerData` validation for the Node kernel worker: `{ idleMinutes, storePort }` and\n * nothing else. `storePort` is checked structurally (the real type lives behind the worker_threads\n * boundary); a wrong shape must not start the kernel.\n */\nexport function isNodeWorkerData(\n value: unknown,\n): value is { readonly idleMinutes: IdleMinutes; readonly storePort: unknown } {\n const data = plainInitObject(value);\n return (\n data !== undefined &&\n Object.keys(data).sort().join(\",\") === \"idleMinutes,storePort\" &&\n isIdleMinutes(data[\"idleMinutes\"]) &&\n typeof data[\"storePort\"] === \"object\" &&\n data[\"storePort\"] !== null\n );\n}\n","/**\n * Main-side half of the store RPC: serves the shared in-memory RecordStore to the worker and pushes\n * \"changed\" notices for commits that did NOT come through this port (the kernel's own commits must\n * not echo back as external changes).\n */\nimport type { MessagePort } from \"node:worker_threads\";\n\nimport { KernelError } from \"@qntx/wallet-kernel\";\nimport type { KernelErrorCode, RecordStore } from \"@qntx/wallet-kernel\";\n\nimport type { StoreReply, StoreRequest } from \"../shared.ts\";\nimport { encodeImage } from \"../shared.ts\";\n\n// Internal wire between this package's two halves — malformed payloads get dropped.\nfunction isStoreRequest(raw: unknown): raw is StoreRequest {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return false;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain object above\n const request = raw as Record<string, unknown>;\n if (typeof request[\"id\"] !== \"number\") {\n return false;\n }\n return request[\"t\"] === \"load\" || (request[\"t\"] === \"commit\" && Array.isArray(request[\"ops\"]));\n}\n\nexport function serveStore(store: RecordStore, port: MessagePort): () => void {\n let ownCommits = 0;\n\n const post = (reply: StoreReply): void => {\n port.postMessage(reply);\n };\n\n // A failed load/commit replies \"failed\" with the KernelError code (or \"unavailable\" for a\n // non-kernel failure) — a request that hangs would deadlock the kernel's sequential queue.\n const failed = (id: number, error: unknown): void => {\n const code: KernelErrorCode = error instanceof KernelError ? error.code : \"unavailable\";\n post({ t: \"failed\", id, code });\n };\n\n const answer = async (request: StoreRequest): Promise<void> => {\n if (request.t === \"load\") {\n try {\n post({ t: \"loaded\", id: request.id, image: encodeImage(await store.load()) });\n } catch (error) {\n failed(request.id, error);\n }\n return;\n }\n ownCommits++;\n try {\n await store.commit(request.ops);\n } catch (error) {\n ownCommits--; // a failed commit fires no watch — do not eat the next external notice\n failed(request.id, error);\n return;\n }\n post({ t: \"committed\", id: request.id });\n };\n\n const onMessage = (raw: unknown): void => {\n if (!isStoreRequest(raw)) {\n return;\n }\n void (async (): Promise<void> => {\n try {\n await answer(raw);\n } catch {\n // A dead worker cannot be answered; the exit path handles it.\n }\n })();\n };\n\n const unwatch = store.watch(() => {\n if (ownCommits > 0) {\n ownCommits--;\n return;\n }\n post({ t: \"changed\" });\n });\n\n port.on(\"message\", onMessage);\n port.start();\n\n return () => {\n unwatch();\n port.off(\"message\", onMessage);\n port.close();\n };\n}\n","/**\n * CreateSoftwarePasskey — a TEST-ONLY PasskeyCeremony. There is no authenticator, no user presence\n * check, no credential store: the \"passkey\" is a deterministic function of `seed`, so anyone\n * holding the seed owns every wallet it ever protects. Use it in tests and demos only.\n *\n * CredentialId = SHA-256(seed ‖ \"credential\" ‖ u32be(n)) (n increments per create) PRF(salt) =\n * HMAC-SHA256(HMAC-SHA256(seed, credentialId), SHA-256(UTF-8(\"WebAuthn PRF\") ‖ 0x00 ‖ salt))\n * UserHandle = purpose byte ‖ SHA-256(seed ‖ \"user-handle\" ‖ credentialId)[0:15] — the same\n * 16-byte, purpose-prefixed shape the browser create path puts in `user.id`.\n */\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, concatBytes, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\nimport { WalletError } from \"@qntx/wallet\";\nimport { PASSKEY_PURPOSE_VAULT, PASSKEY_PURPOSE_WALLET } from \"@qntx/wallet/host\";\nimport type { PasskeyCeremony, PrfResult, PrfSalts } from \"@qntx/wallet/host\";\n\nexport function createSoftwarePasskey(\n seed: Uint8Array,\n options?: { readonly synced?: boolean },\n): PasskeyCeremony {\n const synced = options?.synced ?? true; // software credentials pretend to be synced by default\n let counter = 0;\n let lastCreated: Uint8Array | undefined;\n const known = new Map<string, { credentialId: Uint8Array; userHandle: Uint8Array }>();\n\n const prf = (credentialId: Uint8Array, salt: Uint8Array): Uint8Array => {\n const key = hmac(sha256, seed, credentialId);\n const message = sha256(concatBytes(utf8ToBytes(\"WebAuthn PRF\"), new Uint8Array([0]), salt));\n return hmac(sha256, key, message);\n };\n\n const result = (\n credentialId: Uint8Array,\n salts: PrfSalts,\n userHandle?: Uint8Array,\n ): PrfResult => ({\n credentialId: new Uint8Array(credentialId),\n first: prf(credentialId, salts.first),\n ...(salts.second === undefined ? {} : { second: prf(credentialId, salts.second) }),\n ...(userHandle === undefined ? {} : { userHandle: new Uint8Array(userHandle) }),\n synced,\n });\n\n return {\n // oxlint-disable-next-line typescript/require-await -- the ceremony contract is async; this test double computes synchronously\n create: async ({ purpose, salts }) => {\n const counterBytes = new Uint8Array(4);\n new DataView(counterBytes.buffer).setUint32(0, counter);\n counter++;\n const credentialId = sha256(concatBytes(seed, utf8ToBytes(\"credential\"), counterBytes));\n const purposeByte = purpose === \"wallet\" ? PASSKEY_PURPOSE_WALLET : PASSKEY_PURPOSE_VAULT;\n const userHandle = new Uint8Array(16);\n userHandle[0] = purposeByte;\n userHandle.set(\n sha256(concatBytes(seed, utf8ToBytes(\"user-handle\"), credentialId)).subarray(0, 15),\n 1,\n );\n known.set(bytesToHex(credentialId), { credentialId, userHandle });\n lastCreated = credentialId;\n return result(credentialId, salts);\n },\n // oxlint-disable-next-line typescript/require-await -- the ceremony contract is async; this test double computes synchronously\n assert: async ({ credentialIds, salts }) => {\n const credentialId =\n credentialIds === undefined\n ? lastCreated\n : credentialIds.find((id) => known.has(bytesToHex(id)));\n if (credentialId === undefined) {\n throw new WalletError(\n \"passkey-prf-unsupported\",\n credentialIds === undefined\n ? \"no software credential exists yet\"\n : \"unknown software credential\",\n );\n }\n const entry = known.get(bytesToHex(credentialId));\n return result(credentialId, salts, entry?.userHandle);\n },\n };\n}\n","/**\n * The Node host: `createNodeWallet` spawns the bundled kernel worker (dist/kernel.node.js) and\n * keeps the vault image — ciphertext + public headers, never secrets — in the main thread's\n * in-memory store, served to each worker over a MessageChannel. That is what lets a lock destroy\n * the whole worker without losing the vault.\n */\nimport { MessageChannel, Worker } from \"node:worker_threads\";\n\nimport { WalletError } from \"@qntx/wallet\";\nimport type { Wallet, WalletOptions } from \"@qntx/wallet\";\nimport { createMemoryStore } from \"@qntx/wallet-kernel\";\nimport { connectKernel } from \"@qntx/wallet/host\";\nimport type { MainPort, PasskeyCeremony } from \"@qntx/wallet/host\";\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nimport type { NodeWorkerData } from \"../worker/node.ts\";\nimport { serveStore } from \"./store-server.ts\";\n\nexport { createSoftwarePasskey } from \"./software-passkey.ts\";\n\nexport type NodeWalletOptions = WalletOptions & {\n readonly authenticator?: PasskeyCeremony;\n /**\n * Test/debug hook: the worker file location and a spawn observer (count spawns, watch 'exit').\n * Defaults to the bundled dist/kernel.node.js next to this module.\n */\n readonly kernelUrl?: string | URL;\n readonly onSpawn?: (worker: Worker) => void;\n};\n\nexport async function createNodeWallet(options: NodeWalletOptions): Promise<Wallet> {\n const { autoLock } = options;\n if (autoLock.platform !== \"web\") {\n throw new WalletError(\"invalid-input\", \"createNodeWallet accepts only the web autoLock policy\");\n }\n // The host sends only the idle choice; the worker owns the maximum session duration.\n const workerData = { idleMinutes: autoLock.idleMinutes };\n const store = createMemoryStore(); // ciphertext + public headers only — safe in the main thread\n const kernelUrl = options.kernelUrl ?? new URL(\"kernel.node.js\", import.meta.url);\n\n const spawn = (): MainPort => {\n const channel = new MessageChannel();\n const stopStore = serveStore(store, channel.port1);\n const worker = new Worker(kernelUrl, {\n workerData: { ...workerData, storePort: channel.port2 } satisfies NodeWorkerData,\n transferList: [channel.port2],\n });\n options.onSpawn?.(worker);\n return {\n post: (message: ProtocolValue, transfer: ArrayBuffer[]) => {\n worker.postMessage(message, transfer);\n },\n listen: (handler) => {\n const listener = (message: unknown) => {\n handler(message);\n };\n worker.on(\"message\", listener);\n return () => {\n worker.off(\"message\", listener);\n };\n },\n onExit: (handler) => {\n const listener = () => {\n handler(\"crashed\");\n };\n worker.once(\"exit\", listener);\n return () => {\n worker.off(\"exit\", listener);\n };\n },\n terminate: () => {\n stopStore();\n void worker.terminate();\n },\n };\n };\n\n return connectKernel({\n factors: \"software\",\n spawn,\n passkey: options.passkey,\n verifyEvent: options.verifyEvent,\n ceremony: options.authenticator,\n setTimer: (delayMs, fn) => {\n const timer = setTimeout(fn, delayMs);\n return () => {\n clearTimeout(timer);\n };\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;;;;;CAKA;;C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AqB;KACrC,QAAQ,OAAO;IACjB;IACA,OAAO,GAAG,WAAW,QAAQ;IAC7B,aAAa;KACX,OAAO,IAAI,WAAW,QAAQ;IAChC;GACF;GACA,SAAS,YAAY;IACnB,MAAM,iBAAiB;KACrB,QAAQ,SAAS;IACnB;IACA,OAAO,KAAK,QAAQ,QAAQ;IAC5B,aAAa;KACX,OAAO,IAAI,QAAQ,QAAQ;IAC7B;GACF;GACA,iBAAiB;IACf,UAAU;IACV,OAAY,UAAU;GACxB;EACF;CACF;CAEA,OAAO,cAAc;EACnB,SAAS;EACT;EACA,SAAS,QAAQ;EACjB,aAAa,QAAQ;EACrB,UAAU,QAAQ;EAClB,WAAW,SAAS,OAAO;GACzB,MAAM,QAAQ,WAAW,IAAI,OAAO;GACpC,aAAa;IACX,aAAa,KAAK;GACpB;EACF;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qntx/wallet-worker",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Web Worker and worker_threads hosts for @qntx/wallet",
5
5
  "keywords": [
6
6
  "nostr",
@@ -67,8 +67,8 @@
67
67
  "@qntx/spark": "0.5.2",
68
68
  "@qntx/spark-wasm": "0.5.2",
69
69
  "@qntx/tsconfig": "1.0.1",
70
- "@qntx/wallet": "0.10.0",
71
- "@qntx/wallet-kernel": "0.10.0",
70
+ "@qntx/wallet": "0.11.0",
71
+ "@qntx/wallet-kernel": "0.11.0",
72
72
  "@scure/base": "2.4.0",
73
73
  "@scure/btc-signer": "2.4.1",
74
74
  "@types/node": "26.6.6",
@@ -77,7 +77,7 @@
77
77
  "vite-plus": "1.4.0"
78
78
  },
79
79
  "peerDependencies": {
80
- "@qntx/wallet": "0.10.0"
80
+ "@qntx/wallet": "0.11.0"
81
81
  },
82
82
  "devEngines": {
83
83
  "packageManager": {