@oxyhq/core 12.7.0 → 12.9.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.
Files changed (56) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/boot/sessionColdBoot.js +16 -3
  3. package/dist/cjs/crypto/identityMarker.js +255 -0
  4. package/dist/cjs/crypto/keyManager.js +844 -106
  5. package/dist/cjs/index.js +8 -4
  6. package/dist/cjs/mixins/OxyServices.auth.js +21 -6
  7. package/dist/cjs/mixins/OxyServices.deviceBoot.js +9 -1
  8. package/dist/cjs/mixins/OxyServices.utility.js +11 -1
  9. package/dist/cjs/server/auth.js +3 -0
  10. package/dist/cjs/server/index.js +2 -1
  11. package/dist/cjs/utils/oxyServiceEnvironment.js +19 -0
  12. package/dist/esm/.tsbuildinfo +1 -1
  13. package/dist/esm/boot/sessionColdBoot.js +16 -3
  14. package/dist/esm/crypto/identityMarker.js +248 -0
  15. package/dist/esm/crypto/keyManager.js +843 -106
  16. package/dist/esm/index.js +2 -1
  17. package/dist/esm/mixins/OxyServices.auth.js +21 -6
  18. package/dist/esm/mixins/OxyServices.deviceBoot.js +9 -1
  19. package/dist/esm/mixins/OxyServices.utility.js +11 -1
  20. package/dist/esm/server/auth.js +2 -0
  21. package/dist/esm/server/index.js +1 -1
  22. package/dist/esm/utils/oxyServiceEnvironment.js +16 -0
  23. package/dist/types/.tsbuildinfo +1 -1
  24. package/dist/types/boot/sessionColdBoot.d.ts +25 -0
  25. package/dist/types/crypto/identityMarker.d.ts +94 -0
  26. package/dist/types/crypto/keyManager.d.ts +212 -3
  27. package/dist/types/index.d.ts +4 -2
  28. package/dist/types/mixins/OxyServices.auth.d.ts +27 -2
  29. package/dist/types/mixins/OxyServices.deviceBoot.d.ts +8 -0
  30. package/dist/types/mixins/OxyServices.utility.d.ts +3 -0
  31. package/dist/types/server/auth.d.ts +4 -0
  32. package/dist/types/server/index.d.ts +2 -2
  33. package/dist/types/utils/oxyServiceEnvironment.d.ts +17 -0
  34. package/package.json +1 -1
  35. package/src/boot/__tests__/sessionColdBoot.test.ts +113 -0
  36. package/src/boot/sessionColdBoot.ts +42 -3
  37. package/src/crypto/__tests__/identityMocks.ts +125 -0
  38. package/src/crypto/__tests__/keyManager.atomicity.test.ts +79 -94
  39. package/src/crypto/__tests__/keyManager.cacheSafety.test.ts +175 -0
  40. package/src/crypto/__tests__/keyManager.identityStatus.test.ts +217 -0
  41. package/src/crypto/__tests__/keyManager.recoveryLadder.test.ts +179 -0
  42. package/src/crypto/__tests__/keyManager.storageMigration.test.ts +227 -0
  43. package/src/crypto/__tests__/keyManager.test.ts +77 -87
  44. package/src/crypto/identityMarker.ts +291 -0
  45. package/src/crypto/keyManager.ts +1026 -105
  46. package/src/index.ts +7 -1
  47. package/src/mixins/OxyServices.auth.ts +31 -7
  48. package/src/mixins/OxyServices.deviceBoot.ts +9 -1
  49. package/src/mixins/OxyServices.utility.ts +19 -1
  50. package/src/mixins/__tests__/OxyServices.deviceBoot.test.ts +4 -2
  51. package/src/mixins/__tests__/commonsSignIn.test.ts +84 -1
  52. package/src/mixins/__tests__/serviceAuth.test.ts +65 -0
  53. package/src/server/auth.ts +5 -0
  54. package/src/server/index.ts +2 -0
  55. package/src/utils/__tests__/oxyServiceEnvironment.test.ts +7 -0
  56. package/src/utils/oxyServiceEnvironment.ts +17 -0
@@ -7,9 +7,10 @@
7
7
  import _cjs_elliptic from 'elliptic';
8
8
  const { ec: EC } = _cjs_elliptic;
9
9
  import { isWeb, isIOS, isAndroid } from '../utils/platform.js';
10
- import { isReactNative, isNodeJS, loadExpoCrypto, loadNodeCrypto, loadSecureStore, loadSharedIdentityBridge } from '@oxyhq/protocol';
10
+ import { isReactNative, isNodeJS, loadAsyncStorage, loadExpoCrypto, loadNodeCrypto, loadSecureStore, loadSharedIdentityBridge } from '@oxyhq/protocol';
11
11
  import { isDev, logger } from '../logger/index.js';
12
12
  import { hkdfSha256 } from './kdf.js';
13
+ import { clearIdentityMarker, readIdentityMarker, updateIdentityMarker, writeIdentityMarker, } from './identityMarker.js';
13
14
  /**
14
15
  * Thrown when an identity-mutating operation (createIdentity / importKeyPair)
15
16
  * is invoked while a valid identity already exists on the device.
@@ -41,6 +42,25 @@ export class IdentityPersistError extends Error {
41
42
  this.name = 'IdentityPersistError';
42
43
  }
43
44
  }
45
+ /**
46
+ * Thrown when identity storage cannot be read/written right now — the keychain
47
+ * is locked, the module failed to load, or a read threw — as opposed to the
48
+ * identity being genuinely absent.
49
+ *
50
+ * This is the crux of the corruption-vs-fresh-install fix: a storage THROW must
51
+ * NEVER be flattened into "no identity" (the old behavior, which let onboarding
52
+ * treat a momentarily-locked keystore as a blank device). Callers that used to
53
+ * tolerate a `false`/`null` from `hasIdentity()`/`getPublicKey()` on error must
54
+ * now treat this typed error as "cannot determine" — retry, surface a locked
55
+ * state, or abort a destructive path — never as "safe to create/overwrite".
56
+ */
57
+ export class IdentityUnavailableError extends Error {
58
+ constructor(message, cause) {
59
+ super(message);
60
+ this.cause = cause;
61
+ this.name = 'IdentityUnavailableError';
62
+ }
63
+ }
44
64
  const ec = new EC('secp256k1');
