@qntx/wallet 0.0.0-stage → 0.2.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,375 @@
1
+ import { WalletError } from "./types.mjs";
2
+ import { a as kernelEvent, i as isProtocolValue, l as ValidationError, o as responseError, t as METHODS } from "./protocol-D9_0sY_Y.mjs";
3
+ import { base64urlnopad } from "@scure/base";
4
+ //#region src/channel.ts
5
+ /**
6
+ * The host side of the kernel channel (design/enclave.mdx "协议与传输"): port lifecycle, respawn,
7
+ * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for
8
+ * host packages (wallet-worker, wallet-native); applications must not use it.
9
+ */
10
+ function integrity(message) {
11
+ return new WalletError("integrity", message);
12
+ }
13
+ var Channel = class {
14
+ /** The live kernel session; attached to every request and cleared whenever it is gone. */
15
+ session;
16
+ port;
17
+ unlisten;
18
+ unlistenExit;
19
+ generation = 0;
20
+ pending = /* @__PURE__ */ new Map();
21
+ nextId = 1;
22
+ destroyed = false;
23
+ /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */
24
+ broken;
25
+ /** Whether the current port has delivered its first valid status event. */
26
+ portReady = false;
27
+ readyPromise;
28
+ resolveReady;
29
+ rejectReady;
30
+ spawn;
31
+ handlers;
32
+ constructor(spawn, handlers) {
33
+ this.spawn = spawn;
34
+ this.handlers = handlers;
35
+ this.readyPromise = new Promise((resolve, reject) => {
36
+ this.resolveReady = resolve;
37
+ this.rejectReady = reject;
38
+ });
39
+ }
40
+ /** Spawns the first kernel and resolves once its initial status event arrives. */
41
+ async start() {
42
+ this.respawn();
43
+ return this.readyPromise;
44
+ }
45
+ /** Resolves when the current port has delivered its first status event. */
46
+ get ready() {
47
+ return this.readyPromise;
48
+ }
49
+ /**
50
+ * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the
51
+ * host-side store survives the worker). "Lock destroys the enclave."
52
+ */
53
+ respawn() {
54
+ if (this.destroyed || this.broken !== void 0) return;
55
+ this.unlisten?.();
56
+ this.unlistenExit?.();
57
+ this.port?.terminate();
58
+ this.port = void 0;
59
+ this.session = void 0;
60
+ this.portReady = false;
61
+ const generation = ++this.generation;
62
+ this.readyPromise.catch(() => void 0);
63
+ this.rejectReady?.(new WalletError("locked", "the kernel restarted"));
64
+ this.readyPromise = new Promise((resolve, reject) => {
65
+ this.resolveReady = resolve;
66
+ this.rejectReady = reject;
67
+ });
68
+ this.readyPromise.catch(() => void 0);
69
+ try {
70
+ const port = this.spawn();
71
+ this.unlisten = port.listen((message) => {
72
+ this.onMessage(message, generation);
73
+ });
74
+ this.unlistenExit = port.onExit(() => {
75
+ this.onExit(generation);
76
+ });
77
+ this.port = port;
78
+ } catch {
79
+ this.breakChannel(integrity("could not spawn the kernel port"));
80
+ }
81
+ }
82
+ onExit(generation) {
83
+ if (generation !== this.generation || this.destroyed || this.broken !== void 0) return;
84
+ this.session = void 0;
85
+ if (!this.portReady) {
86
+ this.breakChannel(integrity("the kernel port died before its first status"));
87
+ return;
88
+ }
89
+ this.failPending(new WalletError("crashed", "the kernel port exited"));
90
+ this.handlers.onCrashed();
91
+ this.respawn();
92
+ }
93
+ failPending(error) {
94
+ for (const [, pending] of this.pending) pending.reject(error);
95
+ this.pending.clear();
96
+ }
97
+ /**
98
+ * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every
99
+ * later call rejects with the same error. The snapshot is left untouched.
100
+ */
101
+ breakChannel(error) {
102
+ this.broken = error;
103
+ this.session = void 0;
104
+ this.failPending(error);
105
+ this.rejectReady?.(error);
106
+ this.unlisten?.();
107
+ this.unlistenExit?.();
108
+ this.port?.terminate();
109
+ this.port = void 0;
110
+ this.generation++;
111
+ }
112
+ /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */
113
+ poison(reason) {
114
+ this.breakChannel(integrity(reason));
115
+ }
116
+ onMessage(raw, generation) {
117
+ if (generation !== this.generation) return;
118
+ if (!isProtocolValue(raw) || typeof raw !== "object" || raw === null || raw instanceof Uint8Array || Array.isArray(raw)) {
119
+ this.poison("malformed kernel message");
120
+ return;
121
+ }
122
+ const message = raw;
123
+ if ("id" in message) {
124
+ this.onResponse(message);
125
+ return;
126
+ }
127
+ if ("event" in message) {
128
+ let event;
129
+ try {
130
+ event = kernelEvent(message);
131
+ } catch (error) {
132
+ if (!(error instanceof ValidationError)) throw error;
133
+ this.poison("malformed kernel event");
134
+ return;
135
+ }
136
+ if (event.event === "status") {
137
+ if (event.status.vault !== "unlocked") this.session = void 0;
138
+ this.portReady = true;
139
+ this.handlers.onStatus(event.status);
140
+ this.resolveReady?.();
141
+ } else {
142
+ this.session = void 0;
143
+ this.handlers.onLocked(event.reason);
144
+ this.failPending(new WalletError("locked", "the vault locked"));
145
+ this.respawn();
146
+ }
147
+ return;
148
+ }
149
+ this.poison("unrecognised kernel message");
150
+ }
151
+ onResponse(message) {
152
+ const { id } = message;
153
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || message["v"] !== 1) {
154
+ this.poison("malformed response envelope");
155
+ return;
156
+ }
157
+ const pending = this.pending.get(id);
158
+ if (pending === void 0) {
159
+ this.poison("response for an unknown request");
160
+ return;
161
+ }
162
+ const hasOk = "ok" in message;
163
+ const hasErr = "err" in message;
164
+ if (hasOk === hasErr) {
165
+ this.poison("malformed response body");
166
+ return;
167
+ }
168
+ if (hasErr) {
169
+ try {
170
+ const err = responseError(message["err"]);
171
+ this.pending.delete(id);
172
+ pending.reject(new WalletError(err.code, `kernel returned ${err.code}`, typeof err.retryAt === "number" ? err.retryAt : void 0));
173
+ } catch (error) {
174
+ if (!(error instanceof ValidationError)) throw error;
175
+ this.poison("malformed error payload");
176
+ }
177
+ return;
178
+ }
179
+ try {
180
+ const result = METHODS[pending.method].result(message["ok"]);
181
+ this.pending.delete(id);
182
+ pending.resolve(result);
183
+ } catch (error) {
184
+ if (!(error instanceof ValidationError)) throw error;
185
+ this.poison("invalid result from the kernel");
186
+ }
187
+ }
188
+ /**
189
+ * Sends one request and resolves with the validated result. The kernel answers with status →
190
+ * response → locked, so the snapshot is already current when this promise settles.
191
+ */
192
+ async call(method, params, transfer = []) {
193
+ await this.readyPromise;
194
+ if (this.broken !== void 0) throw this.broken;
195
+ const { port } = this;
196
+ if (this.destroyed || port === void 0) throw new WalletError("locked", "wallet is destroyed");
197
+ const id = this.nextId++;
198
+ const message = {
199
+ v: 1,
200
+ id,
201
+ method,
202
+ params
203
+ };
204
+ if (this.session !== void 0) message["session"] = this.session;
205
+ return await new Promise((resolve, reject) => {
206
+ this.pending.set(id, {
207
+ method,
208
+ resolve,
209
+ reject
210
+ });
211
+ try {
212
+ port.post(message, transfer);
213
+ } catch {
214
+ this.pending.delete(id);
215
+ reject(integrity("the kernel port refused the message"));
216
+ }
217
+ });
218
+ }
219
+ /** Terminates the port without respawn; later calls fail "locked". */
220
+ destroy() {
221
+ if (this.destroyed) return;
222
+ this.destroyed = true;
223
+ this.unlisten?.();
224
+ this.unlistenExit?.();
225
+ this.port?.terminate();
226
+ this.port = void 0;
227
+ this.session = void 0;
228
+ this.rejectReady?.(new WalletError("locked", "wallet is destroyed"));
229
+ this.failPending(new WalletError("locked", "wallet is destroyed"));
230
+ }
231
+ };
232
+ //#endregion
233
+ //#region src/factors.ts
234
+ /**
235
+ * Factor plumbing for the host connector: public `UnlockFactor`/`InitialFactor` inputs become wire
236
+ * `Factor` material, passkey material comes from the host's WebAuthn ceremony, and every secret
237
+ * byte travels in a fresh exact-size buffer on the transfer list.
238
+ */
239
+ function vaultSaltBytes(source) {
240
+ return new TextEncoder().encode(source.passkey.vaultSalt);
241
+ }
242
+ function walletSaltBytes(source) {
243
+ return new TextEncoder().encode(source.passkey.walletSalt);
244
+ }
245
+ /** Passkey credential ids of the current vault factors, for `assert`'s allowCredentials. */
246
+ function passkeyCredentialIds(source) {
247
+ return source.factors().flatMap((factor) => factor.kind === "passkey" ? [base64urlnopad.decode(factor.credentialId)] : []);
248
+ }
249
+ /**
250
+ * A Uint8Array is placed on the wire in a fresh exact-size buffer whose ArrayBuffer goes into the
251
+ * transfer list — the bytes move to the kernel and cannot detach caller-owned memory. Secret
252
+ * sources are wiped after copying.
253
+ */
254
+ function wireBytes(source, transfer, wipeSource = false) {
255
+ const wire = new Uint8Array(source);
256
+ if (wipeSource) source.fill(0);
257
+ transfer.push(wire.buffer);
258
+ return wire;
259
+ }
260
+ function wireSecretText(text, transfer) {
261
+ return wireBytes(new TextEncoder().encode(text), transfer);
262
+ }
263
+ function requireCeremony(source) {
264
+ if (source.ceremony === void 0) throw new WalletError("factor-unavailable", "no passkey ceremony is configured");
265
+ return source.ceremony;
266
+ }
267
+ /** A passkey credential's display name: trimmed, 1–64 UTF-16 code units, else invalid-input. */
268
+ function passkeyName(name) {
269
+ const trimmed = name.trim();
270
+ if (trimmed.length === 0 || trimmed.length > 64) throw new WalletError("invalid-input", "the passkey name must be 1–64 characters");
271
+ return trimmed;
272
+ }
273
+ /**
274
+ * Resolves a public `UnlockFactor` to wire factor material. `transfer` collects every buffer the
275
+ * port must move. Ceremony errors surface as they are (cancelled / factor-unavailable).
276
+ */
277
+ async function resolveFactor(source, factor, transfer) {
278
+ if (factor.kind === "password") return {
279
+ kind: "password",
280
+ password: wireSecretText(factor.password, transfer)
281
+ };
282
+ const result = await requireCeremony(source).assert({
283
+ credentialIds: passkeyCredentialIds(source),
284
+ salts: { first: vaultSaltBytes(source) }
285
+ });
286
+ return {
287
+ kind: "passkey",
288
+ credentialId: wireBytes(result.credentialId, transfer),
289
+ prf: wireBytes(result.first, transfer, true)
290
+ };
291
+ }
292
+ /**
293
+ * Resolves a public `InitialFactor` (a factor being created). For `create/restoreWithPasskey` the
294
+ * default passkey factor reuses the wallet ceremony's own credential and `second` PRF output.
295
+ */
296
+ async function resolveInitialFactor(source, factor, transfer, walletCeremony) {
297
+ if (factor === void 0 || factor.kind === "passkey") {
298
+ const name = factor === void 0 ? void 0 : passkeyName(factor.name);
299
+ if (walletCeremony !== void 0) {
300
+ const { second } = walletCeremony;
301
+ if (second === void 0) throw new WalletError("factor-unavailable", "the ceremony returned no vault PRF output");
302
+ return {
303
+ kind: "passkey",
304
+ credentialId: wireBytes(walletCeremony.credentialId, transfer),
305
+ prf: wireBytes(second, transfer, true)
306
+ };
307
+ }
308
+ if (name === void 0) throw new WalletError("invalid-input", "a passkey factor requires a name");
309
+ const result = await requireCeremony(source).create({
310
+ purpose: "vault",
311
+ name,
312
+ salts: { first: vaultSaltBytes(source) }
313
+ });
314
+ return {
315
+ kind: "passkey",
316
+ credentialId: wireBytes(result.credentialId, transfer),
317
+ prf: wireBytes(result.first, transfer, true)
318
+ };
319
+ }
320
+ if (factor.kind === "password") {
321
+ walletCeremony?.second?.fill(0);
322
+ return {
323
+ kind: "password",
324
+ password: wireSecretText(factor.password, transfer)
325
+ };
326
+ }
327
+ throw new WalletError("factor-unavailable", "hardware factors exist only on React Native");
328
+ }
329
+ //#endregion
330
+ //#region src/internal.ts
331
+ /**
332
+ * Channel internals shared between the core Wallet and the protocol subpath modules
333
+ * (@qntx/wallet/nostr, later spark/chains). This file is NOT a package subpath — modules look a
334
+ * Wallet up in the WeakMap, so a foreign object has no channel to reach.
335
+ */
336
+ const internals = /* @__PURE__ */ new WeakMap();
337
+ function registerInternals(wallet, value) {
338
+ internals.set(wallet, value);
339
+ }
340
+ /**
341
+ * The internals behind a Wallet from this package — or `invalid-input` for anything else. A foreign
342
+ * object can imitate the Wallet shape but can never hold the channel: modules that look it up here
343
+ * get a closed failure, not a crafted kernel.
344
+ */
345
+ function internalsOf(wallet) {
346
+ const found = internals.get(wallet);
347
+ if (found === void 0) throw new WalletError("invalid-input", "not a Wallet from @qntx/wallet");
348
+ return found;
349
+ }
350
+ //#endregion
351
+ //#region src/secret.ts
352
+ /**
353
+ * One-shot secret bytes handed to the app: `read` returns them exactly once, `wipe` zeroes them.
354
+ * The second `read` fails closed.
355
+ */
356
+ var SingleUseSecret = class {
357
+ bytes;
358
+ constructor(bytes) {
359
+ this.bytes = bytes;
360
+ }
361
+ read() {
362
+ const { bytes } = this;
363
+ if (bytes === void 0) throw new WalletError("invalid-input", "secret already read or wiped");
364
+ this.bytes = void 0;
365
+ return bytes;
366
+ }
367
+ wipe() {
368
+ this.bytes?.fill(0);
369
+ this.bytes = void 0;
370
+ }
371
+ };
372
+ //#endregion
373
+ export { requireCeremony as a, vaultSaltBytes as c, wireSecretText as d, Channel as f, passkeyName as i, walletSaltBytes as l, internalsOf as n, resolveFactor as o, integrity as p, registerInternals as r, resolveInitialFactor as s, SingleUseSecret as t, wireBytes as u };
374
+
375
+ //# sourceMappingURL=secret-B-P3QOym.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-B-P3QOym.mjs","names":[],"sources":["../src/channel.ts","../src/factors.ts","../src/internal.ts","../src/secret.ts"],"sourcesContent":["/**\n * The host side of the kernel channel (design/enclave.mdx \"协议与传输\"): port lifecycle, respawn,\n * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for\n * host packages (wallet-worker, wallet-native); applications must not use it.\n */\nimport {\n isProtocolValue,\n kernelEvent,\n METHODS,\n PROTOCOL_VERSION,\n responseError,\n ValidationError,\n} from \"./protocol/index.ts\";\nimport type { MethodName, ParamsOf, ProtocolValue, ResultOf } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { LockReason, StatusPayload } from \"./types.ts\";\n\n/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */\nexport type MainPort = {\n readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n readonly onExit: (handler: () => void) => () => void;\n readonly terminate: () => void;\n};\n\nexport function integrity(message: string): WalletError {\n return new WalletError(\"integrity\", message);\n}\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/**\n * State callbacks: the channel owns the port lifecycle and message ordering; the wallet owns the\n * snapshot state these events describe. `onLocked`/`onCrashed` fire before the port is replaced so\n * the wallet can stamp the lock reason.\n */\nexport type ChannelHandlers = {\n readonly onStatus: (status: StatusPayload) => void;\n readonly onLocked: (reason: LockReason) => void;\n readonly onCrashed: () => void;\n};\n\nexport class Channel {\n /** The live kernel session; attached to every request and cleared whenever it is gone. */\n session: string | undefined;\n\n private port: MainPort | undefined;\n private unlisten: (() => void) | undefined;\n private unlistenExit: (() => void) | undefined;\n private generation = 0;\n\n private readonly pending = new Map<number, Pending>();\n private nextId = 1;\n private destroyed = false;\n /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */\n private broken: WalletError | undefined;\n /** Whether the current port has delivered its first valid status event. */\n private portReady = false;\n private readyPromise: Promise<void>;\n private resolveReady: (() => void) | undefined;\n private rejectReady: ((error: WalletError) => void) | undefined;\n\n private readonly spawn: () => MainPort;\n private readonly handlers: ChannelHandlers;\n\n constructor(spawn: () => MainPort, handlers: ChannelHandlers) {\n this.spawn = spawn;\n this.handlers = handlers;\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n }\n\n /** Spawns the first kernel and resolves once its initial status event arrives. */\n async start(): Promise<void> {\n this.respawn();\n return this.readyPromise;\n }\n\n /** Resolves when the current port has delivered its first status event. */\n get ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the\n * host-side store survives the worker). \"Lock destroys the enclave.\"\n */\n respawn(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.portReady = false;\n\n const generation = ++this.generation;\n // Settle the previous gate: a call still awaiting it must not hang — the kernel it was\n // waiting for is gone, so \"locked\" (session destroyed) applies.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the stale gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n this.rejectReady?.(new WalletError(\"locked\", \"the kernel restarted\"));\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A rejected gate with nobody awaiting it (e.g. destroy() mid-boot) must not surface as\n // an unhandled rejection; callers that do await still observe the rejection.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n try {\n const port = this.spawn();\n this.unlisten = port.listen((message) => {\n this.onMessage(message, generation);\n });\n this.unlistenExit = port.onExit(() => {\n this.onExit(generation);\n });\n this.port = port;\n } catch {\n // A host that cannot spawn has no kernel to talk to — fail closed like a dead peer.\n this.breakChannel(integrity(\"could not spawn the kernel port\"));\n }\n }\n\n private onExit(generation: number): void {\n if (generation !== this.generation || this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n if (!this.portReady) {\n // Death before the first valid status means the runtime never ran honestly (worker\n // blocked by CSP, a script that fails to load, protocol skew): no respawn — a fresh\n // spawn would face the same broken peer. Initial connect rejects with integrity;\n // a respawned port dying this way breaks the wallet.\n this.breakChannel(integrity(\"the kernel port died before its first status\"));\n return;\n }\n // A proven port dying is a crash: fail everything in flight, mark it, respawn.\n this.failPending(new WalletError(\"crashed\", \"the kernel port exited\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n private failPending(error: WalletError): void {\n for (const [, pending] of this.pending) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n /**\n * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every\n * later call rejects with the same error. The snapshot is left untouched.\n */\n private breakChannel(error: WalletError): void {\n this.broken = error;\n this.session = undefined;\n this.failPending(error);\n this.rejectReady?.(error);\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.generation++; // anything the dead port still emits is stale\n }\n\n /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */\n private poison(reason: string): void {\n this.breakChannel(integrity(reason));\n }\n\n private onMessage(raw: unknown, generation: number): void {\n if (generation !== this.generation) {\n return; // a dead port must not steer the wallet\n }\n if (\n !isProtocolValue(raw) ||\n typeof raw !== \"object\" ||\n raw === null ||\n raw instanceof Uint8Array ||\n Array.isArray(raw)\n ) {\n this.poison(\"malformed kernel message\");\n return;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain record above\n const message = raw as Readonly<Record<string, ProtocolValue>>;\n if (\"id\" in message) {\n this.onResponse(message);\n return;\n }\n if (\"event\" in message) {\n let event;\n try {\n event = kernelEvent(message);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed kernel event\");\n return;\n }\n if (event.event === \"status\") {\n if (event.status.vault !== \"unlocked\") {\n this.session = undefined;\n }\n this.portReady = true;\n this.handlers.onStatus(event.status);\n this.resolveReady?.();\n } else {\n // A locked event destroys the enclave: drop the session, tear down the port, respawn.\n this.session = undefined;\n this.handlers.onLocked(event.reason);\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.respawn();\n }\n return;\n }\n this.poison(\"unrecognised kernel message\");\n }\n\n private onResponse(message: Readonly<Record<string, ProtocolValue>>): void {\n const { id } = message;\n if (typeof id !== \"number\" || !Number.isSafeInteger(id) || message[\"v\"] !== PROTOCOL_VERSION) {\n this.poison(\"malformed response envelope\");\n return;\n }\n const pending = this.pending.get(id);\n if (pending === undefined) {\n // Includes UNATTRIBUTED_ID 0 — never a live request.\n this.poison(\"response for an unknown request\");\n return;\n }\n const hasOk = \"ok\" in message;\n const hasErr = \"err\" in message;\n if (hasOk === hasErr) {\n // Keep the entry so poison's failPending rejects this caller too.\n this.poison(\"malformed response body\");\n return;\n }\n if (hasErr) {\n try {\n const err = responseError(message[\"err\"]);\n this.pending.delete(id);\n pending.reject(\n new WalletError(\n err.code,\n `kernel returned ${err.code}`,\n typeof err.retryAt === \"number\" ? err.retryAt : undefined,\n ),\n );\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed error payload\");\n }\n return;\n }\n try {\n const result = METHODS[pending.method].result(message[\"ok\"]);\n this.pending.delete(id);\n pending.resolve(result);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"invalid result from the kernel\");\n }\n }\n\n /**\n * Sends one request and resolves with the validated result. The kernel answers with status →\n * response → locked, so the snapshot is already current when this promise settles.\n */\n async call<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer: ArrayBuffer[] = [],\n ): Promise<ResultOf<M>> {\n await this.readyPromise;\n if (this.broken !== undefined) {\n throw this.broken;\n }\n const { port } = this;\n if (this.destroyed || port === undefined) {\n throw new WalletError(\"locked\", \"wallet is destroyed\");\n }\n const id = this.nextId++;\n const message: Record<string, ProtocolValue> = { v: PROTOCOL_VERSION, id, method, params };\n // Attach the session whenever we hold one: the create/import methods are session:false\n // in the table because the rule is dynamic (required exactly when the vault is initialized).\n if (this.session !== undefined) {\n message[\"session\"] = this.session;\n }\n const result = await new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n try {\n port.post(message, transfer);\n } catch {\n this.pending.delete(id);\n reject(integrity(\"the kernel port refused the message\"));\n }\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n }\n\n /** Terminates the port without respawn; later calls fail \"locked\". */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.rejectReady?.(new WalletError(\"locked\", \"wallet is destroyed\"));\n this.failPending(new WalletError(\"locked\", \"wallet is destroyed\"));\n }\n}\n","/**\n * Factor plumbing for the host connector: public `UnlockFactor`/`InitialFactor` inputs become wire\n * `Factor` material, passkey material comes from the host's WebAuthn ceremony, and every secret\n * byte travels in a fresh exact-size buffer on the transfer list.\n */\nimport { base64urlnopad } from \"@scure/base\";\n\nimport type { Factor } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { FactorInfo, InitialFactor, PasskeyConfig, UnlockFactor } from \"./types.ts\";\n\nexport type PrfSalts = { readonly first: Uint8Array; readonly second?: Uint8Array };\n\nexport type PrfResult = {\n readonly credentialId: Uint8Array;\n readonly first: Uint8Array;\n readonly second?: Uint8Array;\n};\n\n/**\n * The WebAuthn ceremony the host performs. Implementations throw `WalletError` — \"cancelled\" when\n * the user aborts, \"factor-unavailable\" when the credential cannot produce a PRF. `name` is the new\n * credential's display name, validated by the host before the call (1–64 characters).\n */\nexport type PasskeyCeremony = {\n readonly create: (input: {\n readonly purpose: \"wallet\" | \"vault\";\n readonly name: string;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n readonly assert: (input: {\n readonly credentialIds?: ReadonlyArray<Uint8Array>;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n};\n\n/** What factor resolution needs from the wallet: config, the ceremony, live factor records. */\nexport type FactorSource = {\n readonly passkey: PasskeyConfig;\n readonly ceremony: PasskeyCeremony | undefined;\n readonly factors: () => ReadonlyArray<FactorInfo>;\n};\n\nexport function vaultSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.vaultSalt);\n}\n\nexport function walletSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.walletSalt);\n}\n\n/** Passkey credential ids of the current vault factors, for `assert`'s allowCredentials. */\nfunction passkeyCredentialIds(source: FactorSource): Uint8Array[] {\n return source\n .factors()\n .flatMap((factor) =>\n factor.kind === \"passkey\" ? [base64urlnopad.decode(factor.credentialId)] : [],\n );\n}\n\n/**\n * A Uint8Array is placed on the wire in a fresh exact-size buffer whose ArrayBuffer goes into the\n * transfer list — the bytes move to the kernel and cannot detach caller-owned memory. Secret\n * sources are wiped after copying.\n */\nexport function wireBytes(\n source: Uint8Array,\n transfer: ArrayBuffer[],\n wipeSource = false,\n): Uint8Array {\n // Always a fresh exact-size buffer: transferring must never detach caller-owned memory.\n const wire = new Uint8Array(source);\n if (wipeSource) {\n source.fill(0);\n }\n transfer.push(wire.buffer);\n return wire;\n}\n\nexport function wireSecretText(text: string, transfer: ArrayBuffer[]): Uint8Array {\n return wireBytes(new TextEncoder().encode(text), transfer);\n}\n\nexport function requireCeremony(source: FactorSource): PasskeyCeremony {\n if (source.ceremony === undefined) {\n throw new WalletError(\"factor-unavailable\", \"no passkey ceremony is configured\");\n }\n return source.ceremony;\n}\n\n/** A passkey credential's display name: trimmed, 1–64 UTF-16 code units, else invalid-input. */\nexport function passkeyName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > 64) {\n throw new WalletError(\"invalid-input\", \"the passkey name must be 1–64 characters\");\n }\n return trimmed;\n}\n\n/**\n * Resolves a public `UnlockFactor` to wire factor material. `transfer` collects every buffer the\n * port must move. Ceremony errors surface as they are (cancelled / factor-unavailable).\n */\nexport async function resolveFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<Factor> {\n if (factor.kind === \"password\") {\n return { kind: \"password\", password: wireSecretText(factor.password, transfer) };\n }\n const ceremony = requireCeremony(source);\n const result = await ceremony.assert({\n credentialIds: passkeyCredentialIds(source),\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wireBytes(result.credentialId, transfer),\n prf: wireBytes(result.first, transfer, true),\n };\n}\n\n/**\n * Resolves a public `InitialFactor` (a factor being created). For `create/restoreWithPasskey` the\n * default passkey factor reuses the wallet ceremony's own credential and `second` PRF output.\n */\nexport async function resolveInitialFactor(\n source: FactorSource,\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n walletCeremony?: PrfResult,\n): Promise<Factor> {\n if (factor === undefined || factor.kind === \"passkey\") {\n const name = factor === undefined ? undefined : passkeyName(factor.name);\n if (walletCeremony !== undefined) {\n const { second } = walletCeremony;\n if (second === undefined) {\n throw new WalletError(\"factor-unavailable\", \"the ceremony returned no vault PRF output\");\n }\n return {\n kind: \"passkey\",\n credentialId: wireBytes(walletCeremony.credentialId, transfer),\n prf: wireBytes(second, transfer, true),\n };\n }\n if (name === undefined) {\n // No caller reaches this today (createFactorParam requires a factor), but the ceremony\n // contract needs a name — fail closed rather than inventing one.\n throw new WalletError(\"invalid-input\", \"a passkey factor requires a name\");\n }\n const result = await requireCeremony(source).create({\n purpose: \"vault\",\n name,\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wireBytes(result.credentialId, transfer),\n prf: wireBytes(result.first, transfer, true),\n };\n }\n if (factor.kind === \"password\") {\n walletCeremony?.second?.fill(0); // the passkey vault factor is not needed\n return { kind: \"password\", password: wireSecretText(factor.password, transfer) };\n }\n throw new WalletError(\"factor-unavailable\", \"hardware factors exist only on React Native\");\n}\n","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","import { WalletError } from \"./types.ts\";\nimport type { ExportedSecret } from \"./types.ts\";\n\n/**\n * One-shot secret bytes handed to the app: `read` returns them exactly once, `wipe` zeroes them.\n * The second `read` fails closed.\n */\nexport class SingleUseSecret implements ExportedSecret {\n private bytes: Uint8Array | undefined;\n\n constructor(bytes: Uint8Array) {\n this.bytes = bytes;\n }\n\n read(): Uint8Array {\n const { bytes } = this;\n if (bytes === undefined) {\n throw new WalletError(\"invalid-input\", \"secret already read or wiped\");\n }\n this.bytes = undefined;\n return bytes;\n }\n\n wipe(): void {\n this.bytes?.fill(0);\n this.bytes = undefined;\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgB,UAAU,SAA8B;CACtD,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;AAmBA,IAAa,UAAb,MAAqB;;CAEnB;CAEA;CACA;CACA;CACA,aAAqB;CAErB,0BAA2B,IAAI,IAAqB;CACpD,SAAiB;CACjB,YAAoB;;CAEpB;;CAEA,YAAoB;CACpB;CACA;CACA;CAEA;CACA;CAEA,YAAY,OAAuB,UAA2B;EAC5D,KAAK,QAAQ;EACb,KAAK,WAAW;EAChB,KAAK,eAAe,IAAI,SAAS,SAAS,WAAW;GACnD,KAAK,eAAe;GACpB,KAAK,cAAc;EACrB,CAAC;CACH;;CAGA,MAAM,QAAuB;EAC3B,KAAK,QAAQ;EACb,OAAO,KAAK;CACd;;C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,sBAAsB,6CAA6C;AAC3F;;;;;;;;ACvIA,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;;;;;;;AC1CA,IAAa,kBAAb,MAAuD;CACrD;CAEA,YAAY,OAAmB;EAC7B,KAAK,QAAQ;CACf;CAEA,OAAmB;EACjB,MAAM,EAAE,UAAU;EAClB,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,YAAY,iBAAiB,8BAA8B;EAEvE,KAAK,QAAQ,KAAA;EACb,OAAO;CACT;CAEA,OAAa;EACX,KAAK,OAAO,KAAK,CAAC;EAClB,KAAK,QAAQ,KAAA;CACf;AACF"}
@@ -0,0 +1,168 @@
1
+ //#region src/types.d.ts
2
+ /** Public types of @qntx/wallet, per design/entry.mdx. Secret data never appears here. */
3
+ type LockReason = "cold-start" | "user" | "idle" | "background" | "expired" | "crashed";
4
+ type FactorInfo = {
5
+ readonly kind: "hardware";
6
+ } | {
7
+ readonly kind: "passkey";
8
+ readonly id: string;
9
+ /** Base64url, public data — the main side passes it as allowCredentials. */
10
+ readonly credentialId: string;
11
+ readonly createdAt: number;
12
+ } | {
13
+ readonly kind: "password";
14
+ readonly id: string;
15
+ readonly createdAt: number;
16
+ };
17
+ type WalletInfo = {
18
+ readonly walletId: string;
19
+ readonly origin: "passkey" | "mnemonic";
20
+ readonly words: 12 | 15 | 18 | 21 | 24;
21
+ readonly backedUp: boolean;
22
+ readonly createdAt: number;
23
+ };
24
+ type NostrKeyRef = {
25
+ readonly kind: "derived";
26
+ readonly walletId: string;
27
+ readonly groupIndex: number;
28
+ } | {
29
+ readonly kind: "standalone";
30
+ readonly id: string;
31
+ } | {
32
+ readonly kind: "nip46-client";
33
+ readonly id: string;
34
+ };
35
+ type NostrKeyInfo = {
36
+ readonly ref: NostrKeyRef;
37
+ readonly publicKey: string;
38
+ readonly origin: "derived" | "nsec" | "ncryptsec" | "generated" | "nip46-client";
39
+ readonly createdAt: number;
40
+ };
41
+ /** One entry of a `nostr.discover` result: the public key an account group would produce. */
42
+ type DerivedNostrKey = {
43
+ readonly groupIndex: number;
44
+ readonly publicKey: string;
45
+ };
46
+ type WalletErrorCode = "locked" | "cancelled" | "factor-unavailable" | "factor-invalidated" | "wrong-password" | "rate-limited" | "invalid-input" | "not-found" | "already-exists" | "integrity" | "crashed";
47
+ /**
48
+ * `status` result / status event payload. Locked snapshots come from unauthenticated headers;
49
+ * "corrupted" means the vault data itself failed to load or verify (reset is the only way out).
50
+ * Each protocol module contributes one section (here: `nostr`).
51
+ */
52
+ type StatusPayload = {
53
+ readonly protocol: 1;
54
+ readonly vault: "uninitialized" | "locked" | "unlocked" | "corrupted";
55
+ readonly factors: ReadonlyArray<FactorInfo>;
56
+ readonly wallets: ReadonlyArray<WalletInfo>;
57
+ readonly nostr: {
58
+ readonly keys: ReadonlyArray<NostrKeyInfo>;
59
+ };
60
+ };
61
+ /** One error class for the whole API; `code` carries the distinction. Messages never echo input. */
62
+ declare class WalletError extends Error {
63
+ readonly code: WalletErrorCode;
64
+ readonly retryAt: number | undefined;
65
+ constructor(code: WalletErrorCode, message: string, retryAt?: number);
66
+ }
67
+ /** A factor the user proves again for a guarded operation (Web/Node). */
68
+ type UnlockFactor = {
69
+ readonly kind: "passkey";
70
+ } | {
71
+ readonly kind: "password";
72
+ readonly password: string;
73
+ };
74
+ /**
75
+ * A factor being created; `hardware` exists only on React Native. `name` is the passkey
76
+ * credential's display name — the host validates it before the ceremony (1–64 characters).
77
+ */
78
+ type InitialFactor = {
79
+ readonly kind: "hardware";
80
+ } | {
81
+ readonly kind: "passkey";
82
+ readonly name: string;
83
+ } | {
84
+ readonly kind: "password";
85
+ readonly password: string;
86
+ };
87
+ /** WebAuthn RP identity + PRF salt labels the host configures once (distinct strings). */
88
+ type PasskeyConfig = {
89
+ /** RP id — the origin's effective domain or a registrable parent of it (e.g. meowl.social). */
90
+ readonly rpId: string;
91
+ readonly rpName: string;
92
+ readonly walletSalt: string;
93
+ readonly vaultSalt: string;
94
+ };
95
+ type AutoLockPolicy = {
96
+ readonly platform: "native";
97
+ readonly backgroundSeconds: 0 | 60 | 300 | 900;
98
+ } | {
99
+ readonly platform: "web";
100
+ readonly idleMinutes: 5 | 15 | 60;
101
+ };
102
+ type WalletOptions = {
103
+ readonly passkey: PasskeyConfig;
104
+ readonly autoLock: AutoLockPolicy;
105
+ };
106
+ type WalletSnapshot = {
107
+ readonly vault: "uninitialized" | "locked" | "unlocked" | "corrupted";
108
+ readonly lockReason: LockReason | undefined;
109
+ readonly verifying: boolean;
110
+ readonly factors: ReadonlyArray<FactorInfo>;
111
+ readonly wallets: ReadonlyArray<WalletInfo>;
112
+ readonly nostr: {
113
+ readonly keys: ReadonlyArray<NostrKeyInfo>;
114
+ };
115
+ };
116
+ /** A one-shot secret buffer: `read` detaches the bytes to the caller, `wipe` zeroes them. */
117
+ type ExportedSecret = {
118
+ readonly read: () => Uint8Array;
119
+ readonly wipe: () => void;
120
+ };
121
+ type MnemonicDraft = {
122
+ readonly words: ExportedSecret;
123
+ readonly quiz: ReadonlyArray<number>;
124
+ readonly confirm: (answers: ReadonlyArray<string>) => Promise<WalletInfo>;
125
+ readonly discard: () => Promise<void>;
126
+ };
127
+ type VaultApi = {
128
+ readonly unlock: (factor?: UnlockFactor) => Promise<void>;
129
+ readonly lock: () => Promise<void>;
130
+ readonly addFactor: (factor: InitialFactor, verify: UnlockFactor) => Promise<FactorInfo>;
131
+ readonly removeFactor: (id: string, verify: UnlockFactor) => Promise<void>;
132
+ readonly reset: () => Promise<void>;
133
+ };
134
+ type WalletsApi = {
135
+ readonly createWithPasskey: (options: {
136
+ /** Display name for the new passkey credential (1–64 characters after trimming). */
137
+ readonly name: string;
138
+ readonly factor?: InitialFactor;
139
+ }) => Promise<WalletInfo>;
140
+ readonly restoreWithPasskey: (options?: {
141
+ readonly factor?: InitialFactor;
142
+ }) => Promise<WalletInfo>;
143
+ readonly createMnemonic: (options: {
144
+ readonly words: 12 | 24;
145
+ readonly factor?: InitialFactor;
146
+ }) => Promise<MnemonicDraft>;
147
+ readonly importMnemonic: (options: {
148
+ readonly mnemonic: string;
149
+ readonly factor?: InitialFactor;
150
+ }) => Promise<WalletInfo>;
151
+ /** One-shot mnemonic export; requires re-verification every call. */
152
+ readonly exportMnemonic: (walletId: string, verify: UnlockFactor) => Promise<ExportedSecret>;
153
+ readonly delete: (walletId: string, verify: UnlockFactor) => Promise<void>;
154
+ };
155
+ type DataKeyApi = {
156
+ readonly get: (purpose: string) => Promise<Uint8Array>;
157
+ };
158
+ type Wallet = {
159
+ readonly getSnapshot: () => WalletSnapshot;
160
+ readonly subscribe: (listener: () => void) => () => void;
161
+ readonly vault: VaultApi;
162
+ readonly wallets: WalletsApi;
163
+ readonly dataKeys: DataKeyApi;
164
+ readonly destroy: () => Promise<void>;
165
+ };
166
+ //#endregion
167
+ export { WalletErrorCode as _, FactorInfo as a, WalletSnapshot as b, MnemonicDraft as c, PasskeyConfig as d, StatusPayload as f, WalletError as g, Wallet as h, ExportedSecret as i, NostrKeyInfo as l, VaultApi as m, DataKeyApi as n, InitialFactor as o, UnlockFactor as p, DerivedNostrKey as r, LockReason as s, AutoLockPolicy as t, NostrKeyRef as u, WalletInfo as v, WalletsApi as x, WalletOptions as y };
168
+ //# sourceMappingURL=types-CEy7At1l.d.mts.map
@@ -0,0 +1,2 @@
1
+ import { _ as WalletErrorCode, a as FactorInfo, b as WalletSnapshot, 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 WalletsApi, y as WalletOptions } from "./types-CEy7At1l.mjs";
2
+ export { AutoLockPolicy, DataKeyApi, DerivedNostrKey, ExportedSecret, FactorInfo, InitialFactor, LockReason, MnemonicDraft, NostrKeyInfo, NostrKeyRef, PasskeyConfig, StatusPayload, UnlockFactor, VaultApi, Wallet, WalletError, WalletErrorCode, WalletInfo, WalletOptions, WalletSnapshot, WalletsApi };
package/dist/types.mjs ADDED
@@ -0,0 +1,16 @@
1
+ //#region src/types.ts
2
+ /** One error class for the whole API; `code` carries the distinction. Messages never echo input. */
3
+ var WalletError = class extends Error {
4
+ code;
5
+ retryAt;
6
+ constructor(code, message, retryAt) {
7
+ super(message);
8
+ this.name = "WalletError";
9
+ this.code = code;
10
+ this.retryAt = retryAt;
11
+ }
12
+ };
13
+ //#endregion
14
+ export { WalletError };
15
+
16
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +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 = \"cold-start\" | \"user\" | \"idle\" | \"background\" | \"expired\" | \"crashed\";\n\nexport type FactorInfo =\n | { readonly kind: \"hardware\" }\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 readonly backedUp: boolean;\n readonly createdAt: number;\n};\n\nexport type NostrKeyRef =\n | { readonly kind: \"derived\"; readonly walletId: string; readonly groupIndex: number }\n | { readonly kind: \"standalone\"; readonly id: string }\n | { readonly kind: \"nip46-client\"; readonly id: string };\n\nexport type NostrKeyInfo = {\n readonly ref: NostrKeyRef;\n readonly publicKey: string; // 64 lowercase hex\n readonly origin: \"derived\" | \"nsec\" | \"ncryptsec\" | \"generated\" | \"nip46-client\";\n readonly createdAt: number;\n};\n\n/** One entry of a `nostr.discover` result: the public key an account group would produce. */\nexport type DerivedNostrKey = { readonly groupIndex: number; readonly publicKey: string };\n\nexport type WalletErrorCode =\n | \"locked\"\n | \"cancelled\"\n | \"factor-unavailable\"\n | \"factor-invalidated\"\n | \"wrong-password\"\n | \"rate-limited\"\n | \"invalid-input\"\n | \"not-found\"\n | \"already-exists\"\n | \"integrity\"\n | \"crashed\";\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: 1;\n readonly vault: \"uninitialized\" | \"locked\" | \"unlocked\" | \"corrupted\";\n readonly factors: ReadonlyArray<FactorInfo>;\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly nostr: { readonly keys: ReadonlyArray<NostrKeyInfo> };\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/** A factor the user proves again for a guarded operation (Web/Node). */\nexport type UnlockFactor =\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/** WebAuthn RP identity + PRF salt labels the host configures once (distinct strings). */\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};\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 WalletOptions = {\n readonly passkey: PasskeyConfig;\n readonly autoLock: AutoLockPolicy;\n};\n\nexport type WalletSnapshot = {\n readonly vault: \"uninitialized\" | \"locked\" | \"unlocked\" | \"corrupted\";\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};\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\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 destroy: () => Promise<void>;\n};\n"],"mappings":";;AAgEA,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"}