@qntx/wallet 0.7.0 → 0.8.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 +2 -0
- package/dist/{chains-CuKVAJMN.d.mts → chains-BdcH4YnJ.d.mts} +2 -2
- package/dist/chains.d.mts +2 -2
- package/dist/host.d.mts +3 -2
- package/dist/host.mjs +1 -0
- package/dist/host.mjs.map +1 -1
- package/dist/{index-CIZzbqqv.d.mts → index-BXnQtz55.d.mts} +3 -3
- package/dist/index.d.mts +14 -2
- package/dist/internal-CAKfHjIg.mjs.map +1 -1
- package/dist/nostr.d.mts +1 -1
- package/dist/nostr.mjs +3 -3
- package/dist/nostr.mjs.map +1 -1
- package/dist/protocol.d.mts +3 -3
- package/dist/spark.d.mts +2 -2
- package/dist/{types-BgFsXgyI.d.mts → types-CIYT5uFj.d.mts} +2 -6
- package/dist/types.d.mts +2 -2
- package/dist/types.mjs.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -23,6 +23,8 @@ const wallet = await createWebWallet({
|
|
|
23
23
|
vaultSalt: "example/vault",
|
|
24
24
|
},
|
|
25
25
|
autoLock: { platform: "web", idleMinutes: 15 },
|
|
26
|
+
// Verifies every event the kernel signs; pass your app's native verifier where one exists.
|
|
27
|
+
verifyEvent,
|
|
26
28
|
});
|
|
27
29
|
|
|
28
30
|
// First run: create the wallet and register its passkey.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as WalletErrorCode, s as FactorInfo, x as WalletInfo } from "./types-
|
|
1
|
+
import { b as WalletErrorCode, s as FactorInfo, x as WalletInfo } from "./types-CIYT5uFj.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* Strict validator combinators for the secret-area protocol. Both sides share them: the kernel
|
|
4
4
|
* validates every request, the host validates every response. Anything that does not match is a
|
|
@@ -330,4 +330,4 @@ declare const CHAINS_METHODS: {
|
|
|
330
330
|
readonly "chain.sign": MethodSpec<ChainSignParams, ChainSignResult>;
|
|
331
331
|
};
|
|
332
332
|
export { validate as A, literal as C, record as D, opt as E, str as O, int as S, obj as T, ValidationError as _, ChainSignResult as a, bool as b, BackupUnlockFactor as c, CreatedResult as d, Factor as f, NullValue as g, walletErrorCode as h, ChainSignRequest as i, union as k, CORE_METHODS as l, RestoreWithPasskeyParams as m, ChainAccount as n, ChainTemplate as o, MethodSpec as p, ChainAccountsParams as r, BackupFactor as s, CHAINS_METHODS as t, CreateWithPasskeyParams as u, Validator as v, nullValue as w, bytes as x, arr as y };
|
|
333
|
-
//# sourceMappingURL=chains-
|
|
333
|
+
//# sourceMappingURL=chains-BdcH4YnJ.d.mts.map
|
package/dist/chains.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as UnlockFactor, v as Wallet } from "./types-
|
|
2
|
-
import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-
|
|
1
|
+
import { h as UnlockFactor, v as Wallet } from "./types-CIYT5uFj.mjs";
|
|
2
|
+
import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-BdcH4YnJ.mjs";
|
|
3
3
|
export type ChainsApi = {
|
|
4
4
|
readonly account: (params: ChainAccountsParams) => Promise<ChainAccount>;
|
|
5
5
|
readonly sign: (params: {
|
package/dist/host.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { p as PasskeyConfig, v as Wallet } from "./types-
|
|
2
|
-
import { l as ProtocolValue } from "./index-
|
|
1
|
+
import { p as PasskeyConfig, v as Wallet } from "./types-CIYT5uFj.mjs";
|
|
2
|
+
import { et as SignedEvent, l as ProtocolValue } from "./index-BXnQtz55.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock
|
|
5
5
|
* triggered by the platform (native background expiry — W7).
|
|
@@ -57,6 +57,7 @@ type ConnectOptions = {
|
|
|
57
57
|
/** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */
|
|
58
58
|
readonly factors: FactorMode;
|
|
59
59
|
readonly passkey: PasskeyConfig;
|
|
60
|
+
readonly verifyEvent: (event: SignedEvent) => boolean;
|
|
60
61
|
readonly ceremony: PasskeyCeremony | undefined;
|
|
61
62
|
/** Timer source injected by the host package (globalThis timers on web/node). */
|
|
62
63
|
readonly setTimer: SetTimer;
|
package/dist/host.mjs
CHANGED
|
@@ -72,6 +72,7 @@ var KernelWallet = class KernelWallet {
|
|
|
72
72
|
call: async (method, params, transfer) => this.channel.call(method, params, transfer),
|
|
73
73
|
ready: async () => this.channel.ready,
|
|
74
74
|
snapshot: () => this.snapshotValue,
|
|
75
|
+
verifyEvent: options.verifyEvent,
|
|
75
76
|
withVerifying: async (fn) => this.withVerifying(fn),
|
|
76
77
|
resolveFactor: async (factor, transfer) => resolveFactor(this.factorSource, factor, transfer),
|
|
77
78
|
createFactorParam: async (factor, transfer) => this.createFactorParam(factor, transfer),
|
package/dist/host.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.mjs","names":[],"sources":["../src/wallet.ts"],"sourcesContent":["/**\n * The host-facing `Wallet` (design/entry.mdx \"API\"): snapshot state, the core API groups, and the\n * glue between the kernel `Channel` and factor resolution. `connectKernel` is exported under the\n * `./host` subpath — reserved for host packages; applications must not use it. Protocol modules\n * (@qntx/wallet/nostr and future siblings) reach this wallet's channel through the registered\n * internals in internal.ts — never through the public type.\n */\nimport { Channel } from \"./channel.ts\";\nimport type { MainPort, SetTimer } from \"./channel.ts\";\nimport {\n PASSKEY_PURPOSE_WALLET,\n passkeyName,\n requireCeremony,\n resolveFactor,\n resolveInitialFactor,\n vaultSaltBytes,\n walletSaltBytes,\n wireBytes,\n wireSecretText,\n resolveBackupFactor,\n resolveBackupUnlockFactor,\n defaultUnlockFactor,\n} from \"./factors.ts\";\nimport type { FactorMode, FactorSource, PasskeyCeremony, PrfResult } from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupApi,\n DataKeyApi,\n ExportedSecret,\n FactorInfo,\n InitialFactor,\n LockReason,\n MnemonicDraft,\n PasskeyConfig,\n StatusPayload,\n UnlockFactor,\n VaultApi,\n Wallet,\n WalletInfo,\n WalletSnapshot,\n WalletsApi,\n} from \"./types.ts\";\n\nexport type ConnectOptions = {\n readonly spawn: () => MainPort;\n /** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */\n readonly factors: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly ceremony: PasskeyCeremony | undefined;\n /** Timer source injected by the host package (globalThis timers on web/node). */\n readonly setTimer: SetTimer;\n /**\n * User-presence source: subscribes to activity signals and returns an unsubscribe the wallet\n * owns. Absent means the host has no presence signals (the kernel policy decides what counts).\n */\n readonly presence?: (onActivity: () => void) => () => void;\n /** Runs once inside `destroy()` — host-side cleanup (page listeners, timers). */\n readonly onDestroy?: () => void;\n};\n\n/** One `session.touch` at most per interval — the idle deadline slips at most this much early. */\nexport const PRESENCE_TOUCH_INTERVAL_MS = 30_000;\n\n/** Structural equality over plain snapshot data (validated protocol payloads only). */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((item, index) => deepEqual(item, b[index]))\n );\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every(\n (key) =>\n key in b &&\n deepEqual(\n (a as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n (b as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n ),\n )\n );\n}\n\nexport class KernelWallet implements Wallet {\n private readonly channel: Channel;\n private readonly factorMode: FactorMode;\n private readonly passkeyCfg: PasskeyConfig;\n private readonly ceremony: PasskeyCeremony | undefined;\n private readonly setTimer: SetTimer;\n private readonly onDestroy: (() => void) | undefined;\n private readonly unsubscribePresence: (() => void) | undefined;\n private presenceCooling = false;\n private cancelCooldown: (() => void) | undefined;\n private destroyed = false;\n\n private status: StatusPayload | undefined;\n private lockReason: LockReason | undefined;\n private verifying = 0;\n private snapshotValue: WalletSnapshot;\n private readonly listeners = new Set<() => void>();\n\n private constructor(options: ConnectOptions) {\n this.factorMode = options.factors;\n this.passkeyCfg = options.passkey;\n this.ceremony = options.ceremony;\n this.setTimer = options.setTimer;\n this.onDestroy = options.onDestroy;\n this.snapshotValue = {\n vault: \"uninitialized\",\n lockReason: undefined,\n verifying: false,\n factors: [],\n wallets: [],\n nostr: { keys: [] },\n backup: null,\n };\n this.channel = new Channel(\n options.spawn,\n {\n onStatus: (status) => {\n this.onStatus(status);\n },\n onLocked: (reason) => {\n this.lockReason = reason;\n this.markLocked();\n },\n onCrashed: () => {\n this.lockReason = \"crashed\";\n this.markLocked();\n },\n },\n options.setTimer,\n );\n // The wallet owns the subscription it creates: destroy() unsubscribes — no second owner.\n this.unsubscribePresence = options.presence?.(() => {\n this.onPresence();\n });\n registerInternals(this, {\n call: async (method, params, transfer) => this.channel.call(method, params, transfer),\n ready: async () => this.channel.ready,\n snapshot: () => this.snapshotValue,\n withVerifying: async (fn) => this.withVerifying(fn),\n resolveFactor: async (factor, transfer) => resolveFactor(this.factorSource, factor, transfer),\n createFactorParam: async (factor, transfer) => this.createFactorParam(factor, transfer),\n sessionOf: (result) => {\n this.sessionOf(result);\n },\n });\n }\n\n static async connect(options: ConnectOptions): Promise<KernelWallet> {\n const wallet = new KernelWallet(options);\n await wallet.channel.start();\n return wallet;\n }\n\n /** Runs a host-ceremony passkey call and adopts the returned session and wallet info. */\n private async hostPasskeyWallet(\n method: \"wallet.createWithPasskey\" | \"wallet.restoreWithPasskey\",\n result: PrfResult,\n factor: Factor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<WalletInfo> {\n const created = await this.channel.call(\n method,\n {\n ceremony: \"host\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfWallet: wireBytes(result.first, transfer, true),\n synced: result.synced,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n\n /**\n * Presence refresh, throttled to one touch per interval: once a touch fires, signals are ignored\n * until the cooldown elapses — no clock reads, just the injected timer. Touches only go out while\n * a session is held; failures are silent (a lock or respawn needs no handling).\n */\n private onPresence(): void {\n if (this.presenceCooling || this.destroyed || this.channel.session === undefined) {\n return;\n }\n this.presenceCooling = true;\n this.cancelCooldown = this.setTimer(PRESENCE_TOUCH_INTERVAL_MS, () => {\n this.presenceCooling = false;\n this.cancelCooldown = undefined;\n });\n void this.touchSession();\n }\n\n private async touchSession(): Promise<void> {\n try {\n await this.channel.call(\"session.touch\", null);\n } catch {\n // A racing lock or respawn needs no handling.\n }\n }\n\n /**\n * The worker is dead or replaced — no status will arrive from it, yet an unlocked vault is locked\n * now. Reflect that in the snapshot without waiting for the respawned kernel; other states\n * (uninitialized, corrupted, …) are the kernel's truth and stay untouched.\n */\n private markLocked(): void {\n if (this.status !== undefined && this.status.vault === \"unlocked\") {\n this.status = { ...this.status, vault: \"locked\" };\n }\n this.emit();\n }\n\n private onStatus(status: StatusPayload): void {\n if (this.lockReason === undefined && status.vault === \"locked\") {\n this.lockReason = \"cold-start\"; // locked at first sight, not by an action of ours\n }\n this.status = status;\n this.emit();\n }\n\n /**\n * Rebuilds the immutable snapshot and notifies subscribers — only when the content actually\n * changed (identical status events produce no new reference and no notification).\n */\n private emit(): void {\n const { status } = this;\n const next: WalletSnapshot = {\n vault: status === undefined ? \"uninitialized\" : status.vault,\n lockReason: this.lockReason,\n verifying: this.verifying > 0,\n factors: status === undefined ? [] : status.factors,\n wallets: status === undefined ? [] : status.wallets,\n nostr: { keys: status === undefined ? [] : status.nostr.keys },\n backup: status === undefined ? null : status.backup,\n };\n const current = this.snapshotValue;\n if (\n current.vault === next.vault &&\n current.lockReason === next.lockReason &&\n current.verifying === next.verifying &&\n deepEqual(current.factors, next.factors) &&\n deepEqual(current.wallets, next.wallets) &&\n deepEqual(current.nostr, next.nostr) &&\n deepEqual(current.backup, next.backup)\n ) {\n return;\n }\n this.snapshotValue = next;\n for (const listener of this.listeners) {\n listener();\n }\n }\n\n // Arrow properties: safe unbound, e.g. useSyncExternalStore(wallet.subscribe, wallet.getSnapshot).\n readonly getSnapshot = (): WalletSnapshot => this.snapshotValue;\n\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n private get factorSource(): FactorSource {\n return {\n mode: this.factorMode,\n passkey: this.passkeyCfg,\n ceremony: this.ceremony,\n factors: () => this.snapshotValue.factors,\n };\n }\n\n /** True while a ceremony or a factor-bearing request is in flight; drives `verifying`. */\n private async withVerifying<T>(fn: () => Promise<T>): Promise<T> {\n this.verifying++;\n this.emit();\n try {\n return await fn();\n } finally {\n this.verifying--;\n this.emit();\n }\n }\n\n private initialized(): boolean {\n return this.snapshotValue.vault !== \"uninitialized\";\n }\n\n /** The factor gate on create/import commands; keeps useless ceremonies from firing. */\n private async createFactorParam(\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<Factor | undefined> {\n if (this.initialized()) {\n if (factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n return undefined;\n }\n if (factor === undefined && this.factorMode === \"software\") {\n throw new WalletError(\"invalid-input\", \"an initial factor is required\");\n }\n return resolveInitialFactor(this.factorSource, factor, transfer);\n }\n\n private sessionOf(result: { readonly session: string }): void {\n this.channel.session = result.session;\n this.channel.flushStatus();\n }\n\n readonly vault: VaultApi = {\n unlock: async (factor?: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wire = await resolveFactor(\n this.factorSource,\n factor ?? defaultUnlockFactor(this.factorSource),\n transfer,\n );\n const result = await this.channel.call(\"vault.unlock\", { factor: wire }, transfer);\n this.sessionOf(result);\n }),\n // Host-side lock: immediate, no kernel round trip — fails pending calls, clears the session\n // and respawns the port. Idempotent: re-locking is a no-op.\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n lock: async (): Promise<void> => {\n this.channel.lockNow();\n this.markLocked();\n },\n addFactor: async (factor: InitialFactor, verify: UnlockFactor): Promise<FactorInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const wireFactor = await resolveInitialFactor(this.factorSource, factor, transfer);\n return this.channel.call(\n \"vault.addFactor\",\n { verify: wireVerify, factor: wireFactor },\n transfer,\n );\n }),\n removeFactor: async (id: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"vault.removeFactor\", { verify: wireVerify, id }, transfer);\n }),\n reset: async (): Promise<void> => {\n await this.channel.call(\"vault.reset\", null);\n },\n };\n\n readonly wallets: WalletsApi = {\n createWithPasskey: async (options: {\n readonly name: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const name = passkeyName(options.name);\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n // The kernel runs the platform ceremony: nothing secret crosses the channel.\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n rpName: this.passkeyCfg.rpName,\n name,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.create({\n purpose: \"wallet\",\n name,\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0); // the vault factor slot is not needed\n } else {\n factor = await resolveInitialFactor(this.factorSource, options.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.createWithPasskey\", result, factor, transfer);\n }),\n restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n const factor = await this.createFactorParam(options?.factor, transfer);\n const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.assert({\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n // The asserted credential must be a wallet-purpose passkey: a vault-purpose credential\n // would silently derive a different wallet. Rejected assertions never reach the kernel.\n if (result.userHandle?.[0] !== PASSKEY_PURPOSE_WALLET) {\n result.first.fill(0);\n result.second?.fill(0);\n throw new WalletError(\"wrong-passkey\", \"the passkey is not a wallet credential\");\n }\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options?.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0);\n } else {\n factor = await resolveInitialFactor(this.factorSource, options?.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.restoreWithPasskey\", result, factor, transfer);\n }),\n createMnemonic: async (options: {\n readonly words: 12 | 24;\n readonly factor?: InitialFactor;\n }): Promise<MnemonicDraft> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createMnemonic\",\n { words: options.words, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n const draftId = created.draft;\n return {\n words: new SingleUseSecret(created.words),\n quiz: created.quiz,\n confirm: async (answers: ReadonlyArray<string>): Promise<WalletInfo> => {\n const answerTransfer: ArrayBuffer[] = [];\n const encoded = answers.map((word) => wireSecretText(word, answerTransfer));\n const confirmed = await this.channel.call(\n \"wallet.confirmMnemonic\",\n { draft: draftId, answers: encoded },\n answerTransfer,\n );\n this.sessionOf(confirmed);\n return confirmed.wallet;\n },\n discard: async (): Promise<void> => {\n await this.channel.call(\"wallet.discardMnemonic\", { draft: draftId });\n },\n };\n },\n importMnemonic: async (options: {\n readonly mnemonic: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const mnemonic = wireSecretText(options.mnemonic, transfer);\n const created = await this.channel.call(\n \"wallet.importMnemonic\",\n { mnemonic, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n },\n exportMnemonic: async (walletId: string, verify: UnlockFactor): Promise<ExportedSecret> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const bytes = await this.channel.call(\n \"wallet.exportMnemonic\",\n { verify: wireVerify, walletId },\n transfer,\n );\n return new SingleUseSecret(bytes);\n }),\n delete: async (walletId: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"wallet.delete\", { verify: wireVerify, walletId }, transfer);\n }),\n };\n\n readonly dataKeys: DataKeyApi = {\n get: async (purpose: string): Promise<Uint8Array> =>\n this.channel.call(\"dataKeys.get\", { purpose }),\n };\n\n readonly backup: BackupApi = {\n enable: async (options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, options.verify, transfer);\n const wireFactors = await Promise.all(\n options.factors.map(async (factor) =>\n resolveBackupFactor(this.factorSource, factor, transfer),\n ),\n );\n await this.channel.call(\n \"backup.enable\",\n { verify: wireVerify, factors: wireFactors },\n transfer,\n );\n }),\n update: async (): Promise<string> => {\n const result = await this.channel.call(\"backup.update\", null);\n return result.envelope;\n },\n disable: async (): Promise<void> => {\n await this.channel.call(\"backup.disable\", null);\n },\n restore: async (options: {\n readonly envelope: string;\n readonly backupFactor: UnlockFactor;\n readonly factor?: InitialFactor;\n }): Promise<ReadonlyArray<WalletInfo>> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const backupFactor = await resolveBackupUnlockFactor(\n this.factorSource,\n options.backupFactor,\n transfer,\n );\n const factor = await this.createFactorParam(options.factor, transfer);\n const result = await this.channel.call(\n \"backup.restore\",\n {\n envelope: options.envelope,\n backupFactor,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(result);\n return result.wallets;\n }),\n };\n\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unsubscribePresence?.();\n this.cancelCooldown?.();\n this.onDestroy?.();\n this.channel.destroy();\n }\n}\n\n/**\n * Validates the passkey configuration: the RP identity and both PRF salts are permanent\n * identifiers, so an empty or colliding value is rejected here rather than producing unrecoverable\n * credentials later.\n */\nfunction checkPasskeyConfig(passkey: PasskeyConfig): void {\n const { rpId, rpName, walletSalt, vaultSalt, backupSalt } = passkey;\n if (\n rpId.length === 0 ||\n rpName.length === 0 ||\n walletSalt.length === 0 ||\n vaultSalt.length === 0 ||\n backupSalt.length === 0 ||\n walletSalt === vaultSalt ||\n backupSalt === vaultSalt ||\n backupSalt === walletSalt\n ) {\n throw new WalletError(\n \"invalid-input\",\n \"passkey config requires a non-empty rpId, rpName and two different salts\",\n );\n }\n}\n\n/**\n * Connects a kernel spawned by the host package and returns the host-facing `Wallet`. The first\n * spawn must deliver a status event before this resolves.\n */\nexport async function connectKernel(options: ConnectOptions): Promise<Wallet> {\n checkPasskeyConfig(options.passkey);\n return KernelWallet.connect(options);\n}\n"],"mappings":";;;;;;;;;;;;;AAgEA,MAAa,6BAA6B;;AAG1C,SAAS,UAAU,GAAY,GAAqB;CAClD,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAO,MAAM,YAAY,MAAM,MACxE,OAAO;CAET,IAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAAQ,CAAC,GACrC,OACE,MAAM,QAAQ,CAAC,KACf,MAAM,QAAQ,CAAC,KACf,EAAE,WAAW,EAAE,UACf,EAAE,OAAO,MAAM,UAAU,UAAU,MAAM,EAAE,MAAM,CAAC;CAGtD,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,OACE,MAAM,WAAW,MAAM,UACvB,MAAM,OACH,QACC,OAAO,KACP,UACG,EAA8B,MAC9B,EAA8B,IACjC,CACJ;AAEJ;AAEA,IAAa,eAAb,MAAa,aAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA,kBAA0B;CAC1B;CACA,YAAoB;CAEpB;CACA;CACA,YAAoB;CACpB;CACA,4BAA6B,IAAI,IAAgB;CAEjD,YAAoB,SAAyB;EAC3C,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ;EAC1B,KAAK,WAAW,QAAQ;EACxB,KAAK,WAAW,QAAQ;EACxB,KAAK,YAAY,QAA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E,OAAO;GAC3C,GACA,QACF;GACA,KAAK,UAAU,MAAM;GACrB,OAAO,OAAO;EAChB,CAAC;CACL;CAGA,MAAM,UAAyB;EAC7B,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,sBAAsB;EAC3B,KAAK,iBAAiB;EACtB,KAAK,YAAY;EACjB,KAAK,QAAQ,QAAQ;CACvB;AACF;;;;;;AAOA,SAAS,mBAAmB,SAA8B;CACxD,MAAM,EAAE,MAAM,QAAQ,YAAY,WAAW,eAAe;CAC5D,IACE,KAAK,WAAW,KAChB,OAAO,WAAW,KAClB,WAAW,WAAW,KACtB,UAAU,WAAW,KACrB,WAAW,WAAW,KACtB,eAAe,aACf,eAAe,aACf,eAAe,YAEf,MAAM,IAAI,YACR,iBACA,0EACF;AAEJ;;;;;AAMA,eAAsB,cAAc,SAA0C;CAC5E,mBAAmB,QAAQ,OAAO;CAClC,OAAO,aAAa,QAAQ,OAAO;AACrC"}
|
|
1
|
+
{"version":3,"file":"host.mjs","names":[],"sources":["../src/wallet.ts"],"sourcesContent":["/**\n * The host-facing `Wallet` (design/entry.mdx \"API\"): snapshot state, the core API groups, and the\n * glue between the kernel `Channel` and factor resolution. `connectKernel` is exported under the\n * `./host` subpath — reserved for host packages; applications must not use it. Protocol modules\n * (@qntx/wallet/nostr and future siblings) reach this wallet's channel through the registered\n * internals in internal.ts — never through the public type.\n */\n\nimport { Channel } from \"./channel.ts\";\nimport type { MainPort, SetTimer } from \"./channel.ts\";\nimport {\n PASSKEY_PURPOSE_WALLET,\n passkeyName,\n requireCeremony,\n resolveFactor,\n resolveInitialFactor,\n vaultSaltBytes,\n walletSaltBytes,\n wireBytes,\n wireSecretText,\n resolveBackupFactor,\n resolveBackupUnlockFactor,\n defaultUnlockFactor,\n} from \"./factors.ts\";\nimport type { FactorMode, FactorSource, PasskeyCeremony, PrfResult } from \"./factors.ts\";\nimport { registerInternals } from \"./internal.ts\";\nimport type { Factor, SignedEvent } from \"./protocol/index.ts\";\nimport { SingleUseSecret } from \"./secret.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type {\n BackupApi,\n DataKeyApi,\n ExportedSecret,\n FactorInfo,\n InitialFactor,\n LockReason,\n MnemonicDraft,\n PasskeyConfig,\n StatusPayload,\n UnlockFactor,\n VaultApi,\n Wallet,\n WalletInfo,\n WalletSnapshot,\n WalletsApi,\n} from \"./types.ts\";\n\nexport type ConnectOptions = {\n readonly spawn: () => MainPort;\n /** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */\n readonly factors: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly verifyEvent: (event: SignedEvent) => boolean;\n readonly ceremony: PasskeyCeremony | undefined;\n /** Timer source injected by the host package (globalThis timers on web/node). */\n readonly setTimer: SetTimer;\n /**\n * User-presence source: subscribes to activity signals and returns an unsubscribe the wallet\n * owns. Absent means the host has no presence signals (the kernel policy decides what counts).\n */\n readonly presence?: (onActivity: () => void) => () => void;\n /** Runs once inside `destroy()` — host-side cleanup (page listeners, timers). */\n readonly onDestroy?: () => void;\n};\n\n/** One `session.touch` at most per interval — the idle deadline slips at most this much early. */\nexport const PRESENCE_TOUCH_INTERVAL_MS = 30_000;\n\n/** Structural equality over plain snapshot data (validated protocol payloads only). */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) {\n return false;\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((item, index) => deepEqual(item, b[index]))\n );\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every(\n (key) =>\n key in b &&\n deepEqual(\n (a as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n (b as Record<string, unknown>)[key], // oxlint-disable-line typescript/no-unsafe-type-assertion -- plain-object records\n ),\n )\n );\n}\n\nexport class KernelWallet implements Wallet {\n private readonly channel: Channel;\n private readonly factorMode: FactorMode;\n private readonly passkeyCfg: PasskeyConfig;\n private readonly ceremony: PasskeyCeremony | undefined;\n private readonly setTimer: SetTimer;\n private readonly onDestroy: (() => void) | undefined;\n private readonly unsubscribePresence: (() => void) | undefined;\n private presenceCooling = false;\n private cancelCooldown: (() => void) | undefined;\n private destroyed = false;\n\n private status: StatusPayload | undefined;\n private lockReason: LockReason | undefined;\n private verifying = 0;\n private snapshotValue: WalletSnapshot;\n private readonly listeners = new Set<() => void>();\n\n private constructor(options: ConnectOptions) {\n this.factorMode = options.factors;\n this.passkeyCfg = options.passkey;\n this.ceremony = options.ceremony;\n this.setTimer = options.setTimer;\n this.onDestroy = options.onDestroy;\n this.snapshotValue = {\n vault: \"uninitialized\",\n lockReason: undefined,\n verifying: false,\n factors: [],\n wallets: [],\n nostr: { keys: [] },\n backup: null,\n };\n this.channel = new Channel(\n options.spawn,\n {\n onStatus: (status) => {\n this.onStatus(status);\n },\n onLocked: (reason) => {\n this.lockReason = reason;\n this.markLocked();\n },\n onCrashed: () => {\n this.lockReason = \"crashed\";\n this.markLocked();\n },\n },\n options.setTimer,\n );\n // The wallet owns the subscription it creates: destroy() unsubscribes — no second owner.\n this.unsubscribePresence = options.presence?.(() => {\n this.onPresence();\n });\n registerInternals(this, {\n call: async (method, params, transfer) => this.channel.call(method, params, transfer),\n ready: async () => this.channel.ready,\n snapshot: () => this.snapshotValue,\n verifyEvent: options.verifyEvent,\n withVerifying: async (fn) => this.withVerifying(fn),\n resolveFactor: async (factor, transfer) => resolveFactor(this.factorSource, factor, transfer),\n createFactorParam: async (factor, transfer) => this.createFactorParam(factor, transfer),\n sessionOf: (result) => {\n this.sessionOf(result);\n },\n });\n }\n\n static async connect(options: ConnectOptions): Promise<KernelWallet> {\n const wallet = new KernelWallet(options);\n await wallet.channel.start();\n return wallet;\n }\n\n /** Runs a host-ceremony passkey call and adopts the returned session and wallet info. */\n private async hostPasskeyWallet(\n method: \"wallet.createWithPasskey\" | \"wallet.restoreWithPasskey\",\n result: PrfResult,\n factor: Factor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<WalletInfo> {\n const created = await this.channel.call(\n method,\n {\n ceremony: \"host\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfWallet: wireBytes(result.first, transfer, true),\n synced: result.synced,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n\n /**\n * Presence refresh, throttled to one touch per interval: once a touch fires, signals are ignored\n * until the cooldown elapses — no clock reads, just the injected timer. Touches only go out while\n * a session is held; failures are silent (a lock or respawn needs no handling).\n */\n private onPresence(): void {\n if (this.presenceCooling || this.destroyed || this.channel.session === undefined) {\n return;\n }\n this.presenceCooling = true;\n this.cancelCooldown = this.setTimer(PRESENCE_TOUCH_INTERVAL_MS, () => {\n this.presenceCooling = false;\n this.cancelCooldown = undefined;\n });\n void this.touchSession();\n }\n\n private async touchSession(): Promise<void> {\n try {\n await this.channel.call(\"session.touch\", null);\n } catch {\n // A racing lock or respawn needs no handling.\n }\n }\n\n /**\n * The worker is dead or replaced — no status will arrive from it, yet an unlocked vault is locked\n * now. Reflect that in the snapshot without waiting for the respawned kernel; other states\n * (uninitialized, corrupted, …) are the kernel's truth and stay untouched.\n */\n private markLocked(): void {\n if (this.status !== undefined && this.status.vault === \"unlocked\") {\n this.status = { ...this.status, vault: \"locked\" };\n }\n this.emit();\n }\n\n private onStatus(status: StatusPayload): void {\n if (this.lockReason === undefined && status.vault === \"locked\") {\n this.lockReason = \"cold-start\"; // locked at first sight, not by an action of ours\n }\n this.status = status;\n this.emit();\n }\n\n /**\n * Rebuilds the immutable snapshot and notifies subscribers — only when the content actually\n * changed (identical status events produce no new reference and no notification).\n */\n private emit(): void {\n const { status } = this;\n const next: WalletSnapshot = {\n vault: status === undefined ? \"uninitialized\" : status.vault,\n lockReason: this.lockReason,\n verifying: this.verifying > 0,\n factors: status === undefined ? [] : status.factors,\n wallets: status === undefined ? [] : status.wallets,\n nostr: { keys: status === undefined ? [] : status.nostr.keys },\n backup: status === undefined ? null : status.backup,\n };\n const current = this.snapshotValue;\n if (\n current.vault === next.vault &&\n current.lockReason === next.lockReason &&\n current.verifying === next.verifying &&\n deepEqual(current.factors, next.factors) &&\n deepEqual(current.wallets, next.wallets) &&\n deepEqual(current.nostr, next.nostr) &&\n deepEqual(current.backup, next.backup)\n ) {\n return;\n }\n this.snapshotValue = next;\n for (const listener of this.listeners) {\n listener();\n }\n }\n\n // Arrow properties: safe unbound, e.g. useSyncExternalStore(wallet.subscribe, wallet.getSnapshot).\n readonly getSnapshot = (): WalletSnapshot => this.snapshotValue;\n\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n private get factorSource(): FactorSource {\n return {\n mode: this.factorMode,\n passkey: this.passkeyCfg,\n ceremony: this.ceremony,\n factors: () => this.snapshotValue.factors,\n };\n }\n\n /** True while a ceremony or a factor-bearing request is in flight; drives `verifying`. */\n private async withVerifying<T>(fn: () => Promise<T>): Promise<T> {\n this.verifying++;\n this.emit();\n try {\n return await fn();\n } finally {\n this.verifying--;\n this.emit();\n }\n }\n\n private initialized(): boolean {\n return this.snapshotValue.vault !== \"uninitialized\";\n }\n\n /** The factor gate on create/import commands; keeps useless ceremonies from firing. */\n private async createFactorParam(\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n ): Promise<Factor | undefined> {\n if (this.initialized()) {\n if (factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n return undefined;\n }\n if (factor === undefined && this.factorMode === \"software\") {\n throw new WalletError(\"invalid-input\", \"an initial factor is required\");\n }\n return resolveInitialFactor(this.factorSource, factor, transfer);\n }\n\n private sessionOf(result: { readonly session: string }): void {\n this.channel.session = result.session;\n this.channel.flushStatus();\n }\n\n readonly vault: VaultApi = {\n unlock: async (factor?: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wire = await resolveFactor(\n this.factorSource,\n factor ?? defaultUnlockFactor(this.factorSource),\n transfer,\n );\n const result = await this.channel.call(\"vault.unlock\", { factor: wire }, transfer);\n this.sessionOf(result);\n }),\n // Host-side lock: immediate, no kernel round trip — fails pending calls, clears the session\n // and respawns the port. Idempotent: re-locking is a no-op.\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n lock: async (): Promise<void> => {\n this.channel.lockNow();\n this.markLocked();\n },\n addFactor: async (factor: InitialFactor, verify: UnlockFactor): Promise<FactorInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const wireFactor = await resolveInitialFactor(this.factorSource, factor, transfer);\n return this.channel.call(\n \"vault.addFactor\",\n { verify: wireVerify, factor: wireFactor },\n transfer,\n );\n }),\n removeFactor: async (id: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"vault.removeFactor\", { verify: wireVerify, id }, transfer);\n }),\n reset: async (): Promise<void> => {\n await this.channel.call(\"vault.reset\", null);\n },\n };\n\n readonly wallets: WalletsApi = {\n createWithPasskey: async (options: {\n readonly name: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const name = passkeyName(options.name);\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n // The kernel runs the platform ceremony: nothing secret crosses the channel.\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n rpName: this.passkeyCfg.rpName,\n name,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.create({\n purpose: \"wallet\",\n name,\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0); // the vault factor slot is not needed\n } else {\n factor = await resolveInitialFactor(this.factorSource, options.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.createWithPasskey\", result, factor, transfer);\n }),\n restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n if (this.factorMode === \"hardware\") {\n const factor = await this.createFactorParam(options?.factor, transfer);\n const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\n {\n ceremony: \"kernel\",\n rpId: this.passkeyCfg.rpId,\n walletSalt: this.passkeyCfg.walletSalt,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }\n const ceremony = requireCeremony(this.factorSource);\n const result = await ceremony.assert({\n salts: {\n first: walletSaltBytes(this.factorSource),\n second: vaultSaltBytes(this.factorSource),\n },\n });\n // The asserted credential must be a wallet-purpose passkey: a vault-purpose credential\n // would silently derive a different wallet. Rejected assertions never reach the kernel.\n if (result.userHandle?.[0] !== PASSKEY_PURPOSE_WALLET) {\n result.first.fill(0);\n result.second?.fill(0);\n throw new WalletError(\"wrong-passkey\", \"the passkey is not a wallet credential\");\n }\n let factor: Factor | undefined;\n if (this.initialized()) {\n if (options?.factor !== undefined) {\n throw new WalletError(\"invalid-input\", \"the vault is already initialized\");\n }\n result.second?.fill(0);\n } else {\n factor = await resolveInitialFactor(this.factorSource, options?.factor, transfer, result);\n }\n return this.hostPasskeyWallet(\"wallet.restoreWithPasskey\", result, factor, transfer);\n }),\n createMnemonic: async (options: {\n readonly words: 12 | 24;\n readonly factor?: InitialFactor;\n }): Promise<MnemonicDraft> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const created = await this.channel.call(\n \"wallet.createMnemonic\",\n { words: options.words, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n const draftId = created.draft;\n return {\n words: new SingleUseSecret(created.words),\n quiz: created.quiz,\n confirm: async (answers: ReadonlyArray<string>): Promise<WalletInfo> => {\n const answerTransfer: ArrayBuffer[] = [];\n const encoded = answers.map((word) => wireSecretText(word, answerTransfer));\n const confirmed = await this.channel.call(\n \"wallet.confirmMnemonic\",\n { draft: draftId, answers: encoded },\n answerTransfer,\n );\n this.sessionOf(confirmed);\n return confirmed.wallet;\n },\n discard: async (): Promise<void> => {\n await this.channel.call(\"wallet.discardMnemonic\", { draft: draftId });\n },\n };\n },\n importMnemonic: async (options: {\n readonly mnemonic: string;\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await this.createFactorParam(options.factor, transfer);\n const mnemonic = wireSecretText(options.mnemonic, transfer);\n const created = await this.channel.call(\n \"wallet.importMnemonic\",\n { mnemonic, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n },\n exportMnemonic: async (walletId: string, verify: UnlockFactor): Promise<ExportedSecret> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n const bytes = await this.channel.call(\n \"wallet.exportMnemonic\",\n { verify: wireVerify, walletId },\n transfer,\n );\n return new SingleUseSecret(bytes);\n }),\n delete: async (walletId: string, verify: UnlockFactor): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, verify, transfer);\n await this.channel.call(\"wallet.delete\", { verify: wireVerify, walletId }, transfer);\n }),\n };\n\n readonly dataKeys: DataKeyApi = {\n get: async (purpose: string): Promise<Uint8Array> =>\n this.channel.call(\"dataKeys.get\", { purpose }),\n };\n\n readonly backup: BackupApi = {\n enable: async (options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }): Promise<void> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await resolveFactor(this.factorSource, options.verify, transfer);\n const wireFactors = await Promise.all(\n options.factors.map(async (factor) =>\n resolveBackupFactor(this.factorSource, factor, transfer),\n ),\n );\n await this.channel.call(\n \"backup.enable\",\n { verify: wireVerify, factors: wireFactors },\n transfer,\n );\n }),\n update: async (): Promise<string> => {\n const result = await this.channel.call(\"backup.update\", null);\n return result.envelope;\n },\n disable: async (): Promise<void> => {\n await this.channel.call(\"backup.disable\", null);\n },\n restore: async (options: {\n readonly envelope: string;\n readonly backupFactor: UnlockFactor;\n readonly factor?: InitialFactor;\n }): Promise<ReadonlyArray<WalletInfo>> =>\n this.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const backupFactor = await resolveBackupUnlockFactor(\n this.factorSource,\n options.backupFactor,\n transfer,\n );\n const factor = await this.createFactorParam(options.factor, transfer);\n const result = await this.channel.call(\n \"backup.restore\",\n {\n envelope: options.envelope,\n backupFactor,\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(result);\n return result.wallets;\n }),\n };\n\n // oxlint-disable-next-line typescript/require-await -- the interface's Promise is resolved synchronously\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unsubscribePresence?.();\n this.cancelCooldown?.();\n this.onDestroy?.();\n this.channel.destroy();\n }\n}\n\n/**\n * Validates the passkey configuration: the RP identity and both PRF salts are permanent\n * identifiers, so an empty or colliding value is rejected here rather than producing unrecoverable\n * credentials later.\n */\nfunction checkPasskeyConfig(passkey: PasskeyConfig): void {\n const { rpId, rpName, walletSalt, vaultSalt, backupSalt } = passkey;\n if (\n rpId.length === 0 ||\n rpName.length === 0 ||\n walletSalt.length === 0 ||\n vaultSalt.length === 0 ||\n backupSalt.length === 0 ||\n walletSalt === vaultSalt ||\n backupSalt === vaultSalt ||\n backupSalt === walletSalt\n ) {\n throw new WalletError(\n \"invalid-input\",\n \"passkey config requires a non-empty rpId, rpName and two different salts\",\n );\n }\n}\n\n/**\n * Connects a kernel spawned by the host package and returns the host-facing `Wallet`. The first\n * spawn must deliver a status event before this resolves.\n */\nexport async function connectKernel(options: ConnectOptions): Promise<Wallet> {\n checkPasskeyConfig(options.passkey);\n return KernelWallet.connect(options);\n}\n"],"mappings":";;;;;;;;;;;;;AAkEA,MAAa,6BAA6B;;AAG1C,SAAS,UAAU,GAAY,GAAqB;CAClD,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAO,MAAM,YAAY,MAAM,MACxE,OAAO;CAET,IAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAAQ,CAAC,GACrC,OACE,MAAM,QAAQ,CAAC,KACf,MAAM,QAAQ,CAAC,KACf,EAAE,WAAW,EAAE,UACf,EAAE,OAAO,MAAM,UAAU,UAAU,MAAM,EAAE,MAAM,CAAC;CAGtD,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,OACE,MAAM,WAAW,MAAM,UACvB,MAAM,OACH,QACC,OAAO,KACP,UACG,EAA8B,MAC9B,EAA8B,IACjC,CACJ;AAEJ;AAEA,IAAa,eAAb,MAAa,aAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA,kBAA0B;CAC1B;CACA,YAAoB;CAEpB;CACA;CACA,YAAoB;CACpB;CACA,4BAA6B,IAAI,IAAgB;CAEjD,YAAoB,SAAyB;EAC3C,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ;EAC1B,KAAK,WAAW,QAAQ;EACxB,KAAK,WAAW,QAAQ;EACxB,KAAK,YAAY,QAAQ;EACzB,KAAK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,EAAE,OAAO;GAC3C,GACA,QACF;GACA,KAAK,UAAU,MAAM;GACrB,OAAO,OAAO;EAChB,CAAC;CACL;CAGA,MAAM,UAAyB;EAC7B,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,sBAAsB;EAC3B,KAAK,iBAAiB;EACtB,KAAK,YAAY;EACjB,KAAK,QAAQ,QAAQ;CACvB;AACF;;;;;;AAOA,SAAS,mBAAmB,SAA8B;CACxD,MAAM,EAAE,MAAM,QAAQ,YAAY,WAAW,eAAe;CAC5D,IACE,KAAK,WAAW,KAChB,OAAO,WAAW,KAClB,WAAW,WAAW,KACtB,UAAU,WAAW,KACrB,WAAW,WAAW,KACtB,eAAe,aACf,eAAe,aACf,eAAe,YAEf,MAAM,IAAI,YACR,iBACA,0EACF;AAEJ;;;;;AAMA,eAAsB,cAAc,SAA0C;CAC5E,mBAAmB,QAAQ,OAAO;CAClC,OAAO,aAAa,QAAQ,OAAO;AACrC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as DerivedNostrKey, b as WalletErrorCode, d as NostrKeyInfo, l as LockReason, m as StatusPayload } from "./types-
|
|
2
|
-
import { f as Factor, g as NullValue, l as CORE_METHODS, p as MethodSpec, t as CHAINS_METHODS, v as Validator } from "./chains-
|
|
1
|
+
import { a as DerivedNostrKey, b as WalletErrorCode, d as NostrKeyInfo, l as LockReason, m as StatusPayload } from "./types-CIYT5uFj.mjs";
|
|
2
|
+
import { f as Factor, g as NullValue, l as CORE_METHODS, p as MethodSpec, t as CHAINS_METHODS, v as Validator } from "./chains-BdcH4YnJ.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* The unsigned event input the kernel signs. `pubkey` is optional: callers may omit it and the
|
|
5
5
|
* kernel fills the signing key's own. Structurally compatible with @qntx/nostr's UnsignedEvent.
|
|
@@ -487,4 +487,4 @@ declare const responseError: Validator<{
|
|
|
487
487
|
retryAt?: number | undefined;
|
|
488
488
|
}>;
|
|
489
489
|
export { Rumor as $, HtlcTimeoutSignRequest as A, SigningCommitment as B, backupEnvelope as C, backupInfo as D, backupHeader as E, PreparedClaim as F, SparkKey as G, SparkAccountRef as H, PreparedLightningReceive as I, StaticDepositClaimRequest as J, SparkLeafKey as K, PreparedTransfer as L, OperatorCommitment as M, PrepareClaimRequest as N, FrostAggregateJob as O, PrepareTransferRequest as P, NostrExportFormat as Q, PreparedTransferLeaf as R, BackupInfo as S, backupEnvelopeText as T, SparkApprovalSummary as U, SigningTarget as V, SparkApproveIntent as W, StaticDepositClaimStatement as X, StaticDepositClaimResult as Y, NOSTR_METHODS as Z, responseError as _, MethodName as a, BackupHeaderWallet as b, ParamsOf as c, Response as d, SignedEvent as et, ResultOf as f, requestBytes as g, kernelEvent as h, METHODS as i, IdentityStatement as j, FrostSignJob as k, ProtocolValue as l, isProtocolValue as m, KernelEvent as n, UnwrapResult as nt, MethodTablesDisjoint as o, UNATTRIBUTED_ID as p, SparkNetwork as q, MAX_REQUEST_BYTES as r, PROTOCOL_VERSION as s, ErrorPayload as t, UnsignedEventInput as tt, Request as u, BackupEnvelopeFactor as v, backupEnvelopeFactor as w, BackupHeaderWire as x, BackupEnvelopeWire as y, SPARK_METHODS as z };
|
|
490
|
-
//# sourceMappingURL=index-
|
|
490
|
+
//# sourceMappingURL=index-BXnQtz55.d.mts.map
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as
|
|
2
|
-
import { x as BackupHeaderWire } from "./index-
|
|
1
|
+
import { C as WalletsApi, S as WalletSnapshot, _ as VaultState, a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, g as VaultApi, h as UnlockFactor, i as DataKeyApi, l as LockReason, m as StatusPayload, n as BackupApi, o as ExportedSecret, p as PasskeyConfig, r as BackupInfo, s as FactorInfo, t as AutoLockPolicy, u as MnemonicDraft, v as Wallet, x as WalletInfo, y as WalletError } from "./types-CIYT5uFj.mjs";
|
|
2
|
+
import { et as SignedEvent, x as BackupHeaderWire } from "./index-BXnQtz55.mjs";
|
|
3
3
|
type BackupHeaderWallet = BackupHeaderWire["wallets"][number];
|
|
4
4
|
type BackupHeader = {
|
|
5
5
|
readonly version: 1;
|
|
@@ -10,5 +10,17 @@ type BackupHeader = {
|
|
|
10
10
|
};
|
|
11
11
|
/** Strictly validates the envelope and returns the header fields — no secrets, no writes. */
|
|
12
12
|
export declare function parseBackupHeader(envelope: string): BackupHeader;
|
|
13
|
+
type WalletOptions = {
|
|
14
|
+
readonly passkey: PasskeyConfig;
|
|
15
|
+
readonly autoLock: AutoLockPolicy;
|
|
16
|
+
/**
|
|
17
|
+
* Verifies the signature of every event the kernel signs, before the wallet hands it back.
|
|
18
|
+
* Required, with no default: `@qntx/nostr`'s own `verifyEvent` is bound to the pure-JS noble
|
|
19
|
+
* backend, which costs tens of milliseconds per event on Hermes. Pass the verifier your app
|
|
20
|
+
* already uses for relay events (for example `createEventVerifier(nativeBackend)`), so an event
|
|
21
|
+
* is verified once, natively, and the wallet shares its cache.
|
|
22
|
+
*/
|
|
23
|
+
readonly verifyEvent: (event: SignedEvent) => boolean;
|
|
24
|
+
};
|
|
13
25
|
export { type AutoLockPolicy, type BackupApi, type BackupHeader, type BackupHeaderWallet, type BackupInfo, type DataKeyApi, type DerivedNostrKey, type ExportedSecret, type FactorInfo, type InitialFactor, type LockReason, type MnemonicDraft, type NostrKeyInfo, type NostrKeyRef, type PasskeyConfig, type StatusPayload, type UnlockFactor, type VaultApi, type VaultState, type Wallet, WalletError, type WalletErrorCode, type WalletInfo, type WalletOptions, type WalletSnapshot, type WalletsApi };
|
|
14
26
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-CAKfHjIg.mjs","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import type { Factor, MethodName, ParamsOf, ResultOf } from \"./protocol/index.ts\";\n/**\n * Channel internals shared between the core Wallet and the protocol subpath modules\n * (@qntx/wallet/nostr, later spark/chains). This file is NOT a package subpath — modules look a\n * Wallet up in the WeakMap, so a foreign object has no channel to reach.\n */\nimport { WalletError } from \"./types.ts\";\nimport type { InitialFactor, UnlockFactor, Wallet, WalletSnapshot } from \"./types.ts\";\n\nexport type WalletInternals = {\n /** One validated request on the kernel channel (awaits the live port's first status). */\n readonly call: <M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer?: ArrayBuffer[],\n ) => Promise<ResultOf<M>>;\n /** The live kernel port's first-status gate — re-read per call (a respawn replaces it). */\n readonly ready: () => Promise<void>;\n readonly snapshot: () => WalletSnapshot;\n /** Marks a user verification in flight on the snapshot (`verifying`). */\n readonly withVerifying: <T>(fn: () => Promise<T>) => Promise<T>;\n /** Public UnlockFactor → wire factor material (the passkey ceremony runs here). */\n readonly resolveFactor: (factor: UnlockFactor, transfer: ArrayBuffer[]) => Promise<Factor>;\n /** The create/import factor gate: required on an uninitialized vault, forbidden after. */\n readonly createFactorParam: (\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n ) => Promise<Factor | undefined>;\n /** Adopts the session a create/import result opened onto the channel. */\n readonly sessionOf: (result: { readonly session: string }) => void;\n};\n\nconst internals = new WeakMap<Wallet, WalletInternals>();\n\nexport function registerInternals(wallet: Wallet, value: WalletInternals): void {\n internals.set(wallet, value);\n}\n\n/**\n * The internals behind a Wallet from this package — or `invalid-input` for anything else. A foreign\n * object can imitate the Wallet shape but can never hold the channel: modules that look it up here\n * get a closed failure, not a crafted kernel.\n */\nexport function internalsOf(wallet: Wallet): WalletInternals {\n const found = internals.get(wallet);\n if (found === undefined) {\n throw new WalletError(\"invalid-input\", \"not a Wallet from @qntx/wallet\");\n }\n return found;\n}\n"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"internal-CAKfHjIg.mjs","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import type { Factor, MethodName, ParamsOf, ResultOf, SignedEvent } from \"./protocol/index.ts\";\n/**\n * Channel internals shared between the core Wallet and the protocol subpath modules\n * (@qntx/wallet/nostr, later spark/chains). This file is NOT a package subpath — modules look a\n * Wallet up in the WeakMap, so a foreign object has no channel to reach.\n */\nimport { WalletError } from \"./types.ts\";\nimport type { InitialFactor, UnlockFactor, Wallet, WalletSnapshot } from \"./types.ts\";\n\nexport type WalletInternals = {\n /** One validated request on the kernel channel (awaits the live port's first status). */\n readonly call: <M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer?: ArrayBuffer[],\n ) => Promise<ResultOf<M>>;\n /** The live kernel port's first-status gate — re-read per call (a respawn replaces it). */\n readonly ready: () => Promise<void>;\n readonly snapshot: () => WalletSnapshot;\n /** The host-injected event verifier: the wallet never binds a signing backend itself. */\n readonly verifyEvent: (event: SignedEvent) => boolean;\n /** Marks a user verification in flight on the snapshot (`verifying`). */\n readonly withVerifying: <T>(fn: () => Promise<T>) => Promise<T>;\n /** Public UnlockFactor → wire factor material (the passkey ceremony runs here). */\n readonly resolveFactor: (factor: UnlockFactor, transfer: ArrayBuffer[]) => Promise<Factor>;\n /** The create/import factor gate: required on an uninitialized vault, forbidden after. */\n readonly createFactorParam: (\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n ) => Promise<Factor | undefined>;\n /** Adopts the session a create/import result opened onto the channel. */\n readonly sessionOf: (result: { readonly session: string }) => void;\n};\n\nconst internals = new WeakMap<Wallet, WalletInternals>();\n\nexport function registerInternals(wallet: Wallet, value: WalletInternals): void {\n internals.set(wallet, value);\n}\n\n/**\n * The internals behind a Wallet from this package — or `invalid-input` for anything else. A foreign\n * object can imitate the Wallet shape but can never hold the channel: modules that look it up here\n * get a closed failure, not a crafted kernel.\n */\nexport function internalsOf(wallet: Wallet): WalletInternals {\n const found = internals.get(wallet);\n if (found === undefined) {\n throw new WalletError(\"invalid-input\", \"not a Wallet from @qntx/wallet\");\n }\n return found;\n}\n"],"mappings":";;;;;;;AAkCA,MAAM,4BAAY,IAAI,QAAiC;AAEvD,SAAgB,kBAAkB,QAAgB,OAA8B;CAC9E,UAAU,IAAI,QAAQ,KAAK;AAC7B;;;;;;AAOA,SAAgB,YAAY,QAAiC;CAC3D,MAAM,QAAQ,UAAU,IAAI,MAAM;CAClC,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,YAAY,iBAAiB,gCAAgC;CAEzE,OAAO;AACT"}
|
package/dist/nostr.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as DerivedNostrKey, b as WalletErrorCode, d as NostrKeyInfo, f as NostrKeyRef, h as UnlockFactor, o as ExportedSecret, v as Wallet } from "./types-
|
|
1
|
+
import { a as DerivedNostrKey, b as WalletErrorCode, d as NostrKeyInfo, f as NostrKeyRef, h as UnlockFactor, o as ExportedSecret, v as Wallet } from "./types-CIYT5uFj.mjs";
|
|
2
2
|
import { Event, NostrSigner, UnsignedEvent } from "@qntx/nostr";
|
|
3
3
|
import { Rumor } from "@qntx/nostr/nips/nip59";
|
|
4
4
|
type NostrUnwrapResult = {
|
package/dist/nostr.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { WalletError } from "./types.mjs";
|
|
|
2
2
|
import { n as integrity } from "./channel-Iiz28m-e.mjs";
|
|
3
3
|
import { t as internalsOf } from "./internal-CAKfHjIg.mjs";
|
|
4
4
|
import { m as wireSecretText, t as SingleUseSecret } from "./secret-Dz_ItVt6.mjs";
|
|
5
|
-
import { signedMatchesUnsigned
|
|
5
|
+
import { signedMatchesUnsigned } from "@qntx/nostr";
|
|
6
6
|
// src/nostr/signer.ts
|
|
7
7
|
/**
|
|
8
8
|
* The proxy NostrSigner: the ref resolves against the CURRENT snapshot at every call, so the same
|
|
@@ -51,7 +51,7 @@ function proxySigner(ref, internals) {
|
|
|
51
51
|
content: unsigned.content,
|
|
52
52
|
pubkey: publicKey
|
|
53
53
|
};
|
|
54
|
-
if (signed.pubkey !== publicKey || !signedMatchesUnsigned(signed, requested) || !verifyEvent(signed)) throw integrity("the kernel returned a forged event");
|
|
54
|
+
if (signed.pubkey !== publicKey || !signedMatchesUnsigned(signed, requested) || !internals.verifyEvent(signed)) throw integrity("the kernel returned a forged event");
|
|
55
55
|
return signed;
|
|
56
56
|
},
|
|
57
57
|
nip04Encrypt: async (peer, plaintext) => internals.call("nostr.nip04Encrypt", {
|
|
@@ -121,7 +121,7 @@ function syncSigner(walletId, internals) {
|
|
|
121
121
|
content: unsigned.content,
|
|
122
122
|
pubkey: expected
|
|
123
123
|
};
|
|
124
|
-
if (signed.pubkey !== expected || !signedMatchesUnsigned(signed, requested) || !verifyEvent(signed)) throw integrity("the kernel returned a forged event");
|
|
124
|
+
if (signed.pubkey !== expected || !signedMatchesUnsigned(signed, requested) || !internals.verifyEvent(signed)) throw integrity("the kernel returned a forged event");
|
|
125
125
|
return signed;
|
|
126
126
|
},
|
|
127
127
|
encrypt: async (text) => internals.call("nostr.syncEncrypt", {
|
package/dist/nostr.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nostr.mjs","names":[],"sources":["../src/nostr/signer.ts","../src/nostr/index.ts"],"sourcesContent":["/**\n * The proxy NostrSigner: the ref resolves against the CURRENT snapshot at every call, so the same\n * signer object keeps working across lock/unlock and worker respawns. Returned events are checked\n * against the request — a compromised kernel cannot make a valid signature over different content\n * pass as the requested event.\n */\nimport { signedMatchesUnsigned, verifyEvent } from \"@qntx/nostr\";\nimport type { UnsignedEvent } from \"@qntx/nostr\";\nimport type { Rumor } from \"@qntx/nostr/nips/nip59\";\n\nimport { integrity } from \"../channel.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { MAX_BATCH } from \"../protocol/core.ts\";\nimport type { UnsignedEventInput } from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { NostrKeyInfo, NostrKeyRef } from \"../types.ts\";\nimport type { WalletSigner, WalletSyncSigner } from \"./types.ts\";\n\n/** Resolves a public ref to its stored key record; missing refs are `not-found`. */\nexport function keyInfoOf(internals: WalletInternals, ref: NostrKeyRef): NostrKeyInfo {\n const info = internals.snapshot().nostr.keys.find((key) => {\n const k = key.ref;\n return ref.kind === \"derived\" && k.walletId === ref.walletId && k.index === ref.index;\n });\n if (info === undefined) {\n throw new WalletError(\"not-found\", \"no such nostr key\");\n }\n return info;\n}\n\nexport function proxySigner(ref: NostrKeyRef, internals: WalletInternals): WalletSigner {\n const resolvePublicKey = (): string => keyInfoOf(internals, ref).publicKey;\n return {\n getPublicKey: async () => {\n await internals.ready();\n return resolvePublicKey();\n },\n signEvent: async (unsigned) => {\n const publicKey = resolvePublicKey();\n // An absent pubkey must stay absent: `pubkey: undefined` is not a ProtocolValue and the\n // kernel would reject the params outright.\n const event: UnsignedEventInput =\n unsigned.pubkey === undefined\n ? {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n }\n : {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: unsigned.pubkey,\n };\n const signed = await internals.call(\"nostr.signEvent\", { publicKey, event });\n // The kernel output must be the requested event, signed by the expected key.\n const requested: UnsignedEvent = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: publicKey,\n };\n if (\n signed.pubkey !== publicKey ||\n !signedMatchesUnsigned(signed, requested) ||\n !verifyEvent(signed)\n ) {\n throw integrity(\"the kernel returned a forged event\");\n }\n return signed;\n },\n nip04Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip04Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip04Decrypt: async (peer, ciphertext) =>\n internals.call(\"nostr.nip04Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: ciphertext,\n }),\n nip44Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip44Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip44Decrypt: async (peer, payload) =>\n internals.call(\"nostr.nip44Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: payload,\n }),\n unwrapGiftWraps: async (events) => {\n if (events.length === 0) {\n return [];\n }\n const publicKey = resolvePublicKey();\n const results: Array<Rumor | Error> = [];\n // The wire caps one batch at MAX_BATCH; chunk sequentially and concatenate in order —\n // other requests can interleave between chunks.\n for (let start = 0; start < events.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"nostr.unwrapGiftWraps\", {\n publicKey,\n events: events.slice(start, start + MAX_BATCH),\n });\n for (const r of batch.results) {\n results.push(\"ok\" in r ? r.ok : new Error(r.err));\n }\n }\n return results;\n },\n };\n}\n\n/**\n * The wallet metadata sync signer (WD-076): the key lives at the reserved NIP-06 segment and is\n * sealed by `nostr.syncKey` on first use, so `getPublicKey` both returns and creates it. Signed\n * events pass the same forged-event check as `proxySigner`.\n */\nexport function syncSigner(walletId: string, internals: WalletInternals): WalletSyncSigner {\n let cached: string | undefined;\n const publicKey = async (): Promise<string> => {\n if (cached === undefined) {\n const resolved = await internals.call(\"nostr.syncKey\", { walletId });\n cached = resolved.publicKey;\n }\n return cached;\n };\n return {\n getPublicKey: publicKey,\n signEvent: async (unsigned) => {\n const expected = await publicKey();\n const event: UnsignedEventInput = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n };\n const signed = await internals.call(\"nostr.syncSign\", { walletId, event });\n const requested: UnsignedEvent = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: expected,\n };\n if (\n signed.pubkey !== expected ||\n !signedMatchesUnsigned(signed, requested) ||\n !verifyEvent(signed)\n ) {\n throw integrity(\"the kernel returned a forged event\");\n }\n return signed;\n },\n encrypt: async (text) => internals.call(\"nostr.syncEncrypt\", { walletId, text }),\n decrypt: async (payload) => internals.call(\"nostr.syncDecrypt\", { walletId, text: payload }),\n };\n}\n","/**\n * The nostr module of @qntx/wallet: `nostr(wallet)` returns the wallet's Nostr API — signer\n * proxies, key discovery/derivation/derivation, guarded export and removal. The API is memoized per\n * wallet so repeated calls return the same object (stable React identity); a foreign object is\n * rejected because only a Wallet from this package holds a registered channel.\n */\nimport { wireSecretText } from \"../factors.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { SingleUseSecret } from \"../secret.ts\";\nimport type {\n DerivedNostrKey,\n ExportedSecret,\n NostrKeyInfo,\n NostrKeyRef,\n UnlockFactor,\n Wallet,\n} from \"../types.ts\";\nimport { keyInfoOf, proxySigner, syncSigner } from \"./signer.ts\";\nimport type { NostrApi, NostrExportKeyFormat, WalletSigner, WalletSyncSigner } from \"./types.ts\";\n\nexport type {\n DerivedNostrKey,\n NostrApi,\n NostrExportKeyFormat,\n NostrKeyInfo,\n NostrKeyRef,\n NostrUnwrapResult,\n WalletSigner,\n WalletSyncSigner,\n} from \"./types.ts\";\n\nfunction createNostrApi(internals: WalletInternals): NostrApi {\n return {\n signer: (ref: NostrKeyRef): WalletSigner => proxySigner(ref, internals),\n\n syncSigner: (walletId: string): WalletSyncSigner => syncSigner(walletId, internals),\n\n discover: async (\n walletId: string,\n from: number,\n count: number,\n ): Promise<ReadonlyArray<DerivedNostrKey>> => {\n const result = await internals.call(\"nostr.discover\", { walletId, from, count });\n return result.keys;\n },\n\n deriveKey: async (walletId: string, index: number): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.deriveKey\", { walletId, index }),\n\n removeKey: async (ref: NostrKeyRef): Promise<void> => {\n await internals.call(\"nostr.removeKey\", {\n publicKey: keyInfoOf(internals, ref).publicKey,\n });\n },\n\n exportKey: async (\n ref: NostrKeyRef,\n format: NostrExportKeyFormat,\n verify: UnlockFactor,\n ): Promise<ExportedSecret> =>\n internals.withVerifying(async () => {\n const { publicKey } = keyInfoOf(internals, ref);\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await internals.resolveFactor(verify, transfer);\n const wireFormat =\n format.kind === \"nsec\"\n ? { kind: \"nsec\" as const }\n : {\n kind: \"ncryptsec\" as const,\n password: wireSecretText(format.password, transfer),\n };\n const bytes = await internals.call(\n \"nostr.exportKey\",\n { verify: wireVerify, publicKey, format: wireFormat },\n transfer,\n );\n return new SingleUseSecret(bytes);\n }),\n };\n}\n\nconst apis = new WeakMap<Wallet, NostrApi>();\n\nexport function nostr(wallet: Wallet): NostrApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createNostrApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,SAAgB,UAAU,WAA4B,KAAgC;CACpF,MAAM,OAAO,UAAU,SAAS,CAAC,CAAC,MAAM,KAAK,MAAM,QAAQ;EACzD,MAAM,IAAI,IAAI;EACd,OAAO,IAAI,SAAS,aAAa,EAAE,aAAa,IAAI,YAAY,EAAE,UAAU,IAAI;CAClF,CAAC;CACD,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,YAAY,aAAa,mBAAmB;CAExD,OAAO;AACT;AAEA,SAAgB,YAAY,KAAkB,WAA0C;CACtF,MAAM,yBAAiC,UAAU,WAAW,GAAG,CAAC,CAAC;CACjE,OAAO;EACL,cAAc,YAAY;GACxB,MAAM,UAAU,MAAM;GACtB,OAAO,iBAAiB;EAC1B;EACA,WAAW,OAAO,aAAa;GAC7B,MAAM,YAAY,iBAAiB;GAGnC,MAAM,QACJ,SAAS,WAAW,KAAA,IAChB;IACE,MAAM,SAAS;IACf,YAAY,SAAS;IACrB,MAAM,SAAS;IACf,SAAS,SAAS;GACpB,IACA;IACE,MAAM,SAAS;IACf,YAAY,SAAS;IACrB,MAAM,SAAS;IACf,SAAS,SAAS;IAClB,QAAQ,SAAS;GACnB;GACN,MAAM,SAAS,MAAM,UAAU,KAAK,mBAAmB;IAAE;IAAW;GAAM,CAAC;GAE3E,MAAM,YAA2B;IAC/B,MAAM,S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,OAAO,SAAS,SACZ,EAAE,MAAM,OAAgB,IACxB;IACE,MAAM;IACN,UAAU,eAAe,OAAO,UAAU,QAAQ;GACpD;GACN,MAAM,QAAQ,MAAM,UAAU,KAC5B,mBACA;IAAE,QAAQ;IAAY;IAAW,QAAQ;GAAW,GACpD,QACF;GACA,OAAO,IAAI,gBAAgB,KAAK;EAClC,CAAC;CACL;AACF;AAEA,MAAM,uBAAO,IAAI,QAA0B;AAE3C,SAAgB,MAAM,QAA0B;CAC9C,MAAM,YAAY,YAAY,MAAM;CACpC,IAAI,MAAM,KAAK,IAAI,MAAM;CACzB,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,eAAe,SAAS;EAC9B,KAAK,IAAI,QAAQ,GAAG;CACtB;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"nostr.mjs","names":[],"sources":["../src/nostr/signer.ts","../src/nostr/index.ts"],"sourcesContent":["/**\n * The proxy NostrSigner: the ref resolves against the CURRENT snapshot at every call, so the same\n * signer object keeps working across lock/unlock and worker respawns. Returned events are checked\n * against the request — a compromised kernel cannot make a valid signature over different content\n * pass as the requested event.\n */\nimport { signedMatchesUnsigned } from \"@qntx/nostr\";\nimport type { UnsignedEvent } from \"@qntx/nostr\";\nimport type { Rumor } from \"@qntx/nostr/nips/nip59\";\n\nimport { integrity } from \"../channel.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { MAX_BATCH } from \"../protocol/core.ts\";\nimport type { UnsignedEventInput } from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { NostrKeyInfo, NostrKeyRef } from \"../types.ts\";\nimport type { WalletSigner, WalletSyncSigner } from \"./types.ts\";\n\n/** Resolves a public ref to its stored key record; missing refs are `not-found`. */\nexport function keyInfoOf(internals: WalletInternals, ref: NostrKeyRef): NostrKeyInfo {\n const info = internals.snapshot().nostr.keys.find((key) => {\n const k = key.ref;\n return ref.kind === \"derived\" && k.walletId === ref.walletId && k.index === ref.index;\n });\n if (info === undefined) {\n throw new WalletError(\"not-found\", \"no such nostr key\");\n }\n return info;\n}\n\nexport function proxySigner(ref: NostrKeyRef, internals: WalletInternals): WalletSigner {\n const resolvePublicKey = (): string => keyInfoOf(internals, ref).publicKey;\n return {\n getPublicKey: async () => {\n await internals.ready();\n return resolvePublicKey();\n },\n signEvent: async (unsigned) => {\n const publicKey = resolvePublicKey();\n // An absent pubkey must stay absent: `pubkey: undefined` is not a ProtocolValue and the\n // kernel would reject the params outright.\n const event: UnsignedEventInput =\n unsigned.pubkey === undefined\n ? {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n }\n : {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: unsigned.pubkey,\n };\n const signed = await internals.call(\"nostr.signEvent\", { publicKey, event });\n // The kernel output must be the requested event, signed by the expected key.\n const requested: UnsignedEvent = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: publicKey,\n };\n if (\n signed.pubkey !== publicKey ||\n !signedMatchesUnsigned(signed, requested) ||\n !internals.verifyEvent(signed)\n ) {\n throw integrity(\"the kernel returned a forged event\");\n }\n return signed;\n },\n nip04Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip04Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip04Decrypt: async (peer, ciphertext) =>\n internals.call(\"nostr.nip04Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: ciphertext,\n }),\n nip44Encrypt: async (peer, plaintext) =>\n internals.call(\"nostr.nip44Encrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: plaintext,\n }),\n nip44Decrypt: async (peer, payload) =>\n internals.call(\"nostr.nip44Decrypt\", {\n publicKey: resolvePublicKey(),\n peer,\n text: payload,\n }),\n unwrapGiftWraps: async (events) => {\n if (events.length === 0) {\n return [];\n }\n const publicKey = resolvePublicKey();\n const results: Array<Rumor | Error> = [];\n // The wire caps one batch at MAX_BATCH; chunk sequentially and concatenate in order —\n // other requests can interleave between chunks.\n for (let start = 0; start < events.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"nostr.unwrapGiftWraps\", {\n publicKey,\n events: events.slice(start, start + MAX_BATCH),\n });\n for (const r of batch.results) {\n results.push(\"ok\" in r ? r.ok : new Error(r.err));\n }\n }\n return results;\n },\n };\n}\n\n/**\n * The wallet metadata sync signer (WD-076): the key lives at the reserved NIP-06 segment and is\n * sealed by `nostr.syncKey` on first use, so `getPublicKey` both returns and creates it. Signed\n * events pass the same forged-event check as `proxySigner`.\n */\nexport function syncSigner(walletId: string, internals: WalletInternals): WalletSyncSigner {\n let cached: string | undefined;\n const publicKey = async (): Promise<string> => {\n if (cached === undefined) {\n const resolved = await internals.call(\"nostr.syncKey\", { walletId });\n cached = resolved.publicKey;\n }\n return cached;\n };\n return {\n getPublicKey: publicKey,\n signEvent: async (unsigned) => {\n const expected = await publicKey();\n const event: UnsignedEventInput = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n };\n const signed = await internals.call(\"nostr.syncSign\", { walletId, event });\n const requested: UnsignedEvent = {\n kind: unsigned.kind,\n created_at: unsigned.created_at,\n tags: unsigned.tags,\n content: unsigned.content,\n pubkey: expected,\n };\n if (\n signed.pubkey !== expected ||\n !signedMatchesUnsigned(signed, requested) ||\n !internals.verifyEvent(signed)\n ) {\n throw integrity(\"the kernel returned a forged event\");\n }\n return signed;\n },\n encrypt: async (text) => internals.call(\"nostr.syncEncrypt\", { walletId, text }),\n decrypt: async (payload) => internals.call(\"nostr.syncDecrypt\", { walletId, text: payload }),\n };\n}\n","/**\n * The nostr module of @qntx/wallet: `nostr(wallet)` returns the wallet's Nostr API — signer\n * proxies, key discovery/derivation/derivation, guarded export and removal. The API is memoized per\n * wallet so repeated calls return the same object (stable React identity); a foreign object is\n * rejected because only a Wallet from this package holds a registered channel.\n */\nimport { wireSecretText } from \"../factors.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport { SingleUseSecret } from \"../secret.ts\";\nimport type {\n DerivedNostrKey,\n ExportedSecret,\n NostrKeyInfo,\n NostrKeyRef,\n UnlockFactor,\n Wallet,\n} from \"../types.ts\";\nimport { keyInfoOf, proxySigner, syncSigner } from \"./signer.ts\";\nimport type { NostrApi, NostrExportKeyFormat, WalletSigner, WalletSyncSigner } from \"./types.ts\";\n\nexport type {\n DerivedNostrKey,\n NostrApi,\n NostrExportKeyFormat,\n NostrKeyInfo,\n NostrKeyRef,\n NostrUnwrapResult,\n WalletSigner,\n WalletSyncSigner,\n} from \"./types.ts\";\n\nfunction createNostrApi(internals: WalletInternals): NostrApi {\n return {\n signer: (ref: NostrKeyRef): WalletSigner => proxySigner(ref, internals),\n\n syncSigner: (walletId: string): WalletSyncSigner => syncSigner(walletId, internals),\n\n discover: async (\n walletId: string,\n from: number,\n count: number,\n ): Promise<ReadonlyArray<DerivedNostrKey>> => {\n const result = await internals.call(\"nostr.discover\", { walletId, from, count });\n return result.keys;\n },\n\n deriveKey: async (walletId: string, index: number): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.deriveKey\", { walletId, index }),\n\n removeKey: async (ref: NostrKeyRef): Promise<void> => {\n await internals.call(\"nostr.removeKey\", {\n publicKey: keyInfoOf(internals, ref).publicKey,\n });\n },\n\n exportKey: async (\n ref: NostrKeyRef,\n format: NostrExportKeyFormat,\n verify: UnlockFactor,\n ): Promise<ExportedSecret> =>\n internals.withVerifying(async () => {\n const { publicKey } = keyInfoOf(internals, ref);\n const transfer: ArrayBuffer[] = [];\n const wireVerify = await internals.resolveFactor(verify, transfer);\n const wireFormat =\n format.kind === \"nsec\"\n ? { kind: \"nsec\" as const }\n : {\n kind: \"ncryptsec\" as const,\n password: wireSecretText(format.password, transfer),\n };\n const bytes = await internals.call(\n \"nostr.exportKey\",\n { verify: wireVerify, publicKey, format: wireFormat },\n transfer,\n );\n return new SingleUseSecret(bytes);\n }),\n };\n}\n\nconst apis = new WeakMap<Wallet, NostrApi>();\n\nexport function nostr(wallet: Wallet): NostrApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createNostrApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,SAAgB,UAAU,WAA4B,KAAgC;CACpF,MAAM,OAAO,UAAU,SAAS,CAAC,CAAC,MAAM,KAAK,MAAM,QAAQ;EACzD,MAAM,IAAI,IAAI;EACd,OAAO,IAAI,SAAS,aAAa,EAAE,aAAa,IAAI,YAAY,EAAE,UAAU,IAAI;CAClF,CAAC;CACD,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,YAAY,aAAa,mBAAmB;CAExD,OAAO;AACT;AAEA,SAAgB,YAAY,KAAkB,WAA0C;CACtF,MAAM,yBAAiC,UAAU,WAAW,GAAG,CAAC,CAAC;CACjE,OAAO;EACL,cAAc,YAAY;GACxB,MAAM,UAAU,MAAM;GACtB,OAAO,iBAAiB;EAC1B;EACA,WAAW,OAAO,aAAa;GAC7B,MAAM,YAAY,iBAAiB;GAGnC,MAAM,QACJ,SAAS,WAAW,KAAA,IAChB;IACE,MAAM,SAAS;IACf,YAAY,SAAS;IACrB,MAAM,SAAS;IACf,SAAS,SAAS;GACpB,IACA;IACE,MAAM,SAAS;IACf,YAAY,SAAS;IACrB,MAAM,SAAS;IACf,SAAS,SAAS;IAClB,QAAQ,SAAS;GACnB;GACN,MAAM,SAAS,MAAM,UAAU,KAAK,mBAAmB;IAAE;IAAW;GAAM,CAAC;GAE3E,MAAM,YAA2B;IAC/B,MAAM,SAAS;IACf,YAAY,SAAS;IACrB,MAAM,SAAS;IACf,SAAS,SAAS;IAClB,QAAQ;GACV;GACA,IACE,OAAO,WAAW,aAClB,CAAC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pD;GACN,MAAM,QAAQ,MAAM,UAAU,KAC5B,mBACA;IAAE,QAAQ;IAAY;IAAW,QAAQ;GAAW,GACpD,QACF;GACA,OAAO,IAAI,gBAAgB,KAAK;EAClC,CAAC;CACL;AACF;AAEA,MAAM,uBAAO,IAAI,QAA0B;AAE3C,SAAgB,MAAM,QAA0B;CAC9C,MAAM,YAAY,YAAY,MAAM;CACpC,IAAI,MAAM,KAAK,IAAI,MAAM;CACzB,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,eAAe,SAAS;EAC9B,KAAK,IAAI,QAAQ,GAAG;CACtB;CACA,OAAO;AACT"}
|
package/dist/protocol.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as WalletErrorCode } from "./types-
|
|
2
|
-
import { A as validate, C as literal, D as record, E as opt, O as str, S as int, T as obj, _ as ValidationError, a as ChainSignResult, b as bool, c as BackupUnlockFactor, d as CreatedResult, f as Factor, g as NullValue, h as walletErrorCode, k as union, l as CORE_METHODS, m as RestoreWithPasskeyParams, n as ChainAccount, o as ChainTemplate, p as MethodSpec, r as ChainAccountsParams, s as BackupFactor, t as CHAINS_METHODS, u as CreateWithPasskeyParams, v as Validator, w as nullValue, x as bytes, y as arr } from "./chains-
|
|
3
|
-
import { $ as Rumor, A as HtlcTimeoutSignRequest, B as SigningCommitment, C as backupEnvelope, D as backupInfo, E as backupHeader, F as PreparedClaim, G as SparkKey, H as SparkAccountRef, I as PreparedLightningReceive, J as StaticDepositClaimRequest, K as SparkLeafKey, L as PreparedTransfer, M as OperatorCommitment, N as PrepareClaimRequest, O as FrostAggregateJob, P as PrepareTransferRequest, Q as NostrExportFormat, R as PreparedTransferLeaf, S as BackupInfo, T as backupEnvelopeText, U as SparkApprovalSummary, V as SigningTarget, W as SparkApproveIntent, X as StaticDepositClaimStatement, Y as StaticDepositClaimResult, Z as NOSTR_METHODS, _ as responseError, a as MethodName, b as BackupHeaderWallet, c as ParamsOf, d as Response, et as SignedEvent, f as ResultOf, g as requestBytes, h as kernelEvent, i as METHODS, j as IdentityStatement, k as FrostSignJob, l as ProtocolValue, m as isProtocolValue, n as KernelEvent, nt as UnwrapResult, o as MethodTablesDisjoint, p as UNATTRIBUTED_ID, q as SparkNetwork, r as MAX_REQUEST_BYTES, s as PROTOCOL_VERSION, t as ErrorPayload, tt as UnsignedEventInput, u as Request, v as BackupEnvelopeFactor, w as backupEnvelopeFactor, x as BackupHeaderWire, y as BackupEnvelopeWire, z as SPARK_METHODS } from "./index-
|
|
1
|
+
import { b as WalletErrorCode } from "./types-CIYT5uFj.mjs";
|
|
2
|
+
import { A as validate, C as literal, D as record, E as opt, O as str, S as int, T as obj, _ as ValidationError, a as ChainSignResult, b as bool, c as BackupUnlockFactor, d as CreatedResult, f as Factor, g as NullValue, h as walletErrorCode, k as union, l as CORE_METHODS, m as RestoreWithPasskeyParams, n as ChainAccount, o as ChainTemplate, p as MethodSpec, r as ChainAccountsParams, s as BackupFactor, t as CHAINS_METHODS, u as CreateWithPasskeyParams, v as Validator, w as nullValue, x as bytes, y as arr } from "./chains-BdcH4YnJ.mjs";
|
|
3
|
+
import { $ as Rumor, A as HtlcTimeoutSignRequest, B as SigningCommitment, C as backupEnvelope, D as backupInfo, E as backupHeader, F as PreparedClaim, G as SparkKey, H as SparkAccountRef, I as PreparedLightningReceive, J as StaticDepositClaimRequest, K as SparkLeafKey, L as PreparedTransfer, M as OperatorCommitment, N as PrepareClaimRequest, O as FrostAggregateJob, P as PrepareTransferRequest, Q as NostrExportFormat, R as PreparedTransferLeaf, S as BackupInfo, T as backupEnvelopeText, U as SparkApprovalSummary, V as SigningTarget, W as SparkApproveIntent, X as StaticDepositClaimStatement, Y as StaticDepositClaimResult, Z as NOSTR_METHODS, _ as responseError, a as MethodName, b as BackupHeaderWallet, c as ParamsOf, d as Response, et as SignedEvent, f as ResultOf, g as requestBytes, h as kernelEvent, i as METHODS, j as IdentityStatement, k as FrostSignJob, l as ProtocolValue, m as isProtocolValue, n as KernelEvent, nt as UnwrapResult, o as MethodTablesDisjoint, p as UNATTRIBUTED_ID, q as SparkNetwork, r as MAX_REQUEST_BYTES, s as PROTOCOL_VERSION, t as ErrorPayload, tt as UnsignedEventInput, u as Request, v as BackupEnvelopeFactor, w as backupEnvelopeFactor, x as BackupHeaderWire, y as BackupEnvelopeWire, z as SPARK_METHODS } from "./index-BXnQtz55.mjs";
|
|
4
4
|
export { type BackupEnvelopeFactor, type BackupEnvelopeWire, type BackupFactor, type BackupHeaderWallet, type BackupHeaderWire, type BackupInfo, type BackupUnlockFactor, CHAINS_METHODS, CORE_METHODS, type ChainAccount, type ChainAccountsParams, type ChainSignResult, type ChainTemplate, type CreateWithPasskeyParams, type CreatedResult, ErrorPayload, type Factor, type FrostAggregateJob, type FrostSignJob, type HtlcTimeoutSignRequest, type IdentityStatement, KernelEvent, MAX_REQUEST_BYTES, METHODS, MethodName, type MethodSpec, MethodTablesDisjoint, NOSTR_METHODS, type NostrExportFormat, type NullValue, type OperatorCommitment, PROTOCOL_VERSION, ParamsOf, type PrepareClaimRequest, type PrepareTransferRequest, type PreparedClaim, type PreparedLightningReceive, type PreparedTransfer, type PreparedTransferLeaf, ProtocolValue, Request, Response, type RestoreWithPasskeyParams, ResultOf, type Rumor, SPARK_METHODS, type SignedEvent, type SigningCommitment, type SigningTarget, type SparkAccountRef, type SparkApprovalSummary, type SparkApproveIntent, type SparkKey, type SparkLeafKey, type SparkNetwork, type StaticDepositClaimRequest, type StaticDepositClaimResult, type StaticDepositClaimStatement, UNATTRIBUTED_ID, type UnsignedEventInput, type UnwrapResult, ValidationError, type Validator, type WalletErrorCode, arr, backupEnvelope, backupEnvelopeFactor, backupEnvelopeText, backupHeader, backupInfo, bool, bytes, int, isProtocolValue, kernelEvent, literal, nullValue, obj, opt, record, requestBytes, responseError, str, union, validate, walletErrorCode };
|
package/dist/spark.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as UnlockFactor, v as Wallet } from "./types-
|
|
2
|
-
import { H as SparkAccountRef, U as SparkApprovalSummary, W as SparkApproveIntent } from "./index-
|
|
1
|
+
import { h as UnlockFactor, v as Wallet } from "./types-CIYT5uFj.mjs";
|
|
2
|
+
import { H as SparkAccountRef, U as SparkApprovalSummary, W as SparkApproveIntent } from "./index-BXnQtz55.mjs";
|
|
3
3
|
import { SparkSigner, SparkSigner as SparkSigner$1 } from "@qntx/spark/signer";
|
|
4
4
|
type SparkApi = {
|
|
5
5
|
/**
|
|
@@ -125,10 +125,6 @@ type AutoLockPolicy = {
|
|
|
125
125
|
readonly platform: "web";
|
|
126
126
|
readonly idleMinutes: 5 | 15 | 60;
|
|
127
127
|
};
|
|
128
|
-
type WalletOptions = {
|
|
129
|
-
readonly passkey: PasskeyConfig;
|
|
130
|
-
readonly autoLock: AutoLockPolicy;
|
|
131
|
-
};
|
|
132
128
|
type WalletSnapshot = {
|
|
133
129
|
readonly vault: VaultState;
|
|
134
130
|
readonly lockReason: LockReason | undefined;
|
|
@@ -211,5 +207,5 @@ type Wallet = {
|
|
|
211
207
|
readonly backup: BackupApi;
|
|
212
208
|
readonly destroy: () => Promise<void>;
|
|
213
209
|
};
|
|
214
|
-
export {
|
|
215
|
-
//# sourceMappingURL=types-
|
|
210
|
+
export { WalletsApi as C, WalletSnapshot as S, VaultState as _, DerivedNostrKey as a, WalletErrorCode as b, InitialFactor as c, NostrKeyInfo as d, NostrKeyRef as f, VaultApi as g, UnlockFactor as h, DataKeyApi as i, LockReason as l, StatusPayload as m, BackupApi as n, ExportedSecret as o, PasskeyConfig as p, BackupInfo as r, FactorInfo as s, AutoLockPolicy as t, MnemonicDraft as u, Wallet as v, WalletInfo as x, WalletError as y };
|
|
211
|
+
//# sourceMappingURL=types-CIYT5uFj.d.mts.map
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as
|
|
2
|
-
export { AutoLockPolicy, BackupApi, BackupInfo, DataKeyApi, DerivedNostrKey, ExportedSecret, FactorInfo, InitialFactor, LockReason, MnemonicDraft, NostrKeyInfo, NostrKeyRef, PasskeyConfig, StatusPayload, UnlockFactor, VaultApi, VaultState, Wallet, WalletError, WalletErrorCode, WalletInfo,
|
|
1
|
+
import { C as WalletsApi, S as WalletSnapshot, _ as VaultState, a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, g as VaultApi, h as UnlockFactor, i as DataKeyApi, l as LockReason, m as StatusPayload, n as BackupApi, o as ExportedSecret, p as PasskeyConfig, r as BackupInfo, s as FactorInfo, t as AutoLockPolicy, u as MnemonicDraft, v as Wallet, x as WalletInfo, y as WalletError } from "./types-CIYT5uFj.mjs";
|
|
2
|
+
export { AutoLockPolicy, BackupApi, BackupInfo, DataKeyApi, DerivedNostrKey, ExportedSecret, FactorInfo, InitialFactor, LockReason, MnemonicDraft, NostrKeyInfo, NostrKeyRef, PasskeyConfig, StatusPayload, UnlockFactor, VaultApi, VaultState, Wallet, WalletError, WalletErrorCode, WalletInfo, WalletSnapshot, WalletsApi };
|
package/dist/types.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","names":[],"sources":["../src/types.ts"],"sourcesContent":["/** Public types of @qntx/wallet, per design/entry.mdx. Secret data never appears here. */\nexport type LockReason =\n | \"cold-start\"\n | \"user\"\n | \"idle\"\n | \"background\"\n | \"expired\"\n | \"crashed\"\n | \"invalidated\";\n\nexport type FactorInfo =\n | { readonly kind: \"hardware\"; readonly id: string; readonly createdAt: number }\n | {\n readonly kind: \"passkey\";\n readonly id: string;\n /** Base64url, public data — the main side passes it as allowCredentials. */\n readonly credentialId: string;\n readonly createdAt: number;\n }\n | { readonly kind: \"password\"; readonly id: string; readonly createdAt: number };\n\nexport type WalletInfo = {\n readonly walletId: string;\n readonly origin: \"passkey\" | \"mnemonic\";\n readonly words: 12 | 15 | 18 | 21 | 24;\n /**\n * Mnemonic: the user holds the phrase (passed the writing-down quiz, imported it, or exported at\n * least once). passkey: protected only by a synced passkey — still lost when the password manager\n * or account is lost, so the UI should prompt to export. none: exists only on this device (a\n * device-bound passkey).\n */\n readonly backup: \"none\" | \"passkey\" | \"mnemonic\";\n readonly createdAt: number;\n};\n\nexport type NostrKeyRef = {\n readonly kind: \"derived\";\n readonly walletId: string;\n readonly index: number;\n};\n\nexport type NostrKeyInfo = {\n readonly ref: NostrKeyRef;\n readonly publicKey: string; // 64 lowercase hex\n readonly createdAt: number;\n};\n\n/** One entry of a `nostr.discover` result: the public key an identity index produces. */\nexport type DerivedNostrKey = { readonly index: number; readonly publicKey: string };\n\nexport type WalletErrorCode =\n | \"locked\"\n | \"cancelled\"\n | \"factor-unavailable\"\n | \"factor-invalidated\"\n | \"wrong-password\"\n | \"wrong-passkey\"\n | \"rate-limited\"\n | \"invalid-input\"\n | \"not-found\"\n | \"already-exists\"\n | \"conflict\"\n | \"unsupported\"\n | \"unavailable\"\n | \"integrity\"\n | \"approval-required\"\n | \"crashed\";\n\n/**\n * The vault half of the status payload: `corrupted` means authentication or structural data failed\n * to verify, `unsupported` means a newer build wrote it (data untouched, update the app),\n * `unavailable` means a transient store I/O failure (retried on the next request or change).\n */\nexport type VaultState =\n | \"uninitialized\"\n | \"locked\"\n | \"unlocked\"\n | \"corrupted\"\n | \"unsupported\"\n | \"unavailable\";\n\n/**\n * `status` result / status event payload. Locked snapshots come from unauthenticated headers;\n * \"corrupted\" means the vault data itself failed to load or verify (reset is the only way out).\n * Each protocol module contributes one section (here: `nostr`).\n */\nexport type StatusPayload = {\n readonly protocol: 2; // PROTOCOL_VERSION — literal to keep types.ts import-free\n readonly vault: VaultState;\n readonly factors: ReadonlyArray<FactorInfo>;\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly nostr: { readonly keys: ReadonlyArray<NostrKeyInfo> };\n // oxlint-disable-next-line typescript/no-restricted-types -- wire contract: backup is null when off\n readonly backup: BackupInfo | null;\n};\n\n/** Public summary of a retained backup key — factors are the unwrap paths, never secrets. */\nexport type BackupInfo = {\n readonly id: string; // 32 lowercase hex, derived from the BEK\n readonly factors: ReadonlyArray<\"passkey\" | \"password\">;\n readonly createdAt: number;\n};\n\n/** One error class for the whole API; `code` carries the distinction. Messages never echo input. */\nexport class WalletError extends Error {\n readonly code: WalletErrorCode;\n readonly retryAt: number | undefined;\n\n constructor(code: WalletErrorCode, message: string, retryAt?: number) {\n super(message);\n this.name = \"WalletError\";\n this.code = code;\n this.retryAt = retryAt;\n }\n}\n\n/**\n * A factor the user proves again for a guarded operation. `hardware` is the React Native factor:\n * the kernel shows the system verification prompt with text it renders itself.\n */\nexport type UnlockFactor =\n | { readonly kind: \"hardware\" }\n | { readonly kind: \"passkey\" }\n | { readonly kind: \"password\"; readonly password: string };\n\n/**\n * A factor being created; `hardware` exists only on React Native. `name` is the passkey\n * credential's display name — the host validates it before the ceremony (1–64 characters).\n */\nexport type InitialFactor =\n | { readonly kind: \"hardware\" }\n | { readonly kind: \"passkey\"; readonly name: string }\n | { readonly kind: \"password\"; readonly password: string };\n\n/**\n * WebAuthn RP identity + PRF salt labels the host configures once. `rpId`, `walletSalt` and\n * `vaultSalt` are permanent identifiers: changing any of them makes every existing passkey factor\n * and passkey-derived wallet unrecoverable, and the two salts must differ. Moving a wallet to a\n * different domain requires WebAuthn related origins (`/.well-known/webauthn`); hosts should offer\n * `exportMnemonic` for passkey-derived wallets so they survive an RP migration.\n */\nexport type PasskeyConfig = {\n /** RP id — the origin's effective domain or a registrable parent of it (e.g. meowl.social). */\n readonly rpId: string;\n readonly rpName: string;\n readonly walletSalt: string;\n readonly vaultSalt: string;\n /** PRF salt for the cloud-backup factor — a third, distinct permanent label. */\n readonly backupSalt: string;\n};\n\nexport type AutoLockPolicy =\n | { readonly platform: \"native\"; readonly backgroundSeconds: 0 | 60 | 300 | 900 }\n | { readonly platform: \"web\"; readonly idleMinutes: 5 | 15 | 60 };\n\nexport type
|
|
1
|
+
{"version":3,"file":"types.mjs","names":[],"sources":["../src/types.ts"],"sourcesContent":["/** Public types of @qntx/wallet, per design/entry.mdx. Secret data never appears here. */\nexport type LockReason =\n | \"cold-start\"\n | \"user\"\n | \"idle\"\n | \"background\"\n | \"expired\"\n | \"crashed\"\n | \"invalidated\";\n\nexport type FactorInfo =\n | { readonly kind: \"hardware\"; readonly id: string; readonly createdAt: number }\n | {\n readonly kind: \"passkey\";\n readonly id: string;\n /** Base64url, public data — the main side passes it as allowCredentials. */\n readonly credentialId: string;\n readonly createdAt: number;\n }\n | { readonly kind: \"password\"; readonly id: string; readonly createdAt: number };\n\nexport type WalletInfo = {\n readonly walletId: string;\n readonly origin: \"passkey\" | \"mnemonic\";\n readonly words: 12 | 15 | 18 | 21 | 24;\n /**\n * Mnemonic: the user holds the phrase (passed the writing-down quiz, imported it, or exported at\n * least once). passkey: protected only by a synced passkey — still lost when the password manager\n * or account is lost, so the UI should prompt to export. none: exists only on this device (a\n * device-bound passkey).\n */\n readonly backup: \"none\" | \"passkey\" | \"mnemonic\";\n readonly createdAt: number;\n};\n\nexport type NostrKeyRef = {\n readonly kind: \"derived\";\n readonly walletId: string;\n readonly index: number;\n};\n\nexport type NostrKeyInfo = {\n readonly ref: NostrKeyRef;\n readonly publicKey: string; // 64 lowercase hex\n readonly createdAt: number;\n};\n\n/** One entry of a `nostr.discover` result: the public key an identity index produces. */\nexport type DerivedNostrKey = { readonly index: number; readonly publicKey: string };\n\nexport type WalletErrorCode =\n | \"locked\"\n | \"cancelled\"\n | \"factor-unavailable\"\n | \"factor-invalidated\"\n | \"wrong-password\"\n | \"wrong-passkey\"\n | \"rate-limited\"\n | \"invalid-input\"\n | \"not-found\"\n | \"already-exists\"\n | \"conflict\"\n | \"unsupported\"\n | \"unavailable\"\n | \"integrity\"\n | \"approval-required\"\n | \"crashed\";\n\n/**\n * The vault half of the status payload: `corrupted` means authentication or structural data failed\n * to verify, `unsupported` means a newer build wrote it (data untouched, update the app),\n * `unavailable` means a transient store I/O failure (retried on the next request or change).\n */\nexport type VaultState =\n | \"uninitialized\"\n | \"locked\"\n | \"unlocked\"\n | \"corrupted\"\n | \"unsupported\"\n | \"unavailable\";\n\n/**\n * `status` result / status event payload. Locked snapshots come from unauthenticated headers;\n * \"corrupted\" means the vault data itself failed to load or verify (reset is the only way out).\n * Each protocol module contributes one section (here: `nostr`).\n */\nexport type StatusPayload = {\n readonly protocol: 2; // PROTOCOL_VERSION — literal to keep types.ts import-free\n readonly vault: VaultState;\n readonly factors: ReadonlyArray<FactorInfo>;\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly nostr: { readonly keys: ReadonlyArray<NostrKeyInfo> };\n // oxlint-disable-next-line typescript/no-restricted-types -- wire contract: backup is null when off\n readonly backup: BackupInfo | null;\n};\n\n/** Public summary of a retained backup key — factors are the unwrap paths, never secrets. */\nexport type BackupInfo = {\n readonly id: string; // 32 lowercase hex, derived from the BEK\n readonly factors: ReadonlyArray<\"passkey\" | \"password\">;\n readonly createdAt: number;\n};\n\n/** One error class for the whole API; `code` carries the distinction. Messages never echo input. */\nexport class WalletError extends Error {\n readonly code: WalletErrorCode;\n readonly retryAt: number | undefined;\n\n constructor(code: WalletErrorCode, message: string, retryAt?: number) {\n super(message);\n this.name = \"WalletError\";\n this.code = code;\n this.retryAt = retryAt;\n }\n}\n\n/**\n * A factor the user proves again for a guarded operation. `hardware` is the React Native factor:\n * the kernel shows the system verification prompt with text it renders itself.\n */\nexport type UnlockFactor =\n | { readonly kind: \"hardware\" }\n | { readonly kind: \"passkey\" }\n | { readonly kind: \"password\"; readonly password: string };\n\n/**\n * A factor being created; `hardware` exists only on React Native. `name` is the passkey\n * credential's display name — the host validates it before the ceremony (1–64 characters).\n */\nexport type InitialFactor =\n | { readonly kind: \"hardware\" }\n | { readonly kind: \"passkey\"; readonly name: string }\n | { readonly kind: \"password\"; readonly password: string };\n\n/**\n * WebAuthn RP identity + PRF salt labels the host configures once. `rpId`, `walletSalt` and\n * `vaultSalt` are permanent identifiers: changing any of them makes every existing passkey factor\n * and passkey-derived wallet unrecoverable, and the two salts must differ. Moving a wallet to a\n * different domain requires WebAuthn related origins (`/.well-known/webauthn`); hosts should offer\n * `exportMnemonic` for passkey-derived wallets so they survive an RP migration.\n */\nexport type PasskeyConfig = {\n /** RP id — the origin's effective domain or a registrable parent of it (e.g. meowl.social). */\n readonly rpId: string;\n readonly rpName: string;\n readonly walletSalt: string;\n readonly vaultSalt: string;\n /** PRF salt for the cloud-backup factor — a third, distinct permanent label. */\n readonly backupSalt: string;\n};\n\nexport type AutoLockPolicy =\n | { readonly platform: \"native\"; readonly backgroundSeconds: 0 | 60 | 300 | 900 }\n | { readonly platform: \"web\"; readonly idleMinutes: 5 | 15 | 60 };\n\nexport type WalletSnapshot = {\n readonly vault: VaultState;\n readonly lockReason: LockReason | undefined;\n readonly verifying: boolean; // a user verification is in flight\n readonly factors: ReadonlyArray<FactorInfo>;\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly nostr: { readonly keys: ReadonlyArray<NostrKeyInfo> };\n /** The retained backup key's public id, or null when cloud backup is off. */\n // oxlint-disable-next-line typescript/no-restricted-types -- wire contract: backup is null when off\n readonly backup: BackupInfo | null;\n};\n\n/** A one-shot secret buffer: `read` detaches the bytes to the caller, `wipe` zeroes them. */\nexport type ExportedSecret = {\n readonly read: () => Uint8Array; // UTF-8 text; single use — the second call throws\n readonly wipe: () => void;\n};\n\nexport type MnemonicDraft = {\n readonly words: ExportedSecret; // read once, then the host is responsible for wiping\n readonly quiz: ReadonlyArray<number>; // three positions the enclave picked\n readonly confirm: (answers: ReadonlyArray<string>) => Promise<WalletInfo>;\n readonly discard: () => Promise<void>;\n};\n\nexport type VaultApi = {\n readonly unlock: (factor?: UnlockFactor) => Promise<void>;\n readonly lock: () => Promise<void>;\n readonly addFactor: (factor: InitialFactor, verify: UnlockFactor) => Promise<FactorInfo>;\n readonly removeFactor: (id: string, verify: UnlockFactor) => Promise<void>; // ≥1 factor remains\n readonly reset: () => Promise<void>;\n};\n\nexport type WalletsApi = {\n readonly createWithPasskey: (options: {\n /** Display name for the new passkey credential (1–64 characters after trimming). */\n readonly name: string;\n readonly factor?: InitialFactor;\n }) => Promise<WalletInfo>;\n readonly restoreWithPasskey: (options?: {\n readonly factor?: InitialFactor;\n }) => Promise<WalletInfo>;\n readonly createMnemonic: (options: {\n readonly words: 12 | 24;\n readonly factor?: InitialFactor;\n }) => Promise<MnemonicDraft>;\n readonly importMnemonic: (options: {\n readonly mnemonic: string;\n readonly factor?: InitialFactor;\n }) => Promise<WalletInfo>;\n /** One-shot mnemonic export; requires re-verification every call. */\n readonly exportMnemonic: (walletId: string, verify: UnlockFactor) => Promise<ExportedSecret>;\n readonly delete: (walletId: string, verify: UnlockFactor) => Promise<void>;\n};\n\nexport type DataKeyApi = {\n readonly get: (purpose: string) => Promise<Uint8Array>;\n};\n\n/**\n * Cloud-backup entry points. `enable` re-verifies and retains a fresh BEK in the vault; `update`\n * rewrites the sealed envelope JSON with the retained BEK (no factor ceremony, so an auto-sync can\n * run silently); `restore` merges an envelope into the vault. Factor inputs reuse `UnlockFactor` —\n * passkey assertions evaluate the PRF over `backupSalt`.\n */\nexport type BackupApi = {\n readonly enable: (options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }) => Promise<void>;\n readonly update: () => Promise<string>;\n readonly disable: () => Promise<void>;\n readonly restore: (options: {\n readonly envelope: string;\n readonly backupFactor: UnlockFactor;\n readonly factor?: InitialFactor;\n }) => Promise<ReadonlyArray<WalletInfo>>;\n};\n\nexport type Wallet = {\n readonly getSnapshot: () => WalletSnapshot;\n readonly subscribe: (listener: () => void) => () => void;\n readonly vault: VaultApi;\n readonly wallets: WalletsApi;\n readonly dataKeys: DataKeyApi;\n readonly backup: BackupApi;\n readonly destroy: () => Promise<void>;\n};\n"],"mappings":";;AAwGA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;CAEA,YAAY,MAAuB,SAAiB,SAAkB;EACpE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;CACjB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qntx/wallet",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Self-custodial wallet SDK: Wallet host entry, protocol and types",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sdk",
|
|
@@ -77,14 +77,14 @@
|
|
|
77
77
|
"pack:local": "vp pack && bun pm pack"
|
|
78
78
|
},
|
|
79
79
|
"dependencies": {
|
|
80
|
-
"@scure/base": "
|
|
80
|
+
"@scure/base": "2.4.0"
|
|
81
81
|
},
|
|
82
82
|
"devDependencies": {
|
|
83
83
|
"@arethetypeswrong/cli": "0.18.5",
|
|
84
84
|
"@qntx/nostr": "0.15.3",
|
|
85
85
|
"@qntx/spark": "0.5.2",
|
|
86
86
|
"@qntx/tsconfig": "1.0.1",
|
|
87
|
-
"@qntx/wallet-chains": "0.
|
|
87
|
+
"@qntx/wallet-chains": "0.8.0",
|
|
88
88
|
"@scure/bip32": "2.4.0",
|
|
89
89
|
"@scure/bip39": "2.4.0",
|
|
90
90
|
"@scure/btc-signer": "2.4.1",
|
|
@@ -94,9 +94,9 @@
|
|
|
94
94
|
"vite-plus": "1.4.0"
|
|
95
95
|
},
|
|
96
96
|
"peerDependencies": {
|
|
97
|
-
"@qntx/nostr": "
|
|
98
|
-
"@qntx/spark": "
|
|
99
|
-
"@qntx/wallet-chains": "0.
|
|
97
|
+
"@qntx/nostr": "~0.15.3",
|
|
98
|
+
"@qntx/spark": "~0.5.2",
|
|
99
|
+
"@qntx/wallet-chains": "0.8.0"
|
|
100
100
|
},
|
|
101
101
|
"peerDependenciesMeta": {
|
|
102
102
|
"@qntx/nostr": {
|