45
65
  /**
46
66
  * HKDF salt that domain-separates every identity-scoped seed produced by
@@ -73,6 +93,56 @@ const STORAGE_KEYS = {
73
93
  SHARED_SESSION_TOKEN: 'oxy_shared_session_token',
74
94
  SHARED_SESSION_ID: 'oxy_shared_session_id',
75
95
  };
96
+ /**
97
+ * v2 identity slot layout — blast-radius isolation.
98
+ *
99
+ * The legacy keys above were written WITHOUT a `keychainService`, so on Android
100
+ * they all shared expo-secure-store's single default `key_v1` AndroidKeyStore
101
+ * key — meaning ONE keystore invalidation deleted the primary AND the backup
102
+ * together (the exact loss this hardening closes). The v2 layout gives the
103
+ * primary and the backup DISTINCT keychain services (→ independent AndroidKeyStore
104
+ * keys, independent iOS keychain items), so they can no longer die together, and
105
+ * DISTINCT key names (`_v2`) so the post-copy migration verify can only observe
106
+ * what it actually wrote (old/new locations are non-aliasable).
107
+ *
108
+ * Migration from the legacy layout is lazy + verify-before-delete — see
109
+ * {@link KeyManager._runSlotMigration}.
110
+ */
111
+ const V2_PRIMARY_KEYCHAIN_SERVICE = 'oxy_identity';
112
+ const V2_BACKUP_KEYCHAIN_SERVICE = 'oxy_identity_backup';
113
+ const V2_STORAGE_KEYS = {
114
+ PRIVATE_KEY: 'oxy_identity_private_key_v2',
115
+ PUBLIC_KEY: 'oxy_identity_public_key_v2',
116
+ BACKUP_PRIVATE_KEY: 'oxy_identity_backup_private_key_v2',
117
+ BACKUP_PUBLIC_KEY: 'oxy_identity_backup_public_key_v2',
118
+ BACKUP_TIMESTAMP: 'oxy_identity_backup_timestamp_v2',
119
+ };
120
+ /**
121
+ * Advisory AsyncStorage fast-path flag: set once the v2 slots own the identity.
122
+ * Re-derivable (its loss just re-runs the cheap slot check), so it lives in
123
+ * plain AsyncStorage rather than the keychain. It only SKIPS re-reading the
124
+ * legacy slots on an already-migrated device; it is never trusted over an actual
125
+ * v2 read (a set flag with an unhealthy v2 pair falls through to full migration).
126
+ */
127
+ const SLOTS_MIGRATED_FLAG_KEY = 'oxy_identity_slots_migrated_v2';
128
+ const V2_SLOT_LAYOUT = {
129
+ primaryService: V2_PRIMARY_KEYCHAIN_SERVICE,
130
+ primaryPrivateKeyName: V2_STORAGE_KEYS.PRIVATE_KEY,
131
+ primaryPublicKeyName: V2_STORAGE_KEYS.PUBLIC_KEY,
132
+ backupService: V2_BACKUP_KEYCHAIN_SERVICE,
133
+ backupPrivateKeyName: V2_STORAGE_KEYS.BACKUP_PRIVATE_KEY,
134
+ backupPublicKeyName: V2_STORAGE_KEYS.BACKUP_PUBLIC_KEY,
135
+ backupTimestampName: V2_STORAGE_KEYS.BACKUP_TIMESTAMP,
136
+ };
137
+ const LEGACY_SLOT_LAYOUT = {
138
+ primaryService: undefined,
139
+ primaryPrivateKeyName: STORAGE_KEYS.PRIVATE_KEY,
140
+ primaryPublicKeyName: STORAGE_KEYS.PUBLIC_KEY,
141
+ backupService: undefined,
142
+ backupPrivateKeyName: STORAGE_KEYS.BACKUP_PRIVATE_KEY,
143
+ backupPublicKeyName: STORAGE_KEYS.BACKUP_PUBLIC_KEY,
144
+ backupTimestampName: STORAGE_KEYS.BACKUP_TIMESTAMP,
145
+ };
76
146
  /**
77
147
  * iOS Keychain Access Group for sharing identities across Oxy apps
78
148
  * All Oxy apps must have this access group enabled in their entitlements
@@ -157,6 +227,320 @@ export class KeyManager {
157
227
  static invalidateCache() {
158
228
  KeyManager.cachedPublicKey = null;
159
229
  KeyManager.cachedHasIdentity = null;
230
+ KeyManager.cachedPublicKeyResolved = false;
231
+ KeyManager.notifyIdentityChanged();
232
+ }
233
+ /**
234
+ * Subscribe to identity-verdict changes (create / import / delete / restore /
235
+ * cache invalidation). Fires synchronously; the returned function unsubscribes.
236
+ * Consumed via `useOxyEvent`-style hooks in commons to invalidate the routing
237
+ * queries the instant the identity state moves, without polling.
238
+ */
239
+ static subscribeIdentityChanged(listener) {
240
+ KeyManager.identityChangeListeners.add(listener);
241
+ return () => {
242
+ KeyManager.identityChangeListeners.delete(listener);
243
+ };
244
+ }
245
+ /** Synchronous fan-out with per-listener isolation (one throwing listener never blocks the rest). */
246
+ static notifyIdentityChanged() {
247
+ // Snapshot first — a listener may unsubscribe (mutate the Set) during fan-out.
248
+ for (const listener of Array.from(KeyManager.identityChangeListeners)) {
249
+ try {
250
+ listener();
251
+ }
252
+ catch (error) {
253
+ logger.warn('Identity-change listener threw', { component: 'KeyManager' }, error);
254
+ }
255
+ }
256
+ }
257
+ /** Build `getItemAsync`/`deleteItemAsync` options for a given keychain service (read/delete). */
258
+ static _slotOpts(service) {
259
+ return service ? { keychainService: service } : {};
260
+ }
261
+ /** Build private-key write options (device-only accessibility) for a given keychain service. */
262
+ static _privateWriteOpts(store, service) {
263
+ const opts = { keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY };
264
+ if (service) {
265
+ opts.keychainService = service;
266
+ }
267
+ return opts;
268
+ }
269
+ /** True only when both keys are present, well-formed, AND the public derives from the private. */
270
+ static _isHealthyPair(privateKey, publicKey) {
271
+ if (!privateKey || !publicKey) {
272
+ return false;
273
+ }
274
+ if (!KeyManager.isValidPrivateKey(privateKey) || !KeyManager.isValidPublicKey(publicKey)) {
275
+ return false;
276
+ }
277
+ try {
278
+ return KeyManager.derivePublicKey(privateKey).toLowerCase() === publicKey.toLowerCase();
279
+ }
280
+ catch {
281
+ return false;
282
+ }
283
+ }
284
+ /**
285
+ * Resolve the AsyncStorage-backed KV store for the advisory migration flag, or
286
+ * `null` off-RN / when unavailable. Independent of the keychain, so the flag
287
+ * cannot be taken down by the keystore event this whole subsystem defends
288
+ * against.
289
+ */
290
+ static async _advisoryStorage() {
291
+ if (!isReactNative()) {
292
+ return null;
293
+ }
294
+ try {
295
+ const mod = await loadAsyncStorage();
296
+ return mod.default;
297
+ }
298
+ catch {
299
+ // Advisory only — absence just means the slot check runs in full.
300
+ return null;
301
+ }
302
+ }
303
+ static async _readSlotsMigratedFlag() {
304
+ const storage = await KeyManager._advisoryStorage();
305
+ if (!storage) {
306
+ return false;
307
+ }
308
+ try {
309
+ return (await storage.getItem(SLOTS_MIGRATED_FLAG_KEY)) === 'true';
310
+ }
311
+ catch {
312
+ // Advisory only — treat an unreadable flag as "not yet migrated".
313
+ return false;
314
+ }
315
+ }
316
+ static async _setSlotsMigratedFlag() {
317
+ const storage = await KeyManager._advisoryStorage();
318
+ if (!storage) {
319
+ return;
320
+ }
321
+ try {
322
+ await storage.setItem(SLOTS_MIGRATED_FLAG_KEY, 'true');
323
+ }
324
+ catch (error) {
325
+ // Advisory only — a failed write just re-runs the cheap slot check next launch.
326
+ if (isDev()) {
327
+ logger.debug('Failed to set slots-migrated flag (advisory)', { component: 'KeyManager' }, error);
328
+ }
329
+ }
330
+ }
331
+ /**
332
+ * Ensure the identity has been migrated onto the isolated v2 slots (or that we
333
+ * know we must read legacy this session). Memoized so concurrent callers share
334
+ * ONE run; a `deferred` (read-threw) outcome is not cached so a later call
335
+ * retries after the keychain unlocks. Every identity-slot accessor awaits this
336
+ * before touching storage.
337
+ */
338
+ static async _ensureIdentitySlotsMigrated() {
339
+ if (KeyManager.slotMigrationResult && KeyManager.slotMigrationResult.mode !== 'deferred') {
340
+ return KeyManager.slotMigrationResult;
341
+ }
342
+ if (!KeyManager.slotMigrationPromise) {
343
+ const run = (async () => {
344
+ const result = await KeyManager._runSlotMigration();
345
+ KeyManager.slotMigrationResult = result;
346
+ return result;
347
+ })();
348
+ KeyManager.slotMigrationPromise = run;
349
+ // Clear the in-flight handle once settled so a deferred outcome retries.
350
+ run
351
+ .then((result) => {
352
+ if (result.mode === 'deferred') {
353
+ KeyManager.slotMigrationPromise = null;
354
+ }
355
+ })
356
+ .catch(() => {
357
+ KeyManager.slotMigrationPromise = null;
358
+ });
359
+ }
360
+ return KeyManager.slotMigrationPromise;
361
+ }
362
+ /**
363
+ * One-shot slot migration state machine. All reads are DIRECT and a thrown
364
+ * read defers everything (zero writes/deletes) so a locked keychain is never
365
+ * mistaken for an empty one. INVARIANT: at every instant ≥1 readable copy of a
366
+ * previously-existing identity remains — legacy is deleted ONLY after the v2
367
+ * copy is verified re-readable in its new (non-aliasable) location.
368
+ */
369
+ static async _runSlotMigration() {
370
+ let store;
371
+ try {
372
+ store = await initSecureStore();
373
+ }
374
+ catch (error) {
375
+ return { mode: 'deferred', cause: error };
376
+ }
377
+ const migratedFlag = await KeyManager._readSlotsMigratedFlag();
378
+ // Read the v2 primary (dedicated keychain service).
379
+ let v2Private;
380
+ let v2Public;
381
+ try {
382
+ v2Private = await store.getItemAsync(V2_STORAGE_KEYS.PRIVATE_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
383
+ v2Public = await store.getItemAsync(V2_STORAGE_KEYS.PUBLIC_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
384
+ }
385
+ catch (error) {
386
+ return { mode: 'deferred', cause: error };
387
+ }
388
+ if (KeyManager._isHealthyPair(v2Private, v2Public)) {
389
+ // v2 already owns the identity. On the first observation, clean up any
390
+ // stale legacy copy and record the fast-path flag.
391
+ if (!migratedFlag) {
392
+ await KeyManager._bestEffortDeleteLegacyPrimaryAndBackup(store);
393
+ await KeyManager._setSlotsMigratedFlag();
394
+ }
395
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
396
+ }
397
+ // v2 primary absent/partial but the flag says migration finished → v2 is
398
+ // simply empty (identity deleted / never created). No legacy to rescue.
399
+ if (migratedFlag) {
400
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
401
+ }
402
+ // Read the legacy primary (default keychain service = the old `key_v1`).
403
+ let legacyPrivate;
404
+ let legacyPublic;
405
+ try {
406
+ legacyPrivate = await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
407
+ legacyPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
408
+ }
409
+ catch (error) {
410
+ return { mode: 'deferred', cause: error };
411
+ }
412
+ if (!KeyManager._isHealthyPair(legacyPrivate, legacyPublic)) {
413
+ // Nothing readable in either generation → v2 is the canonical (empty) home.
414
+ // The marker (not this migration) decides fresh-vs-lost.
415
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
416
+ }
417
+ // legacy healthy, v2 absent → migrate: copy → read-back verify → only then delete legacy.
418
+ const canonicalPrivate = KeyManager.canonicalPrivateKey(legacyPrivate);
419
+ const canonicalPublic = legacyPublic.toLowerCase();
420
+ try {
421
+ await store.setItemAsync(V2_STORAGE_KEYS.PUBLIC_KEY, canonicalPublic, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
422
+ await store.setItemAsync(V2_STORAGE_KEYS.PRIVATE_KEY, canonicalPrivate, KeyManager._privateWriteOpts(store, V2_PRIMARY_KEYCHAIN_SERVICE));
423
+ const readBackPrivate = await store.getItemAsync(V2_STORAGE_KEYS.PRIVATE_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
424
+ const readBackPublic = await store.getItemAsync(V2_STORAGE_KEYS.PUBLIC_KEY, KeyManager._slotOpts(V2_PRIMARY_KEYCHAIN_SERVICE));
425
+ const verified = readBackPrivate?.toLowerCase() === canonicalPrivate &&
426
+ readBackPublic?.toLowerCase() === canonicalPublic &&
427
+ KeyManager._isHealthyPair(readBackPrivate, readBackPublic);
428
+ if (!verified) {
429
+ // v2 write did not durably land — remove the partial v2 and serve reads
430
+ // from legacy this session (legacy is UNTOUCHED). Retry next launch.
431
+ await KeyManager._bestEffortDeleteV2Primary(store);
432
+ logger.warn('Identity slot migration verify failed; serving identity from legacy slots this session', { component: 'KeyManager' });
433
+ return { mode: 'legacy', layout: LEGACY_SLOT_LAYOUT };
434
+ }
435
+ }
436
+ catch (error) {
437
+ await KeyManager._bestEffortDeleteV2Primary(store);
438
+ logger.warn('Identity slot migration write threw; serving identity from legacy slots this session', { component: 'KeyManager' }, error);
439
+ return { mode: 'legacy', layout: LEGACY_SLOT_LAYOUT };
440
+ }
441
+ // v2 primary is verified re-readable. Migrate the backup slot (best-effort),
442
+ // then it is finally safe to delete the legacy generation.
443
+ await KeyManager._migrateBackupSlotToV2(store, canonicalPrivate, canonicalPublic);
444
+ await KeyManager._bestEffortDeleteLegacyPrimaryAndBackup(store);
445
+ await KeyManager._setSlotsMigratedFlag();
446
+ return { mode: 'v2', layout: V2_SLOT_LAYOUT };
447
+ }
448
+ /**
449
+ * Seed the v2 backup slot during migration. Prefers a healthy legacy backup;
450
+ * otherwise mirrors the (already-verified) v2 primary material so a v2 backup
451
+ * always exists on an independent keychain key. Best-effort — a failure just
452
+ * defers backup population to the next {@link _persistIdentityAtomic}.
453
+ */
454
+ static async _migrateBackupSlotToV2(store, primaryPrivate, primaryPublic) {
455
+ try {
456
+ let backupPrivate = null;
457
+ let backupPublic = null;
458
+ try {
459
+ backupPrivate = await store.getItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
460
+ backupPublic = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
461
+ }
462
+ catch (error) {
463
+ if (isDev()) {
464
+ logger.debug('Legacy backup unreadable during migration (non-fatal)', { component: 'KeyManager' }, error);
465
+ }
466
+ backupPrivate = null;
467
+ backupPublic = null;
468
+ }
469
+ let seedPrivate;
470
+ let seedPublic;
471
+ if (KeyManager._isHealthyPair(backupPrivate, backupPublic)) {
472
+ seedPrivate = KeyManager.canonicalPrivateKey(backupPrivate);
473
+ seedPublic = backupPublic.toLowerCase();
474
+ }
475
+ else {
476
+ seedPrivate = primaryPrivate;
477
+ seedPublic = primaryPublic;
478
+ }
479
+ await store.setItemAsync(V2_STORAGE_KEYS.BACKUP_PUBLIC_KEY, seedPublic, KeyManager._slotOpts(V2_BACKUP_KEYCHAIN_SERVICE));
480
+ await store.setItemAsync(V2_STORAGE_KEYS.BACKUP_PRIVATE_KEY, seedPrivate, KeyManager._privateWriteOpts(store, V2_BACKUP_KEYCHAIN_SERVICE));
481
+ await store.setItemAsync(V2_STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString(), KeyManager._slotOpts(V2_BACKUP_KEYCHAIN_SERVICE));
482
+ }
483
+ catch (error) {
484
+ logger.warn('Failed to migrate identity backup slot to v2 (non-fatal)', { component: 'KeyManager' }, error);
485
+ }
486
+ }
487
+ /** Best-effort single delete under an optional keychain service. Cleanup only — never surfaces. */
488
+ static async _bestEffortDelete(store, key, service) {
489
+ try {
490
+ await store.deleteItemAsync(key, KeyManager._slotOpts(service));
491
+ }
492
+ catch (error) {
493
+ if (isDev()) {
494
+ logger.debug('Best-effort identity delete failed', { component: 'KeyManager' }, error);
495
+ }
496
+ }
497
+ }
498
+ static async _bestEffortDeleteV2Primary(store) {
499
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.PRIVATE_KEY, V2_PRIMARY_KEYCHAIN_SERVICE);
500
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.PUBLIC_KEY, V2_PRIMARY_KEYCHAIN_SERVICE);
501
+ }
502
+ static async _bestEffortDeleteLegacyPrimaryAndBackup(store) {
503
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PRIVATE_KEY);
504
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PUBLIC_KEY);
505
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PRIVATE_KEY);
506
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PUBLIC_KEY);
507
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_TIMESTAMP);
508
+ }
509
+ static async _bestEffortDeleteBackupsAllGenerations(store) {
510
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.BACKUP_PRIVATE_KEY, V2_BACKUP_KEYCHAIN_SERVICE);
511
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.BACKUP_PUBLIC_KEY, V2_BACKUP_KEYCHAIN_SERVICE);
512
+ await KeyManager._bestEffortDelete(store, V2_STORAGE_KEYS.BACKUP_TIMESTAMP, V2_BACKUP_KEYCHAIN_SERVICE);
513
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PRIVATE_KEY);
514
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_PUBLIC_KEY);
515
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.BACKUP_TIMESTAMP);
516
+ }
517
+ /**
518
+ * Clear the cross-app shared identity slot (force-delete only) so a deleted
519
+ * identity cannot be resurrected via the recovery ladder's shared rung.
520
+ * Best-effort — the shared slot is a redundant convenience copy.
521
+ */
522
+ static async _clearSharedSlot(store) {
523
+ try {
524
+ if (isIOS()) {
525
+ const opts = { keychainAccessGroup: IOS_KEYCHAIN_GROUP };
526
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY, opts);
527
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY, opts);
528
+ }
529
+ else if (isAndroid()) {
530
+ const bridge = await loadSharedIdentityBridge();
531
+ if (bridge) {
532
+ await bridge.clearShared();
533
+ }
534
+ else {
535
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PRIVATE_KEY);
536
+ await store.deleteItemAsync(STORAGE_KEYS.SHARED_PUBLIC_KEY);
537
+ }
538
+ }
539
+ KeyManager.invalidateSharedCache();
540
+ }
541
+ catch (error) {
542
+ logger.warn('Failed to clear shared identity slot during force delete', { component: 'KeyManager' }, error);
543
+ }
160
544
  }
