@qntx/wallet 0.0.0-stage → 0.1.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.
@@ -0,0 +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 } from \"./channel.ts\";\nimport {\n passkeyName,\n requireCeremony,\n resolveFactor,\n resolveInitialFactor,\n vaultSaltBytes,\n walletSaltBytes,\n wireBytes,\n wireSecretText,\n} from \"./factors.ts\";\nimport type { FactorSource, PasskeyCeremony } 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 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 readonly passkey: PasskeyConfig;\n readonly ceremony: PasskeyCeremony | undefined;\n /** Runs once inside `destroy()` — host-side cleanup (page listeners, timers). */\n readonly onDestroy?: () => void;\n};\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 passkeyCfg: PasskeyConfig;\n private readonly ceremony: PasskeyCeremony | undefined;\n private readonly onDestroy: (() => 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.passkeyCfg = options.passkey;\n this.ceremony = options.ceremony;\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 };\n this.channel = new Channel(options.spawn, {\n onStatus: (status) => {\n this.onStatus(status);\n },\n onLocked: (reason) => {\n this.lockReason = reason;\n this.emit();\n },\n onCrashed: () => {\n this.lockReason = \"crashed\";\n this.emit();\n },\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 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 };\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 ) {\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 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) {\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 }\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 ?? { kind: \"passkey\" },\n transfer,\n );\n const result = await this.channel.call(\"vault.unlock\", { factor: wire }, transfer);\n this.sessionOf(result);\n }),\n lock: async (): Promise<void> => {\n try {\n await this.channel.call(\"vault.lock\", null);\n } catch (error) {\n // Locking an already-locked (or just-locked) vault is the postcondition anyway.\n if (!(error instanceof WalletError) || error.code !== \"locked\") {\n throw error;\n }\n }\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 ceremony = requireCeremony(this.factorSource);\n const name = passkeyName(options.name);\n const transfer: ArrayBuffer[] = [];\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 const created = await this.channel.call(\n \"wallet.createWithPasskey\",\n {\n credentialId: wireBytes(result.credentialId, transfer),\n prfWallet: wireBytes(result.first, transfer, true),\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\n }),\n restoreWithPasskey: async (options?: {\n readonly factor?: InitialFactor;\n }): Promise<WalletInfo> =>\n this.withVerifying(async () => {\n const ceremony = requireCeremony(this.factorSource);\n const transfer: ArrayBuffer[] = [];\n const result = await ceremony.assert({\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);\n } else {\n factor = await resolveInitialFactor(this.factorSource, options?.factor, transfer, result);\n }\n const created = await this.channel.call(\n \"wallet.restoreWithPasskey\",\n {\n credentialId: wireBytes(result.credentialId, transfer),\n prfWallet: wireBytes(result.first, transfer, true),\n ...(factor === undefined ? {} : { factor }),\n },\n transfer,\n );\n this.sessionOf(created);\n return created.wallet;\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 // 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.onDestroy?.();\n this.channel.destroy();\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 return KernelWall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,OAAO;AACrC"}
@@ -0,0 +1,286 @@
1
+ import { _ as WalletErrorCode, a as FactorInfo, f as StatusPayload, l as NostrKeyInfo, r as DerivedNostrKey, s as LockReason, v as WalletInfo } from "./types-DXNdAt_L.mjs";
2
+ //#region src/protocol/validate.d.ts
3
+ declare class ValidationError extends Error {
4
+ name: string;
5
+ }
6
+ type Validator<T> = (value: unknown) => T;
7
+ declare function literal<T extends NullValue | boolean | number | string>(expected: T): Validator<T>;
8
+ declare const nullValue: Validator<NullValue>;
9
+ declare const bool: Validator<boolean>;
10
+ declare function int(min: number, max: number): Validator<number>;
11
+ declare function str(max: number, pattern?: RegExp): Validator<string>;
12
+ declare function bytes(min: number, max?: number): Validator<Uint8Array>;
13
+ declare function arr<T>(item: Validator<T>, max: number, min?: number): Validator<ReadonlyArray<T>>;
14
+ declare class Opt<T> {
15
+ readonly validator: Validator<T>;
16
+ constructor(validator: Validator<T>);
17
+ }
18
+ declare function opt<T>(validator: Validator<T>): Opt<T>;
19
+ type Field = Validator<unknown> | Opt<unknown>;
20
+ type Shape = Record<string, Field>;
21
+ type RequiredKeys<S extends Shape> = { readonly [K in keyof S as S[K] extends Opt<unknown> ? never : K]: S[K] extends Validator<infer T> ? T : never; };
22
+ type OptionalKeys<S extends Shape> = { readonly [K in keyof S as S[K] extends Opt<unknown> ? K : never]?: S[K] extends Opt<infer T> ? T : never; };
23
+ type ShapeResult<S extends Shape> = RequiredKeys<S> & OptionalKeys<S>;
24
+ /** Exact key set: required keys present, optional keys allowed, nothing else. */
25
+ declare function obj<S extends Shape>(shape: S): Validator<ShapeResult<S>>;
26
+ /** Tries each branch in order; the first match wins. */
27
+ declare function union<Vs extends ReadonlyArray<Validator<unknown>>>(...branches: Vs): Validator<ReturnType<Vs[number]>>;
28
+ /** Validates a value and returns it, or undefined on a shape mismatch. */
29
+ declare function validate<T>(validator: Validator<T>, value: unknown): T | undefined;
30
+ //#endregion
31
+ //#region src/protocol/core.d.ts
32
+ type MethodSpec<P, R> = {
33
+ readonly session: boolean;
34
+ readonly params: Validator<P>;
35
+ readonly result: Validator<R>;
36
+ };
37
+ type Factor = {
38
+ readonly kind: "password";
39
+ readonly password: Uint8Array;
40
+ } | {
41
+ readonly kind: "passkey";
42
+ readonly credentialId: Uint8Array;
43
+ readonly prf: Uint8Array;
44
+ };
45
+ /**
46
+ * The result of every "create or import" wallet command: the new wallet's public info plus the
47
+ * session it opened. Creating a wallet derives no protocol keys — modules add keys separately.
48
+ */
49
+ type CreatedResult = {
50
+ readonly wallet: WalletInfo;
51
+ readonly session: string;
52
+ };
53
+ declare const CORE_METHODS: {
54
+ readonly "vault.unlock": MethodSpec<{
55
+ readonly factor: Factor;
56
+ }, {
57
+ readonly session: string;
58
+ }>;
59
+ readonly "vault.lock": MethodSpec<NullValue, NullValue>;
60
+ readonly "vault.reset": MethodSpec<NullValue, NullValue>;
61
+ readonly "vault.addFactor": MethodSpec<{
62
+ readonly verify: Factor;
63
+ readonly factor: Factor;
64
+ }, FactorInfo>;
65
+ readonly "vault.removeFactor": MethodSpec<{
66
+ readonly verify: Factor;
67
+ readonly id: string;
68
+ }, NullValue>;
69
+ readonly "wallet.createWithPasskey": MethodSpec<{
70
+ readonly credentialId: Uint8Array;
71
+ readonly prfWallet: Uint8Array;
72
+ readonly factor?: Factor;
73
+ }, CreatedResult>;
74
+ readonly "wallet.restoreWithPasskey": MethodSpec<{
75
+ readonly credentialId: Uint8Array;
76
+ readonly prfWallet: Uint8Array;
77
+ readonly factor?: Factor;
78
+ }, CreatedResult>;
79
+ readonly "wallet.createMnemonic": MethodSpec<{
80
+ readonly words: 12 | 24;
81
+ readonly factor?: Factor;
82
+ }, {
83
+ readonly draft: string;
84
+ readonly words: Uint8Array;
85
+ readonly quiz: ReadonlyArray<number>;
86
+ }>;
87
+ readonly "wallet.confirmMnemonic": MethodSpec<{
88
+ readonly draft: string;
89
+ readonly answers: ReadonlyArray<Uint8Array>;
90
+ }, CreatedResult>;
91
+ readonly "wallet.discardMnemonic": MethodSpec<{
92
+ readonly draft: string;
93
+ }, NullValue>;
94
+ readonly "wallet.importMnemonic": MethodSpec<{
95
+ readonly mnemonic: Uint8Array;
96
+ readonly factor?: Factor;
97
+ }, CreatedResult>;
98
+ readonly "wallet.exportMnemonic": MethodSpec<{
99
+ readonly verify: Factor;
100
+ readonly walletId: string;
101
+ }, Uint8Array>;
102
+ readonly "wallet.delete": MethodSpec<{
103
+ readonly verify: Factor;
104
+ readonly walletId: string;
105
+ }, NullValue>;
106
+ readonly "dataKeys.get": MethodSpec<{
107
+ readonly purpose: string;
108
+ }, Uint8Array>;
109
+ };
110
+ //#endregion
111
+ //#region src/protocol/nostr.d.ts
112
+ /**
113
+ * The unsigned event input the kernel signs. `pubkey` is optional: callers may omit it and the
114
+ * kernel fills the signing key's own. Structurally compatible with @qntx/nostr's UnsignedEvent.
115
+ */
116
+ type UnsignedEventInput = {
117
+ readonly kind: number;
118
+ readonly created_at: number;
119
+ readonly tags: ReadonlyArray<ReadonlyArray<string>>;
120
+ readonly content: string;
121
+ readonly pubkey?: string;
122
+ };
123
+ /** The signed event the kernel returns — the Nostr event minus `id`-less forms. */
124
+ type SignedEvent = {
125
+ readonly id: string;
126
+ readonly pubkey: string;
127
+ readonly sig: string;
128
+ readonly kind: number;
129
+ readonly created_at: number;
130
+ readonly tags: ReadonlyArray<ReadonlyArray<string>>;
131
+ readonly content: string;
132
+ };
133
+ /** A NIP-59 rumor: an unsigned event carrying a computed `id` but no `sig`. */
134
+ type Rumor = {
135
+ readonly id: string;
136
+ readonly pubkey: string;
137
+ readonly kind: number;
138
+ readonly created_at: number;
139
+ readonly tags: ReadonlyArray<ReadonlyArray<string>>;
140
+ readonly content: string;
141
+ };
142
+ type NostrImportInput = {
143
+ readonly kind: "nsec";
144
+ readonly nsec: Uint8Array;
145
+ } | {
146
+ readonly kind: "ncryptsec";
147
+ readonly ncryptsec: string;
148
+ readonly password: Uint8Array;
149
+ };
150
+ type NostrExportFormat = {
151
+ readonly kind: "nsec";
152
+ } | {
153
+ readonly kind: "ncryptsec";
154
+ readonly password: Uint8Array;
155
+ };
156
+ /** One "import/generate a key" result: the key's public info plus the session it may have opened. */
157
+ type KeyResult = {
158
+ readonly key: NostrKeyInfo;
159
+ readonly session: string;
160
+ };
161
+ type UnwrapResult = {
162
+ readonly ok: Rumor;
163
+ } | {
164
+ readonly err: WalletErrorCode;
165
+ };
166
+ declare const NOSTR_METHODS: {
167
+ readonly "nostr.discover": MethodSpec<{
168
+ readonly walletId: string;
169
+ readonly from: number;
170
+ readonly count: number;
171
+ }, {
172
+ readonly keys: ReadonlyArray<DerivedNostrKey>;
173
+ }>;
174
+ readonly "nostr.deriveKey": MethodSpec<{
175
+ readonly walletId: string;
176
+ readonly groupIndex: number;
177
+ }, NostrKeyInfo>;
178
+ readonly "nostr.importKey": MethodSpec<{
179
+ readonly input: NostrImportInput;
180
+ readonly factor?: Factor;
181
+ }, KeyResult>;
182
+ readonly "nostr.generateKey": MethodSpec<{
183
+ readonly factor?: Factor;
184
+ }, KeyResult>;
185
+ readonly "nostr.createNip46ClientKey": MethodSpec<NullValue, NostrKeyInfo>;
186
+ readonly "nostr.removeKey": MethodSpec<{
187
+ readonly publicKey: string;
188
+ readonly verify?: Factor;
189
+ }, NullValue>;
190
+ readonly "nostr.exportKey": MethodSpec<{
191
+ readonly verify: Factor;
192
+ readonly publicKey: string;
193
+ readonly format: NostrExportFormat;
194
+ }, Uint8Array>;
195
+ readonly "nostr.signEvent": MethodSpec<{
196
+ readonly publicKey: string;
197
+ readonly event: UnsignedEventInput;
198
+ }, SignedEvent>;
199
+ readonly "nostr.nip04Encrypt": MethodSpec<{
200
+ readonly publicKey: string;
201
+ readonly peer: string;
202
+ readonly text: string;
203
+ }, string>;
204
+ readonly "nostr.nip04Decrypt": MethodSpec<{
205
+ readonly publicKey: string;
206
+ readonly peer: string;
207
+ readonly text: string;
208
+ }, string>;
209
+ readonly "nostr.nip44Encrypt": MethodSpec<{
210
+ readonly publicKey: string;
211
+ readonly peer: string;
212
+ readonly text: string;
213
+ }, string>;
214
+ readonly "nostr.nip44Decrypt": MethodSpec<{
215
+ readonly publicKey: string;
216
+ readonly peer: string;
217
+ readonly text: string;
218
+ }, string>;
219
+ readonly "nostr.unwrapGiftWraps": MethodSpec<{
220
+ readonly publicKey: string;
221
+ readonly events: ReadonlyArray<SignedEvent>;
222
+ }, {
223
+ readonly results: ReadonlyArray<UnwrapResult>;
224
+ }>;
225
+ };
226
+ //#endregion
227
+ //#region src/protocol/index.d.ts
228
+ declare const PROTOCOL_VERSION = 1;
229
+ /**
230
+ * Responses to requests whose `id` cannot be parsed (malformed envelope) carry id 0. Main-side
231
+ * request ids start at 1, so a `0` is never a real pending request.
232
+ */
233
+ declare const UNATTRIBUTED_ID = 0;
234
+ type NullValue = null;
235
+ type ProtocolValue = NullValue | boolean | number | string | Uint8Array | ReadonlyArray<ProtocolValue> | {
236
+ readonly [key: string]: ProtocolValue;
237
+ };
238
+ type Request = {
239
+ readonly v: 1;
240
+ readonly id: number;
241
+ readonly method: string;
242
+ readonly session?: string;
243
+ readonly params: ProtocolValue;
244
+ };
245
+ type ErrorPayload = {
246
+ readonly code: WalletErrorCode;
247
+ readonly retryAt?: number;
248
+ };
249
+ type Response = {
250
+ readonly v: 1;
251
+ readonly id: number;
252
+ readonly ok: ProtocolValue;
253
+ } | {
254
+ readonly v: 1;
255
+ readonly id: number;
256
+ readonly err: ErrorPayload;
257
+ };
258
+ type KernelEvent = {
259
+ readonly v: 1;
260
+ readonly event: "status";
261
+ readonly status: StatusPayload;
262
+ } | {
263
+ readonly v: 1;
264
+ readonly event: "locked";
265
+ readonly reason: LockReason;
266
+ };
267
+ /** Deep check that a structured-cloned value is a strict ProtocolValue (no cycles detected). */
268
+ declare function isProtocolValue(value: unknown): value is ProtocolValue;
269
+ declare const METHODS: {
270
+ readonly status: MethodSpec<NullValue, StatusPayload>;
271
+ } & typeof CORE_METHODS & typeof NOSTR_METHODS;
272
+ type AssertNever<T extends never> = T;
273
+ type MethodTablesDisjoint = AssertNever<keyof typeof CORE_METHODS & keyof typeof NOSTR_METHODS>;
274
+ type MethodName = keyof typeof METHODS;
275
+ type ParamsOf<M extends MethodName> = ReturnType<(typeof METHODS)[M]["params"]>;
276
+ type ResultOf<M extends MethodName> = ReturnType<(typeof METHODS)[M]["result"]>;
277
+ /** Host-side validators: `kernelEvent` covers the two push messages. */
278
+ declare const kernelEvent: Validator<KernelEvent>;
279
+ /** Validates the `err` payload of a response; `ok` is checked against `METHODS[m].result`. */
280
+ declare const responseError: Validator<{
281
+ code: WalletErrorCode;
282
+ retryAt?: number | undefined;
283
+ }>;
284
+ //#endregion
285
+ export { Validator as A, union as B, UnsignedEventInput as C, Factor as D, CreatedResult as E, literal as F, nullValue as I, obj as L, bool as M, bytes as N, MethodSpec as O, int as P, opt as R, SignedEvent as S, CORE_METHODS as T, validate as V, KeyResult as _, MethodTablesDisjoint as a, NostrImportInput as b, ParamsOf as c, Response as d, ResultOf as f, responseError as g, kernelEvent as h, MethodName as i, arr as j, ValidationError as k, ProtocolValue as l, isProtocolValue as m, KernelEvent as n, NullValue as o, UNATTRIBUTED_ID as p, METHODS as r, PROTOCOL_VERSION as s, ErrorPayload as t, Request as u, NOSTR_METHODS as v, UnwrapResult as w, Rumor as x, NostrExportFormat as y, str as z };
286
+ //# sourceMappingURL=index-0nfJuuWM.d.mts.map
@@ -0,0 +1,2 @@
1
+ import { S as WalletsApi, _ as WalletErrorCode, a as FactorInfo, b as WalletOptions, c as MnemonicDraft, d as PasskeyConfig, f as StatusPayload, g as WalletError, h as Wallet, i as ExportedSecret, l as NostrKeyInfo, m as VaultApi, n as DataKeyApi, o as InitialFactor, p as UnlockFactor, r as DerivedNostrKey, s as LockReason, t as AutoLockPolicy, u as NostrKeyRef, v as WalletInfo, x as WalletSnapshot, y as WalletLogger } from "./types-DXNdAt_L.mjs";
2
+ export { type AutoLockPolicy, 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 Wallet, WalletError, type WalletErrorCode, type WalletInfo, type WalletLogger, type WalletOptions, type WalletSnapshot, type WalletsApi };
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { WalletError } from "./types.mjs";
2
+ export { WalletError };
@@ -0,0 +1,47 @@
1
+ import { _ as WalletErrorCode, h as Wallet, i as ExportedSecret, l as NostrKeyInfo, o as InitialFactor, p as UnlockFactor, r as DerivedNostrKey, u as NostrKeyRef } from "./types-DXNdAt_L.mjs";
2
+ import { Event, NostrSigner } from "@qntx/nostr";
3
+ import { Rumor } from "@qntx/nostr/nips/nip59";
4
+ //#region src/nostr/types.d.ts
5
+ type NostrUnwrapResult = {
6
+ readonly ok: Rumor;
7
+ } | {
8
+ readonly err: WalletErrorCode;
9
+ };
10
+ /** A proxy NostrSigner: the kernel key is resolved per call, so it survives lock/unlock cycles. */
11
+ type WalletSigner = {
12
+ readonly unwrapGiftWraps: (events: ReadonlyArray<Event>) => Promise<ReadonlyArray<NostrUnwrapResult>>;
13
+ } & NostrSigner;
14
+ type NostrImportKeyInput = {
15
+ readonly nsec: string;
16
+ } | {
17
+ readonly ncryptsec: string;
18
+ readonly password: string;
19
+ };
20
+ type NostrExportKeyFormat = {
21
+ readonly kind: "nsec";
22
+ } | {
23
+ readonly kind: "ncryptsec";
24
+ readonly password: string;
25
+ };
26
+ type NostrApi = {
27
+ readonly signer: (ref: NostrKeyRef) => WalletSigner;
28
+ /** Public keys a wallet's account groups would derive — discovery before deriveKey. */
29
+ readonly discover: (walletId: string, from: number, count: number) => Promise<ReadonlyArray<DerivedNostrKey>>;
30
+ readonly deriveKey: (walletId: string, groupIndex: number) => Promise<NostrKeyInfo>;
31
+ readonly importKey: (input: NostrImportKeyInput, options?: {
32
+ readonly factor?: InitialFactor;
33
+ }) => Promise<NostrKeyInfo>;
34
+ readonly generateKey: (options?: {
35
+ readonly factor?: InitialFactor;
36
+ }) => Promise<NostrKeyInfo>;
37
+ readonly createNip46ClientKey: () => Promise<NostrKeyInfo>;
38
+ readonly removeKey: (ref: NostrKeyRef, verify?: UnlockFactor) => Promise<void>;
39
+ /** One-shot key export; requires re-verification every call. */
40
+ readonly exportKey: (ref: NostrKeyRef, format: NostrExportKeyFormat, verify: UnlockFactor) => Promise<ExportedSecret>;
41
+ };
42
+ //#endregion
43
+ //#region src/nostr/index.d.ts
44
+ export declare function nostr(wallet: Wallet): NostrApi;
45
+ //#endregion
46
+ export type { DerivedNostrKey, NostrApi, NostrExportKeyFormat, NostrImportKeyInput, NostrKeyInfo, NostrKeyRef, NostrUnwrapResult, WalletSigner };
47
+ //# sourceMappingURL=nostr.d.mts.map
package/dist/nostr.mjs ADDED
@@ -0,0 +1,174 @@
1
+ import { WalletError } from "./types.mjs";
2
+ import { d as wireSecretText, n as internalsOf, p as integrity, t as SingleUseSecret } from "./secret-B-P3QOym.mjs";
3
+ import { signedMatchesUnsigned, verifyEvent } from "@qntx/nostr";
4
+ //#region src/nostr/signer.ts
5
+ /**
6
+ * The proxy NostrSigner: the ref resolves against the CURRENT snapshot at every call, so the same
7
+ * signer object keeps working across lock/unlock and worker respawns. Returned events are checked
8
+ * against the request — a compromised kernel cannot make a valid signature over different content
9
+ * pass as the requested event.
10
+ */
11
+ /** Resolves a public ref to its stored key record; missing refs are `not-found`. */
12
+ function keyInfoOf(internals, ref) {
13
+ const info = internals.snapshot().nostr.keys.find((key) => {
14
+ const k = key.ref;
15
+ return ref.kind === "derived" && k.kind === "derived" && k.walletId === ref.walletId && k.groupIndex === ref.groupIndex || ref.kind === "nip46-client" && k.kind === "nip46-client" && k.id === ref.id || ref.kind === "standalone" && k.kind === "standalone" && k.id === ref.id;
16
+ });
17
+ if (info === void 0) throw new WalletError("not-found", "no such nostr key");
18
+ return info;
19
+ }
20
+ function proxySigner(ref, internals) {
21
+ const resolvePublicKey = () => keyInfoOf(internals, ref).publicKey;
22
+ return {
23
+ getPublicKey: async () => {
24
+ await internals.ready();
25
+ return resolvePublicKey();
26
+ },
27
+ signEvent: async (unsigned) => {
28
+ const publicKey = resolvePublicKey();
29
+ const event = unsigned.pubkey === void 0 ? {
30
+ kind: unsigned.kind,
31
+ created_at: unsigned.created_at,
32
+ tags: unsigned.tags,
33
+ content: unsigned.content
34
+ } : {
35
+ kind: unsigned.kind,
36
+ created_at: unsigned.created_at,
37
+ tags: unsigned.tags,
38
+ content: unsigned.content,
39
+ pubkey: unsigned.pubkey
40
+ };
41
+ const signed = await internals.call("nostr.signEvent", {
42
+ publicKey,
43
+ event
44
+ });
45
+ const requested = {
46
+ kind: unsigned.kind,
47
+ created_at: unsigned.created_at,
48
+ tags: unsigned.tags,
49
+ content: unsigned.content,
50
+ pubkey: publicKey
51
+ };
52
+ if (signed.pubkey !== publicKey || !signedMatchesUnsigned(signed, requested) || !verifyEvent(signed)) throw integrity("the kernel returned a forged event");
53
+ return signed;
54
+ },
55
+ nip04Encrypt: async (peer, plaintext) => internals.call("nostr.nip04Encrypt", {
56
+ publicKey: resolvePublicKey(),
57
+ peer,
58
+ text: plaintext
59
+ }),
60
+ nip04Decrypt: async (peer, ciphertext) => internals.call("nostr.nip04Decrypt", {
61
+ publicKey: resolvePublicKey(),
62
+ peer,
63
+ text: ciphertext
64
+ }),
65
+ nip44Encrypt: async (peer, plaintext) => internals.call("nostr.nip44Encrypt", {
66
+ publicKey: resolvePublicKey(),
67
+ peer,
68
+ text: plaintext
69
+ }),
70
+ nip44Decrypt: async (peer, payload) => internals.call("nostr.nip44Decrypt", {
71
+ publicKey: resolvePublicKey(),
72
+ peer,
73
+ text: payload
74
+ }),
75
+ unwrapGiftWraps: async (events) => {
76
+ return (await internals.call("nostr.unwrapGiftWraps", {
77
+ publicKey: resolvePublicKey(),
78
+ events: [...events]
79
+ })).results;
80
+ }
81
+ };
82
+ }
83
+ //#endregion
84
+ //#region src/nostr/index.ts
85
+ /**
86
+ * The nostr module of @qntx/wallet: `nostr(wallet)` returns the wallet's Nostr API — signer
87
+ * proxies, key discovery/derivation/import/generation, guarded export and removal. The API is
88
+ * memoized per wallet so repeated calls return the same object (stable React identity); a foreign
89
+ * object is rejected because only a Wallet from this package holds a registered channel.
90
+ */
91
+ function createNostrApi(internals) {
92
+ return {
93
+ signer: (ref) => proxySigner(ref, internals),
94
+ discover: async (walletId, from, count) => {
95
+ return (await internals.call("nostr.discover", {
96
+ walletId,
97
+ from,
98
+ count
99
+ })).keys;
100
+ },
101
+ deriveKey: async (walletId, groupIndex) => internals.call("nostr.deriveKey", {
102
+ walletId,
103
+ groupIndex
104
+ }),
105
+ importKey: async (input, options) => {
106
+ const transfer = [];
107
+ const factor = await internals.createFactorParam(options?.factor, transfer);
108
+ const wireInput = "nsec" in input ? {
109
+ kind: "nsec",
110
+ nsec: wireSecretText(input.nsec, transfer)
111
+ } : {
112
+ kind: "ncryptsec",
113
+ ncryptsec: input.ncryptsec,
114
+ password: wireSecretText(input.password, transfer)
115
+ };
116
+ const result = await internals.call("nostr.importKey", {
117
+ input: wireInput,
118
+ ...factor === void 0 ? {} : { factor }
119
+ }, transfer);
120
+ internals.sessionOf(result);
121
+ return result.key;
122
+ },
123
+ generateKey: async (options) => {
124
+ const transfer = [];
125
+ const factor = await internals.createFactorParam(options?.factor, transfer);
126
+ const result = await internals.call("nostr.generateKey", factor === void 0 ? {} : { factor }, transfer);
127
+ internals.sessionOf(result);
128
+ return result.key;
129
+ },
130
+ createNip46ClientKey: async () => internals.call("nostr.createNip46ClientKey", null),
131
+ removeKey: async (ref, verify) => internals.withVerifying(async () => {
132
+ const info = keyInfoOf(internals, ref);
133
+ const transfer = [];
134
+ let wireVerify;
135
+ if (info.origin !== "nip46-client") {
136
+ if (verify === void 0) throw new WalletError("invalid-input", "factor verification is required");
137
+ wireVerify = await internals.resolveFactor(verify, transfer);
138
+ }
139
+ await internals.call("nostr.removeKey", {
140
+ publicKey: info.publicKey,
141
+ ...wireVerify === void 0 ? {} : { verify: wireVerify }
142
+ }, transfer);
143
+ }),
144
+ exportKey: async (ref, format, verify) => internals.withVerifying(async () => {
145
+ const { publicKey } = keyInfoOf(internals, ref);
146
+ const transfer = [];
147
+ const wireVerify = await internals.resolveFactor(verify, transfer);
148
+ const wireFormat = format.kind === "nsec" ? { kind: "nsec" } : {
149
+ kind: "ncryptsec",
150
+ password: wireSecretText(format.password, transfer)
151
+ };
152
+ const bytes = await internals.call("nostr.exportKey", {
153
+ verify: wireVerify,
154
+ publicKey,
155
+ format: wireFormat
156
+ }, transfer);
157
+ return new SingleUseSecret(bytes);
158
+ })
159
+ };
160
+ }
161
+ const apis = /* @__PURE__ */ new WeakMap();
162
+ function nostr(wallet) {
163
+ const internals = internalsOf(wallet);
164
+ let api = apis.get(wallet);
165
+ if (api === void 0) {
166
+ api = createNostrApi(internals);
167
+ apis.set(wallet, api);
168
+ }
169
+ return api;
170
+ }
171
+ //#endregion
172
+ export { nostr };
173
+
174
+ //# sourceMappingURL=nostr.mjs.map
@@ -0,0 +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\";\n\nimport { integrity } from \"../channel.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type { UnsignedEventInput } from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { NostrKeyInfo, NostrKeyRef } from \"../types.ts\";\nimport type { NostrUnwrapResult, WalletSigner } 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 (\n (ref.kind === \"derived\" &&\n k.kind === \"derived\" &&\n k.walletId === ref.walletId &&\n k.groupIndex === ref.groupIndex) ||\n (ref.kind === \"nip46-client\" && k.kind === \"nip46-client\" && k.id === ref.id) ||\n (ref.kind === \"standalone\" && k.kind === \"standalone\" && k.id === ref.id)\n );\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): Promise<ReadonlyArray<NostrUnwrapResult>> => {\n const result = await internals.call(\"nostr.unwrapGiftWraps\", {\n publicKey: resolvePublicKey(),\n events: [...events],\n });\n return result.results;\n },\n };\n}\n","/**\n * The nostr module of @qntx/wallet: `nostr(wallet)` returns the wallet's Nostr API — signer\n * proxies, key discovery/derivation/import/generation, guarded export and removal. The API is\n * memoized per wallet so repeated calls return the same object (stable React identity); a foreign\n * object is 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 { WalletError } from \"../types.ts\";\nimport type {\n DerivedNostrKey,\n ExportedSecret,\n InitialFactor,\n NostrKeyInfo,\n NostrKeyRef,\n UnlockFactor,\n Wallet,\n} from \"../types.ts\";\nimport { keyInfoOf, proxySigner } from \"./signer.ts\";\nimport type { NostrApi, NostrExportKeyFormat, NostrImportKeyInput, WalletSigner } from \"./types.ts\";\n\nexport type {\n DerivedNostrKey,\n NostrApi,\n NostrExportKeyFormat,\n NostrImportKeyInput,\n NostrKeyInfo,\n NostrKeyRef,\n NostrUnwrapResult,\n WalletSigner,\n} from \"./types.ts\";\n\nfunction createNostrApi(internals: WalletInternals): NostrApi {\n return {\n signer: (ref: NostrKeyRef): WalletSigner => proxySigner(ref, 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, groupIndex: number): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.deriveKey\", { walletId, groupIndex }),\n\n importKey: async (\n input: NostrImportKeyInput,\n options?: { readonly factor?: InitialFactor },\n ): Promise<NostrKeyInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await internals.createFactorParam(options?.factor, transfer);\n const wireInput =\n \"nsec\" in input\n ? { kind: \"nsec\" as const, nsec: wireSecretText(input.nsec, transfer) }\n : {\n kind: \"ncryptsec\" as const,\n ncryptsec: input.ncryptsec,\n password: wireSecretText(input.password, transfer),\n };\n const result = await internals.call(\n \"nostr.importKey\",\n { input: wireInput, ...(factor === undefined ? {} : { factor }) },\n transfer,\n );\n internals.sessionOf(result);\n return result.key;\n },\n\n generateKey: async (options?: { readonly factor?: InitialFactor }): Promise<NostrKeyInfo> => {\n const transfer: ArrayBuffer[] = [];\n const factor = await internals.createFactorParam(options?.factor, transfer);\n const result = await internals.call(\n \"nostr.generateKey\",\n factor === undefined ? {} : { factor },\n transfer,\n );\n internals.sessionOf(result);\n return result.key;\n },\n\n createNip46ClientKey: async (): Promise<NostrKeyInfo> =>\n internals.call(\"nostr.createNip46ClientKey\", null),\n\n removeKey: async (ref: NostrKeyRef, verify?: UnlockFactor): Promise<void> =>\n internals.withVerifying(async () => {\n const info = keyInfoOf(internals, ref); // resolves ref → publicKey + origin\n const transfer: ArrayBuffer[] = [];\n let wireVerify;\n if (info.origin !== \"nip46-client\") {\n if (verify === undefined) {\n throw new WalletError(\"invalid-input\", \"factor verification is required\");\n }\n wireVerify = await internals.resolveFactor(verify, transfer);\n }\n await internals.call(\n \"nostr.removeKey\",\n {\n publicKey: info.publicKey,\n ...(wireVerify === undefined ? {} : { verify: wireVerify }),\n },\n transfer,\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":";;;;;;;;;;;AAiBA,SAAgB,UAAU,WAA4B,KAAgC;CACpF,MAAM,OAAO,UAAU,SAAS,CAAC,CAAC,MAAM,KAAK,MAAM,QAAQ;EACzD,MAAM,IAAI,IAAI;EACd,OACG,IAAI,SAAS,aACZ,EAAE,SAAS,aACX,EAAE,aAAa,IAAI,YACnB,EAAE,eAAe,IAAI,cACtB,IAAI,SAAS,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,OAAO,IAAI,MACzE,IAAI,SAAS,gBAAgB,EAAE,SAAS,gBAAgB,EAAE,OAAO,IAAI;CAE1E,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,SA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