@qntx/wallet-native 0.8.0 → 0.9.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/README.md CHANGED
@@ -73,6 +73,9 @@ const wallet = await createNativeWallet({
73
73
  salt for the cloud-backup factor — a third, distinct permanent label.
74
74
  - `autoLock` — must be `{ platform: "native", backgroundSeconds }`. The native host owns the
75
75
  signal: it calls `host.lock()` when the app has spent `backgroundSeconds` in the background.
76
+ - `createHost` — optional factory for the `KernelHost` (a like-shaped fake in tests). A host serves one
77
+ kernel runtime: after a lock, a wallet deletion or a crash it is spent, and the wallet calls the
78
+ factory again for the next unlock.
76
79
  A platform authentication prompt on screen does **not** count as background time.
77
80
  - `verifyEvent` — required. Checks every event the kernel signs before it is returned. There is no
78
81
  default: `@qntx/nostr`'s own verifier is the pure-JS noble backend, slow on Hermes. Pass the
package/dist/index.d.mts CHANGED
@@ -26,10 +26,12 @@ export declare function encodeFrame(value: ProtocolValue): ArrayBuffer;
26
26
  export declare function decodeFrame(frame: ArrayBuffer | Uint8Array): ProtocolValue;
27
27
  export type NativeWalletOptions = WalletOptions & {
28
28
  /**
29
- * The Nitro `KernelHost` hybrid object (or a like-shaped fake for tests). Defaults to
29
+ * Creates one `KernelHost` per kernel runtime (a Nitro hybrid object, or a like-shaped fake for
30
+ * tests). A host lives for a single runtime: after a lock or a crash it is spent, and the wallet
31
+ * asks for a new one for the next unlock. Defaults to
30
32
  * `NitroModules.createHybridObject("KernelHost")` — the only Nitro-registered object.
31
33
  */
32
- readonly host?: KernelHostLike;
34
+ readonly createHost?: () => KernelHostLike;
33
35
  };
34
36
  export declare function createNativeWallet(options: NativeWalletOptions): Promise<Wallet>;
35
37
  export type { CborErrorCode, KernelExitReason, KernelHostLike };
package/dist/index.mjs CHANGED
@@ -146,16 +146,16 @@ const setTimer = (delayMs, fn) => {
146
146
  clearTimeout(id);
147
147
  };
148
148
  };
149
- async function defaultHost() {
149
+ async function defaultHostFactory() {
150
150
  const { NitroModules } = await import("react-native-nitro-modules");
151
- return NitroModules.createHybridObject("KernelHost");
151
+ return () => NitroModules.createHybridObject("KernelHost");
152
152
  }
153
153
  async function createNativeWallet(options) {
154
154
  const { autoLock } = options;
155
- const host = options.host ?? await defaultHost();
156
155
  if (autoLock.platform !== "native") throw new WalletError("invalid-input", "createNativeWallet accepts only the native autoLock policy");
156
+ const createHost = options.createHost ?? await defaultHostFactory();
157
157
  return connectKernel({
158
- spawn: () => spawnFromHost(host, autoLock.backgroundSeconds),
158
+ spawn: () => spawnFromHost(createHost(), autoLock.backgroundSeconds),
159
159
  factors: "hardware",
160
160
  passkey: options.passkey,
161
161
  verifyEvent: options.verifyEvent,
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/cbor.ts","../src/host.ts","../src/index.ts"],"sourcesContent":["/**\n * CBOR framing for the kernel channel. `ProtocolValue` travels main-side ↔ kernel-side as CBOR; the\n * C++ layer moves bytes only. Decode is deliberately strict: floats, unsafe integers, undefined,\n * tags, non-string map keys, duplicate keys and indefinite-length items are all rejected — the wire\n * format carries exactly one value domain.\n */\nimport { decode, encode } from \"cborg\";\nimport type { DecodeOptions } from \"cborg\";\n\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nexport const FRAME_MAX_BYTES: number = 1024 * 1024;\n\nexport type CborErrorCode =\n | \"oversize\"\n | \"truncated\"\n | \"malformed\"\n | \"float\"\n | \"unsafe-int\"\n | \"bigint\"\n | \"undefined\"\n | \"tag\"\n | \"non-string-key\"\n | \"duplicate-key\"\n | \"indefinite\"\n | \"bad-type\";\n\nexport class CborError extends Error {\n readonly code: CborErrorCode;\n constructor(code: CborErrorCode, message: string) {\n super(message);\n this.name = \"CborError\";\n this.code = code;\n }\n}\n\nconst DECODE_OPTIONS: DecodeOptions = {\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n allowUndefined: false,\n allowIndefinite: false,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: false,\n};\n\n/** Reject non-safe-integer numbers and non-string map keys; cborg flags cover the rest. */\nfunction validate(value: unknown): asserts value is ProtocolValue {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value)) {\n throw new CborError(\"float\", \"cbor frame: non-integer number\");\n }\n if (!Number.isSafeInteger(value)) {\n throw new CborError(\"unsafe-int\", \"cbor frame: integer outside the safe range\");\n }\n return;\n }\n if (value instanceof Uint8Array) {\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n validate(item);\n }\n return;\n }\n if (typeof value === \"object\") {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the object came from a CBOR map\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (typeof key !== \"string\") {\n throw new CborError(\"non-string-key\", \"cbor frame: non-string map key\");\n }\n validate(item);\n }\n return;\n }\n throw new CborError(\"bad-type\", `cbor frame: unsupported value type ${typeof value}`);\n}\n\n/** Classify a cborg rejection into the frame error taxonomy. */\nfunction classify(error: unknown): CborError {\n if (error instanceof CborError) {\n return error;\n }\n const text = error instanceof Error ? error.message : String(error);\n const table: ReadonlyArray<[RegExp, CborErrorCode]> = [\n [/duplicate key|repeat map key/i, \"duplicate-key\"],\n [/indefinite/i, \"indefinite\"],\n [/undefined/i, \"undefined\"],\n [/bigint|safe integer range/i, \"unsafe-int\"],\n [/tag/i, \"tag\"],\n [/string/i, \"non-string-key\"],\n ];\n for (const [pattern, code] of table) {\n if (pattern.test(text)) {\n return new CborError(code, `cbor frame: ${text}`);\n }\n }\n return new CborError(\"malformed\", `cbor frame: ${text}`);\n}\n\n/** Encode a `ProtocolValue` to a CBOR frame, enforcing the 1 MiB cap. */\nexport function encodeFrame(value: ProtocolValue): ArrayBuffer {\n validate(value);\n const bytes = encode(value);\n if (bytes.byteLength > FRAME_MAX_BYTES) {\n throw new CborError(\"oversize\", `cbor frame: ${bytes.byteLength} bytes exceeds the 1 MiB cap`);\n }\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n}\n\n/** Decode a CBOR frame back to a `ProtocolValue`, enforcing the 1 MiB cap and strictness. */\nexport function decodeFrame(frame: ArrayBuffer | Uint8Array): ProtocolValue {\n const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame);\n if (bytes.byteLength > FRAME_MAX_BYTES) {\n throw new CborError(\"oversize\", `cbor frame: ${bytes.byteLength} bytes exceeds the 1 MiB cap`);\n }\n if (bytes.byteLength === 0) {\n throw new CborError(\"truncated\", \"cbor frame: empty frame\");\n }\n try {\n const value: unknown = decode(bytes, DECODE_OPTIONS);\n validate(value);\n return value;\n } catch (error) {\n throw classify(error);\n }\n}\n","/**\n * `KernelHost` JS wrapper: CBOR frames over a Nitro-host-shaped channel. The host moves bytes only\n * — encode/decode happens here and in the kernel entry — so a malformed inbound frame can never\n * reach the message domain: the port exits `integrity` and the host runtime is destroyed.\n */\nimport type { MainPort, PortExit } from \"@qntx/wallet/host\";\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nimport { decodeFrame, encodeFrame } from \"./cbor.ts\";\n\nexport type KernelExitReason = \"locked\" | \"crashed\" | \"integrity\" | \"background\";\n\n/**\n * Structural mirror of the Nitro `KernelHost` spec (W2b registers the real hybrid object; tests\n * drive the same shape over an in-memory frame pipe).\n */\nexport type KernelHostLike = {\n readonly start: (backgroundLockSeconds: number) => void;\n readonly post: (frame: ArrayBuffer) => void;\n readonly onMessage: (cb: (frame: ArrayBuffer) => void) => void;\n readonly onExit: (cb: (reason: KernelExitReason) => void) => void;\n readonly lock: () => void;\n};\n\nexport function spawnFromHost(host: KernelHostLike, backgroundLockSeconds: number): MainPort {\n const exitHandlers = new Set<(reason: PortExit) => void>();\n let exited = false;\n\n const exit = (reason: PortExit): void => {\n if (exited) {\n return;\n }\n exited = true;\n for (const handler of exitHandlers) {\n handler(reason);\n }\n host.lock();\n };\n\n host.onMessage((frame) => {\n let message: ProtocolValue;\n try {\n message = decodeFrame(frame);\n } catch {\n exit(\"crashed\");\n return;\n }\n dispatch(message);\n });\n\n // The platform locked the enclave in the background — report it honestly so\n // the channel takes the lock path, not the crash path.\n host.onExit((reason) => {\n exit(reason === \"background\" ? \"background\" : \"crashed\");\n });\n\n const messageHandlers = new Set<(message: unknown) => void>();\n const dispatch = (message: unknown): void => {\n for (const handler of messageHandlers) {\n handler(message);\n }\n };\n\n host.start(backgroundLockSeconds);\n\n return {\n post: (message, transfer) => {\n const frame = encodeFrame(message);\n host.post(frame);\n // Structured clone would neuter transferred buffers on the web; the main↔kernel\n // contract is the same here — the caller's buffers hold secrets (passwords, PRF\n // output) and are zeroed once their bytes are inside the frame.\n for (const buffer of transfer) {\n new Uint8Array(buffer).fill(0);\n }\n },\n listen: (handler) => {\n messageHandlers.add(handler);\n return () => {\n messageHandlers.delete(handler);\n };\n },\n onExit: (handler) => {\n exitHandlers.add(handler);\n return () => {\n exitHandlers.delete(handler);\n };\n },\n terminate: () => {\n exit(\"crashed\");\n },\n };\n}\n","import { WalletError } from \"@qntx/wallet\";\nimport type { Wallet, WalletOptions } from \"@qntx/wallet\";\nimport type { SetTimer } from \"@qntx/wallet/host\";\n/**\n * `@qntx/wallet-native`: the RN host entry. `createNativeWallet` adapts a `KernelHost` (Nitro\n * hybrid from W2b, or any object with the same shape) to the wallet `connectKernel` entry — the\n * returned `Wallet` is the same type as the web/node host.\n */\nimport { connectKernel } from \"@qntx/wallet/host\";\n\nimport { spawnFromHost } from \"./host.ts\";\nimport type { KernelHostLike } from \"./host.ts\";\nimport type { KernelHost } from \"./specs/kernel-host.nitro.ts\";\n\nexport type NativeWalletOptions = WalletOptions & {\n /**\n * The Nitro `KernelHost` hybrid object (or a like-shaped fake for tests). Defaults to\n * `NitroModules.createHybridObject(\"KernelHost\")` — the only Nitro-registered object.\n */\n readonly host?: KernelHostLike;\n};\n\nconst setTimer: SetTimer = (delayMs, fn) => {\n const id = setTimeout(fn, delayMs);\n return () => {\n clearTimeout(id);\n };\n};\n\nasync function defaultHost(): Promise<KernelHostLike> {\n const { NitroModules } = await import(\"react-native-nitro-modules\");\n return NitroModules.createHybridObject<KernelHost>(\"KernelHost\");\n}\n\nexport async function createNativeWallet(options: NativeWalletOptions): Promise<Wallet> {\n const { autoLock } = options;\n const host = options.host ?? (await defaultHost());\n if (autoLock.platform !== \"native\") {\n throw new WalletError(\n \"invalid-input\",\n \"createNativeWallet accepts only the native autoLock policy\",\n );\n }\n // The native host owns the auto-lock signal: the platform layer calls host.lock() on\n // background expiry — the kernel never sees a presence source here.\n return connectKernel({\n spawn: () => spawnFromHost(host, autoLock.backgroundSeconds),\n factors: \"hardware\",\n passkey: options.passkey,\n verifyEvent: options.verifyEvent,\n ceremony: undefined,\n setTimer,\n });\n}\n\nexport { spawnFromHost, type KernelHostLike, type KernelExitReason } from \"./host.ts\";\nexport {\n encodeFrame,\n decodeFrame,\n CborError,\n FRAME_MAX_BYTES,\n type CborErrorCode,\n} from \"./cbor.ts\";\n"],"mappings":";;;;;;;;;;AAWA,MAAa,kBAA0B;AAgBvC,IAAa,YAAb,cAA+B,MAAM;CACnC;CACA,YAAY,MAAqB,SAAiB;EAChD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,MAAM,iBAAgC;CACpC,QAAQ;CACR,SAAS;CACT,wBAAwB;CACxB,gBAAgB;CAChB,iBAAiB;CACjB,UAAU;CACV,eAAe;CACf,aAAa;AACf;;AAGA,SAAS,SAAS,OAAgD;CAChE,IAAI,UAAU,QAAQ,OAAO,UAAU,aAAa,OAAO,UAAU,UACnE;CAEF,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,UAAU,KAAK,GACzB,MAAM,IAAI,UAAU,SAAS,gCAAgC;EAE/D,IAAI,CAAC,OAAO,cAAc,KAAK,GAC7B,MAAM,IAAI,UAAU,cAAc,4CAA4C;EAEhF;CACF;CACA,IAAI,iBAAiB,YACnB;CAEF,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,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,OAAO,aAAa,mBAA+B,YAAY;AACjE;AAEA,eAAsB,mBAAmB,SAA+C;CACtF,MAAM,EAAE,aAAa;CACrB,MAAM,OAAO,QAAQ,QAAS,MAAM,YAAY;CAChD,IAAI,SAAS,aAAa,UACxB,MAAM,IAAI,YACR,iBACA,4DACF;CAIF,OAAO,cAAc;EACnB,aAAa,cAAc,MAAM,SAAS,iBAAiB;EAC3D,SAAS;EACT,SAAS,QAAQ;EACjB,aAAa,QAAQ;EACrB,UAAU,KAAA;EACV;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/cbor.ts","../src/host.ts","../src/index.ts"],"sourcesContent":["/**\n * CBOR framing for the kernel channel. `ProtocolValue` travels main-side ↔ kernel-side as CBOR; the\n * C++ layer moves bytes only. Decode is deliberately strict: floats, unsafe integers, undefined,\n * tags, non-string map keys, duplicate keys and indefinite-length items are all rejected — the wire\n * format carries exactly one value domain.\n */\nimport { decode, encode } from \"cborg\";\nimport type { DecodeOptions } from \"cborg\";\n\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nexport const FRAME_MAX_BYTES: number = 1024 * 1024;\n\nexport type CborErrorCode =\n | \"oversize\"\n | \"truncated\"\n | \"malformed\"\n | \"float\"\n | \"unsafe-int\"\n | \"bigint\"\n | \"undefined\"\n | \"tag\"\n | \"non-string-key\"\n | \"duplicate-key\"\n | \"indefinite\"\n | \"bad-type\";\n\nexport class CborError extends Error {\n readonly code: CborErrorCode;\n constructor(code: CborErrorCode, message: string) {\n super(message);\n this.name = \"CborError\";\n this.code = code;\n }\n}\n\nconst DECODE_OPTIONS: DecodeOptions = {\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n allowUndefined: false,\n allowIndefinite: false,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: false,\n};\n\n/** Reject non-safe-integer numbers and non-string map keys; cborg flags cover the rest. */\nfunction validate(value: unknown): asserts value is ProtocolValue {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return;\n }\n if (typeof value === \"number\") {\n if (!Number.isInteger(value)) {\n throw new CborError(\"float\", \"cbor frame: non-integer number\");\n }\n if (!Number.isSafeInteger(value)) {\n throw new CborError(\"unsafe-int\", \"cbor frame: integer outside the safe range\");\n }\n return;\n }\n if (value instanceof Uint8Array) {\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n validate(item);\n }\n return;\n }\n if (typeof value === \"object\") {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the object came from a CBOR map\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (typeof key !== \"string\") {\n throw new CborError(\"non-string-key\", \"cbor frame: non-string map key\");\n }\n validate(item);\n }\n return;\n }\n throw new CborError(\"bad-type\", `cbor frame: unsupported value type ${typeof value}`);\n}\n\n/** Classify a cborg rejection into the frame error taxonomy. */\nfunction classify(error: unknown): CborError {\n if (error instanceof CborError) {\n return error;\n }\n const text = error instanceof Error ? error.message : String(error);\n const table: ReadonlyArray<[RegExp, CborErrorCode]> = [\n [/duplicate key|repeat map key/i, \"duplicate-key\"],\n [/indefinite/i, \"indefinite\"],\n [/undefined/i, \"undefined\"],\n [/bigint|safe integer range/i, \"unsafe-int\"],\n [/tag/i, \"tag\"],\n [/string/i, \"non-string-key\"],\n ];\n for (const [pattern, code] of table) {\n if (pattern.test(text)) {\n return new CborError(code, `cbor frame: ${text}`);\n }\n }\n return new CborError(\"malformed\", `cbor frame: ${text}`);\n}\n\n/** Encode a `ProtocolValue` to a CBOR frame, enforcing the 1 MiB cap. */\nexport function encodeFrame(value: ProtocolValue): ArrayBuffer {\n validate(value);\n const bytes = encode(value);\n if (bytes.byteLength > FRAME_MAX_BYTES) {\n throw new CborError(\"oversize\", `cbor frame: ${bytes.byteLength} bytes exceeds the 1 MiB cap`);\n }\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n}\n\n/** Decode a CBOR frame back to a `ProtocolValue`, enforcing the 1 MiB cap and strictness. */\nexport function decodeFrame(frame: ArrayBuffer | Uint8Array): ProtocolValue {\n const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame);\n if (bytes.byteLength > FRAME_MAX_BYTES) {\n throw new CborError(\"oversize\", `cbor frame: ${bytes.byteLength} bytes exceeds the 1 MiB cap`);\n }\n if (bytes.byteLength === 0) {\n throw new CborError(\"truncated\", \"cbor frame: empty frame\");\n }\n try {\n const value: unknown = decode(bytes, DECODE_OPTIONS);\n validate(value);\n return value;\n } catch (error) {\n throw classify(error);\n }\n}\n","/**\n * `KernelHost` JS wrapper: CBOR frames over a Nitro-host-shaped channel. The host moves bytes only\n * — encode/decode happens here and in the kernel entry — so a malformed inbound frame can never\n * reach the message domain: the port exits `integrity` and the host runtime is destroyed.\n */\nimport type { MainPort, PortExit } from \"@qntx/wallet/host\";\nimport type { ProtocolValue } from \"@qntx/wallet/protocol\";\n\nimport { decodeFrame, encodeFrame } from \"./cbor.ts\";\n\nexport type KernelExitReason = \"locked\" | \"crashed\" | \"integrity\" | \"background\";\n\n/**\n * Structural mirror of the Nitro `KernelHost` spec (W2b registers the real hybrid object; tests\n * drive the same shape over an in-memory frame pipe).\n */\nexport type KernelHostLike = {\n readonly start: (backgroundLockSeconds: number) => void;\n readonly post: (frame: ArrayBuffer) => void;\n readonly onMessage: (cb: (frame: ArrayBuffer) => void) => void;\n readonly onExit: (cb: (reason: KernelExitReason) => void) => void;\n readonly lock: () => void;\n};\n\nexport function spawnFromHost(host: KernelHostLike, backgroundLockSeconds: number): MainPort {\n const exitHandlers = new Set<(reason: PortExit) => void>();\n let exited = false;\n\n const exit = (reason: PortExit): void => {\n if (exited) {\n return;\n }\n exited = true;\n for (const handler of exitHandlers) {\n handler(reason);\n }\n host.lock();\n };\n\n host.onMessage((frame) => {\n let message: ProtocolValue;\n try {\n message = decodeFrame(frame);\n } catch {\n exit(\"crashed\");\n return;\n }\n dispatch(message);\n });\n\n // The platform locked the enclave in the background — report it honestly so\n // the channel takes the lock path, not the crash path.\n host.onExit((reason) => {\n exit(reason === \"background\" ? \"background\" : \"crashed\");\n });\n\n const messageHandlers = new Set<(message: unknown) => void>();\n const dispatch = (message: unknown): void => {\n for (const handler of messageHandlers) {\n handler(message);\n }\n };\n\n host.start(backgroundLockSeconds);\n\n return {\n post: (message, transfer) => {\n const frame = encodeFrame(message);\n host.post(frame);\n // Structured clone would neuter transferred buffers on the web; the main↔kernel\n // contract is the same here — the caller's buffers hold secrets (passwords, PRF\n // output) and are zeroed once their bytes are inside the frame.\n for (const buffer of transfer) {\n new Uint8Array(buffer).fill(0);\n }\n },\n listen: (handler) => {\n messageHandlers.add(handler);\n return () => {\n messageHandlers.delete(handler);\n };\n },\n onExit: (handler) => {\n exitHandlers.add(handler);\n return () => {\n exitHandlers.delete(handler);\n };\n },\n terminate: () => {\n exit(\"crashed\");\n },\n };\n}\n","import { WalletError } from \"@qntx/wallet\";\nimport type { Wallet, WalletOptions } from \"@qntx/wallet\";\nimport type { SetTimer } from \"@qntx/wallet/host\";\n/**\n * `@qntx/wallet-native`: the RN host entry. `createNativeWallet` adapts a `KernelHost` (Nitro\n * hybrid from W2b, or any object with the same shape) to the wallet `connectKernel` entry — the\n * returned `Wallet` is the same type as the web/node host.\n */\nimport { connectKernel } from \"@qntx/wallet/host\";\n\nimport { spawnFromHost } from \"./host.ts\";\nimport type { KernelHostLike } from \"./host.ts\";\nimport type { KernelHost } from \"./specs/kernel-host.nitro.ts\";\n\nexport type NativeWalletOptions = WalletOptions & {\n /**\n * Creates one `KernelHost` per kernel runtime (a Nitro hybrid object, or a like-shaped fake for\n * tests). A host lives for a single runtime: after a lock or a crash it is spent, and the wallet\n * asks for a new one for the next unlock. Defaults to\n * `NitroModules.createHybridObject(\"KernelHost\")` — the only Nitro-registered object.\n */\n readonly createHost?: () => KernelHostLike;\n};\n\nconst setTimer: SetTimer = (delayMs, fn) => {\n const id = setTimeout(fn, delayMs);\n return () => {\n clearTimeout(id);\n };\n};\n\nasync function defaultHostFactory(): Promise<() => KernelHostLike> {\n const { NitroModules } = await import(\"react-native-nitro-modules\");\n return () => NitroModules.createHybridObject<KernelHost>(\"KernelHost\");\n}\n\nexport async function createNativeWallet(options: NativeWalletOptions): Promise<Wallet> {\n const { autoLock } = options;\n if (autoLock.platform !== \"native\") {\n throw new WalletError(\n \"invalid-input\",\n \"createNativeWallet accepts only the native autoLock policy\",\n );\n }\n const createHost = options.createHost ?? (await defaultHostFactory());\n // The native host owns the auto-lock signal: the platform layer calls host.lock() on\n // background expiry — the kernel never sees a presence source here.\n return connectKernel({\n spawn: () => spawnFromHost(createHost(), autoLock.backgroundSeconds),\n factors: \"hardware\",\n passkey: options.passkey,\n verifyEvent: options.verifyEvent,\n ceremony: undefined,\n setTimer,\n });\n}\n\nexport { spawnFromHost, type KernelHostLike, type KernelExitReason } from \"./host.ts\";\nexport {\n encodeFrame,\n decodeFrame,\n CborError,\n FRAME_MAX_BYTES,\n type CborErrorCode,\n} from \"./cbor.ts\";\n"],"mappings":";;;;;;;;;;AAWA,MAAa,kBAA0B;AAgBvC,IAAa,YAAb,cAA+B,MAAM;CACnC;CACA,YAAY,MAAqB,SAAiB;EAChD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,MAAM,iBAAgC;CACpC,QAAQ;CACR,SAAS;CACT,wBAAwB;CACxB,gBAAgB;CAChB,iBAAiB;CACjB,UAAU;CACV,eAAe;CACf,aAAa;AACf;;AAGA,SAAS,SAAS,OAAgD;CAChE,IAAI,UAAU,QAAQ,OAAO,UAAU,aAAa,OAAO,UAAU,UACnE;CAEF,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,UAAU,KAAK,GACzB,MAAM,IAAI,UAAU,SAAS,gCAAgC;EAE/D,IAAI,CAAC,OAAO,cAAc,KAAK,GAC7B,MAAM,IAAI,UAAU,cAAc,4CAA4C;EAEhF;CACF;CACA,IAAI,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A,eAAe,qBAAoD;CACjE,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,aAAa,aAAa,mBAA+B,YAAY;AACvE;AAEA,eAAsB,mBAAmB,SAA+C;CACtF,MAAM,EAAE,aAAa;CACrB,IAAI,SAAS,aAAa,UACxB,MAAM,IAAI,YACR,iBACA,4DACF;CAEF,MAAM,aAAa,QAAQ,cAAe,MAAM,mBAAmB;CAGnE,OAAO,cAAc;EACnB,aAAa,cAAc,WAAW,GAAG,SAAS,iBAAiB;EACnE,SAAS;EACT,SAAS,QAAQ;EACjB,aAAa,QAAQ;EACrB,UAAU,KAAA;EACV;CACF,CAAC;AACH"}
@@ -18044,7 +18044,7 @@ zoo`.split("\n"));
18044
18044
  }
18045
18045
  };
18046
18046
  }));
18047
- // packages/wallet-chains/dist/message-DuJ5KSRT.mjs
18047
+ // packages/wallet-chains/dist/message-Dv18g8ii.mjs
18048
18048
  init_secp256k1();
18049
18049
  init_utils();
18050
18050
  init_transaction();
@@ -18116,9 +18116,14 @@ zoo`.split("\n"));
18116
18116
  }