161
545
  /**
162
546
  * Invalidate cached shared identity state
@@ -621,8 +1005,23 @@ export class KeyManager {
621
1005
  *
622
1006
  * @internal
623
1007
  */
624
- static async _persistIdentityAtomic(privateKey, publicKey) {
1008
+ static async _persistIdentityAtomic(privateKey, publicKey, origin) {
625
1009
  const store = await initSecureStore();
1010
+ // Resolve the active slot layout (normally v2; legacy only in the rare
1011
+ // migration-fallback session). Reading and writing the SAME layout keeps the
1012
+ // snapshot/rollback machinery below internally consistent. A deferred
1013
+ // migration (keychain locked) must never write blind.
1014
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1015
+ if (migration.mode === 'deferred') {
1016
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable; refusing to persist an identity.', migration.cause);
1017
+ }
1018
+ const layout = migration.layout;
1019
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
1020
+ const primaryPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.primaryService);
1021
+ const primaryPubWriteOpts = KeyManager._slotOpts(layout.primaryService);
1022
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
1023
+ const backupPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.backupService);
1024
+ const backupPubWriteOpts = KeyManager._slotOpts(layout.backupService);
626
1025
  // Canonicalize BEFORE persistence so the stored value is always in
627
1026
  // canonical 64-hex-char lowercase form going forward. This is the single
