@bsv/expo-wallet-toolbox 0.11.8 → 0.13.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 (62) hide show
  1. package/CHANGELOG.md +159 -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/config.tsx +1 -1
  7. package/core/context/WalletContext.tsx +904 -184
  8. package/core/i18n/translations.tsx +496 -12
  9. package/core/identity/handleRegistry/registration.ts +57 -3
  10. package/core/index.ts +26 -1
  11. package/core/mandala/createRuntime.ts +3 -3
  12. package/core/mandala/runtime.ts +7 -2
  13. package/core/mnemonicWallet.ts +46 -40
  14. package/core/monitor/MonitorSupervisor.ts +35 -1
  15. package/core/monitor/TaskCreditInbox.ts +24 -0
  16. package/core/pay/beefRepair.ts +8 -3
  17. package/core/pay/rails/address.ts +43 -3
  18. package/core/pay/rails/handle.ts +5 -3
  19. package/core/pay/sweeper.ts +39 -4
  20. package/core/peerpay/outbox.ts +11 -1
  21. package/core/profiles/assertProfileEmpty.ts +287 -0
  22. package/core/profiles/discovery.ts +84 -0
  23. package/core/profiles/profileLabel.ts +13 -0
  24. package/core/profiles/profileStore.ts +265 -0
  25. package/core/profiles/purgeProfile.ts +76 -0
  26. package/core/profiles/removeProfile.ts +257 -0
  27. package/core/push/events.ts +189 -0
  28. package/core/push/identities.ts +55 -0
  29. package/core/push/profilePush.ts +143 -0
  30. package/core/push/pushAdvisory.ts +33 -0
  31. package/core/push/registration.ts +391 -0
  32. package/core/push/types.ts +35 -0
  33. package/core/services/arcTokenStorage.ts +17 -2
  34. package/core/services/vault/transfers.ts +6 -1
  35. package/core/services/vault/vaultStore.ts +16 -3
  36. package/core/stores/ConnectionStore.ts +11 -7
  37. package/core/toolboxConfig.ts +31 -4
  38. package/core/userAvatar.ts +12 -5
  39. package/core/walletDbRegistry.ts +73 -0
  40. package/package.json +1 -1
  41. package/ui/backupShares.ts +2 -3
  42. package/ui/components/pay/HandleReceive.tsx +141 -16
  43. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  44. package/ui/components/pay/NotificationAdvisoryModal.tsx +124 -0
  45. package/ui/components/ui/PencilEditField.tsx +5 -2
  46. package/ui/components/wallet/Balance.tsx +3 -1
  47. package/ui/components/wallet/ProfileButton.tsx +92 -18
  48. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  49. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  50. package/ui/hooks/useSpendableBalance.ts +3 -1
  51. package/ui/index.ts +1 -0
  52. package/ui/printRecoveryShares.ts +6 -7
  53. package/ui/screens/PairScreen.tsx +2 -1
  54. package/ui/screens/PayScreen.tsx +53 -0
  55. package/ui/screens/ProfileScreen.tsx +195 -4
  56. package/ui/screens/SettingsScreen.tsx +80 -6
  57. package/ui/screens/VaultScreen.tsx +31 -2
  58. package/ui/screens/VaultTransferScreen.tsx +25 -2
  59. package/ui/screens/WalletCheckScreen.tsx +2 -1
  60. package/ui/screens/WalletConfigScreen.tsx +51 -21
  61. package/ui/screens/WalletHomeScreen.tsx +6 -3
  62. package/ui/tokenSeen.ts +13 -9