18117
18117
  return out;
18118
18118
  };
18119
- /** CompactSize length prefix (values here are always < 253). */
18119
+ /** CompactSize length prefix for the one-byte form. */
18120
18120
  var varint = (n) => Uint8Array.of(n);
18121
- var pushData = (data) => concat$2(varint(data.length), data);
18121
+ var COMPACT_SIZE_ONE_BYTE_MAX = 252;
18122
+ /** A length-prefixed push; longer data would need a multi-byte CompactSize this code never emits. */
18123
+ var pushData = (data) => {
18124
+ if (data.length > COMPACT_SIZE_ONE_BYTE_MAX) throw new ChainError("invalid-request", "BIP-322 script data exceeds 252 bytes");
18125
+ return concat$2(varint(data.length), data);
18126
+ };
18122
18127
  var u32le$1 = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
18123
18128
  var u64le$1 = (n) => {
18124
18129
  const out = /* @__PURE__ */ new Uint8Array(8);
@@ -25132,6 +25137,8 @@ zoo`.split("\n"));
25132
25137
  }
25133
25138
  // packages/wallet-chains/dist/evm.mjs
25134
25139
  init_objectSpread2();
25140
+ /** The native asset id in `AssetFlow` and simulated asset changes. */
25141
+ var EVM_NATIVE_ASSET = "native";
25135
25142
  var USDC$1 = Object.freeze({
25136
25143
  symbol: "USDC",
25137
25144
  decimals: 6,
@@ -25168,7 +25175,6 @@ zoo`.split("\n"));
25168
25175
  var ERC721_TRANSFER_FROM = from$2("function transferFrom(address from, address to, uint256 tokenId)");