628
1027
  // place all primary writes flow through, so once a value lands here all
@@ -637,8 +1036,8 @@ export class KeyManager {
637
1036
  let priorPrivate;
638
1037
  let priorPublic;
639
1038
  try {
640
- priorPrivate = await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
641
- priorPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
1039
+ priorPrivate = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1040
+ priorPublic = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
642
1041
  }
643
1042
  catch (error) {
644
1043
  logger.error('Failed to read existing primary before persist', error, { component: 'KeyManager' });
@@ -660,18 +1059,16 @@ export class KeyManager {
660
1059
  if (priorIsHealthyDifferent && priorPrivate && priorPublic) {
661
1060
  let existingBackupPublic = null;
662
1061
  try {
663
- existingBackupPublic = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
1062
+ existingBackupPublic = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
664
1063
  }
665
1064
  catch {
666
1065
  existingBackupPublic = null;
667
1066
  }
668
1067
  if (existingBackupPublic?.toLowerCase() !== priorPublic.toLowerCase()) {
669
1068
  try {
670
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, KeyManager.canonicalPrivateKey(priorPrivate), {
671
- keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
672
- });
673
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, priorPublic.toLowerCase());
674
- await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
1069
+ await store.setItemAsync(layout.backupPrivateKeyName, KeyManager.canonicalPrivateKey(priorPrivate), backupPrivWriteOpts);
1070
+ await store.setItemAsync(layout.backupPublicKeyName, priorPublic.toLowerCase(), backupPubWriteOpts);
1071
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), backupPubWriteOpts);
675
1072
  }
676
1073
  catch (error) {
677
1074
  logger.error('Failed to back up existing identity before overwrite', error, { component: 'KeyManager' });
@@ -684,14 +1081,12 @@ export class KeyManager {
684
1081
  // NOT touched here — it still holds the previous good identity until the
685
1082
  // new primary is proven durable.
686
1083
  try {
687
- await store.setItemAsync(STORAGE_KEYS.PUBLIC_KEY, canonicalPublic);
688
- await store.setItemAsync(STORAGE_KEYS.PRIVATE_KEY, canonicalPrivate, {
689
- keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
690
- });
1084
+ await store.setItemAsync(layout.primaryPublicKeyName, canonicalPublic, primaryPubWriteOpts);
1085
+ await store.setItemAsync(layout.primaryPrivateKeyName, canonicalPrivate, primaryPrivWriteOpts);
691
1086
  }
692
1087
  catch (error) {
693
1088
  logger.error('Failed to write primary identity to secure store', error, { component: 'KeyManager' });
694
- await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
1089
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
695
1090
  throw new IdentityPersistError('Failed to write identity to secure store', error);
696
1091
  }
697
1092
  // Step 2: Verify round-trip. If the store silently drops our writes
@@ -701,12 +1096,12 @@ export class KeyManager {
701
1096
  let readBackPrivate;
702
1097
  let readBackPublic;
703
1098
  try {
704
- readBackPrivate = await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
705
- readBackPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
1099
+ readBackPrivate = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1100
+ readBackPublic = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
706
1101
  }
707
1102
  catch (error) {
708
1103
  logger.error('Failed to read identity back after write', error, { component: 'KeyManager' });
709
- await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
1104
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
710
1105
  throw new IdentityPersistError('Failed to verify identity after write', error);
711
1106
  }
712
1107
  // Hex comparisons are case-insensitive — normalize on both sides so a
@@ -715,7 +1110,7 @@ export class KeyManager {
715
1110
  if (readBackPrivate?.toLowerCase() !== canonicalPrivate ||
716
1111
  readBackPublic?.toLowerCase() !== canonicalPublic) {
717
1112
  logger.error('Identity round-trip mismatch after write', undefined, { component: 'KeyManager' });
718
- await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
1113
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
719
1114
  throw new IdentityPersistError('Identity write was not persisted correctly (round-trip mismatch).');
720
1115
  }
721
1116
  // Final sanity: derive public from the stored private and confirm the
@@ -736,7 +1131,7 @@ export class KeyManager {
736
1131
  }
737
1132
  }
738
1133
  catch (error) {
739
- await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
1134
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
740
1135
  if (error instanceof IdentityPersistError)
741
1136
  throw error;
742
1137
  logger.error('Identity sign/verify probe failed', error, { component: 'KeyManager' });
@@ -753,31 +1148,60 @@ export class KeyManager {
753
1148
  let priorBackupPublic;
754
1149
  let priorBackupTimestamp;
755
1150
  try {
756
- priorBackupPrivate = await store.getItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
757
- priorBackupPublic = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
758
- priorBackupTimestamp = await store.getItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP);
1151
+ priorBackupPrivate = await store.getItemAsync(layout.backupPrivateKeyName, backupReadOpts);
1152
+ priorBackupPublic = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
1153
+ priorBackupTimestamp = await store.getItemAsync(layout.backupTimestampName, backupReadOpts);
759
1154
  }
760
1155
  catch (error) {
761
1156
  logger.error('Failed to snapshot identity backup before refresh', error, { component: 'KeyManager' });
762
- await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
1157
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
763
1158
  throw new IdentityPersistError('Failed to snapshot identity backup before refresh', error);
764
1159
  }
765
1160
  try {
766
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, canonicalPrivate, {
767
- keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
768
- });
769
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, canonicalPublic);
770
- await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
1161
+ await store.setItemAsync(layout.backupPrivateKeyName, canonicalPrivate, backupPrivWriteOpts);
1162
+ await store.setItemAsync(layout.backupPublicKeyName, canonicalPublic, backupPubWriteOpts);
1163
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), backupPubWriteOpts);
771
1164
  }
772
1165
  catch (error) {
773
1166
  logger.error('Failed to refresh identity backup after primary write', error, { component: 'KeyManager' });
774
- await KeyManager._rollbackBackup(store, priorBackupPrivate, priorBackupPublic, priorBackupTimestamp);
775
- await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
1167
+ await KeyManager._rollbackBackup(store, layout, priorBackupPrivate, priorBackupPublic, priorBackupTimestamp);
1168
+ await KeyManager._rollbackPrimary(store, layout, priorPrivate, priorPublic);
776
1169
  throw new IdentityPersistError('Failed to refresh identity backup after primary write', error);
777
1170
  }
778
- // Update cache only after we are certain the identity is durable.
1171
+ // Update cache only after we are certain the identity is durable, then fan
1172
+ // out to identity-change subscribers.
779
1173
  KeyManager.cachedPublicKey = canonicalPublic;
780
1174
  KeyManager.cachedHasIdentity = true;
1175
+ KeyManager.cachedPublicKeyResolved = false;
1176
+ KeyManager.notifyIdentityChanged();
1177
+ // LAST step: mirror the identity into the AndroidKeyStore-independent marker
1178
+ // so a later keystore death can be told apart from a fresh install. This is
1179
+ // best-effort — a marker write failure must NEVER fail an otherwise-durable
1180
+ // persist (a subsequent healthy read re-backfills it). Rollback paths above
1181
+ // return before reaching here, so they never touch the marker.
1182
+ await KeyManager._syncMarkerAfterPersist(canonicalPublic, origin);
1183
+ }
1184
+ /**
1185
+ * Write/refresh the identity marker after a successful persist. A same-identity
1186
+ * re-persist (e.g. backup refresh, idempotent re-import) preserves `createdAt`
1187
+ * and the `onboardingComplete` milestone by only updating `origin`; a NEW or
1188
+ * switched identity writes a fresh marker. Best-effort — never throws.
1189
+ *
1190
+ * @internal
1191
+ */
1192
+ static async _syncMarkerAfterPersist(publicKey, origin) {
1193
+ try {
1194
+ const existing = await readIdentityMarker();
1195
+ if (existing && existing.publicKey.toLowerCase() === publicKey.toLowerCase()) {
1196
+ await updateIdentityMarker({ origin });
1197
+ }
1198
+ else {
1199
+ await writeIdentityMarker({ publicKey, origin });
1200
+ }
1201
+ }
1202
+ catch (error) {
1203
+ logger.warn('Failed to sync identity marker after persist (non-fatal)', { component: 'KeyManager' }, error);
1204
+ }
781
1205
  }
