@evolustr/signer 0.0.0-stage → 0.1.1

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/signer.ts ADDED
@@ -0,0 +1,923 @@
1
+ /**
2
+ * `@evolustr/signer` (SPEC §5): the signer side of Evolustr, embedded by a
3
+ * host signer (iframe signer, browser extension, NIP-46 bunker, Android signer).
4
+ *
5
+ * The host supplies what only it knows: who is calling, how to sign, its nsec
6
+ * (if it holds one), and how to ask the user. Everything else lives here.
7
+ */
8
+ import {
9
+ type Bytes,
10
+ type EvolustrError,
11
+ type Passkeys,
12
+ type Relays,
13
+ type Result,
14
+ type Sealed,
15
+ type UnsignedEvent,
16
+ MASTER_SECRET_LENGTH,
17
+ VAULT_KIND,
18
+ appIdFromOrigin,
19
+ bytesEqual,
20
+ error,
21
+ fromHex,
22
+ hmacSha256,
23
+ signerWrapAuthKey,
24
+ signerMId,
25
+ signerPreviousKey,
26
+ signerRotateKey,
27
+ toHex,
28
+ fetchReplaceable,
29
+ isProtectedDTag,
30
+ ok,
31
+ open,
32
+ publishReplaceable,
33
+ randomBytes as defaultRandomBytes,
34
+ seal,
35
+ sha256,
36
+ utf8,
37
+ signerAppKey,
38
+ hostSecret,
39
+ isHostSecretLabel,
40
+ signerId as computeSignerId,
41
+ signerPasskeyWrapKey,
42
+ signerPrfInput,
43
+ signerSkWrapKey,
44
+ signerVaultDTag,
45
+ signerWrapAad,
46
+ toBase64Url,
47
+ type NostrEvent,
48
+ type Signer,
49
+ } from "@evolustr/core";
50
+
51
+ // ── Types ───────────────────────────────────────────────────────────────────
52
+
53
+ /** Who is calling, as the host knows it (SPEC §5.2). Never taken from request params. */
54
+ export type Caller =
55
+ | { readonly identity: "verified"; readonly origin: string }
56
+ | { readonly identity: "verified"; readonly androidPackage: string }
57
+ | { readonly identity: "connection"; readonly clientPubkey: string };
58
+
59
+ export type SignerWrap =
60
+ | ({ readonly type: "sk"; readonly tag?: string } & Sealed)
61
+ | ({
62
+ readonly type: "passkey";
63
+ readonly rpId: string;
64
+ readonly credId: string;
65
+ /** The passkey was synced (BS flag) when enrolled (#42). */
66
+ readonly synced?: boolean;
67
+ /**
68
+ * HMAC under a key derived from M over the wrap's fields (#54). Wraps from
69
+ * older versions have none.
70
+ */
71
+ readonly tag?: string;
72
+ } & Sealed);
73
+
74
+ export interface SignerVault {
75
+ readonly v: 1;
76
+ readonly wraps: ReadonlyArray<SignerWrap>;
77
+ /**
78
+ * Unix seconds when an `sk` wrap was removed for this M (#52). M didn't
79
+ * change, so anyone who can recover the nsec may still open an older copy.
80
+ */
81
+ readonly skDroppedAt?: number;
82
+ /** Public id of the M this vault holds (#52 phase B); missing in older vaults. */
83
+ readonly mId?: string;
84
+ /** Set after {@link EvolustrSigner.rotateMaster}: the previous M authorises this one. */
85
+ readonly rotatedFrom?: { readonly mId: string; readonly proof: string };
86
+ /** The previous M, sealed with a key from this M, so apps can still open their old wrap. */
87
+ readonly previous?: PreviousMaster;
88
+ /**
89
+ * The Ms before `previous`, newest first (#58): each sealed with a key from
90
+ * the one before it in this chain (`older[0]` with `previous`'s M). Carried
91
+ * over unchanged at each rotation, at most {@link MAX_PREVIOUS_MASTERS} in all.
92
+ */
93
+ readonly older?: ReadonlyArray<PreviousMaster>;
94
+ }
95
+
96
+ /** An earlier M, sealed with `HKDF(M_next, "evolustr/v1/signer-previous")` (#52 phase B, #58). */
97
+ export type PreviousMaster = { readonly mId: string } & Sealed;
98
+
99
+ /** How many earlier Ms a signer vault keeps (`previous` plus `older`, #58). */
100
+ export const MAX_PREVIOUS_MASTERS = 16;
101
+
102
+ export type ConfirmRequest =
103
+ | { readonly kind: "appKey"; readonly appId: string; readonly identity: Caller["identity"] }
104
+ | { readonly kind: "enrollPasskey" }
105
+ | { readonly kind: "rotateMaster" };
106
+
107
+ export interface SignerHost {
108
+ readonly relays: Relays;
109
+ readonly relayUrls: ReadonlyArray<string>;
110
+ /** Stable name of this signer: its origin, extension id, package name or bunker pubkey (SPEC §5.3). */
111
+ readonly signerKey: string;
112
+ /** Signs the signer's own vault event. */
113
+ readonly sign: (event: UnsignedEvent) => Promise<NostrEvent>;
114
+ readonly getPublicKey: () => Promise<string>;
115
+ /** The nsec, for signers that hold it; omit in passthrough mode. */
116
+ readonly getSecretKey?: () => Bytes | null;
117
+ /**
118
+ * False when a third party can recover the nsec (SPEC §5.7). Default true.
119
+ * A function is read on every use, so a host can ask the user and change it
120
+ * at runtime (e.g. OAuth signers, where the user decides).
121
+ */
122
+ readonly allowSkWrap?: boolean | (() => boolean);
123
+ /** Passkeys on the signer's own origin. */
124
+ readonly passkeys?: Passkeys;
125
+ /** Optional device cache for the unlocked M. */
126
+ readonly cache?: {
127
+ readonly get: (pubkey: string) => Promise<Bytes | null>;
128
+ readonly set: (pubkey: string, m: Bytes) => Promise<void>;
129
+ readonly remove: (pubkey: string) => Promise<void>;
130
+ /**
131
+ * The last good signer vault (JSON), kept on the device (#41). Without these,
132
+ * a replaced signer vault on the relays locks out devices that don't have M cached.
133
+ */
134
+ readonly getVault?: (pubkey: string) => Promise<string | null>;
135
+ readonly setVault?: (pubkey: string, json: string) => Promise<void>;
136
+ };
137
+ readonly ui: {
138
+ /** Show a prompt with the verified caller; the host may remember answers. */
139
+ readonly confirm: (request: ConfirmRequest) => Promise<boolean>;
140
+ /** Resolve after the user clicks inside the signer (needed before passkeys and popups). */
141
+ readonly requestGesture: (reason: "unlock" | "enrollPasskey" | "rotateMaster") => Promise<void>;
142
+ };
143
+ readonly knownNsiteGateways?: ReadonlyArray<string>;
144
+ readonly now?: () => number;
145
+ readonly randomBytes?: (length: number) => Bytes;
146
+ readonly timeoutMs?: number;
147
+ /**
148
+ * Enough relays to trust a vault an unlock found (#60): such reads stop
149
+ * waiting once this many answered, so one slow relay doesn't hold them up.
150
+ * "No vault" and reads before a write still wait for every relay (#62).
151
+ * Default: every relay.
152
+ */
153
+ readonly relayQuorum?: number;
154
+ }
155
+
156
+ export interface Capabilities {
157
+ readonly identity: Caller["identity"];
158
+ readonly appId: string;
159
+ readonly signerId: string | null;
160
+ readonly ready: boolean;
161
+ readonly signerPasskey: boolean;
162
+ /** M can be recovered on another device: an `sk` wrap, or a synced signer passkey (#42). */
163
+ readonly recoverable: boolean;
164
+ /** M is protected by the nsec (an `sk` wrap): anyone with the nsec can derive app keys (#43). */
165
+ readonly nsecProtected: boolean;
166
+ /**
167
+ * The nsec could open M now or did before (an `sk` wrap, or one removed for
168
+ * this M): anyone who can recover the nsec may have M and every app key (#52).
169
+ */
170
+ readonly nsecExposed: boolean;
171
+ /**
172
+ * After a key rotation (#52 phase B): this app's signer id under the previous
173
+ * M, so the client can open its old wrap and then replace its root key.
174
+ */
175
+ readonly previousSignerId: string | null;
176
+ /**
177
+ * Every earlier M's signer id for this app, newest first (#58): an app that
178
+ * skipped rotations finds the one its wrap used and asks for that key.
179
+ * `previousSignerIds[0]` is `previousSignerId`.
180
+ */
181
+ readonly previousSignerIds: ReadonlyArray<string>;
182
+ }
183
+
184
+ export const METHODS = ["evolustr_capabilities", "evolustr_get_wrap_key", "evolustr_get_previous_wrap_key", "evolustr_enroll_passkey"] as const;
185
+ export type Method = (typeof METHODS)[number];
186
+
187
+ export interface EvolustrSigner {
188
+ /** For the host's message handler: `caller` comes from the host, never from params. */
189
+ readonly handle: (method: string, params: ReadonlyArray<unknown>, caller: Caller) => Promise<Result<unknown>>;
190
+ /** No prompt, and never creates or publishes anything (#29). */
191
+ readonly capabilities: (caller: Caller) => Promise<Result<Capabilities>>;
192
+ /** 32-byte key for the caller's app vault (SPEC §5.3). */
193
+ readonly getWrapKey: (caller: Caller) => Promise<Result<Bytes>>;
194
+ readonly enrollPasskey: () => Promise<Result<void>>;
195
+ /**
196
+ * The caller's key under an earlier M, after {@link rotateMaster} (#52 phase
197
+ * B): the one whose signer id for this app is `signerId` (#58), else the
198
+ * previous one.
199
+ */
200
+ readonly getPreviousWrapKey: (caller: Caller, signerId?: string) => Promise<Result<Bytes>>;
201
+ /**
202
+ * Replaces M with a new one, from a click in the signer's own UI (#52 phase
203
+ * B). Needs a signer passkey and `allowSkWrap` false. Only the passkey used
204
+ * here wraps the new M: other signer passkeys must be enrolled again.
205
+ */
206
+ readonly rotateMaster: () => Promise<Result<{ readonly droppedWraps: number }>>;
207
+ /**
208
+ * 32-byte secret from M for the host's own use (§5.6), e.g. its synced
209
+ * settings. Host-only: no `handle()` method reaches it, so apps can't ask for
210
+ * it. Unlocks M like `getWrapKey` (passkey if needed), without the app prompt.
211
+ */
212
+ readonly getHostSecret: (label: string) => Promise<Result<Bytes>>;
213
+ /**
214
+ * The same host secret under the previous M, after {@link rotateMaster}, so
215
+ * the host can move its own data across, like apps with getPreviousWrapKey.
216
+ */
217
+ readonly getPreviousHostSecret: (label: string) => Promise<Result<Bytes>>;
218
+ /** The host secret under every earlier M, newest first (#58); empty before any rotation. */
219
+ readonly getPreviousHostSecrets: (label: string) => Promise<Result<ReadonlyArray<Bytes>>>;
220
+ /** For the host's auto-approve list (SPEC §5.5 rule 2). */
221
+ readonly isProtectedEvent: (event: { readonly kind: number; readonly tags: ReadonlyArray<ReadonlyArray<string>> }) => boolean;
222
+ readonly appIdFor: (caller: Caller) => Result<string>;
223
+ readonly lock: () => Promise<void>;
224
+ }
225
+
226
+ // ── Pure helpers ────────────────────────────────────────────────────────────
227
+
228
+ const isRecord = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null;
229
+
230
+ export const parseSignerVault = (json: string): Result<SignerVault, EvolustrError> => {
231
+ let data: unknown;
232
+ try {
233
+ data = JSON.parse(json);
234
+ } catch {
235
+ return error("invalidSignerVault", "Not JSON");
236
+ }
237
+ if (!isRecord(data) || data["v"] !== 1 || !Array.isArray(data["wraps"])) {
238
+ return error("invalidSignerVault", "Unknown format");
239
+ }
240
+ const wraps: SignerWrap[] = [];
241
+ for (const w of data["wraps"]) {
242
+ // A malformed wrap is an error, never skipped: republishing without it
243
+ // would drop someone's way to unlock M (#28).
244
+ if (!isRecord(w) || typeof w["iv"] !== "string" || typeof w["ct"] !== "string") {
245
+ return error("invalidSignerVault", "Malformed wrap");
246
+ }
247
+ if (w["tag"] !== undefined && typeof w["tag"] !== "string") return error("invalidSignerVault", "Malformed wrap");
248
+ const sealed = { iv: w["iv"], ct: w["ct"], ...(typeof w["tag"] === "string" ? { tag: w["tag"] } : {}) };
249
+ if (w["type"] === "sk") wraps.push({ type: "sk", ...sealed });
250
+ else if (w["type"] === "passkey" && typeof w["rpId"] === "string" && typeof w["credId"] === "string") {
251
+ wraps.push({
252
+ type: "passkey",
253
+ rpId: w["rpId"],
254
+ credId: w["credId"],
255
+ ...(typeof w["synced"] === "boolean" ? { synced: w["synced"] } : {}),
256
+ ...sealed,
257
+ });
258
+ } else return error("invalidSignerVault", "Unknown wrap type");
259
+ }
260
+ const dropped = data["skDroppedAt"];
261
+ if (dropped !== undefined && (typeof dropped !== "number" || !Number.isFinite(dropped))) {
262
+ return error("invalidSignerVault", "Malformed skDroppedAt");
263
+ }
264
+ const mId = data["mId"];
265
+ const rotatedFrom = data["rotatedFrom"];
266
+ const previous = data["previous"];
267
+ const older = data["older"];
268
+ if (mId !== undefined && typeof mId !== "string") return error("invalidSignerVault", "Malformed mId");
269
+ if (rotatedFrom !== undefined && !(isRecord(rotatedFrom) && typeof rotatedFrom["mId"] === "string" && typeof rotatedFrom["proof"] === "string")) {
270
+ return error("invalidSignerVault", "Malformed rotatedFrom");
271
+ }
272
+ if (previous !== undefined && !isPreviousMaster(previous)) return error("invalidSignerVault", "Malformed previous");
273
+ if (older !== undefined && !(Array.isArray(older) && older.length < MAX_PREVIOUS_MASTERS && older.every(isPreviousMaster))) {
274
+ return error("invalidSignerVault", "Malformed older");
275
+ }
276
+ const extra = {
277
+ ...(typeof mId === "string" ? { mId } : {}),
278
+ ...(isRecord(rotatedFrom) ? { rotatedFrom: { mId: rotatedFrom["mId"] as string, proof: rotatedFrom["proof"] as string } } : {}),
279
+ ...(isPreviousMaster(previous) ? { previous: previousMaster(previous) } : {}),
280
+ ...(isPreviousMaster(previous) && Array.isArray(older) && older.length > 0 ? { older: older.map(previousMaster) } : {}),
281
+ };
282
+ // A vault that exists but has no wraps isn't "first use" (#28).
283
+ if (wraps.length === 0) return error("invalidSignerVault", "The signer vault has no wraps");
284
+ if (wraps.length > MAX_SIGNER_WRAPS) return error("invalidSignerVault", "Too many wraps");
285
+ return ok({ v: 1, wraps, ...(typeof dropped === "number" ? { skDroppedAt: dropped } : {}), ...extra });
286
+ };
287
+
288
+ const isPreviousMaster = (x: unknown): x is PreviousMaster =>
289
+ isRecord(x) && typeof x["mId"] === "string" && typeof x["iv"] === "string" && typeof x["ct"] === "string";
290
+ const previousMaster = (x: PreviousMaster): PreviousMaster => ({ mId: x.mId, iv: x.iv, ct: x.ct });
291
+
292
+ const wrapId = (w: SignerWrap): string => (w.type === "sk" ? "sk" : w.credId);
293
+
294
+ export const MAX_SIGNER_WRAPS = 32;
295
+ /** Above this many wraps, untagged ones are dropped once M is unlocked (#54). */
296
+ export const UNTAGGED_SIGNER_WRAP_LIMIT = 16;
297
+
298
+ /**
299
+ * Union of two signer vaults by wrap id; `local` wins on the same id (#41).
300
+ * With `dropSk`, `sk` wraps are left out (#52): a relay vault without one is
301
+ * never "healed" back to one by a device that may not use it.
302
+ */
303
+ export const mergeSignerVaults = (
304
+ local: SignerVault,
305
+ fetched: SignerVault,
306
+ opts?: { readonly dropSk?: boolean },
307
+ ): SignerVault => {
308
+ const byId = new Map<string, SignerWrap>();
309
+ const keep = (w: SignerWrap) => opts?.dropSk !== true || w.type !== "sk";
310
+ for (const w of local.wraps) if (keep(w)) byId.set(`${w.type}:${wrapId(w)}`, w);
311
+ for (const w of fetched.wraps) {
312
+ const k = `${w.type}:${wrapId(w)}`;
313
+ if (keep(w) && !byId.has(k) && byId.size < MAX_SIGNER_WRAPS) byId.set(k, w);
314
+ }
315
+ const dropped = Math.max(local.skDroppedAt ?? -1, fetched.skDroppedAt ?? -1);
316
+ const mId = local.mId ?? fetched.mId;
317
+ const rotatedFrom = local.rotatedFrom ?? fetched.rotatedFrom;
318
+ const previous = local.previous ?? fetched.previous;
319
+ // The chain behind that previous M: the longer of the two sides that have it (#58).
320
+ const olderOf = (v: SignerVault) => (v.previous?.mId === previous?.mId ? (v.older ?? []) : []);
321
+ const [a, b] = [olderOf(local), olderOf(fetched)];
322
+ const older = b.length > a.length ? b : a;
323
+ return {
324
+ v: 1,
325
+ wraps: [...byId.values()],
326
+ ...(dropped >= 0 ? { skDroppedAt: dropped } : {}),
327
+ ...(mId === undefined ? {} : { mId }),
328
+ ...(rotatedFrom === undefined ? {} : { rotatedFrom }),
329
+ ...(previous === undefined ? {} : { previous }),
330
+ ...(previous === undefined || older.length === 0 ? {} : { older }),
331
+ };
332
+ };
333
+
334
+ /** Two versions of the signer vault hold different master secrets: never merge them (#52 phase B). */
335
+ export const differentMaster = (a: SignerVault, b: SignerVault): boolean =>
336
+ (a.mId !== undefined && b.mId !== undefined && a.mId !== b.mId) ||
337
+ (b.rotatedFrom !== undefined && a.mId !== b.mId) ||
338
+ (a.rotatedFrom !== undefined && a.mId !== b.mId);
339
+
340
+ /** Proof that the M behind `oldMId` authorised `newMId` (#52 phase B). */
341
+ export const masterRotationProof = (oldM: Bytes, newMId: string): string => toHex(hmacSha256(signerRotateKey(oldM), utf8(newMId)));
342
+
343
+ const rotationValid = (v: SignerVault, oldM: Bytes): boolean => {
344
+ if (v.rotatedFrom === undefined || v.mId === undefined || v.rotatedFrom.mId !== signerMId(oldM)) return false;
345
+ const expected = fromHex(masterRotationProof(oldM, v.mId));
346
+ const given = fromHex(v.rotatedFrom.proof);
347
+ return expected !== null && given !== null && bytesEqual(expected, given);
348
+ };
349
+
350
+ type UntaggedSignerWrap = { readonly type: "sk"; readonly iv: string; readonly ct: string } | {
351
+ readonly type: "passkey";
352
+ readonly rpId: string;
353
+ readonly credId: string;
354
+ readonly synced?: boolean;
355
+ readonly iv: string;
356
+ readonly ct: string;
357
+ };
358
+
359
+ /** HMAC tag of a signer-vault wrap under a key derived from M (#54). Covers `synced` too. */
360
+ export const signerWrapTag = (pubkey: string, signerKey: string, m: Bytes, w: UntaggedSignerWrap): string => {
361
+ const id = w.type === "sk" ? "sk" : w.credId;
362
+ const extra = w.type === "passkey" ? `${w.rpId}|${w.synced === undefined ? "" : String(w.synced)}` : "|";
363
+ const message = `${signerWrapAad(pubkey, signerKey, w.type, id)}|${extra}|${w.iv}|${w.ct}`;
364
+ return toHex(hmacSha256(signerWrapAuthKey(m), utf8(message)));
365
+ };
366
+
367
+ const tagValid = (pubkey: string, signerKey: string, m: Bytes, w: SignerWrap): boolean => {
368
+ if (w.tag === undefined) return false;
369
+ const { tag, ...rest } = w;
370
+ const expected = fromHex(signerWrapTag(pubkey, signerKey, m, rest as UntaggedSignerWrap));
371
+ const given = fromHex(tag);
372
+ return expected !== null && given !== null && bytesEqual(expected, given);
373
+ };
374
+
375
+ /**
376
+ * Once M is known (#54): drops wraps whose tag is wrong. Untagged wraps from
377
+ * older versions are kept, unless the vault has more than
378
+ * {@link UNTAGGED_SIGNER_WRAP_LIMIT} wraps: then only the one just opened stays.
379
+ */
380
+ export const pruneSignerVault = (
381
+ vault: SignerVault,
382
+ pubkey: string,
383
+ signerKey: string,
384
+ m: Bytes,
385
+ openedId?: string,
386
+ ): SignerVault => {
387
+ const kept = vault.wraps.filter((w) => w.tag === undefined || tagValid(pubkey, signerKey, m, w));
388
+ const wraps =
389
+ kept.length > UNTAGGED_SIGNER_WRAP_LIMIT
390
+ ? kept.filter((w) => w.tag !== undefined || `${w.type}:${wrapId(w)}` === openedId)
391
+ : kept;
392
+ return { ...vault, wraps };
393
+ };
394
+
395
+ const PACKAGE_NAME = /^[A-Za-z][\w]*(\.[A-Za-z][\w]*)+$/;
396
+ const HEX_PUBKEY = /^[0-9a-f]{64}$/;
397
+
398
+ /** App identity from the caller only (SPEC §5.2); insecure or malformed callers get none (#30). */
399
+ export const appIdForCaller = (caller: Caller, knownNsiteGateways: ReadonlyArray<string> = []): Result<string, EvolustrError> => {
400
+ if (caller.identity === "connection") {
401
+ return HEX_PUBKEY.test(caller.clientPubkey) ? ok(`nip46:${caller.clientPubkey}`) : error("invalidCaller", "Bad client pubkey");
402
+ }
403
+ if ("androidPackage" in caller) {
404
+ return PACKAGE_NAME.test(caller.androidPackage) ? ok(`android:${caller.androidPackage}`) : error("invalidCaller", "Bad package name");
405
+ }
406
+ return appIdFromOrigin(caller.origin, knownNsiteGateways);
407
+ };
408
+
409
+ export const isProtectedEvent: EvolustrSigner["isProtectedEvent"] = (event) =>
410
+ event.kind === VAULT_KIND && event.tags.some((t) => t[0] === "d" && typeof t[1] === "string" && isProtectedDTag(t[1]));
411
+
412
+ // ── Implementation ──────────────────────────────────────────────────────────
413
+
414
+ export const createEvolustrSigner = (host: SignerHost): EvolustrSigner => {
415
+ const now = host.now ?? (() => Math.floor(Date.now() / 1000));
416
+ const random = host.randomBytes ?? defaultRandomBytes;
417
+ const timeoutMs = host.timeoutMs ?? 5000;
418
+ const allowSk = (): boolean => (typeof host.allowSkWrap === "function" ? host.allowSkWrap() : host.allowSkWrap !== false);
419
+ let m: Bytes | null = null;
420
+ let vault: SignerVault | null = null;
421
+ /** True once the signer vault was read from the relays this session (#40). */
422
+ let vaultLoaded = false;
423
+ /** That read waited for every relay, not a quorum (#62): safe to write on top of. */
424
+ let vaultFull = false;
425
+ /** The relays lack wraps the local copy has (#41); fixed after an approved key request. */
426
+ let needsHeal = false;
427
+ let lastEventAt = 0;
428
+ /** A relay vault with another M than the local copy, checked once M is known (#52 phase B). */
429
+ let candidate: SignerVault | null = null;
430
+ /** The previous M after a rotation, for old app keys. */
431
+ let previousM: Bytes | null = null;
432
+ /** Every earlier M opened from the vault, newest first (#58); null until read. */
433
+ let earlierMs: ReadonlyArray<Bytes> | null = null;
434
+
435
+ const appIdFor = (caller: Caller) => appIdForCaller(caller, host.knownNsiteGateways);
436
+
437
+ /** `full`: wait for every relay, for a read a write builds on (#62). */
438
+ const fetchVault = async (pubkey: string, full: boolean): Promise<Result<SignerVault | null>> => {
439
+ const f = await fetchReplaceable(
440
+ host.relays,
441
+ host.relayUrls,
442
+ { author: pubkey, kind: VAULT_KIND, d: signerVaultDTag(pubkey, host.signerKey) },
443
+ timeoutMs,
444
+ full ? undefined : host.relayQuorum,
445
+ );
446
+ if (f.kind === "none") return ok(null);
447
+ if (f.kind === "incomplete") return error("relaysUnavailable", "Not every relay answered");
448
+ lastEventAt = Math.max(lastEventAt, f.event.created_at);
449
+ return parseSignerVault(f.event.content);
450
+ };
451
+
452
+ /**
453
+ * Loads the signer vault once per session; null when none exists (#40). With a
454
+ * local copy (#41), it's merged with the relay version, or used instead of a
455
+ * missing or invalid one; `needsHeal` marks wraps the relays lack. With
456
+ * `forWrite`, a version read at the quorum is read again from every relay
457
+ * (#62): it may be stale, and a write on it would undo a newer one.
458
+ */
459
+ const loadVault = async (pubkey: string, forWrite = false): Promise<Result<SignerVault | null>> => {
460
+ if (vaultLoaded && (vaultFull || !forWrite)) return ok(vault);
461
+ const full = forWrite || host.relayQuorum === undefined;
462
+ const fetched = await fetchVault(pubkey, full);
463
+ if (!fetched.ok && fetched.error.type !== "invalidSignerVault") return fetched;
464
+ const copyText = (await host.cache?.getVault?.(pubkey)) ?? null;
465
+ const copy = copyText === null ? null : parseSignerVault(copyText);
466
+ const local = copy?.ok ? copy.value : null;
467
+ if (local === null) {
468
+ if (!fetched.ok) return fetched;
469
+ vault = fetched.value;
470
+ } else if (!fetched.ok || fetched.value === null) {
471
+ vault = local;
472
+ needsHeal = true;
473
+ } else if (differentMaster(local, fetched.value)) {
474
+ // Another M on the relays (a rotation, or a forgery): keep the local copy
475
+ // until M is unlocked and can check it; never heal over it (#52 phase B).
476
+ vault = local;
477
+ candidate = fetched.value;
478
+ needsHeal = false;
479
+ } else {
480
+ // The relay vault has no sk wrap and this device may not use one: keep it that way (#52).
481
+ const dropSk = !allowSk() && !fetched.value.wraps.some((w) => w.type === "sk");
482
+ vault = mergeSignerVaults(local, fetched.value, { dropSk });
483
+ const onRelays = new Set(fetched.value.wraps.map((w) => JSON.stringify(w)));
484
+ needsHeal = vault.wraps.some((w) => !onRelays.has(JSON.stringify(w)));
485
+ }
486
+ vaultLoaded = true;
487
+ vaultFull = full;
488
+ return ok(vault);
489
+ };
490
+
491
+ const publish = async (pubkey: string, next: SignerVault): Promise<Result<SignerVault>> => {
492
+ // Never publish from an unknown state: it would drop wraps added elsewhere (#40).
493
+ if (!vaultLoaded) return error("signerVaultUnknown", "Load the signer vault before changing it");
494
+ // Read at the quorum: check every relay first, and don't write over a newer version (#62).
495
+ if (!vaultFull) {
496
+ const before = JSON.stringify(vault);
497
+ const reread = await loadVault(pubkey, true);
498
+ if (!reread.ok) return reread;
499
+ if (JSON.stringify(vault) !== before) return error("signerVaultChanged", "The signer vault changed on another device; try again");
500
+ }
501
+ const at = Math.max(now(), lastEventAt + 1);
502
+ const signer: Signer = {
503
+ getPublicKey: host.getPublicKey,
504
+ signEvent: host.sign,
505
+ nip44Encrypt: () => Promise.reject(new Error("unused")),
506
+ nip44Decrypt: () => Promise.reject(new Error("unused")),
507
+ };
508
+ try {
509
+ await publishReplaceable(
510
+ host.relays,
511
+ host.relayUrls,
512
+ signer,
513
+ { kind: VAULT_KIND, created_at: at, tags: [["d", signerVaultDTag(pubkey, host.signerKey)]], content: JSON.stringify(next) },
514
+ timeoutMs,
515
+ );
516
+ } catch (e) {
517
+ return error("publishFailed", e instanceof Error ? e.message : String(e));
518
+ }
519
+ lastEventAt = at;
520
+ vault = next;
521
+ needsHeal = false;
522
+ await host.cache?.setVault?.(pubkey, JSON.stringify(next));
523
+ return ok(next);
524
+ };
525
+
526
+ const sealM = (pubkey: string, key: Bytes, w: { type: "sk" } | { type: "passkey"; rpId: string; credId: string; synced?: boolean }, secret: Bytes): SignerWrap => {
527
+ const id = w.type === "sk" ? "sk" : w.credId;
528
+ const sealed = { ...w, ...seal(key, secret, signerWrapAad(pubkey, host.signerKey, w.type, id)) } as UntaggedSignerWrap;
529
+ return { ...sealed, tag: signerWrapTag(pubkey, host.signerKey, secret, sealed) } as SignerWrap;
530
+ };
531
+
532
+ const openM = (pubkey: string, w: SignerWrap, key: Bytes): Result<Bytes> => {
533
+ const r = open(key, w, signerWrapAad(pubkey, host.signerKey, w.type, wrapId(w)));
534
+ return r.ok && r.value.length !== MASTER_SECRET_LENGTH ? error("invalidSignerVault", "Wrong secret length") : r;
535
+ };
536
+
537
+ const withWrap = (v: SignerVault | null, w: SignerWrap): SignerVault => ({
538
+ ...(v ?? {}),
539
+ v: 1,
540
+ wraps: [...(v?.wraps ?? []).filter((x) => !(x.type === w.type && wrapId(x) === wrapId(w))), w],
541
+ });
542
+
543
+ /** With M known, drops forged wraps; a change is published on the next approved request (#54). */
544
+ const prune = (pubkey: string, secret: Bytes, openedId?: string) => {
545
+ // Never touch a vault that holds another M (#52 phase B).
546
+ if (vault === null || (vault.mId !== undefined && vault.mId !== signerMId(secret))) return;
547
+ const pruned = pruneSignerVault(vault, pubkey, host.signerKey, secret, openedId);
548
+ if (pruned.wraps.length !== vault.wraps.length) {
549
+ vault = pruned;
550
+ needsHeal = true;
551
+ }
552
+ };
553
+
554
+ /**
555
+ * With M known: if the relays hold a rotation this M authorised, switch to it
556
+ * and forget this M (it must not make new app keys). "rotated" means M must
557
+ * now be unlocked again, from the new vault (#52 phase B).
558
+ */
559
+ const reconcile = async (pubkey: string): Promise<"same" | "rotated" | "foreign"> => {
560
+ if (m === null) return "same";
561
+ const myId = signerMId(m);
562
+ const other = candidate ?? (vault?.mId !== undefined && vault.mId !== myId ? vault : null);
563
+ if (other === null) return "same";
564
+ candidate = null;
565
+ if (!rotationValid(other, m)) return "foreign";
566
+ previousM = m;
567
+ earlierMs = null;
568
+ vault = other;
569
+ m = null;
570
+ needsHeal = false;
571
+ await host.cache?.remove(pubkey);
572
+ await host.cache?.setVault?.(pubkey, JSON.stringify(other));
573
+ return "rotated";
574
+ };
575
+
576
+ /** Called after a wrap opened to M, or after creating M: the vault is good (#41). */
577
+ const remember = async (pubkey: string, secret: Bytes, openedId?: string) => {
578
+ m = secret;
579
+ if ((await reconcile(pubkey)) === "rotated") return;
580
+ prune(pubkey, secret, openedId);
581
+ // Older vaults have no mId: add it, since a wrap of this vault just opened to M.
582
+ if (openedId !== undefined && vault !== null && vault.mId === undefined) {
583
+ vault = { ...vault, mId: signerMId(secret) };
584
+ needsHeal = true;
585
+ }
586
+ await host.cache?.set(pubkey, secret);
587
+ if (vault !== null) await host.cache?.setVault?.(pubkey, JSON.stringify(vault));
588
+ };
589
+
590
+ /**
591
+ * The earlier Ms, newest first, opened from the vault with the current one:
592
+ * `previous` with M, each `older` entry with the one before it (#58). Stops
593
+ * at the first entry that doesn't open.
594
+ */
595
+ const earlierOf = (pubkey: string): ReadonlyArray<Bytes> => {
596
+ if (earlierMs !== null) return earlierMs;
597
+ const first = vault?.previous;
598
+ if (m === null || first === undefined || vault?.mId !== signerMId(m)) return previousM === null ? [] : [previousM];
599
+ const found: Bytes[] = [];
600
+ let key = m;
601
+ for (const p of [first, ...(vault?.older ?? [])]) {
602
+ const opened = open(signerPreviousKey(key), p, signerWrapAad(pubkey, host.signerKey, "previous", p.mId));
603
+ if (!opened.ok || opened.value.length !== MASTER_SECRET_LENGTH || signerMId(opened.value) !== p.mId) break;
604
+ found.push(opened.value);
605
+ key = opened.value;
606
+ }
607
+ if (found.length === 0 && previousM !== null) found.push(previousM);
608
+ earlierMs = found;
609
+ return found;
610
+ };
611
+
612
+ /**
613
+ * Unlocks M without a click if possible: cache, then the nsec. Creates M only
614
+ * when `create` is set and no signer vault exists at all (#28, #29).
615
+ */
616
+ const unlockQuiet = async (pubkey: string, create: boolean): Promise<Result<boolean>> => {
617
+ if (m !== null) return ok(true);
618
+ const cached = await host.cache?.get(pubkey);
619
+ if (cached != null && cached.length === MASTER_SECRET_LENGTH) {
620
+ m = cached;
621
+ // Relays down: keep using the cached M. A rotation it authorised: unlock the new one.
622
+ const read = await loadVault(pubkey);
623
+ if (!read.ok || (await reconcile(pubkey)) !== "rotated") return ok(true);
624
+ }
625
+ const loaded = await loadVault(pubkey);
626
+ if (!loaded.ok) return loaded;
627
+ const sk = host.getSecretKey?.() ?? null;
628
+ if (sk !== null && allowSk()) {
629
+ const skWrap = vault?.wraps.find((w) => w.type === "sk");
630
+ if (skWrap !== undefined) {
631
+ const opened = openM(pubkey, skWrap, signerSkWrapKey(sk));
632
+ if (opened.ok) {
633
+ await remember(pubkey, opened.value, "sk:sk");
634
+ return ok(true);
635
+ }
636
+ }
637
+ if (vault === null && create) {
638
+ // First use: create M and protect it with the nsec.
639
+ const fresh = random(MASTER_SECRET_LENGTH);
640
+ const published = await publish(pubkey, { ...withWrap(vault, sealM(pubkey, signerSkWrapKey(sk), { type: "sk" }, fresh)), mId: signerMId(fresh) });
641
+ if (!published.ok) return published;
642
+ await remember(pubkey, fresh);
643
+ return ok(true);
644
+ }
645
+ }
646
+ return ok(false);
647
+ };
648
+
649
+ /** Unlocks M with a signer passkey, after a click inside the signer. */
650
+ const unlockWithPasskey = async (pubkey: string): Promise<Result<void>> => {
651
+ const passkeys = host.passkeys;
652
+ const wraps = (vault?.wraps ?? []).filter(
653
+ (w): w is Extract<SignerWrap, { type: "passkey" }> => w.type === "passkey" && passkeys !== undefined && w.rpId === passkeys.rpId,
654
+ );
655
+ if (passkeys === undefined || wraps.length === 0) {
656
+ return error("signerLocked", "No way to unlock this signer's Evolustr key here; enroll a signer passkey");
657
+ }
658
+ await host.ui.requestGesture("unlock");
659
+ let result;
660
+ try {
661
+ result = await passkeys.get({ allowCredIds: wraps.map((w) => w.credId), prfInput: signerPrfInput(pubkey) });
662
+ } catch (e) {
663
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
664
+ }
665
+ const wrap = wraps.find((w) => w.credId === result.credId);
666
+ if (wrap === undefined || result.prfOutput === null) return error("passkeyFailed", "The passkey gave no usable result");
667
+ const opened = openM(pubkey, wrap, signerPasskeyWrapKey(result.prfOutput));
668
+ if (!opened.ok) return opened;
669
+ await remember(pubkey, opened.value, `passkey:${wrap.credId}`);
670
+ return ok(undefined);
671
+ };
672
+
673
+ const ensureM = async (): Promise<Result<{ readonly pubkey: string; readonly m: Bytes }>> => {
674
+ const pubkey = await host.getPublicKey();
675
+ const quiet = await unlockQuiet(pubkey, true);
676
+ if (!quiet.ok) return quiet;
677
+ if (!quiet.value) {
678
+ const viaPasskey = await unlockWithPasskey(pubkey);
679
+ if (!viaPasskey.ok) return viaPasskey;
680
+ // That opened the previous M, and the vault moved on to its successor (#52 phase B).
681
+ if (m === null && previousM !== null) {
682
+ const again = await unlockWithPasskey(pubkey);
683
+ if (!again.ok) return again;
684
+ }
685
+ }
686
+ return m === null ? error("signerLocked", "Locked") : ok({ pubkey, m });
687
+ };
688
+
689
+ const capabilities: EvolustrSigner["capabilities"] = async (caller) => {
690
+ const appId = appIdFor(caller);
691
+ if (!appId.ok) return appId;
692
+ const pubkey = await host.getPublicKey();
693
+ if (m === null) await unlockQuiet(pubkey, false);
694
+ // M may come from the cache without the vault being read: read it, ignoring
695
+ // failures (still never creates or publishes anything, #29).
696
+ if (!vaultLoaded) await loadVault(pubkey);
697
+ return ok({
698
+ identity: caller.identity,
699
+ appId: appId.value,
700
+ signerId: m === null ? null : computeSignerId(m, appId.value),
701
+ ready: m !== null,
702
+ signerPasskey: (vault?.wraps ?? []).some((w) => w.type === "passkey"),
703
+ recoverable: (vault?.wraps ?? []).some((w) => w.type === "sk" || (w.type === "passkey" && w.synced === true)),
704
+ nsecProtected: (vault?.wraps ?? []).some((w) => w.type === "sk"),
705
+ nsecExposed: (vault?.wraps ?? []).some((w) => w.type === "sk") || vault?.skDroppedAt !== undefined,
706
+ ...(() => {
707
+ const ids = earlierOf(pubkey).map((x) => computeSignerId(x, appId.value));
708
+ return { previousSignerId: ids[0] ?? null, previousSignerIds: ids };
709
+ })(),
710
+ });
711
+ };
712
+
713
+ const getWrapKey: EvolustrSigner["getWrapKey"] = async (caller) => {
714
+ const appId = appIdFor(caller);
715
+ if (!appId.ok) return appId;
716
+ const allowed = await host.ui.confirm({ kind: "appKey", appId: appId.value, identity: caller.identity });
717
+ if (!allowed) return error("userRefused", "The user didn't allow this app");
718
+ const unlocked = await ensureM();
719
+ if (!unlocked.ok) return unlocked;
720
+ // Self-heal (#41): the user just approved this app and M is unlocked. With M
721
+ // from the cache the vault may not be loaded yet; a failure here doesn't block.
722
+ if (!vaultLoaded) await loadVault(unlocked.value.pubkey);
723
+ prune(unlocked.value.pubkey, unlocked.value.m);
724
+ if (needsHeal && vault !== null) await publish(unlocked.value.pubkey, vault);
725
+ return ok(signerAppKey(unlocked.value.m, appId.value));
726
+ };
727
+
728
+ const getHostSecret: EvolustrSigner["getHostSecret"] = async (label) => {
729
+ if (!isHostSecretLabel(label)) return error("badRequest", "A host secret label is 1–200 characters without '|'");
730
+ const unlocked = await ensureM();
731
+ if (!unlocked.ok) return unlocked;
732
+ return ok(hostSecret(unlocked.value.m, label));
733
+ };
734
+
735
+ const enrollPasskey: EvolustrSigner["enrollPasskey"] = async () => {
736
+ const passkeys = host.passkeys;
737
+ if (passkeys === undefined) return error("noPasskeys", "This signer has no passkey support");
738
+ const pubkey = await host.getPublicKey();
739
+ // The current wrap list must be known before adding to it (#40), from every relay (#62).
740
+ const loaded = await loadVault(pubkey, true);
741
+ if (!loaded.ok) return loaded;
742
+ const quiet = await unlockQuiet(pubkey, false);
743
+ if (!quiet.ok) return quiet;
744
+ if (!(await host.ui.confirm({ kind: "enrollPasskey" }))) return error("userRefused", "Cancelled");
745
+ // Moving from the nsec to a passkey: with the sk wrap no longer allowed, it
746
+ // may still open M once, so the passkey wraps the same M and app keys stay.
747
+ if (m === null && !allowSk()) {
748
+ const sk = host.getSecretKey?.() ?? null;
749
+ const skWrap = vault?.wraps.find((w) => w.type === "sk");
750
+ if (sk !== null && skWrap !== undefined) {
751
+ const opened = openM(pubkey, skWrap, signerSkWrapKey(sk));
752
+ if (opened.ok) await remember(pubkey, opened.value, "sk:sk");
753
+ }
754
+ }
755
+ // A signer vault already exists: unlock M first, never create a second one (#28).
756
+ if (m === null && vault !== null) {
757
+ const unlocked = await unlockWithPasskey(pubkey);
758
+ if (!unlocked.ok) return error("signerLocked", "Unlock this signer's existing Evolustr key before adding a passkey");
759
+ }
760
+ await host.ui.requestGesture("enrollPasskey");
761
+ let created;
762
+ try {
763
+ created = await passkeys.create({
764
+ userId: sha256(utf8(`evolustr-signer|${pubkey}`)),
765
+ userName: pubkey.slice(0, 16),
766
+ excludeCredIds: (vault?.wraps ?? []).flatMap((w) => (w.type === "passkey" && w.rpId === passkeys.rpId ? [w.credId] : [])),
767
+ prfInput: signerPrfInput(pubkey),
768
+ });
769
+ } catch (e) {
770
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
771
+ }
772
+ if (!created.prfEnabled) return error("prfUnsupported", "This authenticator has no PRF support");
773
+ let prfOutput = created.prfOutput;
774
+ if (prfOutput === null) {
775
+ await host.ui.requestGesture("enrollPasskey");
776
+ prfOutput = (await passkeys.get({ allowCredIds: [created.credId], prfInput: signerPrfInput(pubkey) })).prfOutput;
777
+ }
778
+ if (prfOutput === null) return error("prfUnsupported", "The passkey gave no PRF output");
779
+ // Only when no signer vault exists at all: create M now.
780
+ const secret = m ?? random(MASTER_SECRET_LENGTH);
781
+ let next = withWrap(vault, sealM(pubkey, signerPasskeyWrapKey(prfOutput), { type: "passkey", rpId: passkeys.rpId, credId: created.credId, synced: created.synced }, secret));
782
+ if (!allowSk() && next.wraps.some((w) => w.type === "sk")) {
783
+ // M stays the same: whoever can recover the nsec may still have it (#52).
784
+ next = { ...next, wraps: next.wraps.filter((w) => w.type !== "sk"), skDroppedAt: now() };
785
+ }
786
+ if (next.wraps.length > MAX_SIGNER_WRAPS) return error("signerVaultFull", "The signer vault has no room for another wrap");
787
+ next = { ...next, mId: signerMId(secret) };
788
+ const published = await publish(pubkey, next);
789
+ if (!published.ok) return published;
790
+ await remember(pubkey, secret);
791
+ return ok(undefined);
792
+ };
793
+
794
+ const getPreviousWrapKey: EvolustrSigner["getPreviousWrapKey"] = async (caller, signerId) => {
795
+ const appId = appIdFor(caller);
796
+ if (!appId.ok) return appId;
797
+ const allowed = await host.ui.confirm({ kind: "appKey", appId: appId.value, identity: caller.identity });
798
+ if (!allowed) return error("userRefused", "The user didn't allow this app");
799
+ const unlocked = await ensureM();
800
+ if (!unlocked.ok) return unlocked;
801
+ const earlier = earlierOf(unlocked.value.pubkey);
802
+ if (earlier.length === 0) return error("noPreviousKey", "This signer hasn't replaced its key");
803
+ const prev = signerId === undefined ? earlier[0] : earlier.find((x) => computeSignerId(x, appId.value) === signerId);
804
+ return prev === undefined ? error("noPreviousKey", "This signer has no earlier key with that id") : ok(signerAppKey(prev, appId.value));
805
+ };
806
+
807
+ const getPreviousHostSecret: EvolustrSigner["getPreviousHostSecret"] = async (label) => {
808
+ if (!isHostSecretLabel(label)) return error("badRequest", "A host secret label is 1–200 characters without '|'");
809
+ const unlocked = await ensureM();
810
+ if (!unlocked.ok) return unlocked;
811
+ const prev = earlierOf(unlocked.value.pubkey)[0];
812
+ return prev === undefined ? error("noPreviousKey", "This signer hasn't replaced its key") : ok(hostSecret(prev, label));
813
+ };
814
+
815
+ const getPreviousHostSecrets: EvolustrSigner["getPreviousHostSecrets"] = async (label) => {
816
+ if (!isHostSecretLabel(label)) return error("badRequest", "A host secret label is 1–200 characters without '|'");
817
+ const unlocked = await ensureM();
818
+ if (!unlocked.ok) return unlocked;
819
+ return ok(earlierOf(unlocked.value.pubkey).map((x) => hostSecret(x, label)));
820
+ };
821
+
822
+ const rotateMaster: EvolustrSigner["rotateMaster"] = async () => {
823
+ const passkeys = host.passkeys;
824
+ if (passkeys === undefined) return error("noPasskeys", "This signer has no passkey support");
825
+ // The point is to cut off whoever can recover the nsec: an sk wrap would bring it back.
826
+ if (allowSk()) return error("nsecAllowed", "Turn off the nsec protection (allowSkWrap) before replacing the key");
827
+ const pubkey = await host.getPublicKey();
828
+ const loaded = await loadVault(pubkey, true); // a write: from every relay (#62)
829
+ if (!loaded.ok) return loaded;
830
+ if (vault === null) return error("noSignerVault", "This signer has no key to replace yet");
831
+ const wraps = vault.wraps.filter(
832
+ (w): w is Extract<SignerWrap, { type: "passkey" }> => w.type === "passkey" && w.rpId === passkeys.rpId,
833
+ );
834
+ if (wraps.length === 0) return error("noSignerPasskey", "Enroll a signer passkey first");
835
+ if (!(await host.ui.confirm({ kind: "rotateMaster" }))) return error("userRefused", "Cancelled");
836
+ await host.ui.requestGesture("rotateMaster");
837
+ let result;
838
+ try {
839
+ result = await passkeys.get({ allowCredIds: wraps.map((w) => w.credId), prfInput: signerPrfInput(pubkey) });
840
+ } catch (e) {
841
+ return error("passkeyFailed", e instanceof Error ? e.message : String(e));
842
+ }
843
+ const wrap = wraps.find((w) => w.credId === result.credId);
844
+ if (wrap === undefined || result.prfOutput === null) return error("passkeyFailed", "The passkey gave no usable result");
845
+ const key = signerPasskeyWrapKey(result.prfOutput);
846
+ // The passkey in hand proves the user holds the current M.
847
+ const oldM = openM(pubkey, wrap, key);
848
+ if (!oldM.ok) return oldM;
849
+ const newM = random(MASTER_SECRET_LENGTH);
850
+ const oldMId = signerMId(oldM.value);
851
+ const newMId = signerMId(newM);
852
+ // The chain so far moves down one place, unchanged: each entry still opens with the one before it (#58).
853
+ const older = vault.previous === undefined ? [] : [vault.previous, ...(vault.older ?? [])].slice(0, MAX_PREVIOUS_MASTERS - 1);
854
+ const next: SignerVault = {
855
+ v: 1,
856
+ wraps: [sealM(pubkey, key, { type: "passkey", rpId: wrap.rpId, credId: wrap.credId, ...(wrap.synced === undefined ? {} : { synced: wrap.synced }) }, newM)],
857
+ mId: newMId,
858
+ rotatedFrom: { mId: oldMId, proof: masterRotationProof(oldM.value, newMId) },
859
+ previous: { mId: oldMId, ...seal(signerPreviousKey(newM), oldM.value, signerWrapAad(pubkey, host.signerKey, "previous", oldMId)) },
860
+ ...(older.length > 0 ? { older } : {}),
861
+ };
862
+ const droppedWraps = vault.wraps.length - 1;
863
+ const published = await publish(pubkey, next);
864
+ if (!published.ok) return published;
865
+ candidate = null;
866
+ previousM = oldM.value;
867
+ earlierMs = null;
868
+ m = newM;
869
+ await host.cache?.set(pubkey, newM);
870
+ return ok({ droppedWraps });
871
+ };
872
+
873
+ const handle: EvolustrSigner["handle"] = async (method, params, caller) => {
874
+ switch (method) {
875
+ case "evolustr_capabilities":
876
+ return capabilities(caller);
877
+ case "evolustr_get_wrap_key": {
878
+ const key = await getWrapKey(caller);
879
+ return key.ok ? ok(toBase64Url(key.value)) : key;
880
+ }
881
+ case "evolustr_get_previous_wrap_key": {
882
+ // Optional: the signer id the app's wrap was made with (#58).
883
+ const signerId = params[0];
884
+ if (signerId !== undefined && signerId !== null && (typeof signerId !== "string" || !/^[0-9a-f]{16}$/.test(signerId))) {
885
+ return error("badRequest", "signerId must be 16 hex characters");
886
+ }
887
+ const key = await getPreviousWrapKey(caller, typeof signerId === "string" ? signerId : undefined);
888
+ return key.ok ? ok(toBase64Url(key.value)) : key;
889
+ }
890
+ case "evolustr_enroll_passkey":
891
+ return enrollPasskey();
892
+ default:
893
+ return error("unknownMethod", `Unknown method ${method}`);
894
+ }
895
+ };
896
+
897
+ const lock: EvolustrSigner["lock"] = async () => {
898
+ const pubkey = await host.getPublicKey().catch(() => null);
899
+ m = null;
900
+ vault = null;
901
+ vaultLoaded = false;
902
+ needsHeal = false;
903
+ candidate = null;
904
+ previousM = null;
905
+ earlierMs = null;
906
+ if (pubkey !== null) await host.cache?.remove(pubkey);
907
+ };
908
+
909
+ return {
910
+ handle,
911
+ capabilities,
912
+ getWrapKey,
913
+ getPreviousWrapKey,
914
+ enrollPasskey,
915
+ rotateMaster,
916
+ getHostSecret,
917
+ getPreviousHostSecret,
918
+ getPreviousHostSecrets,
919
+ isProtectedEvent,
920
+ appIdFor,
921
+ lock,
922
+ };
923
+ };