25169
25176
  var ERC721_SAFE_FROM = from$2("function safeTransferFrom(address from, address to, uint256 tokenId)");
25170
25177
  var ERC1155_SAFE_FROM = from$2("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
25171
- var NATIVE_ASSET = "native";
25172
25178
  var MAX_UINT256 = 2n ** 256n - 1n;
25173
25179
  var argAddress = (args, index) => {
25174
25180
  const value = args[index];
@@ -25198,7 +25204,7 @@ zoo`.split("\n"));
25198
25204
  }
25199
25205
  };
25200
25206
  var weiAmount = (wei, symbol, decimals) => _objectSpread2(_objectSpread2({
25201
- asset: NATIVE_ASSET,
25207
+ asset: EVM_NATIVE_ASSET,
25202
25208
  amount: wei.toString(10)
25203
25209
  }, symbol === void 0 ? {} : { symbol }), decimals === void 0 ? {} : { decimals });
25204
25210
  var feeWei = (tx) => BigInt(tx.gas) * (tx.type === "eip1559" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));
@@ -26777,8 +26783,11 @@ zoo`.split("\n"));
26777
26783
  numRequiredSignatures: message.numSignerAccounts,
26778
26784
  staticAccounts,
26779
26785
  instructions: message.instructions,
26780
- lookupCount: lookups.length,
26781
- lookupAddresses: lookups.map((l) => l.lookupTableAddress)
26786
+ lookups: lookups.map((l) => ({
26787
+ address: l.lookupTableAddress,
26788
+ writableIndexes: l.writableIndexes,
26789
+ readonlyIndexes: l.readonlyIndexes
26790
+ }))
26782
26791
  };