782
1206
  /**
783
1207
  * Restore the backup slot to a previously-snapshotted state. Best-effort so
@@ -785,34 +1209,35 @@ export class KeyManager {
785
1209
  *
786
1210
  * @internal
787
1211
  */
788
- static async _rollbackBackup(store, priorBackupPrivate, priorBackupPublic, priorBackupTimestamp) {
1212
+ static async _rollbackBackup(store, layout, priorBackupPrivate, priorBackupPublic, priorBackupTimestamp) {
1213
+ const backupPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.backupService);
1214
+ const backupPubWriteOpts = KeyManager._slotOpts(layout.backupService);
1215
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
789
1216
  try {
790
1217
  if (priorBackupPrivate) {
791
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, priorBackupPrivate, {
792
- keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
793
- });
1218
+ await store.setItemAsync(layout.backupPrivateKeyName, priorBackupPrivate, backupPrivWriteOpts);
794
1219
  }
795
1220
  else {
796
1221
  try {
797
- await store.deleteItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
1222
+ await store.deleteItemAsync(layout.backupPrivateKeyName, backupReadOpts);
798
1223
  }
799
1224
  catch { /* best effort */ }
800
1225
  }
801
1226
  if (priorBackupPublic) {
802
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, priorBackupPublic);
1227
+ await store.setItemAsync(layout.backupPublicKeyName, priorBackupPublic, backupPubWriteOpts);
803
1228
  }
804
1229
  else {
805
1230
  try {
806
- await store.deleteItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
1231
+ await store.deleteItemAsync(layout.backupPublicKeyName, backupReadOpts);
807
1232
  }
808
1233
  catch { /* best effort */ }
809
1234
  }
810
1235
  if (priorBackupTimestamp) {
811
- await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, priorBackupTimestamp);
1236
+ await store.setItemAsync(layout.backupTimestampName, priorBackupTimestamp, backupPubWriteOpts);
812
1237
  }
813
1238
  else {
814
1239
  try {
815
- await store.deleteItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP);
1240
+ await store.deleteItemAsync(layout.backupTimestampName, backupReadOpts);
816
1241
  }
817
1242
  catch { /* best effort */ }
818
1243
  }
