@evolustr/client 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.
package/dist/client.js ADDED
@@ -0,0 +1,1181 @@
1
+ /**
2
+ * `@evolustr/client` (SPEC §8): opens the app's Evolu database for the
3
+ * signed-in Nostr user, on any device.
4
+ *
5
+ * All side effects come in through {@link ClientDeps}; every method returns a
6
+ * `Result` instead of throwing. Session state lives in one immutable record
7
+ * that each step replaces.
8
+ */
9
+ import { DATA_SECRET_LENGTH, ROOT_KEY_LENGTH, VAULT_KIND, addRootKey, dataSecretToEvoluMnemonic, addRootWrap, backupRequirement, canOpenOwnVault, hkdf, rootWrapKeyId, toHex, verifyRootWrap, clientPrfInput, createStrictVault, makeStrict as makeStrictVault, makeStrictWithNewRoot, rotateRoot as rotateRootVault, verifyRootRotation, openRootWrap, passkeyRootWrap, passkeyWrapKey, passkeyWrapsFor, signerRootWrap, signerWrapFor, sha256, sha256Hex, utf8, appVaultDTag, createCompatibleVault, decideVault, defaultSettings, emptySettings, mergeSettings, parseSettings, resolveSetting, setSetting, downgrade as downgradeVault, error, fetchReplaceable, hasRootKey, level, mergeVaults, migrationCutoff, nip44OpenSecret, nip44SealSecret, ok, openRootData, parseVault, phraseToRootKey, publishReplaceable, randomBytes as defaultRandomBytes, readVaultEvent, rootKeyToPhrase, serializeVault, vaultEvent, } from "@evolustr/core";
10
+ import { earlierSignerIds } from "./capable.js";
11
+ import { fetchSharedSettings, publishSharedSettings } from "./settings.js";
12
+ import { META_SHARED_SETTINGS, META_VAULT, migrateRows, } from "./database.js";
13
+ /** @deprecated No longer read or written: backup facts live on the device (`hints`, #53). */
14
+ export const META_PHRASE_CONFIRMED = "phraseConfirmed";
15
+ export const META_APP_SETTINGS = "appSettings";
16
+ /** Data secrets this device moved past, for rollback detection beyond the vault's history (#44). */
17
+ export const META_SEEN_SECRETS = "seenSecrets";
18
+ const SEEN_LIMIT = 200;
19
+ /** @deprecated No longer read or written: backup facts live on the device (`hints`, #53). */
20
+ export const META_STRONG_METHODS = "strongMethods";
21
+ // ── Implementation ──────────────────────────────────────────────────────────
22
+ export const createEvolustr = (deps, options) => {
23
+ const now = deps.now ?? (() => Math.floor(Date.now() / 1000));
24
+ const random = deps.randomBytes ?? defaultRandomBytes;
25
+ const timeoutMs = options.timeoutMs ?? 3000;
26
+ const clockMarginMs = options.clockMarginMs ?? 5 * 60_000;
27
+ let session = { kind: "none" };
28
+ let lastEventAt = 0;
29
+ let settingsState = { app: emptySettings, shared: emptySettings };
30
+ const settingsDefaults = options.settingsDefaults ?? defaultSettings();
31
+ const settingsIo = { signer: deps.signer, relays: deps.relays, relayUrls: options.relayUrls, timeoutMs, ...(options.relayQuorum === undefined ? {} : { relayQuorum: options.relayQuorum }) };
32
+ let passkeySupported = false;
33
+ let backupState = {
34
+ methods: [],
35
+ phraseConfirmed: false,
36
+ };
37
+ let pendingPasskey = null;
38
+ const passkeys = deps.passkeys;
39
+ const capable = deps.capableSigner;
40
+ let caps = null;
41
+ const refreshCaps = async () => {
42
+ caps = capable === undefined ? null : await capable.capabilities().catch(() => null);
43
+ return caps;
44
+ };
45
+ /** R through the capable signer's wrap (SPEC §8.2 step 2). May wait for a click in the signer. */
46
+ const rootFromSigner = async (ctx, vault, copy) => {
47
+ if (capable === undefined)
48
+ return error("noCapableSigner", "No Evolustr-capable signer");
49
+ let key;
50
+ try {
51
+ key = await capable.getWrapKey();
52
+ }
53
+ catch (e) {
54
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
55
+ }
56
+ const c = await refreshCaps();
57
+ if (c?.signerId == null)
58
+ return error("noSignerWrap", "This signer has no wrap in the vault yet");
59
+ // The fetched vault's wrap first, then the local copy's (#39).
60
+ const wrapsFor = (id) => [signerWrapFor(vault, id), copy === undefined ? undefined : signerWrapFor(copy, id)].filter((w) => w !== undefined);
61
+ const wraps = wrapsFor(c.signerId);
62
+ for (const wrap of wraps) {
63
+ const opened = openRootWrap(ctx, wrap, key);
64
+ if (opened.ok)
65
+ return opened;
66
+ }
67
+ // After the signer replaced its key, the wrap made with an earlier one (#52
68
+ // phase B), however many replacements ago (#58).
69
+ const earlier = earlierSignerIds(c).map((id, n) => ({ id, n, wraps: wrapsFor(id) })).filter((x) => x.wraps.length > 0);
70
+ if (capable.getPreviousWrapKey !== undefined) {
71
+ for (const { id, n, wraps: old } of earlier) {
72
+ let oldKey;
73
+ try {
74
+ // The newest needs no id, so signers from before #58 still answer.
75
+ oldKey = await capable.getPreviousWrapKey(n === 0 ? undefined : id);
76
+ }
77
+ catch (e) {
78
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
79
+ }
80
+ for (const wrap of old) {
81
+ const opened = openRootWrap(ctx, wrap, oldKey);
82
+ if (opened.ok)
83
+ return opened;
84
+ }
85
+ }
86
+ }
87
+ if (wraps.length === 0 && earlier.length === 0)
88
+ return error("noSignerWrap", "This signer has no wrap in the vault yet");
89
+ return error("signerRefused", "The signer's key didn't open its wrap");
90
+ };
91
+ /** After an unlock: add this signer's wrap, creating R if the vault has none (SPEC §8.2 step 5). */
92
+ const ensureSignerWrap = async () => {
93
+ if (session.kind !== "ready" || capable === undefined)
94
+ return;
95
+ const s = session;
96
+ let c = caps;
97
+ if (c === null)
98
+ return;
99
+ if (c.ready && c.signerId !== null && signerWrapFor(s.vault, c.signerId) !== undefined) {
100
+ // Refresh the record: the signer may have gained an sk wrap or a synced passkey (#42).
101
+ await rememberMethod(s.ctx, { id: `signer:${c.signerId}`, method: { kind: "signer", recoverable: c.recoverable === true } });
102
+ backupState = await readBackupState(s.ctx, s.vault, s.r);
103
+ return;
104
+ }
105
+ // A locked signer that needs a passkey click isn't asked here; the user adds it later.
106
+ if (!c.ready && c.signerPasskey)
107
+ return;
108
+ if (s.r === undefined && hasRootKey(s.vault))
109
+ return; // nip44-only device: can't add (SPEC §3.1)
110
+ let key;
111
+ try {
112
+ // Asks the user to allow this app; a new signer creates its key here (#29).
113
+ key = await capable.getWrapKey();
114
+ }
115
+ catch {
116
+ return;
117
+ }
118
+ c = await refreshCaps();
119
+ if (c === null || c.signerId === null || signerWrapFor(s.vault, c.signerId) !== undefined)
120
+ return;
121
+ const signerIdNow = c.signerId;
122
+ let vault = s.vault;
123
+ const r = s.r ?? random(ROOT_KEY_LENGTH);
124
+ if (s.r === undefined) {
125
+ const withRoot = addRootKey(s.ctx, vault, r, s.s);
126
+ if (!withRoot.ok)
127
+ return;
128
+ vault = withRoot.value;
129
+ }
130
+ const added = addRootWrap(vault, signerRootWrap(s.ctx, key, signerIdNow, r));
131
+ if (!added.ok)
132
+ return;
133
+ const published = await publishVault(s.ctx, added.value);
134
+ if (!published.ok)
135
+ return;
136
+ await rememberMethod(s.ctx, { id: `signer:${signerIdNow}`, method: { kind: "signer", recoverable: c.recoverable === true } });
137
+ // Local copy source (#38): (a) made by this device: its signer wrap added.
138
+ await becomeReady(s.ctx, published.value, s.s, r, s.unlockedWith, s.db);
139
+ };
140
+ const readDoc = async (db, key) => {
141
+ const text = await db.getMeta(key);
142
+ const doc = text === null ? null : parseSettings(text);
143
+ return doc?.ok ? doc.value : emptySettings;
144
+ };
145
+ // ── Relay helpers ──
146
+ /** `full`: wait for every relay, for a read a publish builds on (#62). */
147
+ const fetchVault = async (ctx, urls = options.relayUrls, full = false) => {
148
+ const f = await fetchReplaceable(deps.relays, urls, { author: ctx.pubkey, kind: VAULT_KIND, d: appVaultDTag(ctx.pubkey, ctx.appId) }, timeoutMs, full ? undefined : options.relayQuorum);
149
+ if (f.kind === "none")
150
+ return { kind: "none" };
151
+ if (f.kind === "incomplete")
152
+ return { kind: "unreadable" };
153
+ lastEventAt = Math.max(lastEventAt, f.event.created_at);
154
+ // Not re-sent until it passes the checks: never spread a forged event (#44).
155
+ lastSeenEvent = { event: f.event, missingOn: f.missingOn };
156
+ const v = readVaultEvent(ctx, f.event);
157
+ return v.ok ? { kind: "found", vault: v.value } : { kind: "unreadable" };
158
+ };
159
+ const hintKey = (ctx) => `evolustr:hint:${sha256Hex(`${ctx.pubkey}|${ctx.appId}`)}`;
160
+ const readHint = async (ctx) => {
161
+ try {
162
+ const text = await deps.hints?.get(hintKey(ctx));
163
+ return text == null ? null : JSON.parse(text);
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ };
169
+ // ── Backup facts (SPEC §3.2 rule 3a, #53) ──
170
+ // Kept on the device, never in the app database: before strict, anyone who
171
+ // can decrypt the nip44 wrap can write there through Evolu sync.
172
+ const sessionStore = new Map();
173
+ const localGet = async (key) => deps.hints === undefined ? (sessionStore.get(key) ?? null) : await deps.hints.get(key).catch(() => null);
174
+ const localSet = async (key, value) => deps.hints === undefined ? void sessionStore.set(key, value) : await deps.hints.set(key, value).catch(() => undefined);
175
+ const backupKey = (kind, ctx) => `evolustr:${kind}:${sha256Hex(`${ctx.pubkey}|${ctx.appId}`)}`;
176
+ /** Which root key a phrase confirmation was for; a marker for another R doesn't count. */
177
+ const phraseMarker = (r) => toHex(hkdf(r, "evolustr/v1/phrase-confirmed", 8));
178
+ const readMethodRecords = async (ctx) => {
179
+ try {
180
+ const list = JSON.parse((await localGet(backupKey("methods", ctx))) ?? "[]");
181
+ return Array.isArray(list) ? list : [];
182
+ }
183
+ catch {
184
+ return [];
185
+ }
186
+ };
187
+ const writeMethodRecords = (ctx, list) => localSet(backupKey("methods", ctx), JSON.stringify(list));
188
+ /**
189
+ * The backup facts for this vault. With R, every root wrap whose tag verifies
190
+ * is a method; whether it recovers on its own comes from this device's record,
191
+ * else it counts as not recoverable. Without R, only recorded methods that
192
+ * still have a wrap count.
193
+ */
194
+ const readBackupState = async (ctx, vault, r) => {
195
+ const records = await readMethodRecords(ctx);
196
+ const recordFor = (id) => records.find((m) => m.id === id);
197
+ const wrapIds = vault.rootWraps.filter((w) => r === undefined || verifyRootWrap(ctx, r, w)).map((w) => ({ id: `${w.type}:${rootWrapKeyId(w)}`, type: w.type }));
198
+ const methods = r === undefined
199
+ ? wrapIds.flatMap(({ id }) => {
200
+ const rec = recordFor(id);
201
+ return rec === undefined ? [] : [rec];
202
+ })
203
+ : wrapIds.map(({ id, type }) => recordFor(id) ?? { id, method: type === "passkey" ? { kind: "passkey", synced: false } : { kind: "signer", recoverable: false } });
204
+ const marker = await localGet(backupKey("phrase", ctx));
205
+ const phraseConfirmed = marker !== null && marker !== "" && (r === undefined || marker === phraseMarker(r));
206
+ return { methods, phraseConfirmed };
207
+ };
208
+ /** Secrets this device has moved past, from its local database (#44). */
209
+ let knownSeen = [];
210
+ const readSeen = async (db) => {
211
+ try {
212
+ const list = JSON.parse((await db.getMeta(META_SEEN_SECRETS)) ?? "[]");
213
+ return Array.isArray(list) ? list.filter((x) => typeof x === "string") : [];
214
+ }
215
+ catch {
216
+ return [];
217
+ }
218
+ };
219
+ /** A vault to publish in the background once connect is ready (self-heal, #37). */
220
+ let healAfterConnect = null;
221
+ /** The newest vault event fetched, before it was checked (#44). */
222
+ let lastSeenEvent = null;
223
+ /** Relays that accepted the last publish. */
224
+ let lastAccepted = [];
225
+ const progress = (step) => {
226
+ try {
227
+ options.onProgress?.(step);
228
+ }
229
+ catch {
230
+ /* the app's callback must not break connecting */
231
+ }
232
+ };
233
+ /** The newest vault event seen, and relays that answered without it (#32). */
234
+ let lastFetched = null;
235
+ /** Sends the current vault event to relays that lack it; no new signature needed. */
236
+ const rebroadcastVault = async () => {
237
+ const f = lastFetched;
238
+ if (f === null || f.missingOn.length === 0)
239
+ return;
240
+ await deps.relays.publish(f.missingOn, f.event, timeoutMs).catch(() => undefined);
241
+ lastFetched = { ...f, missingOn: [] };
242
+ };
243
+ /**
244
+ * Publishes, merging with the relay version first when it holds the same S
245
+ * (superset rule). With `requireAll` (rotations, #32), a relay that still
246
+ * refuses after a retry makes it fail with `partialPublish`.
247
+ */
248
+ const publishVault = async (ctx, vault, requireAll = false,
249
+ /** What the caller just fetched; skips a second lookup. */
250
+ known,
251
+ /** R, when the caller knows it and the session doesn't yet. */
252
+ rootKey) => {
253
+ let toPublish = vault;
254
+ progress("publishingVault");
255
+ const sessionR = rootKey ?? (session.kind === "ready" && session.ctx.appId === ctx.appId ? session.r : undefined);
256
+ // With a quorum, what the caller fetched may be stale: read every relay before writing (#62).
257
+ const current = known !== undefined && options.relayQuorum === undefined ? known : await fetchVault(ctx, options.relayUrls, true);
258
+ // Only root wraps come from the relay version: `vault` is the one this
259
+ // device made or verified, and its header is part of the root data wrap's
260
+ // AAD (#50). Without a root key here, the relay's root wraps mean nothing.
261
+ if (current.kind === "found" && current.vault.sHash === vault.sHash && hasRootKey(vault)) {
262
+ // The local version wins on the same wrap id; with R, forged wraps are dropped (#37).
263
+ const merged = mergeVaults(vault, current.vault, { ctx, r: sessionR });
264
+ if (!merged.ok)
265
+ return merged;
266
+ toPublish = { ...vault, rootWraps: merged.value.rootWraps };
267
+ }
268
+ if (!canOpenOwnVault(ctx, toPublish, sessionR)) {
269
+ return error("invalidVault", "Refusing to publish a vault its own root key can't open");
270
+ }
271
+ const at = Math.max(now(), lastEventAt + 1);
272
+ let failed;
273
+ try {
274
+ const published = await publishReplaceable(deps.relays, options.relayUrls, deps.signer, vaultEvent(ctx, toPublish, at), timeoutMs);
275
+ failed = published.failed;
276
+ lastAccepted = published.accepted;
277
+ lastFetched = { event: published.event, missingOn: failed };
278
+ }
279
+ catch (e) {
280
+ return error("publishFailed", e instanceof Error ? e.message : String(e));
281
+ }
282
+ lastEventAt = at;
283
+ if (requireAll && failed.length > 0) {
284
+ return error("partialPublish", `Not every relay accepted the change (${failed.join(", ")}); it completes on the next connect`);
285
+ }
286
+ return ok(toPublish);
287
+ };
288
+ // ── Building blocks ──
289
+ const statusOf = (s) => ({
290
+ pubkey: s.ctx.pubkey,
291
+ signer: caps === null ? "standard" : caps.identity === "verified" ? "capable-verified" : "capable-connection",
292
+ mode: s.vault.mode,
293
+ level: level(s.vault),
294
+ unlockedWith: s.unlockedWith,
295
+ canMakeStrict: s.r !== undefined && s.vault.mode === "compatible",
296
+ canAddStrongMethod: s.r !== undefined || !hasRootKey(s.vault),
297
+ canReplaceRoot: s.vault.mode === "compatible" && s.r === undefined && hasRootKey(s.vault),
298
+ passkeySupported,
299
+ dependsOnNsec: s.vault.mode === "strict" &&
300
+ (caps?.nsecProtected === true || caps?.nsecExposed === true) &&
301
+ caps.signerId !== null &&
302
+ signerWrapFor(s.vault, caps.signerId) !== undefined,
303
+ rootExposed: caps != null && earlierSignerIds(caps).some((id) => signerWrapFor(s.vault, id) !== undefined),
304
+ backupRecommended: s.vault.mode === "strict" &&
305
+ backupRequirement(backupState.methods.map((m) => m.method), backupState.phraseConfirmed) !== "none",
306
+ });
307
+ /**
308
+ * Opens the database for S, keeps the vault copy and the cache, and becomes
309
+ * ready. The only writer of the local vault copy (META_VAULT), the trust anchor
310
+ * of decideVault (#38): every caller passes a vault this device (a) made, (b)
311
+ * opened with R, (c) opened through NIP-44 after the user chose or confirmed
312
+ * it, or (d) merged from the checked copy.
313
+ */
314
+ const becomeReady = async (ctx, vaultIn, s, r, unlockedWith, db) => {
315
+ progress("openingDatabase");
316
+ let vault = vaultIn;
317
+ // The secret this device had before, if it's moving to another one (#44).
318
+ const previous = session.kind === "ready" ? session.db.sHash : session.kind === "pending" ? session.local?.db.sHash : undefined;
319
+ const database = db ?? (await deps.openDatabase(s));
320
+ {
321
+ const seen = [...new Set([...knownSeen, ...(await readSeen(database)), ...(previous !== undefined && previous !== database.sHash ? [previous] : [])])];
322
+ knownSeen = seen.slice(-SEEN_LIMIT);
323
+ if (knownSeen.length > 0)
324
+ await database.setMeta(META_SEEN_SECRETS, JSON.stringify(knownSeen));
325
+ }
326
+ // With R known, drop root wraps whose tag doesn't verify, and put the
327
+ // cleaned vault back on the relays in the background (#37).
328
+ if (r !== undefined) {
329
+ const pruned = mergeVaults(vault, vault, { ctx, r });
330
+ if (pruned.ok && pruned.value.rootWraps.length !== vault.rootWraps.length) {
331
+ vault = pruned.value;
332
+ const cleaned = vault;
333
+ const rootKey = r;
334
+ queueMicrotask(() => void publishVault(ctx, cleaned, false, undefined, rootKey).catch(() => undefined));
335
+ }
336
+ }
337
+ await database.setMeta(META_VAULT, serializeVault(vault));
338
+ await deps.hints?.set(hintKey(ctx), JSON.stringify({ mode: vault.mode, sHash: vault.sHash })).catch(() => undefined);
339
+ // R is the recovery phrase: kept in memory only, unless the app opts in (#27).
340
+ await deps.cache.set(ctx.pubkey, ctx.appId, r === undefined || options.cacheRootKey !== true ? { s } : { s, r });
341
+ const next = { kind: "ready", ctx, vault, s, db: database, unlockedWith, ...(r === undefined ? {} : { r }) };
342
+ session = next;
343
+ settingsState = { app: await readDoc(database, META_APP_SETTINGS), shared: await readDoc(database, META_SHARED_SETTINGS) };
344
+ backupState = await readBackupState(ctx, vault, r);
345
+ const migration = lastMigration;
346
+ lastMigration = null;
347
+ return ok({ pubkey: ctx.pubkey, db: database, status: statusOf(next), ...(migration === null ? {} : { migration }) });
348
+ };
349
+ /** The last migration, reported by the next becomeReady (#51). */
350
+ let lastMigration = null;
351
+ /** An old local database kept because a migration skipped edited rows (#51). */
352
+ let leftBehind = null;
353
+ /** Moves to a new data secret, copying local rows (SPEC §3.4). */
354
+ const switchDatabase = async (from, to, mode) => {
355
+ if (from === undefined || from.sHash === to.sHash)
356
+ return;
357
+ const result = await migrateRows(from, to, mode);
358
+ lastMigration = result;
359
+ // Keep edits that weren't carried over until the app lets the user decide.
360
+ if (mode.kind === "missingOnly" && result.skippedChanged > 0)
361
+ leftBehind = from;
362
+ else
363
+ await from.deleteLocal();
364
+ };
365
+ /**
366
+ * How to copy local rows into the vault's database. Into a strict database
367
+ * from one any decrypting app could write to, only missing rows (#51).
368
+ */
369
+ const migrationModeFor = (vault, localSHash, localMode) => {
370
+ if (vault.mode === "strict" && localMode !== "strict" && options.migrateChangedRows !== true)
371
+ return { kind: "missingOnly" };
372
+ const cutoff = migrationCutoff(vault, localSHash);
373
+ // Not in history: copy only rows missing in the current database (never overwrites).
374
+ return cutoff === null ? { kind: "missingOnly" } : { kind: "since", cutoffMs: cutoff * 1000, marginMs: clockMarginMs };
375
+ };
376
+ const createVault = async (ctx) => {
377
+ if (options.requireStrong === true) {
378
+ session = { kind: "pending", ctx, action: "setupStrong" };
379
+ return ok({ state: "needsUserAction", action: "setupStrong" });
380
+ }
381
+ const s = random(DATA_SECRET_LENGTH);
382
+ let nip44Ct;
383
+ try {
384
+ nip44Ct = await nip44SealSecret(deps.signer, ctx.pubkey, s);
385
+ }
386
+ catch (e) {
387
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
388
+ }
389
+ const vault = createCompatibleVault(ctx, { s, nip44Ct, now: now() });
390
+ if (!vault.ok)
391
+ return vault;
392
+ progress("creatingVault");
393
+ const published = await publishVault(ctx, vault.value, false, { kind: "none" });
394
+ if (!published.ok)
395
+ return published;
396
+ // Create race (SPEC §6.2 rule 2): if another device created one first, use
397
+ // theirs. Asking the relays that just answered is enough and doesn't wait on slow ones.
398
+ const check = await fetchVault(ctx, lastAccepted.length > 0 ? lastAccepted : options.relayUrls);
399
+ if (check.kind === "found" && check.vault.sHash !== published.value.sHash && check.vault.created <= published.value.created) {
400
+ // A vault that appeared after this device's publish is as unknown as on first use (#44).
401
+ return unlockFetched(ctx, check.vault, undefined, options.confirmWeakOnNewDevice !== false);
402
+ }
403
+ // Local copy source (#38): (a) made by this device.
404
+ return withReady(becomeReady(ctx, published.value, s, undefined, "created"));
405
+ };
406
+ const withReady = async (r) => {
407
+ const x = await r;
408
+ return x.ok ? ok({ state: "ready", ...x.value }) : x;
409
+ };
410
+ /** Unlock order without a click (SPEC §8.2 step 2), for a vault this device doesn't have yet. */
411
+ const unlockFetched = async (ctx, vault, local, requireWeakConfirm = false) => {
412
+ const signerHasWrap = caps !== null &&
413
+ ((caps.signerId !== null && signerWrapFor(vault, caps.signerId) !== undefined) ||
414
+ earlierSignerIds(caps).some((id) => signerWrapFor(vault, id) !== undefined));
415
+ if (caps?.ready === true && signerHasWrap) {
416
+ const root = await rootFromSigner(ctx, vault);
417
+ if (root.ok) {
418
+ const s = openRootData(ctx, vault, root.value);
419
+ if (s.ok) {
420
+ const db = await deps.openDatabase(s.value);
421
+ if (local !== undefined)
422
+ await switchDatabase(local.db, db, migrationModeFor(vault, local.db.sHash, local.copy?.mode));
423
+ // Local copy source (#38): (b) opened with R from the signer.
424
+ return withReady(becomeReady(ctx, vault, s.value, root.value, "signer", db));
425
+ }
426
+ }
427
+ }
428
+ if (local?.r !== undefined) {
429
+ const s = openRootData(ctx, vault, local.r);
430
+ if (s.ok) {
431
+ const db = await deps.openDatabase(s.value);
432
+ await switchDatabase(local.db, db, migrationModeFor(vault, local.db.sHash, local.copy?.mode));
433
+ // Local copy source (#38): (b) opened with the cached R.
434
+ return withReady(becomeReady(ctx, vault, s.value, local.r, "cache", db));
435
+ }
436
+ }
437
+ if (vault.mode === "compatible" && requireWeakConfirm) {
438
+ session = { kind: "pending", ctx, action: "confirmWeak", vault, ...(local === undefined ? {} : { local }) };
439
+ return ok({ state: "needsUserAction", action: "confirmWeak" });
440
+ }
441
+ if (vault.mode === "compatible") {
442
+ const s = await nip44OpenSecret(deps.signer, ctx.pubkey, vault);
443
+ if (s.ok) {
444
+ const db = await deps.openDatabase(s.value);
445
+ if (local !== undefined)
446
+ await switchDatabase(local.db, db, migrationModeFor(vault, local.db.sHash, local.copy?.mode));
447
+ // Keep a cached R only if it really opens this vault (#33).
448
+ const r = local?.r !== undefined && openRootData(ctx, vault, local.r).ok ? local.r : undefined;
449
+ // Local copy source (#38): (c) opened through NIP-44: a compatible vault, after confirmWeak on a new device.
450
+ return withReady(becomeReady(ctx, vault, s.value, r, "nip44", db));
451
+ }
452
+ if (s.error.type === "signerRefused")
453
+ return s;
454
+ }
455
+ return askStrongUnlock(ctx, vault, local);
456
+ };
457
+ /** A strong method is needed: a passkey (from a click) if one matches, else the phrase. */
458
+ const askStrongUnlock = (ctx, vault, local) => {
459
+ // Choose from the fetched vault's and the local copy's wraps together (#39).
460
+ const wraps = [...vault.rootWraps, ...(local?.copy?.rootWraps ?? [])];
461
+ const signerCanOpen = caps !== null && wraps.some((w) => w.type === "signer");
462
+ const action = signerCanOpen
463
+ ? "signerUnlock"
464
+ : passkeys !== undefined && passkeySupported && wraps.some((w) => w.type === "passkey" && w.rpId === passkeys.rpId)
465
+ ? "passkey"
466
+ : "recoveryPhrase";
467
+ session = { kind: "pending", ctx, action, vault, ...(local === undefined ? {} : { local }) };
468
+ return ok({ state: "needsUserAction", action });
469
+ };
470
+ /** Opens R with one of this domain's passkeys (SPEC §4.3). Call from a click. */
471
+ /**
472
+ * Opens R with one of this domain's passkeys (SPEC §4.3). Call from a click.
473
+ * Wraps from the local copy are tried too, so a fetched vault with missing or
474
+ * corrupted wraps can't lock the device out (#39).
475
+ */
476
+ const rootFromPasskey = async (ctx, vault, copy) => {
477
+ if (passkeys === undefined)
478
+ return error("noPasskeys", "Passkeys aren't enabled");
479
+ const candidates = [...passkeyWrapsFor(vault, passkeys.rpId), ...(copy === undefined ? [] : passkeyWrapsFor(copy, passkeys.rpId))];
480
+ if (candidates.length === 0)
481
+ return error("noPasskeyWrap", "No passkey for this site is registered in the vault");
482
+ let result;
483
+ try {
484
+ result = await passkeys.get({ allowCredIds: [...new Set(candidates.map((w) => w.credId))], prfInput: clientPrfInput(ctx.pubkey, ctx.appId) });
485
+ }
486
+ catch (e) {
487
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
488
+ }
489
+ if (result.prfOutput === null)
490
+ return error("passkeyFailed", "The passkey gave no usable result");
491
+ const key = passkeyWrapKey(result.prfOutput, ctx.appId);
492
+ for (const wrap of candidates.filter((w) => w.credId === result.credId)) {
493
+ const opened = openRootWrap(ctx, wrap, key);
494
+ if (opened.ok)
495
+ return opened;
496
+ }
497
+ return error("passkeyFailed", "The passkey didn't open any wrap of this vault");
498
+ };
499
+ // ── API ──
500
+ const connect = async () => {
501
+ const result = await connectInner();
502
+ // In the background: a slow relay must not delay opening the app.
503
+ if (result.ok && result.value.state === "ready") {
504
+ const heal = healAfterConnect;
505
+ healAfterConnect = null;
506
+ if (heal !== null && session.kind === "ready")
507
+ void publishVault(session.ctx, heal).catch(() => undefined);
508
+ else
509
+ void rebroadcastVault();
510
+ }
511
+ if (result.ok && result.value.state === "ready" && capable !== undefined) {
512
+ await ensureSignerWrap();
513
+ const st = status();
514
+ if (st !== null)
515
+ return ok({ ...result.value, status: st });
516
+ }
517
+ return result;
518
+ };
519
+ const connectInner = async () => {
520
+ let pubkey;
521
+ try {
522
+ pubkey = await deps.signer.getPublicKey();
523
+ }
524
+ catch (e) {
525
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
526
+ }
527
+ const ctx = { pubkey, appId: options.appId };
528
+ progress("lookingUpVault");
529
+ passkeySupported = passkeys === undefined ? false : await passkeys.supported().catch(() => false);
530
+ await refreshCaps();
531
+ const cached = await deps.cache.get(pubkey, options.appId);
532
+ const fetched = await fetchVault(ctx);
533
+ let local;
534
+ if (cached !== null) {
535
+ const db = await deps.openDatabase(cached.s);
536
+ const copyText = await db.getMeta(META_VAULT);
537
+ const copy = copyText === null ? undefined : parseVault(copyText);
538
+ knownSeen = await readSeen(db);
539
+ local = {
540
+ db,
541
+ s: cached.s,
542
+ ...(cached.r === undefined ? {} : { r: cached.r }),
543
+ ...(copy?.ok ? { copy: copy.value } : {}),
544
+ };
545
+ }
546
+ // Logged out before, but this device knew the database was strict: a weak
547
+ // vault now is a swap, not a first use (#44).
548
+ if (local === undefined && fetched.kind === "found" && fetched.vault.mode === "compatible") {
549
+ const hint = await readHint(ctx);
550
+ if (hint?.mode === "strict") {
551
+ session = { kind: "pending", ctx, action: "choose", vault: fetched.vault };
552
+ // The phrase can't open the fetched (forged) vault, so don't offer it (#54).
553
+ return ok({ state: "vaultChanged", reason: "replaced", options: ["startNew"], advice: "useAnotherDevice" });
554
+ }
555
+ }
556
+ const decision = decideVault(ctx, fetched, local === undefined
557
+ ? null
558
+ : {
559
+ sHash: local.db.sHash,
560
+ seen: knownSeen,
561
+ ...(local.r === undefined ? {} : { r: local.r }),
562
+ ...(local.copy === undefined ? {} : { copy: local.copy }),
563
+ });
564
+ switch (decision.type) {
565
+ case "create":
566
+ return createVault(ctx);
567
+ case "firstUse":
568
+ return unlockFetched(ctx, decision.vault, undefined, decision.warnWeak && options.confirmWeakOnNewDevice !== false);
569
+ case "same": {
570
+ // (d) merged from the checked copy: wraps from the copy are never dropped (#37, #38).
571
+ const fetchedVault = fetched.kind === "found" ? fetched.vault : local.copy;
572
+ const copy = local.copy ?? fetchedVault;
573
+ const merged = mergeVaults(copy, fetchedVault, { ctx, r: local.r });
574
+ // R verified the fetched vault: its header and data wraps win, e.g. after
575
+ // a downgrade elsewhere; the copy's wraps are still kept (#54).
576
+ const verified = local.r !== undefined && fetched.kind === "found" && openRootData(ctx, fetchedVault, local.r).ok;
577
+ const vault = !merged.ok ? copy : verified ? { ...fetchedVault, rootWraps: merged.value.rootWraps } : merged.value;
578
+ // Self-heal (SPEC §6.2 rule 4): the relays lost or altered wraps this device still has.
579
+ const onRelays = new Set(fetchedVault.rootWraps.map((w) => JSON.stringify(w)));
580
+ if (vault.rootWraps.some((w) => !onRelays.has(JSON.stringify(w))))
581
+ healAfterConnect = vault;
582
+ // The fetched event passed the checks unchanged: it may be re-sent to relays that miss it.
583
+ else if (fetched.kind === "found")
584
+ lastFetched = lastSeenEvent;
585
+ return withReady(becomeReady(ctx, vault, local.s, local.r, "cache", local.db));
586
+ }
587
+ case "follow": {
588
+ const db = await deps.openDatabase(decision.s);
589
+ await switchDatabase(local?.db, db, migrationModeFor(decision.vault, local.db.sHash, local.copy?.mode));
590
+ // Local copy source (#38): (b) opened with R (decideVault "follow").
591
+ return withReady(becomeReady(ctx, decision.vault, decision.s, local.r, "cache", db));
592
+ }
593
+ case "needsStrongUnlock":
594
+ return askStrongUnlock(ctx, decision.vault, local);
595
+ case "choose":
596
+ session = {
597
+ kind: "pending",
598
+ ctx,
599
+ action: "choose",
600
+ ...(decision.vault === undefined ? {} : { vault: decision.vault }),
601
+ ...(local === undefined ? {} : { local }),
602
+ };
603
+ return ok({ state: "vaultChanged", reason: decision.reason, options: decision.options });
604
+ }
605
+ };
606
+ /** Opens the pending vault with a recovery phrase, migrating local rows. */
607
+ const openWithPhrase = async (p, words) => {
608
+ const r = phraseToRootKey(words);
609
+ if (!r.ok)
610
+ return r;
611
+ return openWithRoot(p, r.value, "recovery");
612
+ };
613
+ /** Opens the pending vault with R, migrating local rows. */
614
+ const openWithRoot = async (p, root, how) => {
615
+ const r = { value: root };
616
+ let vault = p.vault;
617
+ if (vault === undefined) {
618
+ const f = await fetchVault(p.ctx);
619
+ if (f.kind !== "found")
620
+ return error("noVault", "No vault found to restore");
621
+ vault = f.vault;
622
+ }
623
+ const s = openRootData(p.ctx, vault, r.value);
624
+ if (!s.ok) {
625
+ // R is real (it opens this device's copy), so the fetched vault is foreign (#39).
626
+ if (p.local?.copy !== undefined && openRootData(p.ctx, p.local.copy, r.value).ok) {
627
+ // The old R signed the vault: the user replaced the root key elsewhere (#52 phase C).
628
+ if (verifyRootRotation(p.ctx, vault, r.value)) {
629
+ return error("rootRotated", "The root key was replaced on another device: unlock with the new passkey, signer or recovery phrase");
630
+ }
631
+ session = { kind: "pending", ctx: p.ctx, action: "choose", vault, local: { ...p.local, r: r.value } };
632
+ return error("vaultReplaced", "The vault on the relays isn't yours; restore this device's copy with resolveVaultChange(\"republishCopy\")");
633
+ }
634
+ return error("wrongPhrase", "This recovery phrase doesn't open this app's data");
635
+ }
636
+ const db = await deps.openDatabase(s.value);
637
+ if (p.local !== undefined)
638
+ await switchDatabase(p.local.db, db, migrationModeFor(vault, p.local.db.sHash, p.local.copy?.mode));
639
+ // Local copy source (#38): (b) opened with R from a passkey, signer or the phrase.
640
+ return becomeReady(p.ctx, vault, s.value, r.value, how, db);
641
+ };
642
+ const unlock = async (input) => {
643
+ const result = await unlockInner(input);
644
+ if (result.ok && capable !== undefined) {
645
+ await ensureSignerWrap();
646
+ const st = status();
647
+ if (st !== null)
648
+ return ok({ ...result.value, status: st });
649
+ }
650
+ return result;
651
+ };
652
+ const unlockInner = async (input) => {
653
+ if (session.kind !== "pending")
654
+ return error("nothingToUnlock", "connect() didn't ask for a user action");
655
+ const p = session;
656
+ if (input?.recoveryPhrase !== undefined && p.action !== "setupStrong")
657
+ return openWithPhrase(p, input.recoveryPhrase);
658
+ if (p.action === "recoveryPhrase")
659
+ return error("phraseRequired", "Pass the recovery phrase");
660
+ if (p.action === "passkey") {
661
+ if (p.vault === undefined)
662
+ return error("noVault", "No vault to unlock");
663
+ const root = await rootFromPasskey(p.ctx, p.vault, p.local?.copy);
664
+ return root.ok ? openWithRoot(p, root.value, "passkey") : root;
665
+ }
666
+ if (p.action === "signerUnlock") {
667
+ if (p.vault === undefined)
668
+ return error("noVault", "No vault to unlock");
669
+ const root = await rootFromSigner(p.ctx, p.vault, p.local?.copy);
670
+ return root.ok ? openWithRoot(p, root.value, "signer") : root;
671
+ }
672
+ if (p.action === "setupStrong")
673
+ return setupStrong(p.ctx, input?.acceptDeviceLoss === true);
674
+ if (p.action === "confirmWeak") {
675
+ if (p.vault === undefined)
676
+ return error("noVault", "No vault to open");
677
+ const r = await unlockFetched(p.ctx, p.vault, p.local, false);
678
+ if (!r.ok)
679
+ return r;
680
+ if (r.value.state !== "ready")
681
+ return error("needsUserAction", `Still needs: ${r.value.state === "needsUserAction" ? r.value.action : r.value.state}`);
682
+ const { state: _state, ...ready } = r.value;
683
+ return ok(ready);
684
+ }
685
+ return error("unsupported", `Unlocking with "${p.action}" isn't available in this build`);
686
+ };
687
+ const resolveVaultChange = async (choice, input) => {
688
+ if (session.kind !== "pending" || session.action !== "choose") {
689
+ return error("nothingToResolve", "connect() didn't report a vault change");
690
+ }
691
+ const p = session;
692
+ switch (choice) {
693
+ case "republishCopy": {
694
+ if (p.local?.copy === undefined)
695
+ return error("noCopy", "This device has no copy of the vault");
696
+ // With R known, wraps with a bad tag are dropped (#50).
697
+ const published = await publishVault(p.ctx, p.local.copy, false, undefined, p.local.r);
698
+ if (!published.ok)
699
+ return published;
700
+ // Local copy source (#38): (a) this device's own copy, republished.
701
+ return becomeReady(p.ctx, published.value, p.local.s, p.local.r, "cache", p.local.db);
702
+ }
703
+ case "followRelay": {
704
+ if (p.vault === undefined)
705
+ return error("noVault", "No vault to follow");
706
+ // The user chose this. Use R when it opens the vault; otherwise NIP-44
707
+ // (only a compatible vault has a nip44 wrap; a strict one never falls back).
708
+ const viaRoot = p.local?.r === undefined ? null : openRootData(p.ctx, p.vault, p.local.r);
709
+ // A database protected by a root key never follows a vault only NIP-44 opens (#38).
710
+ if (!viaRoot?.ok && p.local?.copy !== undefined && hasRootKey(p.local.copy)) {
711
+ return error("unsafeFollow", "This device's data is protected by a root key; restore with a strong method instead");
712
+ }
713
+ const s = viaRoot?.ok ? viaRoot : p.vault.mode === "compatible" ? await nip44OpenSecret(deps.signer, p.ctx.pubkey, p.vault) : viaRoot ?? error("rootLocked", "A strong unlock is needed");
714
+ if (!s.ok)
715
+ return s;
716
+ const db = await deps.openDatabase(s.value);
717
+ // Not verifiable: copy only rows missing there, never overwrite, and keep
718
+ // the previous local database (it isn't deleted).
719
+ if (p.local !== undefined && p.local.db.sHash !== db.sHash) {
720
+ lastMigration = await migrateRows(p.local.db, db, { kind: "missingOnly" });
721
+ }
722
+ // Local copy source (#38): (b) opened with R, or (c) through NIP-44 after the user chose to follow.
723
+ return becomeReady(p.ctx, p.vault, s.value, viaRoot?.ok ? p.local?.r : undefined, viaRoot?.ok ? "cache" : "nip44", db);
724
+ }
725
+ case "restorePhrase":
726
+ if (input?.recoveryPhrase === undefined)
727
+ return error("phraseRequired", "Pass the recovery phrase");
728
+ return openWithPhrase(p, input.recoveryPhrase);
729
+ case "startNew": {
730
+ session = { kind: "none" };
731
+ const created = await createVault(p.ctx);
732
+ if (!created.ok)
733
+ return created;
734
+ return created.value.state === "ready"
735
+ ? ok({ pubkey: created.value.pubkey, db: created.value.db, status: created.value.status })
736
+ : error("needsUserAction", "Creating a new database needs a user action first");
737
+ }
738
+ }
739
+ };
740
+ const requireReady = () => session.kind === "ready" ? ok(session) : error("notReady", "Connect first");
741
+ const unlockRoot = async (input) => {
742
+ const s = requireReady();
743
+ if (!s.ok)
744
+ return s;
745
+ const r = input?.recoveryPhrase === undefined ? await rootFromPasskey(s.value.ctx, s.value.vault) : phraseToRootKey(input.recoveryPhrase);
746
+ if (!r.ok)
747
+ return r;
748
+ const check = openRootData(s.value.ctx, s.value.vault, r.value);
749
+ if (!check.ok)
750
+ return error("wrongPhrase", "This recovery phrase doesn't belong to this app's data");
751
+ if (options.cacheRootKey === true)
752
+ await deps.cache.set(s.value.ctx.pubkey, s.value.ctx.appId, { s: s.value.s, r: r.value });
753
+ // Now that R is known, drop root wraps with a bad tag and publish the result (#37).
754
+ const pruned = mergeVaults(s.value.vault, s.value.vault, { ctx: s.value.ctx, r: r.value });
755
+ let vault = s.value.vault;
756
+ if (pruned.ok && pruned.value.rootWraps.length !== vault.rootWraps.length) {
757
+ const published = await publishVault(s.value.ctx, pruned.value, false, undefined, r.value);
758
+ vault = published.ok ? published.value : pruned.value;
759
+ await s.value.db.setMeta(META_VAULT, serializeVault(vault));
760
+ }
761
+ const next = { ...s.value, vault, r: r.value };
762
+ session = next;
763
+ backupState = await readBackupState(next.ctx, vault, r.value);
764
+ return ok(statusOf(next));
765
+ };
766
+ const showRecoveryPhrase = async () => {
767
+ const s = requireReady();
768
+ if (!s.ok)
769
+ return s;
770
+ if (s.value.r !== undefined)
771
+ return ok(rootKeyToPhrase(s.value.r));
772
+ if (hasRootKey(s.value.vault)) {
773
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
774
+ }
775
+ const r = random(ROOT_KEY_LENGTH);
776
+ const withRoot = addRootKey(s.value.ctx, s.value.vault, r, s.value.s);
777
+ if (!withRoot.ok)
778
+ return withRoot;
779
+ const published = await publishVault(s.value.ctx, withRoot.value);
780
+ if (!published.ok)
781
+ return published;
782
+ // Local copy source (#38): (a) made by this device.
783
+ const ready = await becomeReady(s.value.ctx, published.value, s.value.s, r, s.value.unlockedWith, s.value.db);
784
+ return ready.ok ? ok(rootKeyToPhrase(r)) : ready;
785
+ };
786
+ const confirmRecoveryPhrase = async (words) => {
787
+ const s = requireReady();
788
+ if (!s.ok)
789
+ return s;
790
+ const r = phraseToRootKey(words);
791
+ if (!r.ok || s.value.r === undefined || rootKeyToPhrase(r.value) !== rootKeyToPhrase(s.value.r)) {
792
+ return error("wrongPhrase", "The words don't match the recovery phrase");
793
+ }
794
+ await localSet(backupKey("phrase", s.value.ctx), phraseMarker(s.value.r));
795
+ backupState = { ...backupState, phraseConfirmed: true };
796
+ return ok(undefined);
797
+ };
798
+ const restoreFromPhrase = async (words) => {
799
+ if (session.kind === "pending")
800
+ return openWithPhrase(session, words);
801
+ let pubkey;
802
+ try {
803
+ pubkey = await deps.signer.getPublicKey();
804
+ }
805
+ catch (e) {
806
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
807
+ }
808
+ return openWithPhrase({ kind: "pending", ctx: { pubkey, appId: options.appId }, action: "recoveryPhrase" }, words);
809
+ };
810
+ const downgrade = async () => {
811
+ const s = requireReady();
812
+ if (!s.ok)
813
+ return s;
814
+ if (s.value.r === undefined)
815
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
816
+ let ct;
817
+ try {
818
+ ct = await nip44SealSecret(deps.signer, s.value.ctx.pubkey, s.value.s);
819
+ }
820
+ catch (e) {
821
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
822
+ }
823
+ const next = downgradeVault(s.value.ctx, s.value.vault, { r: s.value.r, s: s.value.s, nip44Ct: ct });
824
+ if (!next.ok)
825
+ return next;
826
+ const published = await publishVault(s.value.ctx, next.value, true);
827
+ if (!published.ok && published.error.type !== "partialPublish")
828
+ return published;
829
+ // Local copy source (#38): (a) made by this device (downgrade).
830
+ const ready = await becomeReady(s.value.ctx, published.ok ? published.value : next.value, s.value.s, s.value.r, s.value.unlockedWith, s.value.db);
831
+ if (!ready.ok)
832
+ return ready;
833
+ return published.ok ? ok(ready.value.status) : published;
834
+ };
835
+ const createPasskey = async (ctx, vault) => {
836
+ if (passkeys === undefined)
837
+ return error("noPasskeys", "Passkeys aren't enabled");
838
+ try {
839
+ const created = await passkeys.create({
840
+ userId: sha256(utf8(ctx.pubkey)),
841
+ userName: ctx.pubkey.slice(0, 16),
842
+ excludeCredIds: vault === undefined ? [] : passkeyWrapsFor(vault, passkeys.rpId).map((w) => w.credId),
843
+ prfInput: clientPrfInput(ctx.pubkey, ctx.appId),
844
+ });
845
+ return created.prfEnabled ? ok(created) : error("prfUnsupported", "This authenticator can't be used: no PRF support");
846
+ }
847
+ catch (e) {
848
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
849
+ }
850
+ };
851
+ /** Records on this device whether a method recovers on its own (#53). */
852
+ const rememberMethod = async (ctx, known) => {
853
+ const records = await readMethodRecords(ctx);
854
+ await writeMethodRecords(ctx, [...records.filter((m) => m.id !== known.id), known]);
855
+ };
856
+ /** Adds a passkey wrap of R once the PRF output is known. */
857
+ const completeEnrollment = async (s, created, prfOutput) => {
858
+ if (passkeys === undefined)
859
+ return error("noPasskeys", "Passkeys aren't enabled");
860
+ let vault = s.vault;
861
+ let r = s.r;
862
+ if (r === undefined) {
863
+ if (hasRootKey(vault))
864
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
865
+ r = random(ROOT_KEY_LENGTH);
866
+ const withRoot = addRootKey(s.ctx, vault, r, s.s);
867
+ if (!withRoot.ok)
868
+ return withRoot;
869
+ vault = withRoot.value;
870
+ }
871
+ const wrap = passkeyRootWrap(s.ctx, passkeyWrapKey(prfOutput, s.ctx.appId), passkeys.rpId, created.credId, r);
872
+ const added = addRootWrap(vault, wrap);
873
+ if (!added.ok)
874
+ return added;
875
+ const published = await publishVault(s.ctx, added.value);
876
+ if (!published.ok)
877
+ return published;
878
+ await rememberMethod(s.ctx, { id: `passkey:${created.credId}`, method: { kind: "passkey", synced: created.synced } });
879
+ // Local copy source (#38): (a) made by this device (passkey added).
880
+ const ready = await becomeReady(s.ctx, published.value, s.s, r, s.unlockedWith, s.db);
881
+ return ready.ok ? ok(ready.value.status) : ready;
882
+ };
883
+ const enrollPasskey = async () => {
884
+ const s = requireReady();
885
+ if (!s.ok)
886
+ return s;
887
+ if (s.value.r === undefined && hasRootKey(s.value.vault)) {
888
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
889
+ }
890
+ const created = await createPasskey(s.value.ctx, s.value.vault);
891
+ if (!created.ok)
892
+ return created;
893
+ if (created.value.prfOutput === null) {
894
+ pendingPasskey = created.value;
895
+ return ok({ done: false });
896
+ }
897
+ const done = await completeEnrollment(s.value, created.value, created.value.prfOutput);
898
+ return done.ok ? ok({ done: true }) : done;
899
+ };
900
+ const finishPasskeySetup = async () => {
901
+ const s = requireReady();
902
+ if (!s.ok)
903
+ return s;
904
+ const created = pendingPasskey;
905
+ if (created === null || passkeys === undefined)
906
+ return error("nothingToFinish", "No passkey setup is waiting");
907
+ let result;
908
+ try {
909
+ result = await passkeys.get({ allowCredIds: [created.credId], prfInput: clientPrfInput(s.value.ctx.pubkey, s.value.ctx.appId) });
910
+ }
911
+ catch (e) {
912
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
913
+ }
914
+ if (result.prfOutput === null)
915
+ return error("prfUnsupported", "The passkey gave no PRF output");
916
+ pendingPasskey = null;
917
+ return completeEnrollment(s.value, created, result.prfOutput);
918
+ };
919
+ const makeStrict = async (opts) => {
920
+ const s = requireReady();
921
+ if (!s.ok)
922
+ return s;
923
+ if (s.value.r === undefined) {
924
+ if (opts?.replaceRoot === true && s.value.vault.mode === "compatible")
925
+ return makeStrictNewRoot(s.value, opts.acceptDeviceLoss === true);
926
+ return error("rootLocked", "Unlock the root key on this device first, or call makeStrict({ replaceRoot: true }) to start with a new recovery phrase");
927
+ }
928
+ if (opts?.replaceRoot === true)
929
+ return error("rootKnown", "The root key is unlocked here; call makeStrict() without replaceRoot");
930
+ // Read fresh, checked against the vault with R (#53).
931
+ backupState = await readBackupState(s.value.ctx, s.value.vault, s.value.r);
932
+ const need = backupRequirement(backupState.methods.map((m) => m.method), backupState.phraseConfirmed);
933
+ if (need === "required" && opts?.acceptDeviceLoss !== true) {
934
+ return error("backupRequired", "Save the recovery phrase or add a second passkey first, or accept losing the data with this device");
935
+ }
936
+ const newS = random(DATA_SECRET_LENGTH);
937
+ const next = makeStrictVault(s.value.ctx, s.value.vault, { r: s.value.r, newS, now: now() });
938
+ if (!next.ok)
939
+ return next;
940
+ return rotateTo(s.value, next.value, newS, s.value.r);
941
+ };
942
+ const rotateRoot = async (opts) => {
943
+ const ready = requireReady();
944
+ if (!ready.ok)
945
+ return ready;
946
+ let s = ready.value;
947
+ if (s.r === undefined) {
948
+ // The signer can open the vault, also through its previous key.
949
+ const viaSigner = capable === undefined ? null : await rootFromSigner(s.ctx, s.vault);
950
+ if (viaSigner === null || !viaSigner.ok)
951
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
952
+ if (!openRootData(s.ctx, s.vault, viaSigner.value).ok)
953
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
954
+ s = { ...s, r: viaSigner.value };
955
+ }
956
+ const oldR = s.r;
957
+ const newR = random(ROOT_KEY_LENGTH);
958
+ const strong = await newStrongWrap(s.ctx, newR, opts?.acceptDeviceLoss === true);
959
+ if (!strong.ok)
960
+ return strong;
961
+ const newS = random(DATA_SECRET_LENGTH);
962
+ let nip44Ct;
963
+ if (s.vault.mode === "compatible") {
964
+ try {
965
+ nip44Ct = await nip44SealSecret(deps.signer, s.ctx.pubkey, newS);
966
+ }
967
+ catch (e) {
968
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
969
+ }
970
+ }
971
+ const next = rotateRootVault(s.ctx, s.vault, {
972
+ r: oldR,
973
+ newR,
974
+ newS,
975
+ now: now(),
976
+ rootWraps: [strong.value.wrap],
977
+ ...(nip44Ct === undefined ? {} : { nip44Ct }),
978
+ });
979
+ if (!next.ok)
980
+ return next;
981
+ // Backup facts start over: one method, phrase not confirmed (#53).
982
+ await writeMethodRecords(s.ctx, [strong.value.known]);
983
+ await localSet(backupKey("phrase", s.ctx), "");
984
+ return rotateTo(s, next.value, newS, newR);
985
+ };
986
+ /** Strict with a new root key and a new strong method (#49). */
987
+ const makeStrictNewRoot = async (s, acceptDeviceLoss) => {
988
+ const newR = random(ROOT_KEY_LENGTH);
989
+ const strong = await newStrongWrap(s.ctx, newR, acceptDeviceLoss);
990
+ if (!strong.ok)
991
+ return strong;
992
+ const newS = random(DATA_SECRET_LENGTH);
993
+ const next = makeStrictWithNewRoot(s.ctx, s.vault, { newR, newS, now: now(), rootWraps: [strong.value.wrap] });
994
+ if (!next.ok)
995
+ return next;
996
+ // Backup facts start over: one method, phrase not confirmed (#53).
997
+ await writeMethodRecords(s.ctx, [strong.value.known]);
998
+ await localSet(backupKey("phrase", s.ctx), "");
999
+ return rotateTo(s, next.value, newS, newR);
1000
+ };
1001
+ /** Moves this device to a new strict vault and data secret S' (SPEC §3.4). */
1002
+ const rotateTo = async (s, next, newS, r) => {
1003
+ const db = await deps.openDatabase(newS);
1004
+ await migrateRows(s.db, db, { kind: "all" });
1005
+ for (const key of [META_APP_SETTINGS, META_SHARED_SETTINGS, META_SEEN_SECRETS]) {
1006
+ const v = await s.db.getMeta(key);
1007
+ if (v !== null)
1008
+ await db.setMeta(key, v);
1009
+ }
1010
+ const published = await publishVault(s.ctx, next, true, undefined, r);
1011
+ if (!published.ok && published.error.type !== "partialPublish") {
1012
+ await db.deleteLocal();
1013
+ return published;
1014
+ }
1015
+ if (!published.ok) {
1016
+ // Some relays have the strict vault: continue on S', but keep the old
1017
+ // local database until every relay agrees (#32). connect() re-sends it.
1018
+ // Local copy source (#38): (a) made by this device (makeStrict).
1019
+ const ready = await becomeReady(s.ctx, next, newS, r, s.unlockedWith, db);
1020
+ return ready.ok ? published : ready;
1021
+ }
1022
+ await s.db.deleteLocal();
1023
+ // Local copy source (#38): (a) made by this device (makeStrict).
1024
+ const ready = await becomeReady(s.ctx, published.value, newS, r, s.unlockedWith, db);
1025
+ return ready.ok ? ok(ready.value.status) : ready;
1026
+ };
1027
+ /**
1028
+ * A new strong method sealing R: the capable signer, else a new passkey (from
1029
+ * a click), with the backup check for a single method (SPEC §3.2 rule 3a, #42).
1030
+ */
1031
+ const newStrongWrap = async (ctx, r, acceptDeviceLoss) => {
1032
+ if (capable !== undefined) {
1033
+ let key;
1034
+ try {
1035
+ key = await capable.getWrapKey();
1036
+ }
1037
+ catch (e) {
1038
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
1039
+ }
1040
+ const c = await refreshCaps();
1041
+ if (c?.signerId != null) {
1042
+ const method = { kind: "signer", recoverable: c.recoverable === true };
1043
+ if (backupRequirement([method], false) === "required" && !acceptDeviceLoss) {
1044
+ return error("backupRequired", "This signer's key can't be recovered on another device: accept losing the data with this device, or set up a backup first");
1045
+ }
1046
+ return ok({ wrap: signerRootWrap(ctx, key, c.signerId, r), known: { id: `signer:${c.signerId}`, method }, how: "signer" });
1047
+ }
1048
+ }
1049
+ const created = await createPasskey(ctx, undefined);
1050
+ if (!created.ok)
1051
+ return created;
1052
+ let prfOutput = created.value.prfOutput;
1053
+ if (prfOutput === null && passkeys !== undefined) {
1054
+ try {
1055
+ prfOutput = (await passkeys.get({ allowCredIds: [created.value.credId], prfInput: clientPrfInput(ctx.pubkey, ctx.appId) })).prfOutput;
1056
+ }
1057
+ catch (e) {
1058
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
1059
+ }
1060
+ }
1061
+ if (prfOutput === null || passkeys === undefined)
1062
+ return error("prfUnsupported", "The passkey gave no PRF output");
1063
+ const method = { kind: "passkey", synced: created.value.synced };
1064
+ if (backupRequirement([method], false) === "required" && !acceptDeviceLoss) {
1065
+ return error("backupRequired", "This passkey isn't synced: accept losing the data with this device, or use a synced passkey");
1066
+ }
1067
+ const wrap = passkeyRootWrap(ctx, passkeyWrapKey(prfOutput, ctx.appId), passkeys.rpId, created.value.credId, r);
1068
+ return ok({ wrap, known: { id: `passkey:${created.value.credId}`, method }, how: "passkey" });
1069
+ };
1070
+ /** First vault created strict for `requireStrong` (SPEC §8.2 step 4). */
1071
+ const setupStrong = async (ctx, acceptDeviceLoss) => {
1072
+ const r = random(ROOT_KEY_LENGTH);
1073
+ const strong = await newStrongWrap(ctx, r, acceptDeviceLoss);
1074
+ if (!strong.ok)
1075
+ return strong;
1076
+ const s = random(DATA_SECRET_LENGTH);
1077
+ const vault = createStrictVault(ctx, { s, r, now: now(), rootWraps: [strong.value.wrap] });
1078
+ if (!vault.ok)
1079
+ return vault;
1080
+ const published = await publishVault(ctx, vault.value);
1081
+ if (!published.ok)
1082
+ return published;
1083
+ const db = await deps.openDatabase(s);
1084
+ await rememberMethod(ctx, strong.value.known);
1085
+ // Local copy source (#38): (a) made by this device (requireStrong).
1086
+ return becomeReady(ctx, published.value, s, r, strong.value.how, db);
1087
+ };
1088
+ const exportEvoluMnemonic = () => {
1089
+ const s = requireReady();
1090
+ return s.ok ? ok(dataSecretToEvoluMnemonic(s.value.s)) : s;
1091
+ };
1092
+ const status = () => (session.kind === "ready" ? statusOf(session) : null);
1093
+ const settings = {
1094
+ get: (key) => resolveSetting(key, settingsState.app, settingsState.shared, settingsDefaults),
1095
+ refresh: async () => {
1096
+ const s = requireReady();
1097
+ if (!s.ok)
1098
+ return s;
1099
+ const fetched = await fetchSharedSettings(settingsIo, s.value.ctx.pubkey);
1100
+ if (!fetched.ok)
1101
+ return fetched;
1102
+ const shared = mergeSettings(settingsState.shared, fetched.value);
1103
+ await s.value.db.setMeta(META_SHARED_SETTINGS, JSON.stringify(shared));
1104
+ settingsState = { ...settingsState, shared };
1105
+ return ok(undefined);
1106
+ },
1107
+ setShared: async (key, value) => {
1108
+ const s = requireReady();
1109
+ if (!s.ok)
1110
+ return s;
1111
+ const fetched = await fetchSharedSettings(settingsIo, s.value.ctx.pubkey, true); // a write: every relay (#62)
1112
+ if (!fetched.ok)
1113
+ return fetched;
1114
+ const at = Math.max(now(), lastEventAt + 1);
1115
+ const next = setSetting(mergeSettings(settingsState.shared, fetched.value), key, value, at);
1116
+ if (!next.ok)
1117
+ return next;
1118
+ const published = await publishSharedSettings(settingsIo, s.value.ctx.pubkey, next.value, at);
1119
+ if (!published.ok)
1120
+ return published;
1121
+ lastEventAt = at;
1122
+ await s.value.db.setMeta(META_SHARED_SETTINGS, JSON.stringify(next.value));
1123
+ settingsState = { ...settingsState, shared: next.value };
1124
+ return ok(undefined);
1125
+ },
1126
+ setApp: async (key, value) => {
1127
+ const s = requireReady();
1128
+ if (!s.ok)
1129
+ return s;
1130
+ const next = setSetting(settingsState.app, key, value, now());
1131
+ if (!next.ok)
1132
+ return next;
1133
+ await s.value.db.setMeta(META_APP_SETTINGS, JSON.stringify(next.value));
1134
+ settingsState = { ...settingsState, app: next.value };
1135
+ return ok(undefined);
1136
+ },
1137
+ };
1138
+ const logout = async (opts) => {
1139
+ const s = session;
1140
+ session = { kind: "none" };
1141
+ if (s.kind === "none")
1142
+ return;
1143
+ await deps.cache.remove(s.ctx.pubkey, s.ctx.appId);
1144
+ const db = s.kind === "ready" ? s.db : s.local?.db;
1145
+ if (db === undefined)
1146
+ return;
1147
+ if (opts?.deleteLocalData === true) {
1148
+ await db.deleteLocal();
1149
+ await deps.hints?.remove?.(hintKey(s.ctx)).catch(() => undefined);
1150
+ }
1151
+ else
1152
+ await db.close();
1153
+ };
1154
+ const discardOldDatabase = async () => {
1155
+ const old = leftBehind;
1156
+ leftBehind = null;
1157
+ if (old !== null)
1158
+ await old.deleteLocal();
1159
+ return ok(undefined);
1160
+ };
1161
+ return {
1162
+ discardOldDatabase,
1163
+ connect,
1164
+ unlock,
1165
+ resolveVaultChange,
1166
+ unlockRoot,
1167
+ enrollPasskey,
1168
+ finishPasskeySetup,
1169
+ makeStrict,
1170
+ showRecoveryPhrase,
1171
+ exportEvoluMnemonic,
1172
+ confirmRecoveryPhrase,
1173
+ restoreFromPhrase,
1174
+ downgrade,
1175
+ rotateRoot,
1176
+ status,
1177
+ settings,
1178
+ logout,
1179
+ };
1180
+ };
1181
+ //# sourceMappingURL=client.js.map