26783
26792
  };
26784
26793
  var isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -26838,6 +26847,8 @@ zoo`.split("\n"));
26838
26847
  if (tables === void 0) return;
26839
26848
  for (const table of tables) if (!isSolanaAddress(table.address) || !table.addresses.every(isSolanaAddress)) throw new ChainError("invalid-address", "lookup table entries must be base58 32-byte addresses");
26840
26849
  };
26850
+ /** The native asset id in `AssetFlow` and simulated asset changes. */
26851
+ var SOLANA_NATIVE_ASSET = "lamports";
26841
26852
  var USDC = Object.freeze({
26842
26853
  symbol: "USDC",
26843
26854
  decimals: 6,
@@ -26856,7 +26867,6 @@ zoo`.split("\n"));
26856
26867
  var _table$network;
26857
26868
  return (_table$network = table[network]) === null || _table$network === void 0 ? void 0 : _table$network[mint];
26858
26869
  };
26859
- var LAMPORTS_ASSET = "lamports";
26860
26870
  var u32 = getU32Decoder();
26861
26871
  var u64$1 = getU64Decoder();
26862
26872
  var u32le = (data, offset) => u32.decode(data, offset);
@@ -26920,7 +26930,7 @@ zoo`.split("\n"));
26920
26930
  "ata-create-idempotent"
26921
26931
  ]);
26922
26932
  var classify$1 = (parsed, calls, network, table) => {
26923
- if (parsed.lookupCount > 0) return "partial";
26933
+ if (parsed.lookups.length > 0) return "partial";
26924
26934
  let allFull = true;
26925
26935
  for (const call of calls) {
26926
26936
  var _call$mint;
@@ -26957,7 +26967,7 @@ zoo`.split("\n"));
26957
26967
  if (source === signer) outflows.push({
26958
26968
  to: call.to,
26959
26969
  amount: {
26960
- asset: LAMPORTS_ASSET,
26970
+ asset: SOLANA_NATIVE_ASSET,
26961
26971
  amount: ((_call$amount = call.amount) !== null && _call$amount !== void 0 ? _call$amount : 0n).toString(10)
26962
26972
  },
26963
26973
  verified: true
@@ -26994,7 +27004,7 @@ zoo`.split("\n"));
26994
27004
  outflows,
26995
27005
  approvals,
26996
27006
  fee: fee === void 0 ? void 0 : { max: {
26997
- asset: LAMPORTS_ASSET,
27007
+ asset: SOLANA_NATIVE_ASSET,
26998
27008
  amount: fee.toString(10)
26999
27009
  } },
27000
27010
  warnings: [],
@@ -29022,8 +29032,9 @@ zoo`.split("\n"));
29022
29032
  /**
29023
29033
  * Export `ncryptsec` at logN 16 with key security byte 0x02 ("the client does not track this" in
29024
29034
  * NIP-49's terms): the kernel does not track a key's handling history and any key can be exported
29025
- * as plaintext nsec, so 0x01 would never be honest. Salt and nonce come from the library's RNG
29026
- * (noble randomBytes); not injectable in 0.14.
29035
+ * as plaintext nsec, so 0x01 would never be honest. `nip49Encrypt` draws its salt and nonce from
29036
+ * `crypto.getRandomValues`, which the kernel runtime installs natively (the same source as
29037
+ * `__qntx.random`; in a Web Worker, the platform CSPRNG), so no API-level injection is needed.
29027
29038
  */
29028
29039
  async function ncryptsecFromSecretKey(secretKey, password) {
29029
29040
  const encoded = await encrypt(secretKey, decodeUtf8Secret(password), {
@@ -74,7 +74,7 @@
74
74
  "bundles": [
75
75
  {
76
76
  "file": "kernel-entry.js",
77
- "sha256": "9a88b81c129a6769220ea3a9fb4232070bd25f13c0462efd131cb1879a7e8f32"
77
+ "sha256": "2bd4984208b3bd796a5516f0afb65ec633b4ba25c5f24702fea5db83066abe3a"
78
78
  }
79
79
  ]
80
80
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qntx/wallet-native",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Native kernel runtime host for the qntx wallet — CBOR transport, KernelHost adapter and createNativeWallet",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": "QuantX <x@qntx.org>",
@@ -60,7 +60,7 @@
60
60
  "peerDependencies": {
61
61
  "@qntx/nostr-native": "0.15.3",
62
62
  "@qntx/spark-native": "0.5.2",
63
- "@qntx/wallet": "0.8.0",
63
+ "@qntx/wallet": "0.9.0",
64
64
  "react-native": "~0.88.0",
65
65
  "react-native-nitro-modules": "~0.37.1"
66
66
  }