@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/src/client.ts ADDED
@@ -0,0 +1,1495 @@
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 {
10
+ type Bytes,
11
+ type EvolustrError,
12
+ type Fetched,
13
+ type NostrEvent,
14
+ type Relays,
15
+ type Result,
16
+ type Signer,
17
+ type RootWrap,
18
+ type Vault,
19
+ type VaultChoice,
20
+ type VaultContext,
21
+ type SettingKey,
22
+ type StrongMethod,
23
+ type SettingsDoc,
24
+ type SharedSettings,
25
+ DATA_SECRET_LENGTH,
26
+ ROOT_KEY_LENGTH,
27
+ VAULT_KIND,
28
+ addRootKey,
29
+ dataSecretToEvoluMnemonic,
30
+ addRootWrap,
31
+ backupRequirement,
32
+ canOpenOwnVault,
33
+ hkdf,
34
+ rootWrapKeyId,
35
+ toHex,
36
+ verifyRootWrap,
37
+ clientPrfInput,
38
+ createStrictVault,
39
+ makeStrict as makeStrictVault,
40
+ makeStrictWithNewRoot,
41
+ rotateRoot as rotateRootVault,
42
+ verifyRootRotation,
43
+ openRootWrap,
44
+ passkeyRootWrap,
45
+ passkeyWrapKey,
46
+ passkeyWrapsFor,
47
+ signerRootWrap,
48
+ signerWrapFor,
49
+ sha256,
50
+ sha256Hex,
51
+ utf8,
52
+ appVaultDTag,
53
+ createCompatibleVault,
54
+ decideVault,
55
+ defaultSettings,
56
+ emptySettings,
57
+ mergeSettings,
58
+ parseSettings,
59
+ resolveSetting,
60
+ setSetting,
61
+ downgrade as downgradeVault,
62
+ error,
63
+ fetchReplaceable,
64
+ hasRootKey,
65
+ level,
66
+ mergeVaults,
67
+ migrationCutoff,
68
+ nip44OpenSecret,
69
+ nip44SealSecret,
70
+ ok,
71
+ openRootData,
72
+ parseVault,
73
+ phraseToRootKey,
74
+ publishReplaceable,
75
+ randomBytes as defaultRandomBytes,
76
+ readVaultEvent,
77
+ rootKeyToPhrase,
78
+ serializeVault,
79
+ vaultEvent,
80
+ } from "@evolustr/core";
81
+ import type { SecretCache } from "./cache.ts";
82
+ import { type CapableSigner, earlierSignerIds, type SignerCapabilities } from "./capable.ts";
83
+ import type { CreatedPasskey, Passkeys } from "@evolustr/core";
84
+ import { fetchSharedSettings, publishSharedSettings } from "./settings.ts";
85
+ import {
86
+ type AppDatabase,
87
+ type MigrationMode,
88
+ type MigrationResult,
89
+ type OpenDatabase,
90
+ META_SHARED_SETTINGS,
91
+ META_VAULT,
92
+ migrateRows,
93
+ } from "./database.ts";
94
+
95
+ // ── Public types ────────────────────────────────────────────────────────────
96
+
97
+ export interface ClientDeps {
98
+ readonly signer: Signer;
99
+ readonly relays: Relays;
100
+ readonly openDatabase: OpenDatabase;
101
+ readonly cache: SecretCache;
102
+ /** Client passkeys on this app's domain (SPEC §4); omit to disable. */
103
+ readonly passkeys?: Passkeys | undefined;
104
+ /**
105
+ * A small non-secret store that survives logout (e.g. localStorage): the last
106
+ * mode and secret hash per (pubkey, appId). After a logout it still tells a
107
+ * strict vault swapped for a weak one (#44). It also holds the facts for the
108
+ * backup check (#53): which strong methods recover on their own, and whether
109
+ * the phrase was confirmed. Without it, those last for the session only.
110
+ */
111
+ readonly hints?: {
112
+ readonly get: (key: string) => Promise<string | null>;
113
+ readonly set: (key: string, value: string) => Promise<void>;
114
+ readonly remove?: (key: string) => Promise<void>;
115
+ };
116
+ /** An Evolustr-capable signer (SPEC §5), e.g. from `detectCapableSigner(window.nostr)`. */
117
+ readonly capableSigner?: CapableSigner | undefined;
118
+ /** Unix seconds. */
119
+ readonly now?: () => number;
120
+ readonly randomBytes?: (length: number) => Bytes;
121
+ }
122
+
123
+ export interface ClientOptions {
124
+ readonly appId: string;
125
+ readonly relayUrls: ReadonlyArray<string>;
126
+ /**
127
+ * Enough relays to trust a vault an unlock found (#60): such reads stop
128
+ * waiting once this many answered, so one slow relay doesn't hold them up.
129
+ * "No vault" and reads before a write still wait for every relay (#62).
130
+ * Default: every relay.
131
+ */
132
+ readonly relayQuorum?: number;
133
+ /** Only strict databases (SPEC §3.2 rule 1). Needs passkeys or a capable signer. */
134
+ readonly requireStrong?: boolean;
135
+ readonly timeoutMs?: number;
136
+ /** Margin for devices whose clocks are off, used in migrations (SPEC §3.4). */
137
+ readonly clockMarginMs?: number;
138
+ /** Defaults for shared settings; language and time zone usually come from the browser. */
139
+ readonly settingsDefaults?: SharedSettings;
140
+ /**
141
+ * Ask before using a compatible vault on a new device when nothing stronger can
142
+ * verify it (`needsUserAction: "confirmWeak"`). Default true; turn off only if
143
+ * the app never offers strict mode.
144
+ */
145
+ readonly confirmWeakOnNewDevice?: boolean;
146
+ /**
147
+ * Also keep the root key R (the recovery phrase) in the device cache, so a
148
+ * reload can follow rotations and add strong methods without a passkey or
149
+ * signer click. Default false: R stays in memory for the session (#27).
150
+ */
151
+ readonly cacheRootKey?: boolean;
152
+ /**
153
+ * After the database became strict elsewhere, also copy rows this device
154
+ * changed in the old database, overwriting the strict one. Default false:
155
+ * the old database could be written by any app that could decrypt its secret,
156
+ * so only rows missing in the strict database are copied (#51).
157
+ */
158
+ readonly migrateChangedRows?: boolean;
159
+ /** Called as connect and unlock move through their steps; relays can be slow. */
160
+ readonly onProgress?: (step: ProgressStep) => void;
161
+ }
162
+
163
+ export type UnlockMethod = "signer" | "passkey" | "nip44" | "recovery" | "cache" | "created";
164
+
165
+ export interface Status {
166
+ readonly pubkey: string;
167
+ readonly signer: "capable-verified" | "capable-connection" | "standard";
168
+ readonly mode: "strict" | "compatible";
169
+ readonly level: "strong" | "weak";
170
+ readonly unlockedWith: UnlockMethod;
171
+ /** R is unlocked on this device, so strict is possible (SPEC §8.1). */
172
+ readonly canMakeStrict: boolean;
173
+ /** False after a nip44-only unlock of a vault that has R (SPEC §3.1). */
174
+ readonly canAddStrongMethod: boolean;
175
+ /**
176
+ * A compatible vault whose root key this device can't open: it can still go
177
+ * strict with a new root key, `makeStrict({ replaceRoot: true })` (#49).
178
+ * Earlier passkeys, signer wraps and the old recovery phrase stop working.
179
+ */
180
+ readonly canReplaceRoot: boolean;
181
+ readonly passkeySupported: boolean;
182
+ readonly backupRecommended: boolean;
183
+ /**
184
+ * The vault is strict and this session's capable signer protects its key with
185
+ * the nsec, or did before without changing the key: anyone who has the
186
+ * user's nsec can open this data (#43, #52).
187
+ */
188
+ readonly dependsOnNsec: boolean;
189
+ /**
190
+ * The capable signer replaced its key because the old one was exposed (#52),
191
+ * and this vault still has a wrap made with the old key: whoever had it may
192
+ * know this app's root key and data secret. Offer `rotateRoot()`.
193
+ */
194
+ readonly rootExposed: boolean;
195
+ }
196
+
197
+ /** Steps of connect / unlock, for showing progress (`onProgress`). */
198
+ export type ProgressStep = "lookingUpVault" | "creatingVault" | "publishingVault" | "openingDatabase";
199
+
200
+ export interface UnlockInput {
201
+ readonly recoveryPhrase?: string;
202
+ readonly acceptDeviceLoss?: boolean;
203
+ }
204
+
205
+ export interface MakeStrictOptions {
206
+ readonly acceptDeviceLoss?: boolean;
207
+ /**
208
+ * Only when `status.canReplaceRoot`: go strict with a new root key and a new
209
+ * strong method created in the same call (the capable signer, else a new
210
+ * passkey; call from a click). Earlier passkeys, signer wraps and the old
211
+ * recovery phrase of this database stop working; tell the user first (#49).
212
+ */
213
+ readonly replaceRoot?: boolean;
214
+ }
215
+
216
+ export interface Ready {
217
+ readonly pubkey: string;
218
+ readonly db: AppDatabase;
219
+ readonly status: Status;
220
+ /**
221
+ * Set when this unlock moved local rows to a new data secret. `skippedChanged`
222
+ * counts rows edited here that weren't carried over (#51); the old database
223
+ * is then kept until `discardOldDatabase()`.
224
+ */
225
+ readonly migration?: MigrationResult;
226
+ }
227
+
228
+ /**
229
+ * "confirmWeak": first use on this device of a compatible vault that can only be
230
+ * opened through NIP-44. Someone who can sign for the user could have replaced a
231
+ * strict vault with one like it (#26), so the user confirms before data is written.
232
+ */
233
+ export type UserAction = "passkey" | "signerUnlock" | "recoveryPhrase" | "setupStrong" | "confirmWeak";
234
+
235
+ export type ConnectResult =
236
+ | ({ readonly state: "ready" } & Ready)
237
+ | { readonly state: "needsUserAction"; readonly action: UserAction }
238
+ | {
239
+ readonly state: "vaultChanged";
240
+ readonly reason: "replaced" | "ambiguous" | "missing";
241
+ readonly options: ReadonlyArray<VaultChoice>;
242
+ /**
243
+ * "useAnotherDevice": nothing on this device can restore the real vault.
244
+ * Connect a device that is still signed in: it restores the vault
245
+ * (`republishCopy`); then sign in here again (#54).
246
+ */
247
+ readonly advice?: "useAnotherDevice";
248
+ };
249
+
250
+ export interface Evolustr {
251
+ /** Never prompts for a passkey; safe on page load. */
252
+ readonly connect: () => Promise<Result<ConnectResult>>;
253
+ /**
254
+ * Completes `needsUserAction`, from a click. Pass the phrase for "recoveryPhrase";
255
+ * for "setupStrong" with a device-bound passkey, pass `acceptDeviceLoss`.
256
+ *
257
+ * Errors to handle: `wrongPhrase`; `vaultReplaced` when the unlock proved the
258
+ * vault on the relays isn't the user's (#39): call
259
+ * `resolveVaultChange("republishCopy")` to restore this device's copy.
260
+ */
261
+ readonly unlock: (input?: UnlockInput) => Promise<Result<Ready>>;
262
+ readonly resolveVaultChange: (
263
+ choice: VaultChoice,
264
+ input?: { readonly recoveryPhrase?: string },
265
+ ) => Promise<Result<Ready>>;
266
+ /** Makes R available on this device while ready: phrase, or a passkey from a click (SPEC §8.1). */
267
+ readonly unlockRoot: (input?: { readonly recoveryPhrase?: string }) => Promise<Result<Status>>;
268
+ /** Adds a passkey on this domain, from a click. May need `finishPasskeySetup` (SPEC §4.2). */
269
+ readonly enrollPasskey: () => Promise<Result<{ readonly done: boolean }>>;
270
+ /** Second click when the authenticator returned no PRF output at creation. */
271
+ readonly finishPasskeySetup: () => Promise<Result<Status>>;
272
+ /**
273
+ * User's choice: replaces S and drops the NIP-44 wrap (SPEC §3.2 rules 3–4, §3.4).
274
+ * Protects what is written afterwards; data written before stays as readable
275
+ * as it was. Tell the user before calling it (#31).
276
+ */
277
+ readonly makeStrict: (opts?: MakeStrictOptions) => Promise<Result<Status>>;
278
+ /**
279
+ * This database's Evolu mnemonic (12 words), to use the data with Evolu
280
+ * directly, without Nostr. Anyone with it can read and write all of this
281
+ * database. It is not the recovery phrase: it changes when the database is
282
+ * made strict, and the old one keeps opening the data from before that.
283
+ */
284
+ readonly exportEvoluMnemonic: () => Result<string>;
285
+ /** R as 12 words; creates R if the vault has none yet. */
286
+ readonly showRecoveryPhrase: () => Promise<Result<string>>;
287
+ /** The user typed the phrase back correctly; remembered for the backup check. */
288
+ readonly confirmRecoveryPhrase: (words: string) => Promise<Result<void>>;
289
+ readonly restoreFromPhrase: (words: string) => Promise<Result<Ready>>;
290
+ readonly downgrade: () => Promise<Result<Status>>;
291
+ /**
292
+ * Replaces the root key and the data secret, keeping the mode (#52 phase C),
293
+ * from a click: when `status.rootExposed`, or when the recovery phrase may
294
+ * have leaked. A new strong method seals the new root key (the capable
295
+ * signer, else a new passkey). Every other passkey and signer, and the old
296
+ * recovery phrase, stop working for this app; tell the user first. Data
297
+ * written before stays as readable as it was.
298
+ */
299
+ readonly rotateRoot: (opts?: { readonly acceptDeviceLoss?: boolean }) => Promise<Result<Status>>;
300
+ readonly status: () => Status | null;
301
+ readonly settings: {
302
+ /** `app ?? shared ?? default` (SPEC §9.2). Reads cached values; no prompt. */
303
+ readonly get: <K extends SettingKey>(key: K) => SharedSettings[K];
304
+ /** Fetches the shared settings from relays (may show a decrypt prompt). */
305
+ readonly refresh: () => Promise<Result<void>>;
306
+ /** "Use for all apps": writes to the shared event (signature + encryption). */
307
+ readonly setShared: (key: string, value: unknown) => Promise<Result<void>>;
308
+ /** This app only, stored in the app database. */
309
+ readonly setApp: (key: string, value: unknown) => Promise<Result<void>>;
310
+ };
311
+ readonly logout: (opts?: { readonly deleteLocalData?: boolean }) => Promise<void>;
312
+ /**
313
+ * Deletes the old local database kept after a migration that skipped edited
314
+ * rows (`ready.migration.skippedChanged > 0`), once the user decided (#51).
315
+ */
316
+ readonly discardOldDatabase: () => Promise<Result<void>>;
317
+ }
318
+
319
+ // ── Session state ───────────────────────────────────────────────────────────
320
+
321
+ interface Unlocked {
322
+ readonly kind: "ready";
323
+ readonly ctx: VaultContext;
324
+ readonly vault: Vault;
325
+ readonly s: Bytes;
326
+ readonly r?: Bytes;
327
+ readonly db: AppDatabase;
328
+ readonly unlockedWith: UnlockMethod;
329
+ }
330
+
331
+ interface Pending {
332
+ readonly kind: "pending";
333
+ readonly ctx: VaultContext;
334
+ readonly action: UserAction | "choose";
335
+ readonly vault?: Vault;
336
+ /** Local database and secrets, when this device already had one. */
337
+ readonly local?: { readonly db: AppDatabase; readonly s: Bytes; readonly r?: Bytes; readonly copy?: Vault };
338
+ }
339
+
340
+ type Session = { readonly kind: "none" } | Unlocked | Pending;
341
+
342
+ /** @deprecated No longer read or written: backup facts live on the device (`hints`, #53). */
343
+ export const META_PHRASE_CONFIRMED = "phraseConfirmed";
344
+ export const META_APP_SETTINGS = "appSettings";
345
+ /** Data secrets this device moved past, for rollback detection beyond the vault's history (#44). */
346
+ export const META_SEEN_SECRETS = "seenSecrets";
347
+ const SEEN_LIMIT = 200;
348
+ /** @deprecated No longer read or written: backup facts live on the device (`hints`, #53). */
349
+ export const META_STRONG_METHODS = "strongMethods";
350
+
351
+ interface KnownMethod {
352
+ readonly id: string;
353
+ readonly method: StrongMethod;
354
+ }
355
+
356
+ // ── Implementation ──────────────────────────────────────────────────────────
357
+
358
+ export const createEvolustr = (deps: ClientDeps, options: ClientOptions): Evolustr => {
359
+ const now = deps.now ?? (() => Math.floor(Date.now() / 1000));
360
+ const random = deps.randomBytes ?? defaultRandomBytes;
361
+ const timeoutMs = options.timeoutMs ?? 3000;
362
+ const clockMarginMs = options.clockMarginMs ?? 5 * 60_000;
363
+ let session: Session = { kind: "none" };
364
+ let lastEventAt = 0;
365
+ let settingsState: { readonly app: SettingsDoc; readonly shared: SettingsDoc } = { app: emptySettings, shared: emptySettings };
366
+ const settingsDefaults = options.settingsDefaults ?? defaultSettings();
367
+ const settingsIo = { signer: deps.signer, relays: deps.relays, relayUrls: options.relayUrls, timeoutMs, ...(options.relayQuorum === undefined ? {} : { relayQuorum: options.relayQuorum }) };
368
+ let passkeySupported = false;
369
+ let backupState: { readonly methods: ReadonlyArray<KnownMethod>; readonly phraseConfirmed: boolean } = {
370
+ methods: [],
371
+ phraseConfirmed: false,
372
+ };
373
+ let pendingPasskey: CreatedPasskey | null = null;
374
+ const passkeys = deps.passkeys;
375
+ const capable = deps.capableSigner;
376
+ let caps: SignerCapabilities | null = null;
377
+
378
+ const refreshCaps = async (): Promise<SignerCapabilities | null> => {
379
+ caps = capable === undefined ? null : await capable.capabilities().catch(() => null);
380
+ return caps;
381
+ };
382
+
383
+ /** R through the capable signer's wrap (SPEC §8.2 step 2). May wait for a click in the signer. */
384
+ const rootFromSigner = async (ctx: VaultContext, vault: Vault, copy?: Vault): Promise<Result<Bytes>> => {
385
+ if (capable === undefined) return error("noCapableSigner", "No Evolustr-capable signer");
386
+ let key: Bytes;
387
+ try {
388
+ key = await capable.getWrapKey();
389
+ } catch (e) {
390
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
391
+ }
392
+ const c = await refreshCaps();
393
+ if (c?.signerId == null) return error("noSignerWrap", "This signer has no wrap in the vault yet");
394
+ // The fetched vault's wrap first, then the local copy's (#39).
395
+ const wrapsFor = (id: string) =>
396
+ [signerWrapFor(vault, id), copy === undefined ? undefined : signerWrapFor(copy, id)].filter((w): w is RootWrap => w !== undefined);
397
+ const wraps = wrapsFor(c.signerId);
398
+ for (const wrap of wraps) {
399
+ const opened = openRootWrap(ctx, wrap, key);
400
+ if (opened.ok) return opened;
401
+ }
402
+ // After the signer replaced its key, the wrap made with an earlier one (#52
403
+ // phase B), however many replacements ago (#58).
404
+ const earlier = earlierSignerIds(c).map((id, n) => ({ id, n, wraps: wrapsFor(id) })).filter((x) => x.wraps.length > 0);
405
+ if (capable.getPreviousWrapKey !== undefined) {
406
+ for (const { id, n, wraps: old } of earlier) {
407
+ let oldKey: Bytes;
408
+ try {
409
+ // The newest needs no id, so signers from before #58 still answer.
410
+ oldKey = await capable.getPreviousWrapKey(n === 0 ? undefined : id);
411
+ } catch (e) {
412
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
413
+ }
414
+ for (const wrap of old) {
415
+ const opened = openRootWrap(ctx, wrap, oldKey);
416
+ if (opened.ok) return opened;
417
+ }
418
+ }
419
+ }
420
+ if (wraps.length === 0 && earlier.length === 0) return error("noSignerWrap", "This signer has no wrap in the vault yet");
421
+ return error("signerRefused", "The signer's key didn't open its wrap");
422
+ };
423
+
424
+ /** After an unlock: add this signer's wrap, creating R if the vault has none (SPEC §8.2 step 5). */
425
+ const ensureSignerWrap = async (): Promise<void> => {
426
+ if (session.kind !== "ready" || capable === undefined) return;
427
+ const s = session;
428
+ let c = caps;
429
+ if (c === null) return;
430
+ if (c.ready && c.signerId !== null && signerWrapFor(s.vault, c.signerId) !== undefined) {
431
+ // Refresh the record: the signer may have gained an sk wrap or a synced passkey (#42).
432
+ await rememberMethod(s.ctx, { id: `signer:${c.signerId}`, method: { kind: "signer", recoverable: c.recoverable === true } });
433
+ backupState = await readBackupState(s.ctx, s.vault, s.r);
434
+ return;
435
+ }
436
+ // A locked signer that needs a passkey click isn't asked here; the user adds it later.
437
+ if (!c.ready && c.signerPasskey) return;
438
+ if (s.r === undefined && hasRootKey(s.vault)) return; // nip44-only device: can't add (SPEC §3.1)
439
+ let key: Bytes;
440
+ try {
441
+ // Asks the user to allow this app; a new signer creates its key here (#29).
442
+ key = await capable.getWrapKey();
443
+ } catch {
444
+ return;
445
+ }
446
+ c = await refreshCaps();
447
+ if (c === null || c.signerId === null || signerWrapFor(s.vault, c.signerId) !== undefined) return;
448
+ const signerIdNow = c.signerId;
449
+ let vault = s.vault;
450
+ const r = s.r ?? random(ROOT_KEY_LENGTH);
451
+ if (s.r === undefined) {
452
+ const withRoot = addRootKey(s.ctx, vault, r, s.s);
453
+ if (!withRoot.ok) return;
454
+ vault = withRoot.value;
455
+ }
456
+ const added = addRootWrap(vault, signerRootWrap(s.ctx, key, signerIdNow, r));
457
+ if (!added.ok) return;
458
+ const published = await publishVault(s.ctx, added.value);
459
+ if (!published.ok) return;
460
+ await rememberMethod(s.ctx, { id: `signer:${signerIdNow}`, method: { kind: "signer", recoverable: c.recoverable === true } });
461
+ // Local copy source (#38): (a) made by this device: its signer wrap added.
462
+ await becomeReady(s.ctx, published.value, s.s, r, s.unlockedWith, s.db);
463
+ };
464
+
465
+ const readDoc = async (db: AppDatabase, key: string): Promise<SettingsDoc> => {
466
+ const text = await db.getMeta(key);
467
+ const doc = text === null ? null : parseSettings(text);
468
+ return doc?.ok ? doc.value : emptySettings;
469
+ };
470
+
471
+ // ── Relay helpers ──
472
+
473
+ /** `full`: wait for every relay, for a read a publish builds on (#62). */
474
+ const fetchVault = async (ctx: VaultContext, urls: ReadonlyArray<string> = options.relayUrls, full = false): Promise<Fetched> => {
475
+ const f = await fetchReplaceable(
476
+ deps.relays,
477
+ urls,
478
+ { author: ctx.pubkey, kind: VAULT_KIND, d: appVaultDTag(ctx.pubkey, ctx.appId) },
479
+ timeoutMs,
480
+ full ? undefined : options.relayQuorum,
481
+ );
482
+ if (f.kind === "none") return { kind: "none" };
483
+ if (f.kind === "incomplete") return { kind: "unreadable" };
484
+ lastEventAt = Math.max(lastEventAt, f.event.created_at);
485
+ // Not re-sent until it passes the checks: never spread a forged event (#44).
486
+ lastSeenEvent = { event: f.event, missingOn: f.missingOn };
487
+ const v = readVaultEvent(ctx, f.event);
488
+ return v.ok ? { kind: "found", vault: v.value } : { kind: "unreadable" };
489
+ };
490
+
491
+ const hintKey = (ctx: VaultContext) => `evolustr:hint:${sha256Hex(`${ctx.pubkey}|${ctx.appId}`)}`;
492
+ const readHint = async (ctx: VaultContext): Promise<{ mode?: string; sHash?: string } | null> => {
493
+ try {
494
+ const text = await deps.hints?.get(hintKey(ctx));
495
+ return text == null ? null : (JSON.parse(text) as { mode?: string; sHash?: string });
496
+ } catch {
497
+ return null;
498
+ }
499
+ };
500
+
501
+ // ── Backup facts (SPEC §3.2 rule 3a, #53) ──
502
+ // Kept on the device, never in the app database: before strict, anyone who
503
+ // can decrypt the nip44 wrap can write there through Evolu sync.
504
+ const sessionStore = new Map<string, string>();
505
+ const localGet = async (key: string): Promise<string | null> =>
506
+ deps.hints === undefined ? (sessionStore.get(key) ?? null) : await deps.hints.get(key).catch(() => null);
507
+ const localSet = async (key: string, value: string): Promise<void> =>
508
+ deps.hints === undefined ? void sessionStore.set(key, value) : await deps.hints.set(key, value).catch(() => undefined);
509
+ const backupKey = (kind: "methods" | "phrase", ctx: VaultContext) =>
510
+ `evolustr:${kind}:${sha256Hex(`${ctx.pubkey}|${ctx.appId}`)}`;
511
+ /** Which root key a phrase confirmation was for; a marker for another R doesn't count. */
512
+ const phraseMarker = (r: Bytes) => toHex(hkdf(r, "evolustr/v1/phrase-confirmed", 8));
513
+
514
+ const readMethodRecords = async (ctx: VaultContext): Promise<ReadonlyArray<KnownMethod>> => {
515
+ try {
516
+ const list = JSON.parse((await localGet(backupKey("methods", ctx))) ?? "[]") as unknown;
517
+ return Array.isArray(list) ? (list as KnownMethod[]) : [];
518
+ } catch {
519
+ return [];
520
+ }
521
+ };
522
+ const writeMethodRecords = (ctx: VaultContext, list: ReadonlyArray<KnownMethod>) =>
523
+ localSet(backupKey("methods", ctx), JSON.stringify(list));
524
+
525
+ /**
526
+ * The backup facts for this vault. With R, every root wrap whose tag verifies
527
+ * is a method; whether it recovers on its own comes from this device's record,
528
+ * else it counts as not recoverable. Without R, only recorded methods that
529
+ * still have a wrap count.
530
+ */
531
+ const readBackupState = async (ctx: VaultContext, vault: Vault, r: Bytes | undefined): Promise<typeof backupState> => {
532
+ const records = await readMethodRecords(ctx);
533
+ const recordFor = (id: string) => records.find((m) => m.id === id);
534
+ const wrapIds = vault.rootWraps.filter((w) => r === undefined || verifyRootWrap(ctx, r, w)).map((w) => ({ id: `${w.type}:${rootWrapKeyId(w)}`, type: w.type }));
535
+ const methods: KnownMethod[] =
536
+ r === undefined
537
+ ? wrapIds.flatMap(({ id }) => {
538
+ const rec = recordFor(id);
539
+ return rec === undefined ? [] : [rec];
540
+ })
541
+ : wrapIds.map(({ id, type }) => recordFor(id) ?? { id, method: type === "passkey" ? { kind: "passkey", synced: false } : { kind: "signer", recoverable: false } });
542
+ const marker = await localGet(backupKey("phrase", ctx));
543
+ const phraseConfirmed = marker !== null && marker !== "" && (r === undefined || marker === phraseMarker(r));
544
+ return { methods, phraseConfirmed };
545
+ };
546
+
547
+ /** Secrets this device has moved past, from its local database (#44). */
548
+ let knownSeen: ReadonlyArray<string> = [];
549
+ const readSeen = async (db: AppDatabase): Promise<ReadonlyArray<string>> => {
550
+ try {
551
+ const list = JSON.parse((await db.getMeta(META_SEEN_SECRETS)) ?? "[]") as unknown;
552
+ return Array.isArray(list) ? list.filter((x): x is string => typeof x === "string") : [];
553
+ } catch {
554
+ return [];
555
+ }
556
+ };
557
+
558
+ /** A vault to publish in the background once connect is ready (self-heal, #37). */
559
+ let healAfterConnect: Vault | null = null;
560
+
561
+ /** The newest vault event fetched, before it was checked (#44). */
562
+ let lastSeenEvent: { readonly event: NostrEvent; readonly missingOn: ReadonlyArray<string> } | null = null;
563
+
564
+ /** Relays that accepted the last publish. */
565
+ let lastAccepted: ReadonlyArray<string> = [];
566
+ const progress = (step: ProgressStep) => {
567
+ try {
568
+ options.onProgress?.(step);
569
+ } catch {
570
+ /* the app's callback must not break connecting */
571
+ }
572
+ };
573
+
574
+ /** The newest vault event seen, and relays that answered without it (#32). */
575
+ let lastFetched: { readonly event: NostrEvent; readonly missingOn: ReadonlyArray<string> } | null = null;
576
+
577
+ /** Sends the current vault event to relays that lack it; no new signature needed. */
578
+ const rebroadcastVault = async (): Promise<void> => {
579
+ const f = lastFetched;
580
+ if (f === null || f.missingOn.length === 0) return;
581
+ await deps.relays.publish(f.missingOn, f.event, timeoutMs).catch(() => undefined);
582
+ lastFetched = { ...f, missingOn: [] };
583
+ };
584
+
585
+ /**
586
+ * Publishes, merging with the relay version first when it holds the same S
587
+ * (superset rule). With `requireAll` (rotations, #32), a relay that still
588
+ * refuses after a retry makes it fail with `partialPublish`.
589
+ */
590
+ const publishVault = async (
591
+ ctx: VaultContext,
592
+ vault: Vault,
593
+ requireAll = false,
594
+ /** What the caller just fetched; skips a second lookup. */
595
+ known?: Fetched,
596
+ /** R, when the caller knows it and the session doesn't yet. */
597
+ rootKey?: Bytes,
598
+ ): Promise<Result<Vault>> => {
599
+ let toPublish = vault;
600
+ progress("publishingVault");
601
+ const sessionR = rootKey ?? (session.kind === "ready" && session.ctx.appId === ctx.appId ? session.r : undefined);
602
+ // With a quorum, what the caller fetched may be stale: read every relay before writing (#62).
603
+ const current = known !== undefined && options.relayQuorum === undefined ? known : await fetchVault(ctx, options.relayUrls, true);
604
+ // Only root wraps come from the relay version: `vault` is the one this
605
+ // device made or verified, and its header is part of the root data wrap's
606
+ // AAD (#50). Without a root key here, the relay's root wraps mean nothing.
607
+ if (current.kind === "found" && current.vault.sHash === vault.sHash && hasRootKey(vault)) {
608
+ // The local version wins on the same wrap id; with R, forged wraps are dropped (#37).
609
+ const merged = mergeVaults(vault, current.vault, { ctx, r: sessionR });
610
+ if (!merged.ok) return merged;
611
+ toPublish = { ...vault, rootWraps: merged.value.rootWraps };
612
+ }
613
+ if (!canOpenOwnVault(ctx, toPublish, sessionR)) {
614
+ return error("invalidVault", "Refusing to publish a vault its own root key can't open");
615
+ }
616
+ const at = Math.max(now(), lastEventAt + 1);
617
+ let failed: ReadonlyArray<string>;
618
+ try {
619
+ const published = await publishReplaceable(deps.relays, options.relayUrls, deps.signer, vaultEvent(ctx, toPublish, at), timeoutMs);
620
+ failed = published.failed;
621
+ lastAccepted = published.accepted;
622
+ lastFetched = { event: published.event, missingOn: failed };
623
+ } catch (e) {
624
+ return error("publishFailed", e instanceof Error ? e.message : String(e));
625
+ }
626
+ lastEventAt = at;
627
+ if (requireAll && failed.length > 0) {
628
+ return error("partialPublish", `Not every relay accepted the change (${failed.join(", ")}); it completes on the next connect`);
629
+ }
630
+ return ok(toPublish);
631
+ };
632
+
633
+ // ── Building blocks ──
634
+
635
+ const statusOf = (s: Unlocked): Status => ({
636
+ pubkey: s.ctx.pubkey,
637
+ signer: caps === null ? "standard" : caps.identity === "verified" ? "capable-verified" : "capable-connection",
638
+ mode: s.vault.mode,
639
+ level: level(s.vault),
640
+ unlockedWith: s.unlockedWith,
641
+ canMakeStrict: s.r !== undefined && s.vault.mode === "compatible",
642
+ canAddStrongMethod: s.r !== undefined || !hasRootKey(s.vault),
643
+ canReplaceRoot: s.vault.mode === "compatible" && s.r === undefined && hasRootKey(s.vault),
644
+ passkeySupported,
645
+ dependsOnNsec:
646
+ s.vault.mode === "strict" &&
647
+ (caps?.nsecProtected === true || caps?.nsecExposed === true) &&
648
+ caps.signerId !== null &&
649
+ signerWrapFor(s.vault, caps.signerId) !== undefined,
650
+ rootExposed: caps != null && earlierSignerIds(caps).some((id) => signerWrapFor(s.vault, id) !== undefined),
651
+ backupRecommended:
652
+ s.vault.mode === "strict" &&
653
+ backupRequirement(backupState.methods.map((m) => m.method), backupState.phraseConfirmed) !== "none",
654
+ });
655
+
656
+ /**
657
+ * Opens the database for S, keeps the vault copy and the cache, and becomes
658
+ * ready. The only writer of the local vault copy (META_VAULT), the trust anchor
659
+ * of decideVault (#38): every caller passes a vault this device (a) made, (b)
660
+ * opened with R, (c) opened through NIP-44 after the user chose or confirmed
661
+ * it, or (d) merged from the checked copy.
662
+ */
663
+ const becomeReady = async (
664
+ ctx: VaultContext,
665
+ vaultIn: Vault,
666
+ s: Bytes,
667
+ r: Bytes | undefined,
668
+ unlockedWith: UnlockMethod,
669
+ db?: AppDatabase,
670
+ ): Promise<Result<Ready>> => {
671
+ progress("openingDatabase");
672
+ let vault = vaultIn;
673
+ // The secret this device had before, if it's moving to another one (#44).
674
+ const previous = session.kind === "ready" ? session.db.sHash : session.kind === "pending" ? session.local?.db.sHash : undefined;
675
+ const database = db ?? (await deps.openDatabase(s));
676
+ {
677
+ const seen = [...new Set([...knownSeen, ...(await readSeen(database)), ...(previous !== undefined && previous !== database.sHash ? [previous] : [])])];
678
+ knownSeen = seen.slice(-SEEN_LIMIT);
679
+ if (knownSeen.length > 0) await database.setMeta(META_SEEN_SECRETS, JSON.stringify(knownSeen));
680
+ }
681
+ // With R known, drop root wraps whose tag doesn't verify, and put the
682
+ // cleaned vault back on the relays in the background (#37).
683
+ if (r !== undefined) {
684
+ const pruned = mergeVaults(vault, vault, { ctx, r });
685
+ if (pruned.ok && pruned.value.rootWraps.length !== vault.rootWraps.length) {
686
+ vault = pruned.value;
687
+ const cleaned = vault;
688
+ const rootKey = r;
689
+ queueMicrotask(() => void publishVault(ctx, cleaned, false, undefined, rootKey).catch(() => undefined));
690
+ }
691
+ }
692
+ await database.setMeta(META_VAULT, serializeVault(vault));
693
+ await deps.hints?.set(hintKey(ctx), JSON.stringify({ mode: vault.mode, sHash: vault.sHash })).catch(() => undefined);
694
+ // R is the recovery phrase: kept in memory only, unless the app opts in (#27).
695
+ await deps.cache.set(ctx.pubkey, ctx.appId, r === undefined || options.cacheRootKey !== true ? { s } : { s, r });
696
+ const next: Unlocked = { kind: "ready", ctx, vault, s, db: database, unlockedWith, ...(r === undefined ? {} : { r }) };
697
+ session = next;
698
+ settingsState = { app: await readDoc(database, META_APP_SETTINGS), shared: await readDoc(database, META_SHARED_SETTINGS) };
699
+ backupState = await readBackupState(ctx, vault, r);
700
+ const migration = lastMigration;
701
+ lastMigration = null;
702
+ return ok({ pubkey: ctx.pubkey, db: database, status: statusOf(next), ...(migration === null ? {} : { migration }) });
703
+ };
704
+
705
+ /** The last migration, reported by the next becomeReady (#51). */
706
+ let lastMigration: MigrationResult | null = null;
707
+ /** An old local database kept because a migration skipped edited rows (#51). */
708
+ let leftBehind: AppDatabase | null = null;
709
+
710
+ /** Moves to a new data secret, copying local rows (SPEC §3.4). */
711
+ const switchDatabase = async (
712
+ from: AppDatabase | undefined,
713
+ to: AppDatabase,
714
+ mode: MigrationMode,
715
+ ): Promise<void> => {
716
+ if (from === undefined || from.sHash === to.sHash) return;
717
+ const result = await migrateRows(from, to, mode);
718
+ lastMigration = result;
719
+ // Keep edits that weren't carried over until the app lets the user decide.
720
+ if (mode.kind === "missingOnly" && result.skippedChanged > 0) leftBehind = from;
721
+ else await from.deleteLocal();
722
+ };
723
+
724
+ /**
725
+ * How to copy local rows into the vault's database. Into a strict database
726
+ * from one any decrypting app could write to, only missing rows (#51).
727
+ */
728
+ const migrationModeFor = (vault: Vault, localSHash: string, localMode: Vault["mode"] | undefined): MigrationMode => {
729
+ if (vault.mode === "strict" && localMode !== "strict" && options.migrateChangedRows !== true) return { kind: "missingOnly" };
730
+ const cutoff = migrationCutoff(vault, localSHash);
731
+ // Not in history: copy only rows missing in the current database (never overwrites).
732
+ return cutoff === null ? { kind: "missingOnly" } : { kind: "since", cutoffMs: cutoff * 1000, marginMs: clockMarginMs };
733
+ };
734
+
735
+ const createVault = async (ctx: VaultContext): Promise<Result<ConnectResult>> => {
736
+ if (options.requireStrong === true) {
737
+ session = { kind: "pending", ctx, action: "setupStrong" };
738
+ return ok({ state: "needsUserAction", action: "setupStrong" });
739
+ }
740
+ const s = random(DATA_SECRET_LENGTH);
741
+ let nip44Ct: string;
742
+ try {
743
+ nip44Ct = await nip44SealSecret(deps.signer, ctx.pubkey, s);
744
+ } catch (e) {
745
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
746
+ }
747
+ const vault = createCompatibleVault(ctx, { s, nip44Ct, now: now() });
748
+ if (!vault.ok) return vault;
749
+ progress("creatingVault");
750
+ const published = await publishVault(ctx, vault.value, false, { kind: "none" });
751
+ if (!published.ok) return published;
752
+ // Create race (SPEC §6.2 rule 2): if another device created one first, use
753
+ // theirs. Asking the relays that just answered is enough and doesn't wait on slow ones.
754
+ const check = await fetchVault(ctx, lastAccepted.length > 0 ? lastAccepted : options.relayUrls);
755
+ if (check.kind === "found" && check.vault.sHash !== published.value.sHash && check.vault.created <= published.value.created) {
756
+ // A vault that appeared after this device's publish is as unknown as on first use (#44).
757
+ return unlockFetched(ctx, check.vault, undefined, options.confirmWeakOnNewDevice !== false);
758
+ }
759
+ // Local copy source (#38): (a) made by this device.
760
+ return withReady(becomeReady(ctx, published.value, s, undefined, "created"));
761
+ };
762
+
763
+ const withReady = async (r: Promise<Result<Ready>>): Promise<Result<ConnectResult>> => {
764
+ const x = await r;
765
+ return x.ok ? ok({ state: "ready", ...x.value }) : x;
766
+ };
767
+
768
+ /** Unlock order without a click (SPEC §8.2 step 2), for a vault this device doesn't have yet. */
769
+ const unlockFetched = async (
770
+ ctx: VaultContext,
771
+ vault: Vault,
772
+ local: Pending["local"],
773
+ requireWeakConfirm = false,
774
+ ): Promise<Result<ConnectResult>> => {
775
+ const signerHasWrap =
776
+ caps !== null &&
777
+ ((caps.signerId !== null && signerWrapFor(vault, caps.signerId) !== undefined) ||
778
+ earlierSignerIds(caps).some((id) => signerWrapFor(vault, id) !== undefined));
779
+ if (caps?.ready === true && signerHasWrap) {
780
+ const root = await rootFromSigner(ctx, vault);
781
+ if (root.ok) {
782
+ const s = openRootData(ctx, vault, root.value);
783
+ if (s.ok) {
784
+ const db = await deps.openDatabase(s.value);
785
+ if (local !== undefined) await switchDatabase(local.db, db, migrationModeFor(vault, local.db.sHash, local.copy?.mode));
786
+ // Local copy source (#38): (b) opened with R from the signer.
787
+ return withReady(becomeReady(ctx, vault, s.value, root.value, "signer", db));
788
+ }
789
+ }
790
+ }
791
+ if (local?.r !== undefined) {
792
+ const s = openRootData(ctx, vault, local.r);
793
+ if (s.ok) {
794
+ const db = await deps.openDatabase(s.value);
795
+ await switchDatabase(local.db, db, migrationModeFor(vault, local.db.sHash, local.copy?.mode));
796
+ // Local copy source (#38): (b) opened with the cached R.
797
+ return withReady(becomeReady(ctx, vault, s.value, local.r, "cache", db));
798
+ }
799
+ }
800
+ if (vault.mode === "compatible" && requireWeakConfirm) {
801
+ session = { kind: "pending", ctx, action: "confirmWeak", vault, ...(local === undefined ? {} : { local }) };
802
+ return ok({ state: "needsUserAction", action: "confirmWeak" });
803
+ }
804
+ if (vault.mode === "compatible") {
805
+ const s = await nip44OpenSecret(deps.signer, ctx.pubkey, vault);
806
+ if (s.ok) {
807
+ const db = await deps.openDatabase(s.value);
808
+ if (local !== undefined) await switchDatabase(local.db, db, migrationModeFor(vault, local.db.sHash, local.copy?.mode));
809
+ // Keep a cached R only if it really opens this vault (#33).
810
+ const r = local?.r !== undefined && openRootData(ctx, vault, local.r).ok ? local.r : undefined;
811
+ // Local copy source (#38): (c) opened through NIP-44: a compatible vault, after confirmWeak on a new device.
812
+ return withReady(becomeReady(ctx, vault, s.value, r, "nip44", db));
813
+ }
814
+ if (s.error.type === "signerRefused") return s;
815
+ }
816
+ return askStrongUnlock(ctx, vault, local);
817
+ };
818
+
819
+ /** A strong method is needed: a passkey (from a click) if one matches, else the phrase. */
820
+ const askStrongUnlock = (ctx: VaultContext, vault: Vault, local: Pending["local"]): Result<ConnectResult> => {
821
+ // Choose from the fetched vault's and the local copy's wraps together (#39).
822
+ const wraps = [...vault.rootWraps, ...(local?.copy?.rootWraps ?? [])];
823
+ const signerCanOpen = caps !== null && wraps.some((w) => w.type === "signer");
824
+ const action: UserAction = signerCanOpen
825
+ ? "signerUnlock"
826
+ : passkeys !== undefined && passkeySupported && wraps.some((w) => w.type === "passkey" && w.rpId === passkeys.rpId)
827
+ ? "passkey"
828
+ : "recoveryPhrase";
829
+ session = { kind: "pending", ctx, action, vault, ...(local === undefined ? {} : { local }) };
830
+ return ok({ state: "needsUserAction", action });
831
+ };
832
+
833
+ /** Opens R with one of this domain's passkeys (SPEC §4.3). Call from a click. */
834
+ /**
835
+ * Opens R with one of this domain's passkeys (SPEC §4.3). Call from a click.
836
+ * Wraps from the local copy are tried too, so a fetched vault with missing or
837
+ * corrupted wraps can't lock the device out (#39).
838
+ */
839
+ const rootFromPasskey = async (ctx: VaultContext, vault: Vault, copy?: Vault): Promise<Result<Bytes>> => {
840
+ if (passkeys === undefined) return error("noPasskeys", "Passkeys aren't enabled");
841
+ const candidates = [...passkeyWrapsFor(vault, passkeys.rpId), ...(copy === undefined ? [] : passkeyWrapsFor(copy, passkeys.rpId))];
842
+ if (candidates.length === 0) return error("noPasskeyWrap", "No passkey for this site is registered in the vault");
843
+ let result;
844
+ try {
845
+ result = await passkeys.get({ allowCredIds: [...new Set(candidates.map((w) => w.credId))], prfInput: clientPrfInput(ctx.pubkey, ctx.appId) });
846
+ } catch (e) {
847
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
848
+ }
849
+ if (result.prfOutput === null) return error("passkeyFailed", "The passkey gave no usable result");
850
+ const key = passkeyWrapKey(result.prfOutput, ctx.appId);
851
+ for (const wrap of candidates.filter((w) => w.credId === result.credId)) {
852
+ const opened = openRootWrap(ctx, wrap, key);
853
+ if (opened.ok) return opened;
854
+ }
855
+ return error("passkeyFailed", "The passkey didn't open any wrap of this vault");
856
+ };
857
+
858
+ // ── API ──
859
+
860
+ const connect: Evolustr["connect"] = async () => {
861
+ const result = await connectInner();
862
+ // In the background: a slow relay must not delay opening the app.
863
+ if (result.ok && result.value.state === "ready") {
864
+ const heal = healAfterConnect;
865
+ healAfterConnect = null;
866
+ if (heal !== null && session.kind === "ready") void publishVault(session.ctx, heal).catch(() => undefined);
867
+ else void rebroadcastVault();
868
+ }
869
+ if (result.ok && result.value.state === "ready" && capable !== undefined) {
870
+ await ensureSignerWrap();
871
+ const st = status();
872
+ if (st !== null) return ok({ ...result.value, status: st });
873
+ }
874
+ return result;
875
+ };
876
+
877
+ const connectInner = async (): Promise<Result<ConnectResult>> => {
878
+ let pubkey: string;
879
+ try {
880
+ pubkey = await deps.signer.getPublicKey();
881
+ } catch (e) {
882
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
883
+ }
884
+ const ctx: VaultContext = { pubkey, appId: options.appId };
885
+ progress("lookingUpVault");
886
+ passkeySupported = passkeys === undefined ? false : await passkeys.supported().catch(() => false);
887
+ await refreshCaps();
888
+ const cached = await deps.cache.get(pubkey, options.appId);
889
+ const fetched = await fetchVault(ctx);
890
+
891
+ let local: Pending["local"];
892
+ if (cached !== null) {
893
+ const db = await deps.openDatabase(cached.s);
894
+ const copyText = await db.getMeta(META_VAULT);
895
+ const copy = copyText === null ? undefined : parseVault(copyText);
896
+ knownSeen = await readSeen(db);
897
+ local = {
898
+ db,
899
+ s: cached.s,
900
+ ...(cached.r === undefined ? {} : { r: cached.r }),
901
+ ...(copy?.ok ? { copy: copy.value } : {}),
902
+ };
903
+ }
904
+
905
+ // Logged out before, but this device knew the database was strict: a weak
906
+ // vault now is a swap, not a first use (#44).
907
+ if (local === undefined && fetched.kind === "found" && fetched.vault.mode === "compatible") {
908
+ const hint = await readHint(ctx);
909
+ if (hint?.mode === "strict") {
910
+ session = { kind: "pending", ctx, action: "choose", vault: fetched.vault };
911
+ // The phrase can't open the fetched (forged) vault, so don't offer it (#54).
912
+ return ok({ state: "vaultChanged", reason: "replaced", options: ["startNew"], advice: "useAnotherDevice" });
913
+ }
914
+ }
915
+
916
+ const decision = decideVault(
917
+ ctx,
918
+ fetched,
919
+ local === undefined
920
+ ? null
921
+ : {
922
+ sHash: local.db.sHash,
923
+ seen: knownSeen,
924
+ ...(local.r === undefined ? {} : { r: local.r }),
925
+ ...(local.copy === undefined ? {} : { copy: local.copy }),
926
+ },
927
+ );
928
+
929
+ switch (decision.type) {
930
+ case "create":
931
+ return createVault(ctx);
932
+ case "firstUse":
933
+ return unlockFetched(ctx, decision.vault, undefined, decision.warnWeak && options.confirmWeakOnNewDevice !== false);
934
+ case "same": {
935
+ // (d) merged from the checked copy: wraps from the copy are never dropped (#37, #38).
936
+ const fetchedVault = fetched.kind === "found" ? fetched.vault : local!.copy!;
937
+ const copy = local!.copy ?? fetchedVault;
938
+ const merged = mergeVaults(copy, fetchedVault, { ctx, r: local!.r });
939
+ // R verified the fetched vault: its header and data wraps win, e.g. after
940
+ // a downgrade elsewhere; the copy's wraps are still kept (#54).
941
+ const verified = local!.r !== undefined && fetched.kind === "found" && openRootData(ctx, fetchedVault, local!.r).ok;
942
+ const vault = !merged.ok ? copy : verified ? { ...fetchedVault, rootWraps: merged.value.rootWraps } : merged.value;
943
+ // Self-heal (SPEC §6.2 rule 4): the relays lost or altered wraps this device still has.
944
+ const onRelays = new Set(fetchedVault.rootWraps.map((w) => JSON.stringify(w)));
945
+ if (vault.rootWraps.some((w) => !onRelays.has(JSON.stringify(w)))) healAfterConnect = vault;
946
+ // The fetched event passed the checks unchanged: it may be re-sent to relays that miss it.
947
+ else if (fetched.kind === "found") lastFetched = lastSeenEvent;
948
+ return withReady(becomeReady(ctx, vault, local!.s, local!.r, "cache", local!.db));
949
+ }
950
+ case "follow": {
951
+ const db = await deps.openDatabase(decision.s);
952
+ await switchDatabase(local?.db, db, migrationModeFor(decision.vault, local!.db.sHash, local!.copy?.mode));
953
+ // Local copy source (#38): (b) opened with R (decideVault "follow").
954
+ return withReady(becomeReady(ctx, decision.vault, decision.s, local!.r, "cache", db));
955
+ }
956
+ case "needsStrongUnlock":
957
+ return askStrongUnlock(ctx, decision.vault, local);
958
+ case "choose":
959
+ session = {
960
+ kind: "pending",
961
+ ctx,
962
+ action: "choose",
963
+ ...(decision.vault === undefined ? {} : { vault: decision.vault }),
964
+ ...(local === undefined ? {} : { local }),
965
+ };
966
+ return ok({ state: "vaultChanged", reason: decision.reason, options: decision.options });
967
+ }
968
+ };
969
+
970
+ /** Opens the pending vault with a recovery phrase, migrating local rows. */
971
+ const openWithPhrase = async (p: Pending, words: string): Promise<Result<Ready>> => {
972
+ const r = phraseToRootKey(words);
973
+ if (!r.ok) return r;
974
+ return openWithRoot(p, r.value, "recovery");
975
+ };
976
+
977
+ /** Opens the pending vault with R, migrating local rows. */
978
+ const openWithRoot = async (p: Pending, root: Bytes, how: UnlockMethod): Promise<Result<Ready>> => {
979
+ const r = { value: root };
980
+ let vault = p.vault;
981
+ if (vault === undefined) {
982
+ const f = await fetchVault(p.ctx);
983
+ if (f.kind !== "found") return error("noVault", "No vault found to restore");
984
+ vault = f.vault;
985
+ }
986
+ const s = openRootData(p.ctx, vault, r.value);
987
+ if (!s.ok) {
988
+ // R is real (it opens this device's copy), so the fetched vault is foreign (#39).
989
+ if (p.local?.copy !== undefined && openRootData(p.ctx, p.local.copy, r.value).ok) {
990
+ // The old R signed the vault: the user replaced the root key elsewhere (#52 phase C).
991
+ if (verifyRootRotation(p.ctx, vault, r.value)) {
992
+ return error("rootRotated", "The root key was replaced on another device: unlock with the new passkey, signer or recovery phrase");
993
+ }
994
+ session = { kind: "pending", ctx: p.ctx, action: "choose", vault, local: { ...p.local, r: r.value } };
995
+ return error("vaultReplaced", "The vault on the relays isn't yours; restore this device's copy with resolveVaultChange(\"republishCopy\")");
996
+ }
997
+ return error("wrongPhrase", "This recovery phrase doesn't open this app's data");
998
+ }
999
+ const db = await deps.openDatabase(s.value);
1000
+ if (p.local !== undefined) await switchDatabase(p.local.db, db, migrationModeFor(vault, p.local.db.sHash, p.local.copy?.mode));
1001
+ // Local copy source (#38): (b) opened with R from a passkey, signer or the phrase.
1002
+ return becomeReady(p.ctx, vault, s.value, r.value, how, db);
1003
+ };
1004
+
1005
+ const unlock: Evolustr["unlock"] = async (input) => {
1006
+ const result = await unlockInner(input);
1007
+ if (result.ok && capable !== undefined) {
1008
+ await ensureSignerWrap();
1009
+ const st = status();
1010
+ if (st !== null) return ok({ ...result.value, status: st });
1011
+ }
1012
+ return result;
1013
+ };
1014
+
1015
+ const unlockInner = async (input: UnlockInput | undefined): Promise<Result<Ready>> => {
1016
+ if (session.kind !== "pending") return error("nothingToUnlock", "connect() didn't ask for a user action");
1017
+ const p = session;
1018
+ if (input?.recoveryPhrase !== undefined && p.action !== "setupStrong") return openWithPhrase(p, input.recoveryPhrase);
1019
+ if (p.action === "recoveryPhrase") return error("phraseRequired", "Pass the recovery phrase");
1020
+ if (p.action === "passkey") {
1021
+ if (p.vault === undefined) return error("noVault", "No vault to unlock");
1022
+ const root = await rootFromPasskey(p.ctx, p.vault, p.local?.copy);
1023
+ return root.ok ? openWithRoot(p, root.value, "passkey") : root;
1024
+ }
1025
+ if (p.action === "signerUnlock") {
1026
+ if (p.vault === undefined) return error("noVault", "No vault to unlock");
1027
+ const root = await rootFromSigner(p.ctx, p.vault, p.local?.copy);
1028
+ return root.ok ? openWithRoot(p, root.value, "signer") : root;
1029
+ }
1030
+ if (p.action === "setupStrong") return setupStrong(p.ctx, input?.acceptDeviceLoss === true);
1031
+ if (p.action === "confirmWeak") {
1032
+ if (p.vault === undefined) return error("noVault", "No vault to open");
1033
+ const r = await unlockFetched(p.ctx, p.vault, p.local, false);
1034
+ if (!r.ok) return r;
1035
+ if (r.value.state !== "ready") return error("needsUserAction", `Still needs: ${r.value.state === "needsUserAction" ? r.value.action : r.value.state}`);
1036
+ const { state: _state, ...ready } = r.value;
1037
+ return ok(ready);
1038
+ }
1039
+ return error("unsupported", `Unlocking with "${p.action}" isn't available in this build`);
1040
+ };
1041
+
1042
+ const resolveVaultChange: Evolustr["resolveVaultChange"] = async (choice, input) => {
1043
+ if (session.kind !== "pending" || session.action !== "choose") {
1044
+ return error("nothingToResolve", "connect() didn't report a vault change");
1045
+ }
1046
+ const p = session;
1047
+ switch (choice) {
1048
+ case "republishCopy": {
1049
+ if (p.local?.copy === undefined) return error("noCopy", "This device has no copy of the vault");
1050
+ // With R known, wraps with a bad tag are dropped (#50).
1051
+ const published = await publishVault(p.ctx, p.local.copy, false, undefined, p.local.r);
1052
+ if (!published.ok) return published;
1053
+ // Local copy source (#38): (a) this device's own copy, republished.
1054
+ return becomeReady(p.ctx, published.value, p.local.s, p.local.r, "cache", p.local.db);
1055
+ }
1056
+ case "followRelay": {
1057
+ if (p.vault === undefined) return error("noVault", "No vault to follow");
1058
+ // The user chose this. Use R when it opens the vault; otherwise NIP-44
1059
+ // (only a compatible vault has a nip44 wrap; a strict one never falls back).
1060
+ const viaRoot = p.local?.r === undefined ? null : openRootData(p.ctx, p.vault, p.local.r);
1061
+ // A database protected by a root key never follows a vault only NIP-44 opens (#38).
1062
+ if (!viaRoot?.ok && p.local?.copy !== undefined && hasRootKey(p.local.copy)) {
1063
+ return error("unsafeFollow", "This device's data is protected by a root key; restore with a strong method instead");
1064
+ }
1065
+ 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");
1066
+ if (!s.ok) return s;
1067
+ const db = await deps.openDatabase(s.value);
1068
+ // Not verifiable: copy only rows missing there, never overwrite, and keep
1069
+ // the previous local database (it isn't deleted).
1070
+ if (p.local !== undefined && p.local.db.sHash !== db.sHash) {
1071
+ lastMigration = await migrateRows(p.local.db, db, { kind: "missingOnly" });
1072
+ }
1073
+ // Local copy source (#38): (b) opened with R, or (c) through NIP-44 after the user chose to follow.
1074
+ return becomeReady(p.ctx, p.vault, s.value, viaRoot?.ok ? p.local?.r : undefined, viaRoot?.ok ? "cache" : "nip44", db);
1075
+ }
1076
+ case "restorePhrase":
1077
+ if (input?.recoveryPhrase === undefined) return error("phraseRequired", "Pass the recovery phrase");
1078
+ return openWithPhrase(p, input.recoveryPhrase);
1079
+ case "startNew": {
1080
+ session = { kind: "none" };
1081
+ const created = await createVault(p.ctx);
1082
+ if (!created.ok) return created;
1083
+ return created.value.state === "ready"
1084
+ ? ok({ pubkey: created.value.pubkey, db: created.value.db, status: created.value.status })
1085
+ : error("needsUserAction", "Creating a new database needs a user action first");
1086
+ }
1087
+ }
1088
+ };
1089
+
1090
+ const requireReady = (): Result<Unlocked> =>
1091
+ session.kind === "ready" ? ok(session) : error("notReady", "Connect first");
1092
+
1093
+ const unlockRoot: Evolustr["unlockRoot"] = async (input) => {
1094
+ const s = requireReady();
1095
+ if (!s.ok) return s;
1096
+ const r = input?.recoveryPhrase === undefined ? await rootFromPasskey(s.value.ctx, s.value.vault) : phraseToRootKey(input.recoveryPhrase);
1097
+ if (!r.ok) return r;
1098
+ const check = openRootData(s.value.ctx, s.value.vault, r.value);
1099
+ if (!check.ok) return error("wrongPhrase", "This recovery phrase doesn't belong to this app's data");
1100
+ if (options.cacheRootKey === true) await deps.cache.set(s.value.ctx.pubkey, s.value.ctx.appId, { s: s.value.s, r: r.value });
1101
+ // Now that R is known, drop root wraps with a bad tag and publish the result (#37).
1102
+ const pruned = mergeVaults(s.value.vault, s.value.vault, { ctx: s.value.ctx, r: r.value });
1103
+ let vault = s.value.vault;
1104
+ if (pruned.ok && pruned.value.rootWraps.length !== vault.rootWraps.length) {
1105
+ const published = await publishVault(s.value.ctx, pruned.value, false, undefined, r.value);
1106
+ vault = published.ok ? published.value : pruned.value;
1107
+ await s.value.db.setMeta(META_VAULT, serializeVault(vault));
1108
+ }
1109
+ const next: Unlocked = { ...s.value, vault, r: r.value };
1110
+ session = next;
1111
+ backupState = await readBackupState(next.ctx, vault, r.value);
1112
+ return ok(statusOf(next));
1113
+ };
1114
+
1115
+ const showRecoveryPhrase: Evolustr["showRecoveryPhrase"] = async () => {
1116
+ const s = requireReady();
1117
+ if (!s.ok) return s;
1118
+ if (s.value.r !== undefined) return ok(rootKeyToPhrase(s.value.r));
1119
+ if (hasRootKey(s.value.vault)) {
1120
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
1121
+ }
1122
+ const r = random(ROOT_KEY_LENGTH);
1123
+ const withRoot = addRootKey(s.value.ctx, s.value.vault, r, s.value.s);
1124
+ if (!withRoot.ok) return withRoot;
1125
+ const published = await publishVault(s.value.ctx, withRoot.value);
1126
+ if (!published.ok) return published;
1127
+ // Local copy source (#38): (a) made by this device.
1128
+ const ready = await becomeReady(s.value.ctx, published.value, s.value.s, r, s.value.unlockedWith, s.value.db);
1129
+ return ready.ok ? ok(rootKeyToPhrase(r)) : ready;
1130
+ };
1131
+
1132
+ const confirmRecoveryPhrase: Evolustr["confirmRecoveryPhrase"] = async (words) => {
1133
+ const s = requireReady();
1134
+ if (!s.ok) return s;
1135
+ const r = phraseToRootKey(words);
1136
+ if (!r.ok || s.value.r === undefined || rootKeyToPhrase(r.value) !== rootKeyToPhrase(s.value.r)) {
1137
+ return error("wrongPhrase", "The words don't match the recovery phrase");
1138
+ }
1139
+ await localSet(backupKey("phrase", s.value.ctx), phraseMarker(s.value.r));
1140
+ backupState = { ...backupState, phraseConfirmed: true };
1141
+ return ok(undefined);
1142
+ };
1143
+
1144
+ const restoreFromPhrase: Evolustr["restoreFromPhrase"] = async (words) => {
1145
+ if (session.kind === "pending") return openWithPhrase(session, words);
1146
+ let pubkey: string;
1147
+ try {
1148
+ pubkey = await deps.signer.getPublicKey();
1149
+ } catch (e) {
1150
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
1151
+ }
1152
+ return openWithPhrase({ kind: "pending", ctx: { pubkey, appId: options.appId }, action: "recoveryPhrase" }, words);
1153
+ };
1154
+
1155
+ const downgrade: Evolustr["downgrade"] = async () => {
1156
+ const s = requireReady();
1157
+ if (!s.ok) return s;
1158
+ if (s.value.r === undefined) return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
1159
+ let ct: string;
1160
+ try {
1161
+ ct = await nip44SealSecret(deps.signer, s.value.ctx.pubkey, s.value.s);
1162
+ } catch (e) {
1163
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
1164
+ }
1165
+ const next = downgradeVault(s.value.ctx, s.value.vault, { r: s.value.r, s: s.value.s, nip44Ct: ct });
1166
+ if (!next.ok) return next;
1167
+ const published = await publishVault(s.value.ctx, next.value, true);
1168
+ if (!published.ok && published.error.type !== "partialPublish") return published;
1169
+ // Local copy source (#38): (a) made by this device (downgrade).
1170
+ 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);
1171
+ if (!ready.ok) return ready;
1172
+ return published.ok ? ok(ready.value.status) : published;
1173
+ };
1174
+
1175
+ const createPasskey = async (ctx: VaultContext, vault: Vault | undefined): Promise<Result<CreatedPasskey>> => {
1176
+ if (passkeys === undefined) return error("noPasskeys", "Passkeys aren't enabled");
1177
+ try {
1178
+ const created = await passkeys.create({
1179
+ userId: sha256(utf8(ctx.pubkey)),
1180
+ userName: ctx.pubkey.slice(0, 16),
1181
+ excludeCredIds: vault === undefined ? [] : passkeyWrapsFor(vault, passkeys.rpId).map((w) => w.credId),
1182
+ prfInput: clientPrfInput(ctx.pubkey, ctx.appId),
1183
+ });
1184
+ return created.prfEnabled ? ok(created) : error("prfUnsupported", "This authenticator can't be used: no PRF support");
1185
+ } catch (e) {
1186
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
1187
+ }
1188
+ };
1189
+
1190
+ /** Records on this device whether a method recovers on its own (#53). */
1191
+ const rememberMethod = async (ctx: VaultContext, known: KnownMethod) => {
1192
+ const records = await readMethodRecords(ctx);
1193
+ await writeMethodRecords(ctx, [...records.filter((m) => m.id !== known.id), known]);
1194
+ };
1195
+
1196
+ /** Adds a passkey wrap of R once the PRF output is known. */
1197
+ const completeEnrollment = async (s: Unlocked, created: CreatedPasskey, prfOutput: Bytes): Promise<Result<Status>> => {
1198
+ if (passkeys === undefined) return error("noPasskeys", "Passkeys aren't enabled");
1199
+ let vault = s.vault;
1200
+ let r = s.r;
1201
+ if (r === undefined) {
1202
+ if (hasRootKey(vault)) return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
1203
+ r = random(ROOT_KEY_LENGTH);
1204
+ const withRoot = addRootKey(s.ctx, vault, r, s.s);
1205
+ if (!withRoot.ok) return withRoot;
1206
+ vault = withRoot.value;
1207
+ }
1208
+ const wrap = passkeyRootWrap(s.ctx, passkeyWrapKey(prfOutput, s.ctx.appId), passkeys.rpId, created.credId, r);
1209
+ const added = addRootWrap(vault, wrap);
1210
+ if (!added.ok) return added;
1211
+ const published = await publishVault(s.ctx, added.value);
1212
+ if (!published.ok) return published;
1213
+ await rememberMethod(s.ctx, { id: `passkey:${created.credId}`, method: { kind: "passkey", synced: created.synced } });
1214
+ // Local copy source (#38): (a) made by this device (passkey added).
1215
+ const ready = await becomeReady(s.ctx, published.value, s.s, r, s.unlockedWith, s.db);
1216
+ return ready.ok ? ok(ready.value.status) : ready;
1217
+ };
1218
+
1219
+ const enrollPasskey: Evolustr["enrollPasskey"] = async () => {
1220
+ const s = requireReady();
1221
+ if (!s.ok) return s;
1222
+ if (s.value.r === undefined && hasRootKey(s.value.vault)) {
1223
+ return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
1224
+ }
1225
+ const created = await createPasskey(s.value.ctx, s.value.vault);
1226
+ if (!created.ok) return created;
1227
+ if (created.value.prfOutput === null) {
1228
+ pendingPasskey = created.value;
1229
+ return ok({ done: false });
1230
+ }
1231
+ const done = await completeEnrollment(s.value, created.value, created.value.prfOutput);
1232
+ return done.ok ? ok({ done: true }) : done;
1233
+ };
1234
+
1235
+ const finishPasskeySetup: Evolustr["finishPasskeySetup"] = async () => {
1236
+ const s = requireReady();
1237
+ if (!s.ok) return s;
1238
+ const created = pendingPasskey;
1239
+ if (created === null || passkeys === undefined) return error("nothingToFinish", "No passkey setup is waiting");
1240
+ let result;
1241
+ try {
1242
+ result = await passkeys.get({ allowCredIds: [created.credId], prfInput: clientPrfInput(s.value.ctx.pubkey, s.value.ctx.appId) });
1243
+ } catch (e) {
1244
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
1245
+ }
1246
+ if (result.prfOutput === null) return error("prfUnsupported", "The passkey gave no PRF output");
1247
+ pendingPasskey = null;
1248
+ return completeEnrollment(s.value, created, result.prfOutput);
1249
+ };
1250
+
1251
+ const makeStrict: Evolustr["makeStrict"] = async (opts) => {
1252
+ const s = requireReady();
1253
+ if (!s.ok) return s;
1254
+ if (s.value.r === undefined) {
1255
+ if (opts?.replaceRoot === true && s.value.vault.mode === "compatible") return makeStrictNewRoot(s.value, opts.acceptDeviceLoss === true);
1256
+ return error("rootLocked", "Unlock the root key on this device first, or call makeStrict({ replaceRoot: true }) to start with a new recovery phrase");
1257
+ }
1258
+ if (opts?.replaceRoot === true) return error("rootKnown", "The root key is unlocked here; call makeStrict() without replaceRoot");
1259
+ // Read fresh, checked against the vault with R (#53).
1260
+ backupState = await readBackupState(s.value.ctx, s.value.vault, s.value.r);
1261
+ const need = backupRequirement(backupState.methods.map((m) => m.method), backupState.phraseConfirmed);
1262
+ if (need === "required" && opts?.acceptDeviceLoss !== true) {
1263
+ return error("backupRequired", "Save the recovery phrase or add a second passkey first, or accept losing the data with this device");
1264
+ }
1265
+ const newS = random(DATA_SECRET_LENGTH);
1266
+ const next = makeStrictVault(s.value.ctx, s.value.vault, { r: s.value.r, newS, now: now() });
1267
+ if (!next.ok) return next;
1268
+ return rotateTo(s.value, next.value, newS, s.value.r);
1269
+ };
1270
+
1271
+ const rotateRoot: Evolustr["rotateRoot"] = async (opts) => {
1272
+ const ready = requireReady();
1273
+ if (!ready.ok) return ready;
1274
+ let s = ready.value;
1275
+ if (s.r === undefined) {
1276
+ // The signer can open the vault, also through its previous key.
1277
+ const viaSigner = capable === undefined ? null : await rootFromSigner(s.ctx, s.vault);
1278
+ if (viaSigner === null || !viaSigner.ok) return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
1279
+ if (!openRootData(s.ctx, s.vault, viaSigner.value).ok) return error("rootLocked", "Unlock the root key on this device first (unlockRoot)");
1280
+ s = { ...s, r: viaSigner.value };
1281
+ }
1282
+ const oldR = s.r!;
1283
+ const newR = random(ROOT_KEY_LENGTH);
1284
+ const strong = await newStrongWrap(s.ctx, newR, opts?.acceptDeviceLoss === true);
1285
+ if (!strong.ok) return strong;
1286
+ const newS = random(DATA_SECRET_LENGTH);
1287
+ let nip44Ct: string | undefined;
1288
+ if (s.vault.mode === "compatible") {
1289
+ try {
1290
+ nip44Ct = await nip44SealSecret(deps.signer, s.ctx.pubkey, newS);
1291
+ } catch (e) {
1292
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
1293
+ }
1294
+ }
1295
+ const next = rotateRootVault(s.ctx, s.vault, {
1296
+ r: oldR,
1297
+ newR,
1298
+ newS,
1299
+ now: now(),
1300
+ rootWraps: [strong.value.wrap],
1301
+ ...(nip44Ct === undefined ? {} : { nip44Ct }),
1302
+ });
1303
+ if (!next.ok) return next;
1304
+ // Backup facts start over: one method, phrase not confirmed (#53).
1305
+ await writeMethodRecords(s.ctx, [strong.value.known]);
1306
+ await localSet(backupKey("phrase", s.ctx), "");
1307
+ return rotateTo(s, next.value, newS, newR);
1308
+ };
1309
+
1310
+ /** Strict with a new root key and a new strong method (#49). */
1311
+ const makeStrictNewRoot = async (s: Unlocked, acceptDeviceLoss: boolean): Promise<Result<Status>> => {
1312
+ const newR = random(ROOT_KEY_LENGTH);
1313
+ const strong = await newStrongWrap(s.ctx, newR, acceptDeviceLoss);
1314
+ if (!strong.ok) return strong;
1315
+ const newS = random(DATA_SECRET_LENGTH);
1316
+ const next = makeStrictWithNewRoot(s.ctx, s.vault, { newR, newS, now: now(), rootWraps: [strong.value.wrap] });
1317
+ if (!next.ok) return next;
1318
+ // Backup facts start over: one method, phrase not confirmed (#53).
1319
+ await writeMethodRecords(s.ctx, [strong.value.known]);
1320
+ await localSet(backupKey("phrase", s.ctx), "");
1321
+ return rotateTo(s, next.value, newS, newR);
1322
+ };
1323
+
1324
+ /** Moves this device to a new strict vault and data secret S' (SPEC §3.4). */
1325
+ const rotateTo = async (s: Unlocked, next: Vault, newS: Bytes, r: Bytes): Promise<Result<Status>> => {
1326
+ const db = await deps.openDatabase(newS);
1327
+ await migrateRows(s.db, db, { kind: "all" });
1328
+ for (const key of [META_APP_SETTINGS, META_SHARED_SETTINGS, META_SEEN_SECRETS]) {
1329
+ const v = await s.db.getMeta(key);
1330
+ if (v !== null) await db.setMeta(key, v);
1331
+ }
1332
+ const published = await publishVault(s.ctx, next, true, undefined, r);
1333
+ if (!published.ok && published.error.type !== "partialPublish") {
1334
+ await db.deleteLocal();
1335
+ return published;
1336
+ }
1337
+ if (!published.ok) {
1338
+ // Some relays have the strict vault: continue on S', but keep the old
1339
+ // local database until every relay agrees (#32). connect() re-sends it.
1340
+ // Local copy source (#38): (a) made by this device (makeStrict).
1341
+ const ready = await becomeReady(s.ctx, next, newS, r, s.unlockedWith, db);
1342
+ return ready.ok ? published : ready;
1343
+ }
1344
+ await s.db.deleteLocal();
1345
+ // Local copy source (#38): (a) made by this device (makeStrict).
1346
+ const ready = await becomeReady(s.ctx, published.value, newS, r, s.unlockedWith, db);
1347
+ return ready.ok ? ok(ready.value.status) : ready;
1348
+ };
1349
+
1350
+ /**
1351
+ * A new strong method sealing R: the capable signer, else a new passkey (from
1352
+ * a click), with the backup check for a single method (SPEC §3.2 rule 3a, #42).
1353
+ */
1354
+ const newStrongWrap = async (
1355
+ ctx: VaultContext,
1356
+ r: Bytes,
1357
+ acceptDeviceLoss: boolean,
1358
+ ): Promise<Result<{ readonly wrap: RootWrap; readonly known: KnownMethod; readonly how: UnlockMethod }>> => {
1359
+ if (capable !== undefined) {
1360
+ let key: Bytes;
1361
+ try {
1362
+ key = await capable.getWrapKey();
1363
+ } catch (e) {
1364
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
1365
+ }
1366
+ const c = await refreshCaps();
1367
+ if (c?.signerId != null) {
1368
+ const method: StrongMethod = { kind: "signer", recoverable: c.recoverable === true };
1369
+ if (backupRequirement([method], false) === "required" && !acceptDeviceLoss) {
1370
+ 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");
1371
+ }
1372
+ return ok({ wrap: signerRootWrap(ctx, key, c.signerId, r), known: { id: `signer:${c.signerId}`, method }, how: "signer" });
1373
+ }
1374
+ }
1375
+ const created = await createPasskey(ctx, undefined);
1376
+ if (!created.ok) return created;
1377
+ let prfOutput = created.value.prfOutput;
1378
+ if (prfOutput === null && passkeys !== undefined) {
1379
+ try {
1380
+ prfOutput = (await passkeys.get({ allowCredIds: [created.value.credId], prfInput: clientPrfInput(ctx.pubkey, ctx.appId) })).prfOutput;
1381
+ } catch (e) {
1382
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
1383
+ }
1384
+ }
1385
+ if (prfOutput === null || passkeys === undefined) return error("prfUnsupported", "The passkey gave no PRF output");
1386
+ const method: StrongMethod = { kind: "passkey", synced: created.value.synced };
1387
+ if (backupRequirement([method], false) === "required" && !acceptDeviceLoss) {
1388
+ return error("backupRequired", "This passkey isn't synced: accept losing the data with this device, or use a synced passkey");
1389
+ }
1390
+ const wrap = passkeyRootWrap(ctx, passkeyWrapKey(prfOutput, ctx.appId), passkeys.rpId, created.value.credId, r);
1391
+ return ok({ wrap, known: { id: `passkey:${created.value.credId}`, method }, how: "passkey" });
1392
+ };
1393
+
1394
+ /** First vault created strict for `requireStrong` (SPEC §8.2 step 4). */
1395
+ const setupStrong = async (ctx: VaultContext, acceptDeviceLoss: boolean): Promise<Result<Ready>> => {
1396
+ const r = random(ROOT_KEY_LENGTH);
1397
+ const strong = await newStrongWrap(ctx, r, acceptDeviceLoss);
1398
+ if (!strong.ok) return strong;
1399
+ const s = random(DATA_SECRET_LENGTH);
1400
+ const vault = createStrictVault(ctx, { s, r, now: now(), rootWraps: [strong.value.wrap] });
1401
+ if (!vault.ok) return vault;
1402
+ const published = await publishVault(ctx, vault.value);
1403
+ if (!published.ok) return published;
1404
+ const db = await deps.openDatabase(s);
1405
+ await rememberMethod(ctx, strong.value.known);
1406
+ // Local copy source (#38): (a) made by this device (requireStrong).
1407
+ return becomeReady(ctx, published.value, s, r, strong.value.how, db);
1408
+ };
1409
+
1410
+ const exportEvoluMnemonic: Evolustr["exportEvoluMnemonic"] = () => {
1411
+ const s = requireReady();
1412
+ return s.ok ? ok(dataSecretToEvoluMnemonic(s.value.s)) : s;
1413
+ };
1414
+
1415
+ const status: Evolustr["status"] = () => (session.kind === "ready" ? statusOf(session) : null);
1416
+
1417
+ const settings: Evolustr["settings"] = {
1418
+ get: (key) => resolveSetting(key, settingsState.app, settingsState.shared, settingsDefaults),
1419
+ refresh: async () => {
1420
+ const s = requireReady();
1421
+ if (!s.ok) return s;
1422
+ const fetched = await fetchSharedSettings(settingsIo, s.value.ctx.pubkey);
1423
+ if (!fetched.ok) return fetched;
1424
+ const shared = mergeSettings(settingsState.shared, fetched.value);
1425
+ await s.value.db.setMeta(META_SHARED_SETTINGS, JSON.stringify(shared));
1426
+ settingsState = { ...settingsState, shared };
1427
+ return ok(undefined);
1428
+ },
1429
+ setShared: async (key, value) => {
1430
+ const s = requireReady();
1431
+ if (!s.ok) return s;
1432
+ const fetched = await fetchSharedSettings(settingsIo, s.value.ctx.pubkey, true); // a write: every relay (#62)
1433
+ if (!fetched.ok) return fetched;
1434
+ const at = Math.max(now(), lastEventAt + 1);
1435
+ const next = setSetting(mergeSettings(settingsState.shared, fetched.value), key, value, at);
1436
+ if (!next.ok) return next;
1437
+ const published = await publishSharedSettings(settingsIo, s.value.ctx.pubkey, next.value, at);
1438
+ if (!published.ok) return published;
1439
+ lastEventAt = at;
1440
+ await s.value.db.setMeta(META_SHARED_SETTINGS, JSON.stringify(next.value));
1441
+ settingsState = { ...settingsState, shared: next.value };
1442
+ return ok(undefined);
1443
+ },
1444
+ setApp: async (key, value) => {
1445
+ const s = requireReady();
1446
+ if (!s.ok) return s;
1447
+ const next = setSetting(settingsState.app, key, value, now());
1448
+ if (!next.ok) return next;
1449
+ await s.value.db.setMeta(META_APP_SETTINGS, JSON.stringify(next.value));
1450
+ settingsState = { ...settingsState, app: next.value };
1451
+ return ok(undefined);
1452
+ },
1453
+ };
1454
+
1455
+ const logout: Evolustr["logout"] = async (opts) => {
1456
+ const s = session;
1457
+ session = { kind: "none" };
1458
+ if (s.kind === "none") return;
1459
+ await deps.cache.remove(s.ctx.pubkey, s.ctx.appId);
1460
+ const db = s.kind === "ready" ? s.db : s.local?.db;
1461
+ if (db === undefined) return;
1462
+ if (opts?.deleteLocalData === true) {
1463
+ await db.deleteLocal();
1464
+ await deps.hints?.remove?.(hintKey(s.ctx)).catch(() => undefined);
1465
+ }
1466
+ else await db.close();
1467
+ };
1468
+
1469
+ const discardOldDatabase: Evolustr["discardOldDatabase"] = async () => {
1470
+ const old = leftBehind;
1471
+ leftBehind = null;
1472
+ if (old !== null) await old.deleteLocal();
1473
+ return ok(undefined);
1474
+ };
1475
+
1476
+ return {
1477
+ discardOldDatabase,
1478
+ connect,
1479
+ unlock,
1480
+ resolveVaultChange,
1481
+ unlockRoot,
1482
+ enrollPasskey,
1483
+ finishPasskeySetup,
1484
+ makeStrict,
1485
+ showRecoveryPhrase,
1486
+ exportEvoluMnemonic,
1487
+ confirmRecoveryPhrase,
1488
+ restoreFromPhrase,
1489
+ downgrade,
1490
+ rotateRoot,
1491
+ status,
1492
+ settings,
1493
+ logout,
1494
+ };
1495
+ };