@@ -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
+ }
@@ -0,0 +1,189 @@
1
+ import type { PushAdapter, PushOpenedEvent } from './types'
2
+
3
+ let initialConsumed = false
4
+ /** Test-only. */
5
+ export function __resetInitialNotificationForTests(): void {
6
+ initialConsumed = false
7
+ }
8
+
9
+ /**
10
+ * Push failures are contained, never thrown, but they are not silent: a
11
+ * swallowed failure with no trace is how "push never works on this build"
12
+ * becomes impossible to diagnose. Only the error message is logged — never the
13
+ * push payload, the FCM token or an identity key.
14
+ */
15
+ function warn(what: string, e: unknown): void {
16
+ console.warn(`[push] ${what} failed: ${e instanceof Error ? e.message : String(e)}`)
17
+ }
18
+
19
+ /** Run `fn`, containing a throw: push is an enhancement and must never break its caller. */
20
+ function guarded(what: string, fn: () => void): void {
21
+ try {
22
+ fn()
23
+ } catch (e) {
24
+ warn(what, e)
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Subscribe inside its own try/catch. An adapter can throw synchronously when
30
+ * subscribing (the native Firebase app missing on an old dev-client binary);
31
+ * that listener is then simply absent, and the others still attach.
32
+ */
33
+ function subscribe(what: string, attach: () => () => void): () => void {
34
+ try {
35
+ const off = attach()
36
+ return typeof off === 'function' ? off : () => {}
37
+ } catch (e) {
38
+ warn(`${what} subscribe`, e)
39
+ return () => {}
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Route push events into the existing inbox machinery. A push only ever means
45
+ * "look at the inbox now": the credit, sound and toast come from the normal
46
+ * TaskCreditInbox pass, so nothing is shown or credited twice.
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
+ *
59
+ * Never throws — a broken adapter leaves the wallet exactly as it was without
60
+ * push.
61
+ */
62
+ export function attachPushHandlers(args: {
63
+ adapter: PushAdapter
64
+ requestInboxPass: () => void
65
+ openActivity: () => void
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>
71
+ }): () => void {
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 = () => {
86
+ guarded('requestInboxPass', requestInboxPass)
87
+ guarded('openActivity', openActivity)
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
+
106
+ if (!initialConsumed) {
107
+ initialConsumed = true
108
+ try {
109
+ void adapter
110
+ .getInitialNotification()
111
+ .then(e => {
112
+ if (e) opened(e)
113
+ })
114
+ .catch(e => warn('getInitialNotification', e))
115
+ } catch (e) {
116
+ warn('getInitialNotification', e)
117
+ }
118
+ }
119
+ const offs = [
120
+ subscribe('onNotificationOpened', () => adapter.onNotificationOpened(opened)),
121
+ subscribe('onForegroundMessage', () =>
122
+ adapter.onForegroundMessage(e => {
123
+ if (inactiveProfileOf(e) !== undefined) return
124
+ guarded('requestInboxPass', requestInboxPass)
125
+ })
126
+ ),
127
+ subscribe('onTokenRefresh', () => adapter.onTokenRefresh(() => guarded('onTokenRefresh', onTokenRefresh)))
128
+ ]
129
+ return () => offs.forEach(off => guarded('unsubscribe', off))
130
+ }
131
+
132
+ /**
133
+ * How long one registration sync may run before it is given up on. React
134
+ * Native's Android fetch has no default timeout, so a stalled connection would
135
+ * otherwise hold the lock below until the next wallet build.
136
+ */
137
+ export const PUSH_SYNC_TIMEOUT_MS = 30_000
138
+
139
+ /**
140
+ * Race one run against PUSH_SYNC_TIMEOUT_MS. The run itself cannot be cancelled,
141
+ * so on a timeout it is simply abandoned: whatever it settles with later (its
142
+ * rejection included) is handled by the race and ignored.
143
+ */
144
+ async function runWithTimeout(run: () => Promise<void>): Promise<void> {
145
+ let timer: ReturnType<typeof setTimeout> | undefined
146
+ const timeout = new Promise<never>((_, reject) => {
147
+ timer = setTimeout(() => reject(new Error('timed out')), PUSH_SYNC_TIMEOUT_MS)
148
+ })
149
+ try {
150
+ await Promise.race([run(), timeout])
151
+ } finally {
152
+ clearTimeout(timer)
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Serialize an async job that several triggers can fire at once (startup,
158
+ * token refresh, return to foreground). Never two runs at the same time; calls
159
+ * that land while one is in flight are folded into a single rerun after it
160
+ * finishes, not one rerun each. A run that does not finish within
161
+ * PUSH_SYNC_TIMEOUT_MS is logged and let go, so a hung request cannot block
162
+ * every later sync. The returned promise settles once the work it asked for
163
+ * has run, and never rejects.
164
+ */
165
+ export function coalesceRuns(run: () => Promise<void>): () => Promise<void> {
166
+ let inFlight: Promise<void> | undefined
167
+ let rerun = false
168
+ return () => {
169
+ if (inFlight) {
170
+ rerun = true
171
+ return inFlight
172
+ }
173
+ inFlight = (async () => {
174
+ try {
175
+ do {
176
+ rerun = false
177
+ try {
178
+ await runWithTimeout(run)
179
+ } catch (e) {
180
+ warn('registration sync', e)
181
+ }
182
+ } while (rerun)
183
+ } finally {
184
+ inFlight = undefined
185
+ }
186
+ })()
187
+ return inFlight
188
+ }
189
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The keys behind push registration for every profile of a wallet.
3
+ *
4
+ * Registering a device as a profile needs only BRC-103 authentication, which a
5
+ * `ProtoWallet` built from the profile's primary key (m/0'/n') does with exactly
6
+ * the identity key and signatures the profile's own wallet has. So a profile that
7
+ * is not open is registered without building its wallet, opening its database or
8
+ * going through its permissions manager. Nothing here derives the privileged key.
9
+ */
10
+ import { AuthFetch, PrivateKey, ProtoWallet } from '@bsv/sdk'
11
+ import { hdFromMnemonic, profilePaths } from '../mnemonicWallet'
12
+ import type { PushPost } from './registration'
13
+
14
+ export interface PushProfileKey {
15
+ index: number
16
+ primaryKey: number[]
17
+ }
18
+
19
+ /** One profile as the push sync sees it: who it is, and the wallet that signs in as it. */
20
+ export interface PushProfile {
21
+ index: number
22
+ /** Compressed public key hex, the same string as `ProfileRecord.identityKey`. */
23
+ identityKey: string
24
+ /** A `ProtoWallet`. Opaque here: only the MessageBox client and AuthFetch use it. */
25
+ wallet: unknown
26
+ }
27
+
28
+ /** Primary keys for `indices`, from ONE seed-to-root derivation (the expensive step). Throws on a bad mnemonic. */
29
+ export function derivePushProfileKeys(mnemonic: string, indices: readonly number[]): PushProfileKey[] {
30
+ if (indices.length === 0) return []
31
+ const hd = hdFromMnemonic(mnemonic)
32
+ return indices.map(index => ({ index, primaryKey: hd.derive(profilePaths(index).primary).privKey.toArray() }))
33
+ }
34
+
35
+ export function makePushProfile(index: number, primaryKey: number[]): PushProfile {
36
+ const key = new PrivateKey(primaryKey)
37
+ return { index, identityKey: key.toPublicKey().toString(), wallet: new ProtoWallet(key) }
38
+ }
39
+
40
+ /**
41
+ * `POST` JSON through an AuthFetch signed in as `wallet`'s identity. Resolves with
42
+ * the status of whatever the server answered, any status; rejects only when no
43
+ * answer came. A fresh AuthFetch per call: each runs its own handshake, and none
44
+ * outlives its request.
45
+ */
46
+ export function authPostFor(wallet: unknown): PushPost {
47
+ return async (url, body) => {
48
+ const response = await new AuthFetch(wallet as never).fetch(url, {
49
+ method: 'POST',
50
+ headers: { 'Content-Type': 'application/json' },
51
+ body: JSON.stringify(body)
52
+ })
53
+ return { status: response.status }
54
+ }
55
+ }