@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,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
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Push for every profile of a wallet, for the life of one wallet build.
3
+ *
4
+ * One install has one FCM token, and every live profile registers it with its
5
+ * own MessageBox host under its own identity (see registration.ts), so a payment
6
+ * to any profile wakes the phone. Everything the sync needs about the profiles is
7
+ * handed in once, when the build is wired — their identities and signing wallets,
8
+ * and how to read a host or tell whether a profile is still wanted — so the sync
9
+ * can run from any trigger without reaching for the open profile.
10
+ */
11
+ import { coalesceRuns } from './events'
12
+ import type { PushProfile } from './identities'
13
+ import {
14
+ syncPushRegistrations,
15
+ unregisterPushIdentity,
16
+ type PushMarkerStorage,
17
+ type PushPost,
18
+ type PushTarget,
19
+ type RegisterDeviceClient
20
+ } from './registration'
21
+ import type { PushAdapter } from './types'
22
+
23
+ export interface ProfilePushDeps {
24
+ adapter: PushAdapter | undefined
25
+ /** Every live profile of this build, the open one included. */
26
+ profiles: readonly PushProfile[]
27
+ /** The profile this build belongs to: it registers last. */
28
+ activeIndex: number
29
+ /** That profile's MessageBox host, read from its own settings; undefined when MessageBox is off for it. */
30
+ readHost(index: number): Promise<string | undefined>
31
+ /** False once the profile was removed or this build was replaced. Asked at every step. */
32
+ isCurrent(index: number): boolean
33
+ /**
34
+ * True once the profile was removed (as opposed to this build being replaced).
35
+ * A registration that lands for a removed profile is withdrawn at once.
36
+ */
37
+ isRemoved?(index: number): boolean
38
+ /**
39
+ * Profiles that were removed earlier and whose registration is still on record
40
+ * (their withdrawal did not get through). Never registered and never routed to:
41
+ * each sync just asks once more to withdraw whatever this device still has
42
+ * recorded for them, signing in as them.
43
+ */
44
+ retired?: readonly PushProfile[]
45
+ makeClient(wallet: unknown, host: string): RegisterDeviceClient
46
+ makePost(wallet: unknown): PushPost
47
+ storage?: PushMarkerStorage
48
+ }
49
+
50
+ export interface ProfilePush {
51
+ /** Register every profile that needs it. Serialised and coalesced; never rejects. */
52
+ sync(): Promise<void>
53
+ /**
54
+ * Withdraw the registrations of `identityKeys` (every profile of this build, the
55
+ * retired ones included, when omitted), all at once. Best effort and bounded in
56
+ * time: never rejects. A registration whose withdrawal did not get through stays
57
+ * on record, and a later build asks again (see `retired`).
58
+ */
59
+ unregister(identityKeys?: readonly string[]): Promise<void>
60
+ /** The index of the live profile, other than the open one, whose identity key is `recipient`. */
61
+ inactiveProfileFor(recipient: string): number | undefined
62
+ }
63
+
64
+ const sameKey = (a: string, b: string) => a.toLowerCase() === b.toLowerCase()
65
+
66
+ export function createProfilePush(deps: ProfilePushDeps): ProfilePush {
67
+ const { adapter, profiles, activeIndex, storage } = deps
68
+ const retired = deps.retired ?? []
69
+
70
+ const sync = coalesceRuns(async () => {
71
+ if (!adapter) return
72
+ const live = profiles.filter(p => deps.isCurrent(p.index))
73
+ const targets: PushTarget[] = await Promise.all(
74
+ live.map(async p => {
75
+ let host: string | undefined
76
+ try {
77
+ host = await deps.readHost(p.index)
78
+ } catch (e) {
79
+ console.warn(`[push] could not read the MessageBox host: ${e instanceof Error ? e.message : String(e)}`)
80
+ }
81
+ return {
82
+ index: p.index,
83
+ identityKey: p.identityKey,
84
+ host,
85
+ active: p.index === activeIndex,
86
+ makeClient: (h: string) => deps.makeClient(p.wallet, h),
87
+ isCurrent: () => deps.isCurrent(p.index),
88
+ isRemoved: () => deps.isRemoved?.(p.index) ?? false,
89
+ // Built when it is needed, not now: only a late registration uses it.
90
+ post: (url, body) => deps.makePost(p.wallet)(url, body)
91
+ }
92
+ })
93
+ )
94
+ const results = await syncPushRegistrations({ adapter, targets, storage })
95
+ if (results.some(r => r.result === 'failed'))
96
+ console.warn('[push] device registration with the MessageBox host failed')
97
+ await withdrawRetired()
98
+ })
99
+
100
+ /** Ask once more for every removed profile whose withdrawal did not get through. Nothing to ask means no request. */
101
+ const withdrawRetired = async (): Promise<void> => {
102
+ await Promise.all(
103
+ retired.map(async p => {
104
+ try {
105
+ await unregisterPushIdentity({ identityKey: p.identityKey, post: deps.makePost(p.wallet), storage })
106
+ } catch (e) {
107
+ console.warn(`[push] unregister failed: ${e instanceof Error ? e.message : String(e)}`)
108
+ }
109
+ })
110
+ )
111
+ }
112
+
113
+ const unregister = async (identityKeys?: readonly string[]): Promise<void> => {
114
+ // A retired profile's key is held for exactly this: Delete Wallet is the last
115
+ // time anything can sign as it, since the seed goes with the wallet.
116
+ const held = [...profiles, ...retired]
117
+ const wanted = identityKeys ?? held.map(p => p.identityKey)
118
+ await Promise.all(
119
+ wanted.map(async identityKey => {
120
+ try {
121
+ const profile = held.find(p => sameKey(p.identityKey, identityKey))
122
+ // A key this build holds no wallet for cannot sign a request. Its marker
123
+ // stays: it is what a build that does hold the key withdraws from.
124
+ if (!profile) return
125
+ await unregisterPushIdentity({
126
+ identityKey: profile.identityKey,
127
+ post: deps.makePost(profile.wallet),
128
+ storage
129
+ })
130
+ } catch (e) {
131
+ console.warn(`[push] unregister failed: ${e instanceof Error ? e.message : String(e)}`)
132
+ }
133
+ })
134
+ )
135
+ }
136
+
137
+ const inactiveProfileFor = (recipient: string): number | undefined => {
138
+ const match = profiles.find(p => p.index !== activeIndex && sameKey(p.identityKey, recipient))
139
+ return match && deps.isCurrent(match.index) ? match.index : undefined
140
+ }
141
+
142
+ return { sync, unregister, inactiveProfileFor }
143
+ }
@@ -1,8 +1,29 @@
1
1
  import AsyncStorage from '@react-native-async-storage/async-storage'
