@bsv/expo-wallet-toolbox 0.12.0 → 0.14.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 (57) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/core/backup/erase.ts +7 -1
  3. package/core/backup/preference.ts +12 -4
  4. package/core/backup/push.ts +8 -1
  5. package/core/backup/status.ts +6 -2
  6. package/core/context/WalletContext.tsx +855 -238
  7. package/core/i18n/translations.tsx +376 -0
  8. package/core/identity/handleRegistry/registration.ts +57 -3
  9. package/core/index.ts +24 -1
  10. package/core/mandala/createRuntime.ts +3 -3
  11. package/core/mandala/runtime.ts +7 -2
  12. package/core/mnemonicWallet.ts +46 -40
  13. package/core/monitor/MonitorSupervisor.ts +35 -1
  14. package/core/monitor/TaskCreditInbox.ts +24 -0
  15. package/core/pay/rails/handle.ts +4 -2
  16. package/core/peerpay/outbox.ts +11 -1
  17. package/core/profiles/assertProfileEmpty.ts +287 -0
  18. package/core/profiles/discovery.ts +84 -0
  19. package/core/profiles/profileLabel.ts +13 -0
  20. package/core/profiles/profileStore.ts +265 -0
  21. package/core/profiles/purgeProfile.ts +76 -0
  22. package/core/profiles/removeProfile.ts +257 -0
  23. package/core/push/events.ts +52 -5
  24. package/core/push/identities.ts +55 -0
  25. package/core/push/profilePush.ts +143 -0
  26. package/core/push/registration.ts +362 -24
  27. package/core/push/types.ts +5 -1
  28. package/core/services/arcTokenStorage.ts +17 -2
  29. package/core/services/signingPermissionPolicy.ts +258 -0
  30. package/core/services/vault/guard.ts +55 -14
  31. package/core/services/vault/transfers.ts +6 -1
  32. package/core/services/vault/vaultStore.ts +16 -3
  33. package/core/stores/ConnectionStore.ts +11 -7
  34. package/core/toolboxConfig.ts +7 -3
  35. package/core/userAvatar.ts +12 -5
  36. package/core/walletDbRegistry.ts +73 -0
  37. package/package.json +1 -1
  38. package/ui/backupShares.ts +2 -3
  39. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  40. package/ui/components/ui/PencilEditField.tsx +5 -2
  41. package/ui/components/ui/PermissionSheet.tsx +15 -7
  42. package/ui/components/ui/protocolPrompt.ts +118 -0
  43. package/ui/components/wallet/Balance.tsx +3 -1
  44. package/ui/components/wallet/ProfileButton.tsx +92 -18
  45. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  46. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  47. package/ui/hooks/useSpendableBalance.ts +3 -1
  48. package/ui/printRecoveryShares.ts +6 -7
  49. package/ui/screens/PairScreen.tsx +2 -1
  50. package/ui/screens/ProfileScreen.tsx +195 -4
  51. package/ui/screens/SettingsScreen.tsx +8 -4
  52. package/ui/screens/VaultScreen.tsx +31 -2
  53. package/ui/screens/VaultTransferScreen.tsx +25 -2
  54. package/ui/screens/WalletCheckScreen.tsx +2 -1
  55. package/ui/screens/WalletConfigScreen.tsx +51 -21
  56. package/ui/screens/WalletHomeScreen.tsx +6 -3
  57. package/ui/tokenSeen.ts +13 -9
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Wallet profiles: one mnemonic, many wallets.
3
+ *
4
+ * Profile n is the wallet whose primary key is m/0'/n' (see mnemonicWallet.ts
5
+ * profilePaths). Each one has its own identity, database, backup account and
6
+ * network; the seed, recovery shares and app-wide settings are shared.
7
+ *
8
+ * This store is the one place that says which profile is active and which
9
+ * network each runs on. It lives in AsyncStorage rather than a wallet database
10
+ * because it has to be read BEFORE any database opens — it is what picks the
11
+ * database. Memory is authoritative and synchronous (screens and key builders
12
+ * read it during render); every write is persisted best-effort.
13
+ *
14
+ * A removed profile stays in the list as a tombstone (`deleted: true`). The
15
+ * index is the derivation path m/0'/n' and the key suffix, so it can never be
16
+ * reused: the list stays dense, `appendProfile` keeps counting past tombstones,
17
+ * and nothing that is active ever points at one.
18
+ *
19
+ * Per-profile device state (balance cache, avatar, ARC/MessageBox overrides,
20
+ * auto-approve, connections, seen-token markers) keeps its existing AsyncStorage
21
+ * key through `profileScopedKey`: profile 0 uses the bare key, profile n appends
22
+ * `__p<n>`. The index is known before any build, which an identity key is not.
23
+ */
24
+ import { useSyncExternalStore } from 'react'
25
+ import AsyncStorage from '@react-native-async-storage/async-storage'
26
+ import { DEFAULT_CHAIN, type AppChain } from '../config'
27
+
28
+ export const PROFILES_STORAGE_KEY = 'wallet_profiles_v1'
29
+
30
+ /** Matches every key `profileScopedKey` produces for a profile other than 0. */
31
+ export const PROFILE_KEY_SUFFIX_RE = /__p\d+$/
32
+
33
+ /** A sanity bound, not a product limit: no index past this is ever stored. */
34
+ export const MAX_PROFILES = 100
35
+
36
+ /** Longest private profile name, in characters. */
37
+ export const MAX_PROFILE_NAME_LENGTH = 24
38
+
39
+ export interface ProfileRecord {
40
+ index: number
41
+ network: AppChain
42
+ /** Recorded after this profile's first successful build on this device. Public. */
43
+ identityKey?: string
44
+ /** Replay this profile's remote backup on its next build (set by discovery / add). */
45
+ needsRestore?: boolean
46
+ /**
47
+ * Private label, device-only (not backed up, never published). Trimmed, at most
48
+ * MAX_PROFILE_NAME_LENGTH characters; absent = the default `profile<n+1>`.
49
+ */
50
+ name?: string
51
+ /** Tombstone: removed on this device. Keeps its index and identityKey; never profile 0. */
52
+ deleted?: true
53
+ }
54
+
55
+ export interface ProfilesState {
56
+ active: number
57
+ profiles: ProfileRecord[]
58
+ }
59
+
60
+ const CHAINS: readonly AppChain[] = ['main', 'test', 'teratest']
61
+
62
+ export function defaultProfilesState(): ProfilesState {
63
+ return { active: 0, profiles: [{ index: 0, network: DEFAULT_CHAIN }] }
64
+ }
65
+
66
+ /** Trim and cap a profile name; undefined when nothing is left (the default label applies). */
67
+ export function normalizeProfileName(raw: unknown): string | undefined {
68
+ if (typeof raw !== 'string') return undefined
69
+ // By character, not UTF-16 unit, so the cap never splits an emoji in half.
70
+ const name = Array.from(raw.trim()).slice(0, MAX_PROFILE_NAME_LENGTH).join('').trim()
71
+ return name === '' ? undefined : name
72
+ }
73
+
74
+ /** The index of the live profile closest to `from` (lower index on a tie). Profile 0 is always live. */
75
+ function nearestLive(profiles: ProfileRecord[], from: number): number {
76
+ for (let d = 0; d < profiles.length; d++) {
77
+ for (const i of [from - d, from + d]) {
78
+ if (profiles[i] && !profiles[i].deleted) return i
79
+ }
80
+ }
81
+ return 0
82
+ }
83
+
84
+ /**
85
+ * Tolerant parse: anything unreadable becomes the default, and whatever is
86
+ * readable is normalised into a dense list 0..count-1 so an index always names
87
+ * exactly one record.
88
+ */
89
+ export function parseProfilesState(raw: string | null): ProfilesState {
90
+ if (!raw) return defaultProfilesState()
91
+ let parsed: unknown
92
+ try {
93
+ parsed = JSON.parse(raw)
94
+ } catch {
95
+ return defaultProfilesState()
96
+ }
97
+ const obj = parsed as Partial<ProfilesState> | null
98
+ if (!obj || !Array.isArray(obj.profiles)) return defaultProfilesState()
99
+
100
+ const byIndex = new Map<number, ProfileRecord>()
101
+ for (const entry of obj.profiles as unknown[]) {
102
+ const r = entry as Partial<ProfileRecord> | null
103
+ if (!r || !Number.isInteger(r.index) || (r.index as number) < 0 || (r.index as number) >= MAX_PROFILES) continue
104
+ if (byIndex.has(r.index as number)) continue
105
+ const name = normalizeProfileName(r.name)
106
+ byIndex.set(r.index as number, {
107
+ index: r.index as number,
108
+ network: CHAINS.includes(r.network as AppChain) ? (r.network as AppChain) : DEFAULT_CHAIN,
109
+ ...(typeof r.identityKey === 'string' ? { identityKey: r.identityKey } : {}),
110
+ ...(r.needsRestore === true ? { needsRestore: true } : {}),
111
+ ...(name ? { name } : {}),
112
+ // Profile 0 anchors the seed (vault, discovery, the bare keys): it is never a tombstone.
113
+ ...(r.deleted === true && r.index !== 0 ? { deleted: true as const } : {})
114
+ })
115
+ }
116
+ // Dense from 0: a gap would leave an index the switcher cannot name.
117
+ const profiles: ProfileRecord[] = []
118
+ for (let i = 0; byIndex.has(i); i++) profiles.push(byIndex.get(i)!)
119
+ if (profiles.length === 0) return defaultProfilesState()
120
+
121
+ const stored =
122
+ Number.isInteger(obj.active) && (obj.active as number) < profiles.length && (obj.active as number) >= 0
123
+ ? (obj.active as number)
124
+ : 0
125
+ // Never rest on a tombstone: a crash between a removal's switch and its
126
+ // tombstone, or a store edited elsewhere, must still open a live wallet.
127
+ return { active: profiles[stored].deleted ? nearestLive(profiles, stored) : stored, profiles }
128
+ }
129
+
130
+ let state: ProfilesState = defaultProfilesState()
131
+ const listeners = new Set<() => void>()
132
+
133
+ function publish(next: ProfilesState): void {
134
+ state = next
135
+ listeners.forEach(l => l())
136
+ }
137
+
138
+ async function persist(): Promise<void> {
139
+ try {
140
+ await AsyncStorage.setItem(PROFILES_STORAGE_KEY, JSON.stringify(state))
141
+ } catch (err) {
142
+ console.warn('[profiles] persist failed', err)
143
+ }
144
+ }
145
+
146
+ /** Read the stored state into memory. Call before the first wallet build. */
147
+ export async function loadProfiles(): Promise<ProfilesState> {
148
+ let raw: string | null = null
149
+ try {
150
+ raw = await AsyncStorage.getItem(PROFILES_STORAGE_KEY)
151
+ } catch (err) {
152
+ console.warn('[profiles] load failed', err)
153
+ }
154
+ publish(parseProfilesState(raw))
155
+ return state
156
+ }
157
+
158
+ export function getProfilesState(): ProfilesState {
159
+ return state
160
+ }
161
+
162
+ export function getActiveProfileIndex(): number {
163
+ return state.active
164
+ }
165
+
166
+ export function getActiveProfile(): ProfileRecord {
167
+ const record = state.profiles[state.active]
168
+ if (record && !record.deleted) return record
169
+ return state.profiles[nearestLive(state.profiles, state.active)]
170
+ }
171
+
172
+ /** The profiles that have not been removed, in index order. Defaults to the current state. */
173
+ export function liveProfiles(from: ProfilesState = state): ProfileRecord[] {
174
+ return from.profiles.filter(p => !p.deleted)
175
+ }
176
+
177
+ export async function setActiveProfile(n: number): Promise<void> {
178
+ if (!state.profiles[n]) throw new Error(`Unknown profile index: ${n}`)
179
+ if (state.profiles[n].deleted) throw new Error(`Profile ${n} was removed`)
180
+ if (state.active === n) return
181
+ publish({ ...state, active: n })
182
+ await persist()
183
+ }
184
+
185
+ /** Append the next profile (index = current count). Does not activate it. */
186
+ export async function appendProfile(
187
+ network: AppChain = DEFAULT_CHAIN,
188
+ opts: { needsRestore?: boolean } = {}
189
+ ): Promise<ProfileRecord> {
190
+ const index = state.profiles.length
191
+ if (index >= MAX_PROFILES) throw new Error('Too many profiles')
192
+ const record: ProfileRecord = { index, network, ...(opts.needsRestore ? { needsRestore: true } : {}) }
193
+ publish({ ...state, profiles: [...state.profiles, record] })
194
+ await persist()
195
+ return record
196
+ }
197
+
198
+ export async function updateProfile(n: number, patch: Partial<Omit<ProfileRecord, 'index'>>): Promise<void> {
199
+ const current = state.profiles[n]
200
+ if (!current) return
201
+ if (patch.deleted) {
202
+ // Both would break an invariant the rest of the app leans on. A removal
203
+ // switches away first, so neither is a legitimate request.
204
+ if (n === 0) throw new Error('Profile 0 cannot be removed')
205
+ if (n === state.active) throw new Error('The active profile cannot be removed')
206
+ }
207
+ const next: ProfileRecord = { ...current, ...patch, index: n }
208
+ if (!next.needsRestore) delete next.needsRestore
209
+ if (!next.deleted) delete next.deleted
210
+ const name = normalizeProfileName(next.name)
211
+ if (name) next.name = name
212
+ else delete next.name
213
+ if (
214
+ next.network === current.network &&
215
+ next.identityKey === current.identityKey &&
216
+ next.name === current.name &&
217
+ !!next.deleted === !!current.deleted &&
218
+ !!next.needsRestore === !!current.needsRestore
219
+ ) {
220
+ return
221
+ }
222
+ const profiles = state.profiles.slice()
223
+ profiles[n] = next
224
+ publish({ ...state, profiles })
225
+ await persist()
226
+ }
227
+
228
+ /** Back to a single profile 0 and no stored record (Delete Wallet). */
229
+ export async function resetProfiles(): Promise<void> {
230
+ publish(defaultProfilesState())
231
+ try {
232
+ await AsyncStorage.removeItem(PROFILES_STORAGE_KEY)
233
+ } catch (err) {
234
+ console.warn('[profiles] reset failed', err)
235
+ }
236
+ }
237
+
238
+ export function subscribeProfiles(listener: () => void): () => void {
239
+ listeners.add(listener)
240
+ return () => {
241
+ listeners.delete(listener)
242
+ }
243
+ }
244
+
245
+ export function useProfiles(): ProfilesState {
246
+ return useSyncExternalStore(subscribeProfiles, getProfilesState, getProfilesState)
247
+ }
248
+
249
+ export function useActiveProfileIndex(): number {
250
+ return useSyncExternalStore(subscribeProfiles, getActiveProfileIndex, getActiveProfileIndex)
251
+ }
252
+
253
+ /**
254
+ * The AsyncStorage / SecureStore key for per-profile state. Profile 0 keeps the
255
+ * bare key; profile n appends `__p<n>` (SecureStore allows only [A-Za-z0-9._-]).
256
+ */
257
+ export function profileScopedKey(base: string, index: number = state.active): string {
258
+ return index === 0 ? base : `${base}__p${index}`
259
+ }
260
+
261
+ /** Test-only: forget memory and listeners. */
262
+ export function __resetProfilesForTests(): void {
263
+ state = defaultProfilesState()
264
+ listeners.clear()
265
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Everything a removed profile leaves on this device, and the sweep that takes
3
+ * it away.
4
+ *
5
+ * A profile is a function of the seed, so there is nothing on chain to delete —
6
+ * what a removal erases is local: the profile's wallet databases on every
7
+ * network, its ARC token, and the AsyncStorage keys that belong to it
8
+ * (`profileScopedKey`: the base key with `__p<n>` appended).
9
+ *
10
+ * Run once when a removal lands, and again on every launch for every tombstone
11
+ * in the store: a crash between the tombstone and this sweep must not leave a
12
+ * "removed" profile's history on disk. So it is idempotent, each step stands on
13
+ * its own (one that throws does not stop the rest), and the answer says whether
14
+ * every step ran clean — which only the retry cares about.
15
+ *
16
+ * Nothing here is imported from the app: the four things it touches arrive as
17
+ * `PurgeProfileIo`, so the sweep is testable without a device and the caller
18
+ * owns the real stores.
19
+ */
20
+ import type { ProfileRecord } from './profileStore'
21
+
22
+ export interface PurgeTarget {
23
+ index: number
24
+ /** Absent for a profile that never finished a build here, so it has no database. */
25
+ identityKey?: string
26
+ }
27
+
28
+ export interface PurgeProfileIo {
29
+ /** Every database registered for this identity (the last eight characters of its key), on every network. */
30
+ purgeDbFiles(keySuffix: string): Promise<void>
31
+ clearArcTokens(index: number): Promise<void>
32
+ getAllKeys(): Promise<readonly string[]>
33
+ removeKeys(keys: string[]): Promise<void>
34
+ }
35
+
36
+ /**
37
+ * Anchored at the end of the key, with the index in full: `__p1` must not match
38
+ * `__p10`, and profile 0 has no suffix at all so no pattern may ever match it.
39
+ */
40
+ const suffixPattern = (index: number): RegExp => new RegExp(`__p${index}$`)
41
+
42
+ /**
43
+ * Purge one profile's local data. Returns true when every step ran without
44
+ * error. A profile 0 or a non-positive index is refused outright: profile 0's
45
+ * keys are the bare ones, and sweeping by pattern could reach anything.
46
+ */
47
+ export async function purgeProfile(target: PurgeTarget, io: PurgeProfileIo): Promise<boolean> {
48
+ if (!Number.isInteger(target.index) || target.index <= 0) return false
49
+ let clean = true
50
+ const step = async (name: string, run: () => Promise<void>) => {
51
+ try {
52
+ await run()
53
+ } catch (err) {
54
+ clean = false
55
+ console.warn(`[profiles] purge of profile ${target.index} (${name}) failed`, err)
56
+ }
57
+ }
58
+
59
+ const { identityKey } = target
60
+ if (identityKey) await step('databases', () => io.purgeDbFiles(identityKey.slice(-8)))
61
+ await step('arc token', () => io.clearArcTokens(target.index))
62
+ await step('keys', async () => {
63
+ const pattern = suffixPattern(target.index)
64
+ const stale = (await io.getAllKeys()).filter(key => pattern.test(key))
65
+ if (stale.length > 0) await io.removeKeys(stale)
66
+ })
67
+ return clean
68
+ }
69
+
70
+ /** The startup retry: purge every tombstone in `profiles`. Never throws. */
71
+ export async function purgeRemovedProfiles(profiles: readonly ProfileRecord[], io: PurgeProfileIo): Promise<void> {
72
+ for (const profile of profiles) {
73
+ if (!profile.deleted) continue
74
+ await purgeProfile({ index: profile.index, identityKey: profile.identityKey }, io)
75
+ }
76
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Removing a wallet profile: what runs, in what order, and where it stops.
3
+ *
4
+ * A profile is a pure function of the seed, so it can never be destroyed — to
5
+ * remove one is to forget it on this device and withdraw its public handle. What
6
+ * makes that safe is that nothing the profile holds is left unwatched, and what
7
+ * makes it recoverable is the order: everything that can fail is done before
8
+ * anything is changed here.
9
+ *
10
+ * 1. Guards, then the proof that the profile is empty (`checkEmpty`): the open
11
+ * database and the profile's databases for every other network.
12
+ * 2. Release the handle, if the registry shows one for this identity — bounded
13
+ * in time, and followed by the proof again, since the release is a network
14
+ * round trip during which the profile's inbox tasks keep running.
15
+ * 3. (The remote backup is kept: a removed profile can reappear after a
16
+ * reinstall and seed import, empty, and be removed again.)
17
+ * 4. Disconnect the paired session — `switchToDefault` does this first thing.
18
+ * 5. Switch to profile 0 through the normal switch. Its teardown lets the
19
+ * profile's monitor finish its pass, which can still credit something, so
20
+ * once the profile is closed...
21
+ * 5b. ...its databases are checked a last time from their files (`checkClosed`):
22
+ * nothing writes to them any more, so what they hold now is final.
23
+ * 6. Only once that has landed and found nothing: tombstone the record, purge
24
+ * its databases and keys, and withdraw its push registration.
25
+ *
26
+ * Everything before 5 aborts with the store exactly as it was, and a switch that
27
+ * does not land aborts too, so a failure never strands a profile half-removed.
28
+ * A last check that finds something aborts as well: the profile stays exactly
29
+ * as it was, databases included, and profile 0 is the one that is open. The
30
+ * handle is the one thing that cannot be taken back after step 2: it was
31
+ * released first because releasing needs the live wallet's signer, which the
32
+ * switch tears down.
33
+ *
34
+ * The flow touches nothing itself. The open database, the registry, the switch
35
+ * and the stores arrive as `RemoveProfileDeps`, so the ordering is testable
36
+ * against the real profile store without a device.
37
+ */
38
+ import type { ProfileEmptyResult, RemovalBlocker } from './assertProfileEmpty'
39
+ import type { RegistrationResult } from '../identity/handleRegistry/registration'
40
+ import type { ProfileRecord } from './profileStore'
41
+
42
+ /** Why a removal was not even attempted. */
43
+ export type RemoveRefusal =
44
+ /** A recovered-key wallet has no profiles. */
45
+ | 'unsupported'
46
+ | 'profile-zero'
47
+ /** Not the open profile, or already removed. */
48
+ | 'not-active'
49
+ /** Another switch or removal is running. Set by the caller: it owns that flag. */
50
+ | 'busy'
51
+ /** The wallet is not open (still building, or its build failed), or its identity is unknown. */
52
+ | 'not-ready'
53
+ | 'offline'
54
+
55
+ /** What the registry says about this identity's handle. `failed` is no answer, which is not "none". */
56
+ export type HandleLookup = { kind: 'found'; paymail: string } | { kind: 'none' } | { kind: 'failed' }
57
+
58
+ /** The outcome of asking whether a profile could be removed now. Changes nothing. */
59
+ export type ProfileRemovalCheck =
60
+ /** `handle` is what would be released, for the confirm copy. */
61
+ | { kind: 'ok'; handle: string | null }
62
+ | { kind: 'refused'; reason: RemoveRefusal }
63
+ | { kind: 'blocked'; reasons: RemovalBlocker[] }
64
+ /** The registry could not be read or the handle could not be released: a handle that may still be held blocks removal. */
65
+ | { kind: 'handle-failed' }
66
+ | { kind: 'failed'; message: string }
67
+
68
+ export type RemoveProfileResult =
69
+ | { kind: 'removed'; index: number }
70
+ /**
71
+ * Excludes nothing from the check's own answers, so `blocked` also covers a
72
+ * profile that was empty when the removal began and was not by the time it
73
+ * had to be (money credited during the handle release or the switch). In that
74
+ * case the handle, if there was one, is already released, and after the
75
+ * switch profile 0 is the open profile; nothing else was changed.
76
+ */
77
+ | Exclude<ProfileRemovalCheck, { kind: 'ok' }>
78
+ /** The switch to profile 0 did not land. Nothing was removed; the handle, if there was one, is already released. */
79
+ | { kind: 'switch-failed' }
80
+
81
+ export interface RemoveProfileDeps {
82
+ /** The profile to remove: the one that is open. */
83
+ index: number
84
+ /** False for a recovered-key wallet. */
85
+ supported: boolean
86
+ activeIndex(): number
87
+ record(): ProfileRecord | undefined
88
+ /** The wallet for this profile is open: storage, user and signer are all there. */
89
+ ready(): boolean
90
+ online(): Promise<boolean>
91
+ /** The identity as the live wallet reports it, for a record that never stored one. */
92
+ liveIdentityKey(): Promise<string | undefined>
93
+ /**
94
+ * Finish whatever handle write is journalled, so it is not what blocks the
95
+ * check (a release that timed out leaves one behind). True when nothing is
96
+ * left outstanding.
97
+ */
98
+ settleHandleJournal(): Promise<boolean>
99
+ /**
100
+ * The proof that the profile holds nothing, for this identity: the open
101
+ * database AND its databases for every other network, since removal deletes all
102
+ * of them. Asked once before the handle is released and, when a handle was
103
+ * released, again after.
104
+ */
105
+ checkEmpty(identityKey: string): Promise<ProfileEmptyResult>
106
+ /** Asked of the registry by the identity, which is what the registry keys a handle on. */
107
+ lookupHandle(identityKey: string): Promise<HandleLookup>
108
+ releaseHandle(paymail: string): Promise<RegistrationResult>
109
+ /** The normal switch, with its cover. True when profile 0 is open and built. */
110
+ switchToDefault(): Promise<boolean>
111
+ /**
112
+ * What the profile's databases hold now that its wallet is down — every file
113
+ * registered for the identity, read from the files themselves. Asked after the
114
+ * switch has landed, so whatever the profile's monitor credited while it shut
115
+ * down is in them.
116
+ */
117
+ checkClosed(identityKey: string): Promise<ProfileEmptyResult>
118
+ tombstone(identityKey: string): Promise<void>
119
+ purge(target: { index: number; identityKey: string }): Promise<void>
120
+ /** The push hook: withdraw this identity's device registration. Best effort, never a reason to fail. */
121
+ unregisterPush(target: { index: number; identityKey: string }): Promise<void>
122
+ }
123
+
124
+ /**
125
+ * How long the registry gets to answer a release. The wallet is untouched until
126
+ * it has, so waiting costs only the cover; a registry that never answers must
127
+ * not hold the cover up for good. A release that lands after this has no effect
128
+ * here but a handle released: its journal is finished by the next attempt.
129
+ */
130
+ export const HANDLE_RELEASE_TIMEOUT_MS = 20_000
131
+
132
+ const messageOf = (e: unknown): string => (e instanceof Error ? e.message : String(e))
133
+
134
+ /** `work`'s result, or `undefined` once `ms` have passed. Leaves no timer behind. */
135
+ async function within<T>(work: Promise<T>, ms: number): Promise<T | undefined> {
136
+ let timer: ReturnType<typeof setTimeout> | undefined
137
+ const timeout = new Promise<undefined>(resolve => {
138
+ timer = setTimeout(() => resolve(undefined), ms)
139
+ })
140
+ try {
141
+ return await Promise.race([work, timeout])
142
+ } finally {
143
+ clearTimeout(timer)
144
+ }
145
+ }
146
+
147
+ /**
148
+ * The guards that need no network and no wallet call: whether this profile may
149
+ * be removed at all. The caller can ask before it starts a transition, so a
150
+ * profile that was never eligible does not flash a cover.
151
+ */
152
+ export function removalRefusal(deps: RemoveProfileDeps): RemoveRefusal | null {
153
+ if (!deps.supported) return 'unsupported'
154
+ if (deps.index === 0) return 'profile-zero'
155
+ const record = deps.record()
156
+ if (!record || record.deleted || deps.activeIndex() !== deps.index) return 'not-active'
157
+ if (!deps.ready()) return 'not-ready'
158
+ return null
159
+ }
160
+
161
+ /** Guards, the emptiness proof and the handle lookup: everything that changes nothing. */
162
+ async function prepare(
163
+ deps: RemoveProfileDeps
164
+ ): Promise<
165
+ { kind: 'ready'; identityKey: string; handle: string | null } | Exclude<ProfileRemovalCheck, { kind: 'ok' }>
166
+ > {
167
+ const refusal = removalRefusal(deps)
168
+ if (refusal) return { kind: 'refused', reason: refusal }
169
+ const record = deps.record()
170
+ try {
171
+ // The tombstone keeps the identity, and the purge finds the databases by it.
172
+ const identityKey = record?.identityKey ?? (await deps.liveIdentityKey())
173
+ if (!identityKey) return { kind: 'refused', reason: 'not-ready' }
174
+ if (!(await deps.online())) return { kind: 'refused', reason: 'offline' }
175
+
176
+ if (!(await deps.settleHandleJournal())) return { kind: 'handle-failed' }
177
+ const empty = await deps.checkEmpty(identityKey)
178
+ if (!empty.ok) return { kind: 'blocked', reasons: empty.reasons }
179
+
180
+ const lookup = await deps.lookupHandle(identityKey)
181
+ if (lookup.kind === 'failed') return { kind: 'handle-failed' }
182
+ return { kind: 'ready', identityKey, handle: lookup.kind === 'found' ? lookup.paymail : null }
183
+ } catch (e) {
184
+ return { kind: 'failed', message: messageOf(e) }
185
+ }
186
+ }
187
+
188
+ /** Would removing this profile work right now? Reads and decides; changes nothing. */
189
+ export async function checkProfileRemoval(deps: RemoveProfileDeps): Promise<ProfileRemovalCheck> {
190
+ const prepared = await prepare(deps)
191
+ return prepared.kind === 'ready' ? { kind: 'ok', handle: prepared.handle } : prepared
192
+ }
193
+
194
+ export async function removeProfileFlow(deps: RemoveProfileDeps): Promise<RemoveProfileResult> {
195
+ const prepared = await prepare(deps)
196
+ if (prepared.kind !== 'ready') return prepared
197
+ const { identityKey, handle } = prepared
198
+ const target = { index: deps.index, identityKey }
199
+
200
+ // Step 2. Only a `released` answer means the handle is gone: any other kind
201
+ // (including an unrelated journal finished in its place), and no answer in
202
+ // time, leave it held.
203
+ if (handle !== null) {
204
+ try {
205
+ const released = await within(deps.releaseHandle(handle), HANDLE_RELEASE_TIMEOUT_MS)
206
+ if (released?.kind !== 'released') return { kind: 'handle-failed' }
207
+ // The release was a network round trip, and the profile's inbox tasks kept
208
+ // running throughout: what they credited since the proof above is not in it.
209
+ const again = await deps.checkEmpty(identityKey)
210
+ if (!again.ok) return { kind: 'blocked', reasons: again.reasons }
211
+ } catch (e) {
212
+ return { kind: 'failed', message: messageOf(e) }
213
+ }
214
+ }
215
+
216
+ // Steps 4 and 5. A `true` from the switch is not enough: it also answers true
217
+ // for a build that was overtaken (a logout, say), which says nothing about
218
+ // where the store points. Profile 0 must be the open one before anything is
219
+ // tombstoned.
220
+ let landed = false
221
+ try {
222
+ landed = await deps.switchToDefault()
223
+ } catch {
224
+ landed = false
225
+ }
226
+ if (!landed || deps.activeIndex() !== 0) return { kind: 'switch-failed' }
227
+
228
+ // Step 5b. The switch let the profile's monitor finish its pass before its
229
+ // storage was closed, and that pass can credit a payment after every proof so
230
+ // far. Nothing writes to the databases now, so this is the last word: anything
231
+ // in them, or any failure to look, keeps them.
232
+ try {
233
+ const left = await deps.checkClosed(identityKey)
234
+ if (!left.ok) return { kind: 'blocked', reasons: left.reasons }
235
+ } catch (e) {
236
+ return { kind: 'failed', message: messageOf(e) }
237
+ }
238
+
239
+ // Step 6. The tombstone is the removal; what follows is cleanup that the
240
+ // startup retry repeats, so it can fail without undoing anything.
241
+ try {
242
+ await deps.tombstone(identityKey)
243
+ } catch (e) {
244
+ return { kind: 'failed', message: messageOf(e) }
245
+ }
246
+ try {
247
+ await deps.purge(target)
248
+ } catch (err) {
249
+ console.warn(`[profiles] purge of removed profile ${deps.index} failed; it is retried at startup`, err)
250
+ }
251
+ try {
252
+ await deps.unregisterPush(target)
253
+ } catch (err) {
254
+ console.warn(`[profiles] push unregister for removed profile ${deps.index} failed`, err)
255
+ }
256
+ return { kind: 'removed', index: deps.index }
257
+ }
@@ -1,4 +1,4 @@
1
- import type { PushAdapter } from './types'
1
+ import type { PushAdapter, PushOpenedEvent } from './types'
2
2
 
3
3
  let initialConsumed = false
4
4
  /** Test-only. */
@@ -45,6 +45,17 @@ function subscribe(what: string, attach: () => () => void): () => void {
45
45
  * "look at the inbox now": the credit, sound and toast come from the normal
46
46
  * TaskCreditInbox pass, so nothing is shown or credited twice.
47
47
  *
48
+ * Every profile of the wallet registers this device, so a push can be for a
49
+ * profile that is not the open one. The server says which in `data.recipient`
50
+ * (the recipient's identity key) and `resolveInactiveProfile` maps it to a live
51
+ * profile that is not open. Only that positive match changes anything:
52
+ * - a tap switches to that profile first, then does what a tap always did;
53
+ * - a foreground message does not run the open profile's inbox pass, which
54
+ * would read a different MessageBox and credit nothing.
55
+ * A push with no recipient (a server from before it was sent), for the open
56
+ * profile, or for an identity this device does not know behaves exactly as it
57
+ * did before profiles had their own pushes.
58
+ *
48
59
  * Never throws — a broken adapter leaves the wallet exactly as it was without
49
60
  * push.
50
61
  */
@@ -53,19 +64,52 @@ export function attachPushHandlers(args: {
53
64
  requestInboxPass: () => void
54
65
  openActivity: () => void
55
66
  onTokenRefresh: () => void
67
+ /** The index of the live, non-open profile whose identity key is `recipient`; undefined for anything else. */
68
+ resolveInactiveProfile?: (recipient: string) => number | undefined
69
+ /** Make profile `index` the open one. Resolves true once it is; false (or a throw) when it could not be. */
70
+ switchProfile?: (index: number) => Promise<boolean>
56
71
  }): () => void {
57
- const { adapter, requestInboxPass, openActivity, onTokenRefresh } = args
58
- const opened = () => {
72
+ const { adapter, requestInboxPass, openActivity, onTokenRefresh, resolveInactiveProfile, switchProfile } = args
73
+
74
+ const inactiveProfileOf = (e: PushOpenedEvent | undefined | null): number | undefined => {
75
+ const recipient = e?.data?.recipient
76
+ if (!resolveInactiveProfile || typeof recipient !== 'string' || recipient === '') return undefined
77
+ try {
78
+ return resolveInactiveProfile(recipient)
79
+ } catch (err) {
80
+ warn('resolveInactiveProfile', err)
81
+ return undefined
82
+ }
83
+ }
84
+
85
+ const openOpenProfile = () => {
59
86
  guarded('requestInboxPass', requestInboxPass)
60
87
  guarded('openActivity', openActivity)
61
88
  }
89
+ const switchThenOpen = async (index: number) => {
90
+ let landed = false
91
+ try {
92
+ landed = (await switchProfile?.(index)) === true
93
+ } catch (err) {
94
+ warn('switchProfile', err)
95
+ }
96
+ // A switch that did not land leaves the user on the profile they were on,
97
+ // whose Activity has nothing to do with this push.
98
+ if (landed) openOpenProfile()
99
+ }
100
+ const opened = (e?: PushOpenedEvent | null) => {
101
+ const index = inactiveProfileOf(e)
102
+ if (index === undefined || !switchProfile) return openOpenProfile()
103
+ void switchThenOpen(index)
104
+ }
105
+
62
106
  if (!initialConsumed) {
63
107
  initialConsumed = true
64
108
  try {
65
109
  void adapter
66
110
  .getInitialNotification()
67
111
  .then(e => {
68
- if (e) opened()
112
+ if (e) opened(e)
69
113
  })
70
114
  .catch(e => warn('getInitialNotification', e))
71
115
  } catch (e) {
@@ -75,7 +119,10 @@ export function attachPushHandlers(args: {
75
119
  const offs = [
76
120
  subscribe('onNotificationOpened', () => adapter.onNotificationOpened(opened)),
77
121
  subscribe('onForegroundMessage', () =>
78
- adapter.onForegroundMessage(() => guarded('requestInboxPass', requestInboxPass))
122
+ adapter.onForegroundMessage(e => {
123
+ if (inactiveProfileOf(e) !== undefined) return
124
+ guarded('requestInboxPass', requestInboxPass)
125
+ })
79
126
  ),
80
127
  subscribe('onTokenRefresh', () => adapter.onTokenRefresh(() => guarded('onTokenRefresh', onTokenRefresh)))
81
128
  ]