@@ -830,24 +1255,25 @@ export class KeyManager {
830
1255
  *
831
1256
  * @internal
832
1257
  */
833
- static async _rollbackPrimary(store, priorPrivate, priorPublic) {
1258
+ static async _rollbackPrimary(store, layout, priorPrivate, priorPublic) {
1259
+ const primaryPrivWriteOpts = KeyManager._privateWriteOpts(store, layout.primaryService);
1260
+ const primaryPubWriteOpts = KeyManager._slotOpts(layout.primaryService);
1261
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
834
1262
  try {
835
1263
  if (priorPrivate && priorPublic) {
836
1264
  // Restore exactly what was there before the failed write.
837
- await store.setItemAsync(STORAGE_KEYS.PUBLIC_KEY, priorPublic, {});
838
- await store.setItemAsync(STORAGE_KEYS.PRIVATE_KEY, priorPrivate, {
839
- keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
840
- });
1265
+ await store.setItemAsync(layout.primaryPublicKeyName, priorPublic, primaryPubWriteOpts);
1266
+ await store.setItemAsync(layout.primaryPrivateKeyName, priorPrivate, primaryPrivWriteOpts);
841
1267
  }
842
1268
  else {
843
1269
  // There was no prior identity — leave the device empty rather than
844
1270
  // half-written so hasIdentity() does not lie.
845
1271
  try {
846
- await store.deleteItemAsync(STORAGE_KEYS.PUBLIC_KEY);
1272
+ await store.deleteItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
847
1273
  }
848
1274
  catch { /* best effort */ }
849
1275
  try {
850
- await store.deleteItemAsync(STORAGE_KEYS.PRIVATE_KEY);
1276
+ await store.deleteItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
851
1277
  }
852
1278
  catch { /* best effort */ }
853
1279
  }
@@ -877,16 +1303,50 @@ export class KeyManager {
877
1303
  // The local key IS the account — clobbering it without consent is
878
1304
  // catastrophic. Callers must opt in explicitly when they have already
879
1305
  // confirmed (via UI) that the user has saved their recovery phrase.
1306
+ //
1307
+ // The guard reads storage DIRECTLY (cache-bypassing) AND consults the
1308
+ // AndroidKeyStore-independent marker: either a stored key OR a marker means
1309
+ // an identity exists here → refuse. A storage THROW surfaces as
1310
+ // IdentityUnavailableError (never a blind write over a locked keystore).
880
1311
  if (!options?.overwrite) {
881
- const existing = await KeyManager.getPublicKey();
882
- if (existing) {
883
- throw new IdentityAlreadyExistsError(existing);
1312
+ const marker = await readIdentityMarker();
1313
+ const direct = await KeyManager._readPrimaryDirect();
1314
+ if (direct.publicKey) {
1315
+ throw new IdentityAlreadyExistsError(direct.publicKey);
1316
+ }
1317
+ if (marker) {
1318
+ throw new IdentityAlreadyExistsError(marker.publicKey);
884
1319
  }
885
1320
  }
886
1321
  const { privateKey, publicKey } = await KeyManager.generateKeyPair();
887
- await KeyManager._persistIdentityAtomic(privateKey, publicKey);
1322
+ await KeyManager._persistIdentityAtomic(privateKey, publicKey, 'create');
888
1323
  return publicKey;
889
1324
  }
1325
+ /**
1326
+ * Read the primary key pair DIRECTLY from storage, bypassing the in-memory
1327
+ * cache (which a prior transient failure could have poisoned). Awaits slot
1328
+ * migration first. Throws {@link IdentityUnavailableError} if storage is
1329
+ * deferred/locked or a read throws — so overwrite guards never write blind.
1330
+ *
1331
+ * @internal
1332
+ */
1333
+ static async _readPrimaryDirect() {
1334
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1335
+ if (migration.mode === 'deferred') {
1336
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable; refusing to write blind.', migration.cause);
1337
+ }
1338
+ const layout = migration.layout;
1339
+ const readOpts = KeyManager._slotOpts(layout.primaryService);
1340
+ try {
1341
+ const store = await initSecureStore();
1342
+ const privateKey = await store.getItemAsync(layout.primaryPrivateKeyName, readOpts);
1343
+ const publicKey = await store.getItemAsync(layout.primaryPublicKeyName, readOpts);
1344
+ return { privateKey, publicKey };
1345
+ }
1346
+ catch (error) {
1347
+ throw new IdentityUnavailableError('Could not read existing identity; refusing to write blind.', error);
1348
+ }
1349
+ }
890
1350
  /**
891
1351
  * Import an existing key pair (e.g., from recovery phrase).
892
1352
  *
@@ -909,30 +1369,53 @@ export class KeyManager {
909
1369
  const canonicalPrivate = KeyManager.canonicalPrivateKey(privateKey);
910
1370
  const keyPair = ec.keyFromPrivate(canonicalPrivate);
911
1371
  const publicKey = keyPair.getPublic('hex');
912
- // Refuse silent overwrite — see createIdentity() for rationale.
1372
+ // Refuse silent overwrite — see createIdentity() for rationale. The guard
1373
+ // reads storage DIRECTLY (cache-bypassing) AND the marker, and treats
1374
+ // storage as authoritative:
1375
+ // - stored key === this import → safe idempotent refresh (fall through)
1376
+ // - stored key differs → a DIFFERENT identity is present → refuse
1377
+ // - storage empty + marker for a DIFFERENT identity (lost state) → refuse
1378
+ // - storage empty + marker matches this import (recovery) / no marker → allow
1379
+ // A storage throw surfaces as IdentityUnavailableError (never a blind write).
913
1380
  if (!options?.overwrite) {
914
- const existing = await KeyManager.getPublicKey();
915
- if (existing && existing.toLowerCase() !== publicKey.toLowerCase()) {
916
- throw new IdentityAlreadyExistsError(existing);
917
- }
918
- // If existing === publicKey, the device already has this exact identity;
919
- // re-persisting is a no-op but harmless. Fall through to ensure backup
920
- // is up to date.
921
- }
922
- await KeyManager._persistIdentityAtomic(canonicalPrivate, publicKey);
1381
+ const marker = await readIdentityMarker();
1382
+ const direct = await KeyManager._readPrimaryDirect();
1383
+ const importedPub = publicKey.toLowerCase();
1384
+ const existingPub = direct.publicKey?.toLowerCase() ?? null;
1385
+ const markerPub = marker?.publicKey.toLowerCase() ?? null;
1386
+ if (existingPub && existingPub !== importedPub) {
1387
+ throw new IdentityAlreadyExistsError(direct.publicKey);
1388
+ }
1389
+ if (!existingPub && markerPub && markerPub !== importedPub) {
1390
+ throw new IdentityAlreadyExistsError(marker?.publicKey);
1391
+ }
1392
+ // Otherwise: existing === import (idempotent refresh), or storage empty
1393
+ // with a matching/absent marker (fresh import or lost-identity recovery)
1394
+ // → fall through and (re-)persist to refresh the backup + marker.
1395
+ }
1396
+ await KeyManager._persistIdentityAtomic(canonicalPrivate, publicKey, 'import');
923
1397
  return publicKey;
924
1398
  }
925
1399
  /**
926
1400
  * Get the stored private key
927
1401
  * WARNING: Only use this for signing operations within the app
1402
+ *
1403
+ * Preserves the "return null on any storage failure" contract signing paths
1404
+ * rely on (a locked keychain simply means "cannot sign now"); unlike
1405
+ * {@link getPublicKey}, it does NOT throw {@link IdentityUnavailableError}.
928
1406
  */
929
1407
  static async getPrivateKey() {
930
1408
  if (isWebPlatform()) {
931
1409
  return null; // Identity storage is only available on native platforms
932
1410
  }
933
1411
  try {
1412
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1413
+ if (migration.mode === 'deferred') {
1414
+ // Storage unreadable right now — preserve the null contract.
1415
+ return null;
1416
+ }
934
1417
  const store = await initSecureStore();
935
- return await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
1418
+ return await store.getItemAsync(migration.layout.primaryPrivateKeyName, KeyManager._slotOpts(migration.layout.primaryService));
936
1419
  }
937
1420
  catch (error) {
938
1421
  // If secure store is not available, return null (no identity)
@@ -944,7 +1427,12 @@ export class KeyManager {
944
1427
  }
945
1428
  }
946
1429
  /**
947
- * Get the stored public key (cached for performance)
1430
+ * Get the stored public key (cached for performance).
1431
+ *
1432
+ * Returns the public key, or `null` when a read SUCCEEDS and finds none.
1433
+ * THROWS {@link IdentityUnavailableError} when storage is unreadable (keychain
1434
+ * locked / module load failure) — a thrown read is NEVER flattened to `null`
1435
+ * and NEVER cached, so a poisoned "no identity" verdict can no longer stick.
948
1436
  */
949
1437
  static async getPublicKey() {
950
1438
  if (isWebPlatform()) {
@@ -953,21 +1441,34 @@ export class KeyManager {
953
1441
  if (KeyManager.cachedPublicKey !== null) {
954
1442
  return KeyManager.cachedPublicKey;
955
1443
  }
1444
+ // A genuine-absent result (read succeeded, empty) is cacheable distinctly
1445
+ // from a thrown read — only the former sets this flag.
1446
+ if (KeyManager.cachedPublicKeyResolved) {
1447
+ return null;
1448
+ }
1449
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1450
+ if (migration.mode === 'deferred') {
1451
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable (keychain locked or unreadable).', migration.cause);
1452
+ }
956
1453
  try {
957
1454
  const store = await initSecureStore();
958
- const publicKey = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
959
- // Cache result (null is a valid cache value meaning no identity)
960
- KeyManager.cachedPublicKey = publicKey;
1455
+ const publicKey = await store.getItemAsync(migration.layout.primaryPublicKeyName, KeyManager._slotOpts(migration.layout.primaryService));
1456
+ if (publicKey !== null) {
1457
+ KeyManager.cachedPublicKey = publicKey;
1458
+ }
1459
+ else {
1460
+ // Genuine-absent (successful empty read) IS safe to cache.
1461
+ KeyManager.cachedPublicKeyResolved = true;
1462
+ }
961
1463
  return publicKey;
962
1464
  }
963
1465
  catch (error) {
964
- // If secure store is not available, return null (no identity)
965
- // Cache null to avoid repeated failed attempts
966
- KeyManager.cachedPublicKey = null;
1466
+ // Storage threw AFTER migration resolved transient/unavailable. Do NOT
1467
+ // cache; surface a typed error so callers never misread it as "no identity".
967
1468
  if (isDev()) {
968
1469
  logger.warn('Failed to access secure store', { component: 'KeyManager' }, error);
969
1470
  }
970
- return null;
1471
+ throw new IdentityUnavailableError('Failed to read identity from secure storage.', error);
971
1472
  }
972
1473
  }
973
1474
  /**
@@ -975,8 +1476,11 @@ export class KeyManager {
975
1476
  *
976
1477
  * Returns `true` only when BOTH the private and public keys are present,
977
1478
  * both are well-formed, AND the public key derives from the private key.
978
- * A partially-written or corrupted identity returns `false` so that
979
- * downstream code can resume the create / restore flow correctly.
1479
+ * A partially-written or corrupted identity (read succeeded, bytes empty/bad)
1480
+ * returns `false` so that downstream code can resume the create / restore flow.
1481
+ * THROWS {@link IdentityUnavailableError} when storage is unreadable — a locked
1482
+ * keychain must never be mistaken for "no identity" (the old behavior that let
1483
+ * onboarding treat a transient lock as a blank device).
980
1484
  *
981
1485
  * Note: this does NOT perform the full sign/verify roundtrip — call
982
1486
  * `verifyIdentityIntegrity()` for that.
@@ -988,23 +1492,26 @@ export class KeyManager {
988
1492
  if (KeyManager.cachedHasIdentity !== null) {
989
1493
  return KeyManager.cachedHasIdentity;
990
1494
  }
1495
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1496
+ if (migration.mode === 'deferred') {
1497
+ throw new IdentityUnavailableError('Identity storage is temporarily unavailable.', migration.cause);
1498
+ }
991
1499
  let privateKey;
992
1500
  let publicKey;
993
1501
  try {
994
1502
  const store = await initSecureStore();
995
1503
  [privateKey, publicKey] = await Promise.all([
996
- store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY),
997
- store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY),
1504
+ store.getItemAsync(migration.layout.primaryPrivateKeyName, KeyManager._slotOpts(migration.layout.primaryService)),
1505
+ store.getItemAsync(migration.layout.primaryPublicKeyName, KeyManager._slotOpts(migration.layout.primaryService)),
998
1506
  ]);
999
1507
  }
1000
1508
  catch (error) {
1001
1509
  // Storage threw — could be a transient keychain lock (e.g., background
1002
- // fetch before the device is unlocked). Do NOT cache `false`: if we
1003
- // did, the next call would skip storage entirely and return false even
1004
- // after the device is unlocked. Just return false and let the next
1005
- // call retry from storage.
1510
+ // fetch before the device is unlocked). Do NOT cache; throw a TYPED error
1511
+ // so callers distinguish "temporarily unavailable" from "genuinely absent"
1512
+ // instead of silently treating a locked keystore as a blank device.
1006
1513
  logger.error('Failed to read identity from secure storage', error, { component: 'KeyManager' });
1007
- return false;
1514
+ throw new IdentityUnavailableError('Failed to read identity from secure storage.', error);
1008
1515
  }
1009
1516
  // Storage succeeded. Now classify the result. From here onward, any
1010
1517
  // outcome is stable and safe to cache (the bytes won't change between
@@ -1058,6 +1565,75 @@ export class KeyManager {
1058
1565
  }
1059
1566
  return hasIdentity;
1060
1567
  }
1568
+ /**
1569
+ * Authoritative identity verdict — the corruption-vs-fresh-install
1570
+ * disambiguator that routing (commons) keys off of.
1571
+ *
1572
+ * - Healthy pair → `present` (and the marker is backfilled if missing or
1573
+ * pointing at a different key, `origin: 'backfill'`).
1574
+ * - Read succeeded but no healthy pair, WITH a marker → `lost` (keystore death
1575
+ * / corruption; route to recovery, NEVER to create).
1576
+ * - Read succeeded, no pair, NO marker → `absent` (a genuine fresh device; the
1577
+ * only state that may route to onboarding/create).
1578
+ * - A read THREW → `unavailable` (keychain locked); this verdict is NEVER
1579
+ * cached, so a later call re-reads.
1580
+ *
1581
+ * @param opts.bypassCache When true, never reads OR writes the in-memory cache
1582
+ * — a pure, fresh storage verdict for the auto-create interlock preflight.
1583
+ */
1584
+ static async getIdentityStatus(opts) {
1585
+ if (isWebPlatform()) {
1586
+ return { state: 'absent' }; // Identity storage is only available on native platforms
1587
+ }
1588
+ const bypassCache = opts?.bypassCache === true;
1589
+ // Read the marker FIRST (fail-open null) — it is the AndroidKeyStore-independent
1590
+ // signal that survives a keystore death.
1591
+ const marker = await readIdentityMarker();
1592
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1593
+ if (migration.mode === 'deferred') {
1594
+ return { state: 'unavailable', cause: migration.cause };
1595
+ }
1596
+ let privateKey;
1597
+ let publicKey;
1598
+ try {
1599
+ const store = await initSecureStore();
1600
+ const readOpts = KeyManager._slotOpts(migration.layout.primaryService);
1601
+ privateKey = await store.getItemAsync(migration.layout.primaryPrivateKeyName, readOpts);
1602
+ publicKey = await store.getItemAsync(migration.layout.primaryPublicKeyName, readOpts);
1603
+ }
1604
+ catch (error) {
1605
+ // Storage threw — NEVER cache this verdict; callers retry.
1606
+ return { state: 'unavailable', cause: error };
1607
+ }
1608
+ if (KeyManager._isHealthyPair(privateKey, publicKey) && publicKey) {
1609
+ const canonicalPublic = publicKey.toLowerCase();
1610
+ // Backfill the marker when missing or pointing at a DIFFERENT identity —
1611
+ // e.g. a loss that predates markers, healed on first healthy read.
1612
+ if (!marker || marker.publicKey.toLowerCase() !== canonicalPublic) {
1613
+ try {
1614
+ await writeIdentityMarker({ publicKey: canonicalPublic, origin: 'backfill' });
1615
+ }
1616
+ catch (error) {
1617
+ logger.warn('Failed to backfill identity marker', { component: 'KeyManager' }, error);
1618
+ }
1619
+ }
1620
+ if (!bypassCache) {
1621
+ KeyManager.cachedPublicKey = canonicalPublic;
1622
+ KeyManager.cachedHasIdentity = true;
1623
+ KeyManager.cachedPublicKeyResolved = false;
1624
+ }
1625
+ return { state: 'present', publicKey: canonicalPublic };
1626
+ }
1627
+ // Read succeeded but no healthy pair present.
1628
+ if (!bypassCache) {
1629
+ KeyManager.cachedHasIdentity = false;
1630
+ KeyManager.cachedPublicKeyResolved = true;
1631
+ }
1632
+ if (marker) {
1633
+ return { state: 'lost', marker };
1634
+ }
1635
+ return { state: 'absent' };
1636
+ }
1061
1637
  /**
1062
1638
  * Delete the stored identity (both keys)
1063
1639
  * Use with EXTREME caution - this is irreversible without a recovery phrase
@@ -1075,6 +1651,8 @@ export class KeyManager {
1075
1651
  throw new Error('Identity deletion requires explicit user confirmation. This is a safety measure to prevent accidental data loss.');
1076
1652
  }
1077
1653
  if (!force) {
1654
+ // May throw IdentityUnavailableError if storage is locked — correct: a
1655
+ // non-force delete must abort rather than run against an unreadable store.
1078
1656
  const hasIdentity = await KeyManager.hasIdentity();
1079
1657
  if (!hasIdentity) {
1080
1658
  return; // Nothing to delete
@@ -1095,21 +1673,38 @@ export class KeyManager {
1095
1673
  }
1096
1674
  }
1097
1675
  }
1098
- await store.deleteItemAsync(STORAGE_KEYS.PRIVATE_KEY);
1099
- await store.deleteItemAsync(STORAGE_KEYS.PUBLIC_KEY);
1100
- // Invalidate cache
1101
- KeyManager.invalidateCache();
1102
- // Also clear backup if force deletion
1676
+ // Delete the primary from the active layout (authoritative), then best-effort
1677
+ // delete BOTH generations so a stale legacy copy can never resurrect the
1678
+ // identity after deletion.
1679
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1680
+ if (migration.mode !== 'deferred') {
1681
+ const layout = migration.layout;
1682
+ const readOpts = KeyManager._slotOpts(layout.primaryService);
1683
+ await store.deleteItemAsync(layout.primaryPrivateKeyName, readOpts);
1684
+ await store.deleteItemAsync(layout.primaryPublicKeyName, readOpts);
1685
+ }
1686
+ await KeyManager._bestEffortDeleteV2Primary(store);
1687
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PRIVATE_KEY);
1688
+ await KeyManager._bestEffortDelete(store, STORAGE_KEYS.PUBLIC_KEY);
1689
+ // Also clear backups + the shared slot on force deletion, so a deleted
1690
+ // identity cannot be resurrected from any recovery source.
1103
1691
  if (force) {
1104
- try {
1105
- await store.deleteItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
1106
- await store.deleteItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
1107
- await store.deleteItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP);
1108
- }
1109
- catch (error) {
1110
- // Ignore backup deletion errors
1111
- }
1692
+ await KeyManager._bestEffortDeleteBackupsAllGenerations(store);
1693
+ await KeyManager._clearSharedSlot(store);
1112
1694
  }
1695
+ // Clear the marker AFTER key deletion succeeds — a marker must never outlive
1696
+ // its identity (a leftover marker would route a truly-absent device to
1697
+ // `recovery` instead of `welcome`).
1698
+ try {
1699
+ await clearIdentityMarker();
1700
+ }
1701
+ catch (error) {
1702
+ logger.warn('Failed to clear identity marker during delete', { component: 'KeyManager' }, error);
1703
+ }
1704
+ // Invalidate cache LAST — its subscriber fan-out fires only after both the
1705
+ // keys AND the marker are gone, so a routing subscriber that re-reads on the
1706
+ // notification observes `absent`, never a transient `lost`.
1707
+ KeyManager.invalidateCache();
1113
1708
  }
1114
1709
  /**
1115
1710
  * Backup identity to SecureStore (separate backup storage)
@@ -1121,17 +1716,23 @@ export class KeyManager {
1121
1716
  }
1122
1717
  try {
1123
1718
  const store = await initSecureStore();
1124
- const privateKey = await KeyManager.getPrivateKey();
1125
- const publicKey = await KeyManager.getPublicKey();
1719
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1720
+ if (migration.mode === 'deferred') {
1721
+ return false; // Cannot read the primary safely → nothing to back up
1722
+ }
1723
+ const layout = migration.layout;
1724
+ // Read the primary DIRECTLY (raw) rather than via getPublicKey (which now
1725
+ // throws) — a locked keychain here should simply mean "nothing to back up".
1726
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
1727
+ const privateKey = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1728
+ const publicKey = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
1126
1729
  if (!privateKey || !publicKey) {
1127
1730
  return false; // Nothing to backup
1128
1731
  }
1129
1732
  // Store backup in SecureStore (still secure, but separate from primary storage)
1130
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, privateKey, {
1131
- keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
1132
- });
1133
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, publicKey);
1134
- await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
1733
+ await store.setItemAsync(layout.backupPrivateKeyName, privateKey, KeyManager._privateWriteOpts(store, layout.backupService));
1734
+ await store.setItemAsync(layout.backupPublicKeyName, publicKey, KeyManager._slotOpts(layout.backupService));
1735
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), KeyManager._slotOpts(layout.backupService));
1135
1736
  return true;
1136
1737
  }
1137
1738
  catch (error) {
@@ -1215,6 +1816,15 @@ export class KeyManager {
1215
1816
  }
1216
1817
  try {
1217
1818
  const store = await initSecureStore();
1819
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1820
+ if (migration.mode === 'deferred') {
1821
+ // Storage locked — refuse to restore (guard 2). Retry a later call.
1822
+ logger.warn('restoreIdentityFromBackup: identity storage unavailable. Refusing to restore.', { component: 'KeyManager' });
1823
+ return false;
1824
+ }
1825
+ const layout = migration.layout;
1826
+ const primaryReadOpts = KeyManager._slotOpts(layout.primaryService);
1827
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
1218
1828
  // Read the primary DIRECTLY (not via the error-swallowing getters) so
1219
1829
  // we can distinguish a transient read failure from a genuinely absent
1220
1830
  // key. A thrown read here means the keychain is locked/unavailable —
@@ -1223,8 +1833,8 @@ export class KeyManager {
1223
1833
  let primaryPrivate;
1224
1834
  let primaryPublic;
1225
1835
  try {
1226
- primaryPrivate = await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
1227
- primaryPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
1836
+ primaryPrivate = await store.getItemAsync(layout.primaryPrivateKeyName, primaryReadOpts);
1837
+ primaryPublic = await store.getItemAsync(layout.primaryPublicKeyName, primaryReadOpts);
1228
1838
  }
1229
1839
  catch (error) {
1230
1840
  logger.warn('restoreIdentityFromBackup: could not read primary (transient?). Refusing to restore.', { component: 'KeyManager' }, error);
@@ -1240,8 +1850,8 @@ export class KeyManager {
1240
1850
  }
1241
1851
  }
1242
1852
  // Load + validate the backup.
1243
- const backupPrivateKey = await store.getItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
1244
- const backupPublicKey = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
1853
+ const backupPrivateKey = await store.getItemAsync(layout.backupPrivateKeyName, backupReadOpts);
1854
+ const backupPublicKey = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
1245
1855
  if (!backupPrivateKey || !backupPublicKey) {
1246
1856
  return false; // No backup available
1247
1857
  }
@@ -1277,13 +1887,13 @@ export class KeyManager {
1277
1887
  // Safe to restore: rebuild the primary using the same atomic write
1278
1888
  // path createIdentity uses, including verification.
1279
1889
  try {
1280
- await KeyManager._persistIdentityAtomic(backupPrivateKey, backupPublicKey);
1890
+ await KeyManager._persistIdentityAtomic(backupPrivateKey, backupPublicKey, 'restore');
1281
1891
  }
1282
1892
  catch (error) {
1283
1893
  logger.error('Failed to persist identity restored from backup', error, { component: 'KeyManager' });
1284
1894
  return false;
1285
1895
  }
1286
- await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
1896
+ await store.setItemAsync(layout.backupTimestampName, Date.now().toString(), backupReadOpts);
1287
1897
  return true;
1288
1898
  }
1289
1899
  catch (error) {
@@ -1291,6 +1901,116 @@ export class KeyManager {
1291
1901
  return false;
1292
1902
  }
1293
1903
  }
1904
+ /**
1905
+ * Recovery ladder — restore a `lost` identity from an independent,
1906
+ * `key_v1`-surviving source WITHOUT the user re-entering their recovery phrase.
1907
+ *
1908
+ * Gated on {@link getIdentityStatus} being `lost` (marker present, keys empty):
1909
+ * - `present` / `absent` → `not-lost` (nothing to recover / nothing lost)
1910
+ * - `unavailable` → `unavailable` (keychain locked; retry later)
1911
+ *
1912
+ * Rungs, tried in order, each fully validated (well-formed + derive-match +
1913
+ * `publicKey === marker.publicKey`, so a source holding a DIFFERENT account is
1914
+ * SKIPPED, never restored):
1915
+ * 1. the v2 backup slot (independent keychain key from the primary), then
1916
+ * 2. the cross-app shared slot (Android bridge `getShared` / iOS keychain
1917
+ * group) — the copy that survives a primary+backup `key_v1` death.
1918
+ *
1919
+ * On success it re-persists via {@link _persistIdentityAtomic} (origin
1920
+ * `'restore'`) and invalidates the cache so routing re-reads `present`. When no
1921
+ * rung matches, the UI proceeds to recovery-phrase entry.
1922
+ */
1923
+ static async attemptIdentityRecovery() {
1924
+ if (isWebPlatform()) {
1925
+ return { recovered: false, reason: 'not-lost' };
1926
+ }
1927
+ const status = await KeyManager.getIdentityStatus({ bypassCache: true });
1928
+ if (status.state === 'present' || status.state === 'absent') {
1929
+ return { recovered: false, reason: 'not-lost' };
1930
+ }
1931
+ if (status.state === 'unavailable') {
1932
+ return { recovered: false, reason: 'unavailable' };
1933
+ }
1934
+ // status.state === 'lost'
1935
+ const expectedPublic = status.marker.publicKey.toLowerCase();
1936
+ let sawMismatch = false;
1937
+ // Rung 1: backup slot.
1938
+ const backupCandidate = await KeyManager._readBackupCandidate();
1939
+ if (backupCandidate) {
1940
+ if (backupCandidate.publicKey.toLowerCase() === expectedPublic) {
1941
+ if (await KeyManager._commitRecovery(backupCandidate.privateKey, backupCandidate.publicKey)) {
1942
+ return { recovered: true, source: 'backup', publicKey: backupCandidate.publicKey };
1943
+ }
1944
+ }
1945
+ else {
1946
+ sawMismatch = true;
1947
+ }
1948
+ }
1949
+ // Rung 2: cross-app shared slot.
1950
+ const sharedCandidate = await KeyManager._readSharedCandidate();
1951
+ if (sharedCandidate) {
1952
+ if (sharedCandidate.publicKey.toLowerCase() === expectedPublic) {
1953
+ if (await KeyManager._commitRecovery(sharedCandidate.privateKey, sharedCandidate.publicKey)) {
1954
+ return { recovered: true, source: 'shared', publicKey: sharedCandidate.publicKey };
1955
+ }
1956
+ }
1957
+ else {
1958
+ sawMismatch = true;
1959
+ }
1960
+ }
1961
+ // A source existed but identified a DIFFERENT account — never silently
1962
+ // switched. Report `mismatch` so the UI can require explicit confirmation.
1963
+ return { recovered: false, reason: sawMismatch ? 'mismatch' : 'no-sources' };
1964
+ }
1965
+ /** Read the active-layout backup slot as a healthy candidate, or null. @internal */
1966
+ static async _readBackupCandidate() {
1967
+ try {
1968
+ const migration = await KeyManager._ensureIdentitySlotsMigrated();
1969
+ if (migration.mode === 'deferred') {
1970
+ return null;
1971
+ }
1972
+ const layout = migration.layout;
1973
+ const backupReadOpts = KeyManager._slotOpts(layout.backupService);
1974
+ const store = await initSecureStore();
1975
+ const privateKey = await store.getItemAsync(layout.backupPrivateKeyName, backupReadOpts);
1976
+ const publicKey = await store.getItemAsync(layout.backupPublicKeyName, backupReadOpts);
1977
+ if (KeyManager._isHealthyPair(privateKey, publicKey) && privateKey && publicKey) {
1978
+ return { privateKey, publicKey };
1979
+ }
1980
+ return null;
1981
+ }
1982
+ catch (error) {
1983
+ logger.warn('Recovery: failed to read backup slot', { component: 'KeyManager' }, error);
1984
+ return null;
1985
+ }
1986
+ }
1987
+ /** Read the cross-app shared slot as a healthy candidate, or null. @internal */
1988
+ static async _readSharedCandidate() {
1989
+ try {
1990
+ const privateKey = await KeyManager.getSharedPrivateKey();
1991
+ const publicKey = await KeyManager.getSharedPublicKey();
1992
+ if (KeyManager._isHealthyPair(privateKey, publicKey) && privateKey && publicKey) {
1993
+ return { privateKey, publicKey };
1994
+ }
1995
+ return null;
1996
+ }
1997
+ catch (error) {
1998
+ logger.warn('Recovery: failed to read shared slot', { component: 'KeyManager' }, error);
1999
+ return null;
2000
+ }
2001
+ }
2002
+ /** Persist a validated recovery candidate + refresh caches/subscribers. @internal */
2003
+ static async _commitRecovery(privateKey, publicKey) {
2004
+ try {
2005
+ await KeyManager._persistIdentityAtomic(privateKey, publicKey, 'restore');
2006
+ KeyManager.invalidateCache();
2007
+ return true;
2008
+ }
2009
+ catch (error) {
2010
+ logger.error('Recovery: failed to persist recovered identity', error, { component: 'KeyManager' });
2011
+ return false;
2012
+ }
2013
+ }
1294
2014
  /**
1295
2015
  * Get the elliptic curve key object from the stored private key
1296
2016
  * Used internally for signing operations
@@ -1450,4 +2170,21 @@ KeyManager.cachedPublicKey = null;
1450
2170
  KeyManager.cachedHasIdentity = null;
1451
2171
  KeyManager.cachedSharedPublicKey = null;
1452
2172
  KeyManager.cachedHasSharedIdentity = null;
2173
+ /**
2174
+ * Distinguishes "public key genuinely absent (a successful empty read, safe to
2175
+ * cache)" from "never resolved / storage threw (must NOT be cached)". A `null`
2176
+ * {@link cachedPublicKey} alone is ambiguous — this flag makes the genuine
2177
+ * absence cacheable WITHOUT ever caching a null produced by a thrown read.
2178
+ */
2179
+ KeyManager.cachedPublicKeyResolved = false;
2180
+ /** Listeners notified synchronously whenever the identity verdict may have changed. */
2181
+ KeyManager.identityChangeListeners = new Set();
2182
+ /**
2183
+ * Memoized one-run-per-process slot migration. `slotMigrationResult` caches a
2184
+ * STABLE outcome (`v2`/`legacy`); a `deferred` outcome is intentionally not
2185
+ * cached (the in-flight promise is cleared) so a later call retries once the
2186
+ * keychain unlocks.
2187
+ */
2188
+ KeyManager.slotMigrationPromise = null;
2189
+ KeyManager.slotMigrationResult = null;
1453
2190
  export default KeyManager;