2
2
  import type { PushAdapter } from './types'
3
3
 
4
+ /**
5
+ * What this device has registered, per identity: a JSON map from identity key to
6
+ * `<host>|<token>`. One entry per profile, because every profile of the wallet
7
+ * registers this install's token under its own identity. Holds the token and
8
+ * identity keys in clear AsyncStorage, so Delete Wallet removes it.
9
+ */
4
10
  export const PUSH_REGISTRATION_KEY = 'push_registration_v1'
5
11
 
12
+ /**
13
+ * The identity whose registration was written last. A server that keeps one
14
+ * identity per token (every server before the multi-identity change) hands the
15
+ * token to whoever registered most recently, so that identity is the one the
16
+ * device is actually reachable as. Kept next to the map rather than inside it so
17
+ * the map stays a plain identity -> `host|token` record.
18
+ */
19
+ export const PUSH_REGISTRATION_OWNER_KEY = 'push_registration_owner_v1'
20
+
21
+ /**
22
+ * How long one unregister request may run. It is awaited by Delete Wallet and by
23
+ * profile removal, neither of which may stall on a server that does not answer.
24
+ */
25
+ export const PUSH_UNREGISTER_TIMEOUT_MS = 8_000
26
+
6
27
  export interface RegisterDeviceClient {
7
28
  registerDevice(
8
29
  params: { fcmToken: string; platform?: 'ios' | 'android'; deviceId?: string },
@@ -10,44 +31,361 @@ export interface RegisterDeviceClient {
10
31
  ): Promise<unknown>
11
32
  }
12
33
 
34
+ export interface PushMarkerStorage {
35
+ getItem(k: string): Promise<string | null>
36
+ setItem(k: string, v: string): Promise<void>
37
+ removeItem(k: string): Promise<void>
38
+ }
39
+
13
40
  export type SyncResult = 'registered' | 'unchanged' | 'skipped' | 'failed'
14
41
 
42
+ export interface PushTarget {
43
+ index: number
44
+ identityKey: string
45
+ /** This profile's MessageBox host, or undefined when the user turned MessageBox off for it. */
46
+ host: string | undefined
47
+ /** The open profile. It is registered last (see syncPushRegistrations). */
48
+ active?: boolean
49
+ makeClient: (host: string) => RegisterDeviceClient
50
+ /**
51
+ * Asked again right before this target's network call, and once more when the
52
+ * answer comes back, inside the same step that would record it. False drops the
53
+ * target: the profile was removed, or the build that owns this run was
54
+ * replaced, while the run was under way. A registration that lands after that
55
+ * is not remembered (see syncOne).
56
+ */
57
+ isCurrent?: () => boolean
58
+ /**
59
+ * The profile is gone for good, as opposed to its build merely being replaced
60
+ * by another's. A registration that lands for a removed profile is withdrawn
61
+ * again: the removal's own unregister ran before there was anything to
62
+ * withdraw, and nothing would ever ask again.
63
+ */
64
+ isRemoved?: () => boolean
65
+ /** Signs in as this identity to withdraw a registration that landed late (see `isRemoved`). */
66
+ post?: PushPost
67
+ }
68
+
69
+ export interface TargetResult {
70
+ index: number
71
+ result: SyncResult
72
+ }
73
+
74
+ type Markers = Record<string, string>
75
+
76
+ /** An unreadable, legacy or foreign value reads as "nothing registered": the next sync registers again. */
77
+ function parseMarkers(raw: string | null): Markers {
78
+ if (!raw) return {}
79
+ try {
80
+ const parsed: unknown = JSON.parse(raw)
81
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {}
82
+ const markers: Markers = {}
83
+ for (const [identity, value] of Object.entries(parsed)) {
84
+ if (typeof value === 'string') markers[identity] = value
85
+ }
86
+ return markers
87
+ } catch {
88
+ return {}
89
+ }
90
+ }
91
+
92
+ /** `<host>|<token>`. An FCM token never contains a '|', so the last one splits them. */
93
+ function splitMarker(marker: string): { host: string; token: string } | undefined {
94
+ const at = marker.lastIndexOf('|')
95
+ if (at <= 0 || at === marker.length - 1) return undefined
96
+ return { host: marker.slice(0, at), token: marker.slice(at + 1) }
97
+ }
98
+
99
+ /**
100
+ * Marker updates are read-modify-write on two keys, and a sync run, a removal and
101
+ * Delete Wallet can all write at once. Run them one at a time so no update is
102
+ * lost to another's stale read. `change` returns what to write, or null to leave
103
+ * storage alone.
104
+ */
105
+ let markerQueue: Promise<unknown> = Promise.resolve()
106
+ function updateMarkers(
107
+ storage: PushMarkerStorage,
108
+ change: (markers: Markers, owner: string | null) => { markers: Markers; owner: string | null } | null
109
+ ): Promise<void> {
110
+ const run = markerQueue.then(async () => {
111
+ const markers = parseMarkers(await storage.getItem(PUSH_REGISTRATION_KEY))
112
+ const owner = await storage.getItem(PUSH_REGISTRATION_OWNER_KEY)
113
+ const next = change(markers, owner)
114
+ if (!next) return
115
+ await storage.setItem(PUSH_REGISTRATION_KEY, JSON.stringify(next.markers))
116
+ if (next.owner === null) await storage.removeItem(PUSH_REGISTRATION_OWNER_KEY)
117
+ else if (next.owner !== owner) await storage.setItem(PUSH_REGISTRATION_OWNER_KEY, next.owner)
118
+ })
119
+ markerQueue = run.catch(() => {})
120
+ return run
121
+ }
122
+
123
+ /** The markers, read in line with the updates above so a read never sees half of one. */
124
+ function readMarkers(storage: PushMarkerStorage): Promise<Markers> {
125
+ const run = markerQueue.then(async () => parseMarkers(await storage.getItem(PUSH_REGISTRATION_KEY)))
126
+ markerQueue = run.catch(() => {})
127
+ return run
128
+ }
129
+
130
+ /** Every identity this device holds a registration marker for. Never throws: an unreadable store reads as none. */
131
+ export async function readPushMarkerIdentities(storage: PushMarkerStorage = AsyncStorage): Promise<string[]> {
132
+ try {
133
+ return Object.keys(await readMarkers(storage))
134
+ } catch {
135
+ return []
136
+ }
137
+ }
138
+
139
+ /** Only the error's message is logged, with the token, identity key and host cut out of it. */
140
+ function redactedMessage(e: unknown, secrets: ReadonlyArray<string | null | undefined>): string {
141
+ const raw = e instanceof Error ? e.message : String(e)
142
+ return secrets.reduce<string>((text, secret) => (secret ? text.split(secret).join('[redacted]') : text), raw)
143
+ }
144
+
15
145
  /**
16
- * Make sure the MessageBox host knows this device's FCM token for this
17
- * identity. Idempotent: the last successful (host, identity, token) triple is
18
- * remembered, so the common case is no network call at all. Never throws —
19
- * push is an enhancement and must not take any caller down with it.
146
+ * Make sure the MessageBox host knows this device's FCM token for every profile.
147
+ * Idempotent: the last successful `host|token` is remembered per identity, so the
148
+ * common case is no network call at all. Never throws — push is an enhancement
149
+ * and must not take any caller down with it.
150
+ *
151
+ * Order matters. Inactive profiles go first and the active one last, so that on a
152
+ * server that still keeps one identity per token the active profile ends up the
153
+ * owner, as it was when only the active profile registered. For the same reason
154
+ * the active profile registers again whenever it is not the identity registered
155
+ * last: after a switch its own marker is intact, but the server may have handed
156
+ * the token to the profile just left, and an unchanged marker would never say so.
157
+ * Against a server that keeps one row per (identity, token) that re-registration
158
+ * is an idempotent upsert.
159
+ *
160
+ * A target that fails does not stop the others: its marker is left as it was, so
161
+ * the next trigger retries it.
20
162
  */
21
- export async function syncPushRegistration(args: {
163
+ export async function syncPushRegistrations(args: {
22
164
  adapter: PushAdapter | undefined
23
- host: string | undefined
24
- identityKey: string | undefined
25
- makeClient: (host: string) => RegisterDeviceClient
26
- storage?: { getItem(k: string): Promise<string | null>; setItem(k: string, v: string): Promise<void> }
27
- }): Promise<SyncResult> {
28
- const { adapter, host, identityKey, makeClient } = args
165
+ targets: readonly PushTarget[]
166
+ storage?: PushMarkerStorage
167
+ }): Promise<TargetResult[]> {
168
+ const { adapter, targets } = args
29
169
  const storage = args.storage ?? AsyncStorage
30
- if (!adapter || !host || !identityKey) return 'skipped'
170
+ if (!adapter || targets.length === 0) return targets.map(t => ({ index: t.index, result: 'skipped' }))
171
+
31
172
  let token: string | null | undefined
32
173
  try {
33
- if ((await adapter.getPermission()) !== 'granted') return 'skipped'
174
+ if ((await adapter.getPermission()) !== 'granted') return targets.map(t => ({ index: t.index, result: 'skipped' }))
34
175
  token = await adapter.getToken()
35
- if (!token) return 'skipped'
36
- const marker = `${host}|${identityKey}|${token}`
37
- if ((await storage.getItem(PUSH_REGISTRATION_KEY)) === marker) return 'unchanged'
38
- await makeClient(host).registerDevice({ fcmToken: token, platform: adapter.platform }, host)
39
- await storage.setItem(PUSH_REGISTRATION_KEY, marker)
176
+ } catch (e) {
177
+ console.warn('[push] registerDevice failed: ' + redactedMessage(e, [token]))
178
+ return targets.map(t => ({ index: t.index, result: 'failed' }))
179
+ }
180
+ if (!token) return targets.map(t => ({ index: t.index, result: 'skipped' }))
181
+
182
+ const ordered = [...targets].sort((a, b) => Number(!!a.active) - Number(!!b.active) || a.index - b.index)
183
+ const results: TargetResult[] = []
184
+ for (const target of ordered) {
185
+ results.push({ index: target.index, result: await syncOne(target, token, adapter, storage) })
186
+ }
187
+ return results
188
+ }
189
+
190
+ async function syncOne(
191
+ target: PushTarget,
192
+ token: string,
193
+ adapter: PushAdapter,
194
+ storage: PushMarkerStorage
195
+ ): Promise<SyncResult> {
196
+ const { host, identityKey } = target
197
+ if (!host) return 'skipped'
198
+ try {
199
+ const marker = `${host}|${token}`
200
+ const [markers, owner] = await Promise.all([
201
+ storage.getItem(PUSH_REGISTRATION_KEY).then(parseMarkers),
202
+ storage.getItem(PUSH_REGISTRATION_OWNER_KEY)
203
+ ])
204
+ if (markers[identityKey] === marker && !(target.active && owner !== identityKey)) return 'unchanged'
205
+ if (target.isCurrent && !target.isCurrent()) return 'skipped'
206
+ await target.makeClient(host).registerDevice({ fcmToken: token, platform: adapter.platform }, host)
207
+ // The answer took time, and the profile may have been removed or the wallet
208
+ // deleted meanwhile. Asked again INSIDE the marker update, which a removal's
209
+ // unregister also reads through: either this write lands first and the
210
+ // unregister then sees it, or the unregister ran first and this finds the
211
+ // profile gone. Writing regardless would bring back a marker (and, after
212
+ // Delete Wallet, the token and identity in clear text) that nothing withdraws.
213
+ let late = false
214
+ await updateMarkers(storage, markers => {
215
+ if (target.isCurrent && !target.isCurrent()) {
216
+ late = true
217
+ return null
218
+ }
219
+ return { markers: { ...markers, [identityKey]: marker }, owner: identityKey }
220
+ })
221
+ if (late) {
222
+ await settleLateRegistration(target, host, token, storage)
223
+ return 'skipped'
224
+ }
40
225
  return 'registered'
41
226
  } catch (e) {
42
227
  // Only the error's message is logged, so a failure is diagnosable without
43
228
  // the log ever carrying the token or the identity key. A message that
44
229
  // happens to quote the token, the identity key or the host has them cut out.
45
- const raw = e instanceof Error ? e.message : String(e)
46
- const message = [token, identityKey, host].reduce<string>(
47
- (text, secret) => (secret ? text.split(secret).join('[redacted]') : text),
48
- raw
49
- )
50
- console.warn('[push] registerDevice failed: ' + message)
230
+ console.warn('[push] registerDevice failed: ' + redactedMessage(e, [token, identityKey, host]))
231
+ return 'failed'
232
+ }
233
+ }
234
+
235
+ /** One HTTP answer. `post` resolves for any status the server sent and rejects only when no answer came. */
236
+ export type PushPost = (url: string, body: { fcmToken: string }) => Promise<{ status: number }>
237
+
238
+ export type UnregisterResult =
239
+ /** The server removed (or never had) this identity's registration. */
240
+ | 'unregistered'
241
+ /** A server that has no such endpoint yet. Nothing to withdraw there. */
242
+ | 'unsupported'
243
+ /** This device never registered the identity, so there was nothing to ask. */
244
+ | 'skipped'
245
+ | 'failed'
246
+
247
+ /** A server from before the endpoint existed answers with one of these. */
248
+ const UNSUPPORTED_STATUSES: readonly number[] = [404, 405, 501]
249
+
250
+ /** Loopback hosts may use plain HTTP, like the MessageBox client allows; everything else needs TLS. */
251
+ function isLoopback(hostname: string): boolean {
252
+ const h = hostname.toLowerCase().replace(/^\[|\]$/g, '')
253
+ return h === 'localhost' || h.endsWith('.localhost') || h === '::1' || /^127(\.\d{1,3}){3}$/.test(h)
254
+ }
255
+
256
+ /** The MessageBox host's `/unregisterDevice` URL. Throws for a host the client itself would refuse. */
257
+ function unregisterUrl(host: string): string {
258
+ const url = new URL(host)
259
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback(url.hostname))) {
260
+ throw new TypeError('MessageBox host requires HTTPS except on localhost')
261
+ }
262
+ if (url.username || url.password || url.search || url.hash) throw new TypeError('MessageBox host is not a plain URL')
263
+ return `${url.origin}${url.pathname.replace(/\/+$/, '')}/unregisterDevice`
264
+ }
265
+
266
+ /**
267
+ * One withdrawal request. `refused` is a host this client will not talk to: no
268
+ * later attempt could do any better, unlike `failed`, where the server did not
269
+ * answer or answered with an error.
270
+ */
271
+ type Withdrawal = Exclude<UnregisterResult, 'skipped'> | 'refused'
272
+
273
+ async function withdraw(
274
+ registered: { host: string; token: string },
275
+ identityKey: string,
276
+ post: PushPost
277
+ ): Promise<Withdrawal> {
278
+ const secrets = [registered.token, identityKey, registered.host]
279
+ let url: string
280
+ try {
281
+ url = unregisterUrl(registered.host)
282
+ } catch (e) {
283
+ console.warn('[push] unregisterDevice failed: ' + redactedMessage(e, secrets))
284
+ return 'refused'
285
+ }
286
+ let timer: ReturnType<typeof setTimeout> | undefined
287
+ const timeout = new Promise<never>((_, reject) => {
288
+ timer = setTimeout(() => reject(new Error('timed out')), PUSH_UNREGISTER_TIMEOUT_MS)
289
+ })
290
+ try {
291
+ const { status } = await Promise.race([post(url, { fcmToken: registered.token }), timeout])
292
+ if (status >= 200 && status < 300) return 'unregistered'
293
+ if (UNSUPPORTED_STATUSES.includes(status)) return 'unsupported'
294
+ console.warn(`[push] unregisterDevice failed: HTTP ${status}`)
295
+ return 'failed'
296
+ } catch (e) {
297
+ console.warn('[push] unregisterDevice failed: ' + redactedMessage(e, secrets))
51
298
  return 'failed'
299
+ } finally {
300
+ clearTimeout(timer)
301
+ }
302
+ }
303
+
304
+ /**
305
+ * A registration answered after its profile was removed (`isRemoved`), so the
306
+ * removal's unregister found nothing to withdraw. Withdraw it now, from the host
307
+ * and token it was just registered under. If that cannot be done, the marker is
308
+ * written after all so the retry has something to work from.
309
+ *
310
+ * A build that was merely replaced, or a wallet being deleted, is not a removal:
311
+ * the profile is still wanted (the next build registers it again, which is
312
+ * idempotent) or nothing may be left behind at all, so nothing is written and
313
+ * nothing is sent.
314
+ */
315
+ async function settleLateRegistration(
316
+ target: PushTarget,
317
+ host: string,
318
+ token: string,
319
+ storage: PushMarkerStorage
320
+ ): Promise<void> {
321
+ if (!target.isRemoved?.()) return
322
+ const { identityKey } = target
323
+ const outcome = target.post ? await withdraw({ host, token }, identityKey, target.post) : 'failed'
324
+ if (outcome !== 'failed') return
325
+ try {
326
+ await updateMarkers(storage, (markers, owner) => ({
327
+ markers: { ...markers, [identityKey]: `${host}|${token}` },
328
+ owner
329
+ }))
330
+ } catch (e) {
331
+ console.warn('[push] could not keep a registration for a retry: ' + redactedMessage(e, [token, identityKey, host]))
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Withdraw one identity's device registration, for a removed profile or a wallet
337
+ * being deleted. Best effort: it never throws, and it works from the marker, so
338
+ * it asks exactly the host and token this device registered under — a host
339
+ * changed since then, or a rotated token, still gets the right request.
340
+ *
341
+ * `POST /unregisterDevice` only exists on a server with the multi-identity
342
+ * change. An older one answers 404 (or 405/501), which is reported as
343
+ * `unsupported` and is not a failure: its single row for the token belongs to
344
+ * whichever identity registered last and is not this identity's to remove.
345
+ *
346
+ * The marker is the record of what is still registered, so it is dropped only
347
+ * once nothing is: on `unregistered` and `unsupported`, and when there was no
348
+ * usable marker to begin with (`skipped`). On `failed` (offline, a timeout, an
349
+ * error answer) it stays, and whoever can sign as the identity again asks once
350
+ * more — the next build for a removed profile (see createProfilePush's
351
+ * `retired`). Delete Wallet sweeps the markers afterwards whatever happened,
352
+ * since after it there is no seed left to retry with. A host this client would
353
+ * refuse is dropped too: no retry could ever use it.
354
+ */
355
+ export async function unregisterPushIdentity(args: {
356
+ identityKey: string
357
+ post: PushPost
358
+ storage?: PushMarkerStorage
359
+ }): Promise<UnregisterResult> {
360
+ const { identityKey, post } = args
361
+ const storage = args.storage ?? AsyncStorage
362
+ let entry: string | undefined
363
+ try {
364
+ entry = (await readMarkers(storage))[identityKey]
365
+ } catch (e) {
366
+ console.warn('[push] unregisterDevice failed: ' + redactedMessage(e, [identityKey]))
367
+ return 'failed'
368
+ }
369
+ const registered = entry === undefined ? undefined : splitMarker(entry)
370
+ if (!registered) {
371
+ // Never registered from here, or a marker nothing can read: either way nothing to ask.
372
+ await forgetPushMarker(identityKey, storage)
373
+ return 'skipped'
374
+ }
375
+ const outcome = await withdraw(registered, identityKey, post)
376
+ if (outcome !== 'failed') await forgetPushMarker(identityKey, storage)
377
+ return outcome === 'refused' ? 'failed' : outcome
378
+ }
379
+
380
+ /** Drop one identity's marker (and the owner record, if it points at that identity). Never throws. */
381
+ export async function forgetPushMarker(identityKey: string, storage: PushMarkerStorage = AsyncStorage): Promise<void> {
382
+ try {
383
+ await updateMarkers(storage, (markers, owner) => {
384
+ if (!(identityKey in markers) && owner !== identityKey) return null
385
+ const { [identityKey]: _gone, ...rest } = markers
386
+ return { markers: rest, owner: owner === identityKey ? null : owner }
387
+ })
388
+ } catch (e) {
389
+ console.warn('[push] could not clear a registration marker: ' + redactedMessage(e, [identityKey]))
52
390
  }
53
391
  }
@@ -1,7 +1,11 @@
1
1
  export type PushPermission = 'granted' | 'denied' | 'undetermined'
2
2
 
3
3
  export interface PushOpenedEvent {
4
- /** Data payload from the push (messageId, originator). */
4
+ /**
5
+ * Data payload from the push: messageId, originator, and — from a server that
6
+ * registers one device per identity — recipient (the identity key the message
7
+ * is for) and messageBox. Every value is a string.
8
+ */
5
9
  data: Record<string, string>
6
10
  }
7
11
 
@@ -1,6 +1,7 @@
1
1
  import AsyncStorage from '@react-native-async-storage/async-storage'
2
2
  import * as SecureStore from 'expo-secure-store'
3
3
  import { arcApiTokenStorageKey } from '../constants'
4
+ import { profileScopedKey } from '../profiles/profileStore'
4
5
 
5
6
  /**
6
7
  * XR-106: the custom ARC API token a holder can configure in
@@ -25,7 +26,8 @@ import { arcApiTokenStorageKey } from '../constants'
25
26
  * indefinitely.
26
27
  */
27
28
  export async function getArcApiToken(network: string): Promise<string | null> {
28
- const key = arcApiTokenStorageKey(network)
29
+ // Per wallet profile: each profile carries its own ARC endpoint and token.
30
+ const key = profileScopedKey(arcApiTokenStorageKey(network))
29
31
  const legacy = await AsyncStorage.getItem(key)
30
32
  const secure = await SecureStore.getItemAsync(key)
31
33
  if (legacy === null) return secure
@@ -40,7 +42,7 @@ export async function getArcApiToken(network: string): Promise<string | null> {
40
42
  }
41
43
 
42
44
  export async function setArcApiToken(network: string, token: string | null): Promise<void> {
43
- const key = arcApiTokenStorageKey(network)
45
+ const key = profileScopedKey(arcApiTokenStorageKey(network))
44
46
  // Always clear any plaintext copy, whether or not one exists, so this
45
47
  // function alone is enough to close out a legacy value.
46
48
  await AsyncStorage.removeItem(key)
@@ -50,3 +52,16 @@ export async function setArcApiToken(network: string, token: string | null): Pro
50
52
  await SecureStore.deleteItemAsync(key)
51
53
  }
52
54
  }
55
+
56
+ /** Delete Wallet: drop one profile's token on every network, whichever profile is active. */
57
+ export async function clearArcApiTokensForProfile(index: number): Promise<void> {
58
+ for (const network of ['main', 'test', 'teratest']) {
59
+ const key = profileScopedKey(arcApiTokenStorageKey(network), index)
60
+ try {
61
+ await AsyncStorage.removeItem(key)
62
+ await SecureStore.deleteItemAsync(key)
63
+ } catch {
64
+ // Best-effort: a token that survives is a service-config value, not a wallet secret.
65
+ }
66
+ }
67
+ }