@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,258 @@
1
+ import { Hash, Utils } from '@bsv/sdk'
2
+ import { WalletPermissionsManager } from '@bsv/wallet-toolbox-mobile'
3
+
4
+ /**
5
+ * Protocols a connected app may sign under without a protocol prompt, even
6
+ * though seekProtocolPermissionsForSigning is on.
7
+ *
8
+ * `auth message signature` is the one protocol @bsv/auth signs under: BRC-103
9
+ * mutual authentication and its BRC-104 HTTP transport (AuthFetch) both sign
10
+ * every handshake and message with it. Any site that talks to an
11
+ * authenticated server does this on its first request, so prompting for it
12
+ * would ask on nearly every connection. Names are compared the way
13
+ * KeyDeriver.computeInvoiceNumber normalizes them, since that is the key the
14
+ * signature is made with.
15
+ */
16
+ export const PROMPT_FREE_SIGNING_PROTOCOLS = new Set(['auth message signature'])
17
+
18
+ /**
19
+ * Protocols whose approval is never reused: every signature under them is
20
+ * asked for again, one call at a time. Each approval is still recorded as a
21
+ * permission token, tagged with the key ID it was given for, as a history of
22
+ * what the user approved; the manager just never looks those tokens up.
23
+ *
24
+ * BRC-29 (`3241645161d8`) is where this wallet keeps money: BSV address
25
+ * receipts (counterparty 'anyone', date key IDs), change (counterparty self)
26
+ * and payments from other parties. A grant is keyed by origin, protocol and
27
+ * counterparty, never key ID, so a reused approval for one app key would also
28
+ * cover every one of those. Asking per call keeps each signature the user's
29
+ * decision.
30
+ */
31
+ export const ASK_EVERY_TIME_PROTOCOLS = new Set(['3241645161d8'])
32
+
33
+ type EnsureProtocolPermissionArgs = Parameters<WalletPermissionsManager['ensureProtocolPermission']>[0]
34
+ type CreateSignatureArgs = Parameters<WalletPermissionsManager['createSignature']>
35
+ type VerifySignatureArgs = Parameters<WalletPermissionsManager['verifySignature']>
36
+
37
+ function protocolName(protocolID: unknown): string | undefined {
38
+ return Array.isArray(protocolID) && typeof protocolID[1] === 'string' ? protocolID[1].toLowerCase().trim() : undefined
39
+ }
40
+
41
+ export function isPromptFreeSigning({ usageType, privileged, protocolID }: EnsureProtocolPermissionArgs): boolean {
42
+ const name = protocolName(protocolID)
43
+ return usageType === 'signing' && !privileged && name !== undefined && PROMPT_FREE_SIGNING_PROTOCOLS.has(name)
44
+ }
45
+
46
+ export function isAskEveryTimeProtocol(protocolID: unknown): boolean {
47
+ const name = protocolName(protocolID)
48
+ return name !== undefined && ASK_EVERY_TIME_PROTOCOLS.has(name)
49
+ }
50
+
51
+ /** Matches the manager's protocol cache key,
52
+ * `proto:<origin>:<privileged>:<level>,<name>:<counterparty>`, capturing the
53
+ * name. Origins may carry a port, so the match anchors on the privileged flag. */
54
+ const PROTOCOL_CACHE_KEY = /^proto:.*:(?:true|false):\d+,([^:]*):/
55
+
56
+ function isAskEveryTimeCacheKey(key: unknown): boolean {
57
+ const match = typeof key === 'string' ? PROTOCOL_CACHE_KEY.exec(key) : null
58
+ return match !== null && isAskEveryTimeProtocol([2, match[1]])
59
+ }
60
+
61
+ /** Largest tag the wallet stores (validateTag: 1..300 bytes). */
62
+ const MAX_TAG_BYTES = 300
63
+
64
+ /** The token tag recording which key ID an approval was given for. Tags are
65
+ * lowercased by the wallet and key IDs are case-sensitive (often base64), so
66
+ * the key ID is stored as hex of its UTF-8 bytes, or as its SHA-256 when that
67
+ * would not fit in a tag. */
68
+ export function keyIDTag(keyID: string): string {
69
+ const bytes = Utils.toArray(keyID, 'utf8')
70
+ const tag = `keyid ${Utils.toHex(bytes)}`
71
+ return tag.length <= MAX_TAG_BYTES ? tag : `keyidhash ${Utils.toHex(Hash.sha256(bytes))}`
72
+ }
73
+
74
+ /** A protocol permission request with the key ID this class attaches to it. */
75
+ interface ProtocolRequest {
76
+ type?: string
77
+ originator?: string
78
+ protocolID?: unknown
79
+ keyID?: string
80
+ }
81
+
82
+ /** The manager's internals this class reaches. They are private in the
83
+ * typings only; __tests__/services/signingPermissionPolicy.test.ts runs
84
+ * against the real manager, so an upgrade that renames one fails there. */
85
+ interface ManagerInternals {
86
+ prepareOriginator(originator: string): { normalized: string }
87
+ activeRequests: Map<string, { request: ProtocolRequest }>
88
+ findProtocolToken(originator: string, privileged: boolean, protocolID: unknown, ...rest: unknown[]): Promise<unknown>
89
+ markRecentGrant(request: ProtocolRequest): void
90
+ cachePermission(key: string, expiry: number): void
91
+ buildTagsForRequest(request: ProtocolRequest): string[]
92
+ firePermissionRequestEvent(request: ProtocolRequest, key: string): Promise<void>
93
+ underlying: { verifySignature: WalletPermissionsManager['verifySignature'] }
94
+ fetchManifestPermissions(originator: string): Promise<ManifestPermissions>
95
+ }
96
+
97
+ /** The parts of a site's manifest.json permissions the manager reads. */
98
+ interface ManifestPermissions {
99
+ groupPermissions: { protocolPermissions?: Array<{ protocolID?: unknown }> } | null
100
+ counterpartyPermissions: { protocols?: Array<{ protocolName?: unknown }> } | null
101
+ }
102
+
103
+ /** The manifest's permissions without ASK_EVERY_TIME_PROTOCOLS. A site's
104
+ * manifest may list them in its grouped (bulk) request, but such a grant is
105
+ * never kept, so the manager would find it missing on every call and raise
106
+ * the bulk sheet again before each signature prompt. */
107
+ function withoutAskEveryTime(manifest: ManifestPermissions): ManifestPermissions {
108
+ const { groupPermissions, counterpartyPermissions } = manifest
109
+ return {
110
+ groupPermissions:
111
+ groupPermissions?.protocolPermissions == null
112
+ ? groupPermissions
113
+ : {
114
+ ...groupPermissions,
115
+ protocolPermissions: groupPermissions.protocolPermissions.filter(
116
+ p => !isAskEveryTimeProtocol(p?.protocolID)
117
+ )
118
+ },
119
+ counterpartyPermissions:
120
+ counterpartyPermissions?.protocols == null
121
+ ? counterpartyPermissions
122
+ : {
123
+ ...counterpartyPermissions,
124
+ protocols: counterpartyPermissions.protocols.filter(p => !isAskEveryTimeProtocol([2, p?.protocolName]))
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * WalletPermissionsManager with this wallet's signing policy:
131
+ * - PROMPT_FREE_SIGNING_PROTOCOLS sign with no prompt;
132
+ * - ASK_EVERY_TIME_PROTOCOLS never reuse an approval. Each one is minted as
133
+ * a token tagged with its key ID, but no token, cache entry or recent-grant
134
+ * cover is ever read back for them; a site's manifest never puts them in a
135
+ * grouped request; and one origin's createSignature calls under them run
136
+ * one at a time, so a burst of calls cannot ride on one approval;
137
+ * - a non-privileged verifySignature is never prompted.
138
+ * Every other check runs unchanged.
139
+ */
140
+ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
141
+ private readonly askEveryTimeQueues = new Map<string, Promise<unknown>>()
142
+ /** Key ID of the ask-every-time createSignature call each (normalized)
143
+ * origin has in flight. The per-origin queue keeps it to one at a time. */
144
+ private readonly keyIDInFlight = new Map<string, string>()
145
+
146
+ constructor(...args: ConstructorParameters<typeof WalletPermissionsManager>) {
147
+ super(...args)
148
+ const internals = this as unknown as ManagerInternals
149
+ const findProtocolToken = internals.findProtocolToken.bind(this)
150
+ internals.findProtocolToken = async (originator, privileged, protocolID, ...rest) =>
151
+ isAskEveryTimeProtocol(protocolID)
152
+ ? undefined
153
+ : await findProtocolToken(originator, privileged, protocolID, ...rest)
154
+ const markRecentGrant = internals.markRecentGrant.bind(this)
155
+ internals.markRecentGrant = request => {
156
+ if (request?.type === 'protocol' && isAskEveryTimeProtocol(request.protocolID)) return
157
+ markRecentGrant(request)
158
+ }
159
+ const cachePermission = internals.cachePermission.bind(this)
160
+ internals.cachePermission = (key, expiry) => {
161
+ if (isAskEveryTimeCacheKey(key)) return
162
+ cachePermission(key, expiry)
163
+ }
164
+ const buildTagsForRequest = internals.buildTagsForRequest.bind(this)
165
+ internals.buildTagsForRequest = request => {
166
+ const tags = buildTagsForRequest(request)
167
+ return typeof request?.keyID === 'string' ? [...tags, keyIDTag(request.keyID)] : tags
168
+ }
169
+ // The request object is the one the manager keeps until it is answered,
170
+ // so the key ID set here reaches both the prompt (the event's arguments
171
+ // spread it) and the token a grant mints (buildTagsForRequest above).
172
+ const firePermissionRequestEvent = internals.firePermissionRequestEvent.bind(this)
173
+ internals.firePermissionRequestEvent = async (request, key) => {
174
+ if (request?.type === 'protocol' && isAskEveryTimeProtocol(request.protocolID) && request.originator) {
175
+ const keyID = this.keyIDInFlight.get(request.originator)
176
+ if (keyID !== undefined) request.keyID = keyID
177
+ }
178
+ return await firePermissionRequestEvent(request, key)
179
+ }
180
+ const fetchManifestPermissions = internals.fetchManifestPermissions.bind(this)
181
+ internals.fetchManifestPermissions = async originator =>
182
+ withoutAskEveryTime(await fetchManifestPermissions(originator))
183
+ }
184
+
185
+ private get internals(): ManagerInternals {
186
+ return this as unknown as ManagerInternals
187
+ }
188
+
189
+ override async ensureProtocolPermission(args: EnsureProtocolPermissionArgs): Promise<boolean> {
190
+ if (isPromptFreeSigning(args)) {
191
+ // Still refuse a missing or malformed originator, as the full check
192
+ // does first.
193
+ this.internals.prepareOriginator(args.originator)
194
+ return true
195
+ }
196
+ return await super.ensureProtocolPermission(args)
197
+ }
198
+
199
+ override async createSignature(
200
+ ...args: CreateSignatureArgs
201
+ ): ReturnType<WalletPermissionsManager['createSignature']> {
202
+ return await this.oneAtATime(args[0], args[1], async () => await super.createSignature(...args))
203
+ }
204
+
205
+ /** Verifying a signature reveals nothing and spends nothing, so a
206
+ * non-privileged verification is answered without a protocol prompt. The
207
+ * originator is still validated, and admin-reserved (`admin…`) and
208
+ * module-routed (`p …`) protocols still take the manager's full path. */
209
+ override async verifySignature(
210
+ ...args: VerifySignatureArgs
211
+ ): ReturnType<WalletPermissionsManager['verifySignature']> {
212
+ const [request, originator] = args
213
+ const name = protocolName(request?.protocolID)
214
+ if (request?.privileged || name === undefined || name.startsWith('admin') || name.startsWith('p ')) {
215
+ return await super.verifySignature(...args)
216
+ }
217
+ this.internals.prepareOriginator(String(originator))
218
+ return await this.internals.underlying.verifySignature(request, originator)
219
+ }
220
+
221
+ /**
222
+ * Runs an ask-every-time createSignature call after the same origin's
223
+ * previous one. The manager hands every call already waiting on a request
224
+ * the same answer, so concurrent calls would otherwise share a single
225
+ * approval. While it runs, its key ID is what its prompt shows and what a
226
+ * grant of its request records.
227
+ */
228
+ private async oneAtATime<T>(
229
+ args: { protocolID?: unknown; keyID?: string },
230
+ originator: string | undefined,
231
+ call: () => Promise<T>
232
+ ): Promise<T> {
233
+ if (!isAskEveryTimeProtocol(args?.protocolID)) return await call()
234
+ let origin: string
235
+ try {
236
+ origin = this.internals.prepareOriginator(String(originator)).normalized
237
+ } catch {
238
+ return await call() // the manager refuses it with its own error
239
+ }
240
+ const previous = this.askEveryTimeQueues.get(origin) ?? Promise.resolve()
241
+ const current = previous
242
+ .catch(() => {})
243
+ .then(async () => {
244
+ this.keyIDInFlight.set(origin, String(args.keyID))
245
+ try {
246
+ return await call()
247
+ } finally {
248
+ this.keyIDInFlight.delete(origin)
249
+ }
250
+ })
251
+ this.askEveryTimeQueues.set(origin, current)
252
+ try {
253
+ return await current
254
+ } finally {
255
+ if (this.askEveryTimeQueues.get(origin) === current) this.askEveryTimeQueues.delete(origin)
256
+ }
257
+ }
258
+ }
@@ -32,6 +32,7 @@ import {
32
32
  PrivateKey,
33
33
  PublicKey,
34
34
  Transaction,
35
+ Utils,
35
36
  Validation,
36
37
  type ListActionsArgs,
37
38
  type ListActionsResult,
@@ -121,17 +122,56 @@ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
121
122
  * own vault code ever reaches it. */
122
123
  const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'vault descriptor', 'vault meta'])
123
124
 
124
- /** Protocol namespaces this package's OWN internal, fund-controlling payment
125
- * rails derive under: the BRC-29 address rail / PeerPay (address.ts's
126
- * BRC29_PROTOCOL_ID and localpay/pending.ts's identical PEERPAY_PROTOCOL_ID,
127
- * both `[2, '3241645161d8']`) and the FT/mandala-token rail (localpay/verify.ts's
128
- * FT_PROTOCOL_ID, `[2, 'mandala token']`). These are not Vault state, but
129
- * core/localpay/build.ts proves createSignature+getPublicKey over them is
130
- * sufficient to construct a valid spend -- so a connected origin must not be
131
- * able to mint either primitive under these namespaces itself, exactly as
132
- * for Vault's own namespaces. The one exception is getPublicKey toward
133
- * another party's identity key (see derivesTowardAnotherParty). */
134
- const RESERVED_RAIL_PROTOCOL_NAMES = new Set(['3241645161d8', 'mandala token'])
125
+ /** Protocol namespace this package's OWN internal, fund-controlling FT/
126
+ * mandala-token rail derives under (localpay/verify.ts's FT_PROTOCOL_ID,
127
+ * `[2, 'mandala token']`). It is not Vault state, but core/localpay/build.ts
128
+ * proves createSignature+getPublicKey over it is sufficient to construct a
129
+ * valid spend -- so a connected origin must not be able to mint either
130
+ * primitive under it itself, exactly as for Vault's own namespaces. The one
131
+ * exception is getPublicKey toward another party's identity key (see
132
+ * derivesTowardAnotherParty).
133
+ *
134
+ * BRC-29 (`[2, '3241645161d8']`) was reserved here too (XR-020) and is not any
135
+ * more: it is the standard BRC-100 payment protocol, and refusing it broke
136
+ * every external payment app that signs under it. External signing under it
137
+ * goes through the permissions manager's protocol prompt instead
138
+ * (seekProtocolPermissionsForSigning in WalletContext.tsx), except for the
139
+ * address rail's own key IDs, which stay refused (isAddressRailKeyID). */
140
+ const RESERVED_RAIL_PROTOCOL_NAMES = new Set(['mandala token'])
141
+
142
+ /** base64('legacy'), the suffix every address-rail key ID ends in
143
+ * (pay/rails/address.ts's LEGACY_DERIVATION_SUFFIX). */
144
+ const ADDRESS_RAIL_KEY_SUFFIX = Utils.toBase64(Utils.toArray('legacy', 'utf8'))
145
+
146
+ /** True for a key ID shaped like the BRC-29 address rail's own:
147
+ * `base64(YYYY-MM-DD) + ' ' + base64('legacy')` (pay/rails/address.ts's
148
+ * legacyKeyId). Those keys hold this wallet's BSV-address receipts, and anyone
149
+ * who knows a date can name one, so no connected origin has a reason to ask
150
+ * for them: refused outright, for every method and counterparty, whatever
151
+ * permission the user has given. KeyDeriver uses the key ID verbatim, so the
152
+ * comparison is exact. */
153
+ export function isAddressRailKeyID(keyID: unknown): boolean {
154
+ if (typeof keyID !== 'string') return false
155
+ const parts = keyID.split(' ')
156
+ if (parts.length !== 2 || parts[1] !== ADDRESS_RAIL_KEY_SUFFIX) return false
157
+ try {
158
+ const bytes = Utils.toArray(parts[0], 'base64')
159
+ if (Utils.toBase64(bytes) !== parts[0]) return false
160
+ return /^\d{4}-\d{2}-\d{2}$/.test(Utils.toUTF8(bytes))
161
+ } catch {
162
+ return false
163
+ }
164
+ }
165
+
166
+ /** BRC-29's protocol name, under which the address rail derives. */
167
+ const BRC29_PROTOCOL_NAME = '3241645161d8'
168
+
169
+ function requestsAddressRailKey(args: unknown): boolean {
170
+ return (
171
+ matchesProtocolNamespace(args, new Set([BRC29_PROTOCOL_NAME])) &&
172
+ isAddressRailKeyID((args as { keyID?: unknown }).keyID)
173
+ )
174
+ }
135
175
 
136
176
  /** The BRC-42 'anyone' counterparty (1·G), in canonical form. */
137
177
  const ANYONE_PUBLIC_KEY = new PrivateKey(1).toPublicKey().toString()
@@ -150,13 +190,13 @@ function counterpartyPublicKey(counterparty: unknown): string | undefined {
150
190
  }
151
191
 
152
192
  /** getPublicKey under a reserved rail namespace toward another party's
153
- * identity key is the ordinary BRC-29 / FT payer (forSelf false) and payee
193
+ * identity key is the ordinary FT payer (forSelf false) and payee
154
194
  * (forSelf true) step every payment dApp takes. ECDH is symmetric, so that
155
195
  * party can compute the same public key itself: revealing it neither signs
156
196
  * nor tells anyone anything new. createSignature and the other private-key
157
197
  * methods stay reserved, as do the two counterparties this wallet's own funds
158
- * are locked to where a site could guess the keyID: 'anyone' (the address
159
- * rail's date keyIDs) and the wallet's own identity key (FT change). Any
198
+ * are locked to where a site could guess the keyID: 'anyone' and the
199
+ * wallet's own identity key (FT change). Any
160
200
  * failure to read the identity key counts as a match, so the call is refused. */
161
201
  async function derivesTowardAnotherParty(
162
202
  getPublicKey: (args: any, originator?: string) => Promise<{ publicKey: string }>,
@@ -725,6 +765,7 @@ export function guardVaultAccess<T extends WalletInterface>(
725
765
  requestsVaultProtocol(args) ||
726
766
  requestsConnectionAuthorityProtocol(args) ||
727
767
  requestsPendingAbortAuthorityProtocol(args) ||
768
+ requestsAddressRailKey(args) ||
728
769
  (requestsReservedRailProtocol(args) &&
729
770
  !(method === 'getPublicKey' && (await derivesTowardAnotherParty(bound, args, adminOriginator)))))
730
771
  ) {
@@ -2085,9 +2085,14 @@ async function newVaultOutput(
2085
2085
  function requireReleased(opts: VaultTransferOptions | undefined, scopeToken: VaultScopeToken, what: string): void {
2086
2086
  const enabled = opts?.vaultEnabled ?? isVaultEnabled
2087
2087
  if (!enabled()) throw new VaultError('not-released', `${what} is switched off in this build`)
2088
- if (!isVaultAvailable(scopeToken.chain)) {
2088
+ if (!isVaultAvailable(scopeToken.chain, 0)) {
2089
2089
  throw new VaultError('not-on-mainnet', `${what} is only available on mainnet`)
2090
2090
  }
2091
+ // Captured with the scope, like the chain: a profile switch mid-flight clears
2092
+ // the scope and aborts at assertVaultScope rather than carrying on here.
2093
+ if ((scopeToken.profileIndex ?? 0) !== 0) {
2094
+ throw new VaultError('not-released', `${what} is only available on the default profile`)
2095
+ }
2091
2096
  }
2092
2097
 
2093
2098
  /** A real private-backup configuration needs both a host endpoint and the
@@ -45,6 +45,9 @@ export interface VaultStoreScope {
45
45
  /** Compressed secp256k1 wallet identity key, lowercase hex. */
46
46
  identityKey: string
47
47
  chain: VaultScopeChain
48
+ /** The wallet profile this identity belongs to (default 0). The vault is only
49
+ * ever available on profile 0; transfers check the captured value. */
50
+ profileIndex?: number
48
51
  }
49
52
 
50
53
  /** Opaque capability binding an async operation to one configured scope. */
@@ -52,6 +55,7 @@ export interface VaultScopeToken {
52
55
  readonly generation: number
53
56
  readonly storageKey: string
54
57
  readonly chain: VaultScopeChain
58
+ readonly profileIndex?: number
55
59
  }
56
60
 
57
61
  export interface VaultKeyRecord {
@@ -173,7 +177,11 @@ function normalizeScope(scope: VaultStoreScope): VaultStoreScope {
173
177
  if (scope.chain !== 'main' && scope.chain !== 'test' && scope.chain !== 'teratest') {
174
178
  throw new VaultError('template-invalid', 'Vault scope requires a supported chain')
175
179
  }
176
- return { identityKey: scope.identityKey, chain: scope.chain }
180
+ const profileIndex = scope.profileIndex ?? 0
181
+ if (!Number.isInteger(profileIndex) || profileIndex < 0) {
182
+ throw new VaultError('template-invalid', 'Vault scope requires a valid profile index')
183
+ }
184
+ return { identityKey: scope.identityKey, chain: scope.chain, profileIndex }
177
185
  }
178
186
 
179
187
  function scopedKey(scope = activeScope): string | null {
@@ -297,11 +305,16 @@ function captureScope(required: boolean): VaultScopeToken | null {
297
305
  if (required) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
298
306
  return null
299
307
  }
300
- return { generation: scopeGeneration, storageKey, chain: activeScope!.chain }
308
+ return { generation: scopeGeneration, storageKey, chain: activeScope!.chain, profileIndex: activeScope!.profileIndex ?? 0 }
301
309
  }
302
310
 
303
311
  function assertScope(token: VaultScopeToken): void {
304
- if (token.generation !== scopeGeneration || token.storageKey !== scopedKey() || token.chain !== activeScope?.chain) {
312
+ if (
313
+ token.generation !== scopeGeneration ||
314
+ token.storageKey !== scopedKey() ||
315
+ token.chain !== activeScope?.chain ||
316
+ (token.profileIndex ?? 0) !== (activeScope?.profileIndex ?? 0)
317
+ ) {
305
318
  throw new VaultError('scope-changed', 'Wallet or network changed during the vault operation')
306
319
  }
307
320
  }
@@ -1,5 +1,6 @@
1
1
  import { makeAutoObservable, runInAction } from 'mobx'
2
2
  import AsyncStorage from '@react-native-async-storage/async-storage'
3
+ import { profileScopedKey } from '../profiles/profileStore'
3
4
 
4
5
  export interface Connection {
5
6
  sessionId: string
@@ -81,20 +82,23 @@ class ConnectionStore {
81
82
 
82
83
  private async save() {
83
84
  try {
84
- await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(this.connections))
85
+ await AsyncStorage.setItem(profileScopedKey(STORAGE_KEY), JSON.stringify(this.connections))
85
86
  } catch (e) {
86
87
  console.warn('[ConnectionStore] save failed', e)
87
88
  }
88
89
  }
89
90
 
91
+ /** Pairings belong to one wallet profile: re-read after every profile switch. */
92
+ async reload() {
93
+ await this.load()
94
+ }
95
+
90
96
  private async load() {
91
97
  try {
92
- const raw = await AsyncStorage.getItem(STORAGE_KEY)
93
- if (raw) {
94
- runInAction(() => {
95
- this.connections = JSON.parse(raw) as Connection[]
96
- })
97
- }
98
+ const raw = await AsyncStorage.getItem(profileScopedKey(STORAGE_KEY))
99
+ runInAction(() => {
100
+ this.connections = raw ? (JSON.parse(raw) as Connection[]) : []
101
+ })
98
102
  } catch (e) {
99
103
  console.warn('[ConnectionStore] load failed', e)
100
104
  }
@@ -352,13 +352,17 @@ export function getPushAdapter(): PushAdapter | undefined {
352
352
  * across all of them, so a testnet wizard could offer to factory-reset a live
353
353
  * mainnet signer.
354
354
  *
355
- * Chain is a parameter, not a module read: screens must re-render when the user
355
+ * Only the default wallet profile (index 0) has a vault: a YubiKey is enrolled
356
+ * against one identity, and showing an empty vault on another profile would read
357
+ * as the user's vault being gone.
358
+ *
359
+ * Chain and profile are parameters, not module reads: screens must re-render when the user
356
360
  * switches network, and `selectedNetwork` from the wallet context is what makes
357
361
  * that reactive. Keeping it a parameter also keeps this module a leaf — it must
358
362
  * never import `vaultStore`.
359
363
  */
360
- export function isVaultAvailable(chain: AppChain): boolean {
361
- return isVaultEnabled() && chain === 'main'
364
+ export function isVaultAvailable(chain: AppChain, profileIndex: number): boolean {
365
+ return isVaultEnabled() && chain === 'main' && profileIndex === 0
362
366
  }
363
367
 
364
368
  /** Test-only: drop the installed configuration. */
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { useSyncExternalStore } from 'react'
16
16
  import AsyncStorage from '@react-native-async-storage/async-storage'
17
+ import { profileScopedKey } from './profiles/profileStore'
17
18
 
18
19
  export type AvatarIconFamily = 'ionicons' | 'material-community'
19
20
 
@@ -38,8 +39,10 @@ export function setUserAvatarIcon(next: AvatarIcon | null): void {
38
39
  listeners.forEach(l => l())
39
40
  // Fire-and-forget: the choice is already live in memory, and a failed write
40
41
  // costs the next launch's avatar, never the one on screen now.
41
- if (next) void AsyncStorage.setItem(STORAGE_KEY, `${next.family}/${next.name}`).catch(() => {})
42
- else void AsyncStorage.removeItem(STORAGE_KEY).catch(() => {})
42
+ // Per wallet profile: the avatar is how the user tells profiles apart.
43
+ const key = profileScopedKey(STORAGE_KEY)
44
+ if (next) void AsyncStorage.setItem(key, `${next.family}/${next.name}`).catch(() => {})
45
+ else void AsyncStorage.removeItem(key).catch(() => {})
43
46
  }
44
47
 
45
48
  export function subscribeUserAvatar(listener: () => void): () => void {
@@ -60,11 +63,15 @@ function parse(stored: string | null): AvatarIcon | null {
60
63
  return { family, name }
61
64
  }
62
65
 
63
- /** Restore the stored choice. Call once at startup; safe to call twice. */
66
+ /**
67
+ * Restore the active profile's stored choice. Call at startup and after every
68
+ * profile switch; safe to call twice. A profile with no choice gets the default
69
+ * disc, never the previous profile's icon.
70
+ */
64
71
  export async function loadUserAvatarIcon(): Promise<void> {
65
72
  try {
66
- const next = parse(await AsyncStorage.getItem(STORAGE_KEY))
67
- if (next && (next.family !== icon?.family || next.name !== icon?.name)) {
73
+ const next = parse(await AsyncStorage.getItem(profileScopedKey(STORAGE_KEY)))
74
+ if (next?.family !== icon?.family || next?.name !== icon?.name) {
68
75
  icon = next
69
76
  listeners.forEach(l => l())
70
77
  }
@@ -113,6 +113,19 @@ export async function getRegisteredDbs(keySuffix: string, chain: string): Promis
113
113
  }
114
114
  }
115
115
 
116
+ /** The networks a wallet database can belong to. */
117
+ const WALLET_DB_CHAINS = ['main', 'test', 'teratest'] as const
118
+
119
+ /**
120
+ * Every registered wallet DB filename for an identity, on every network. Unlike
121
+ * the purge below, a registry that cannot be read rejects: this answers "what
122
+ * exists", and a guess of "nothing" would be wrong in the dangerous direction.
123
+ */
124
+ export async function getAllRegisteredDbs(keySuffix: string): Promise<string[]> {
125
+ const perChain = await Promise.all(WALLET_DB_CHAINS.map(chain => getRegisteredDbs(keySuffix, chain)))
126
+ return [...new Set(perChain.flat())]
127
+ }
128
+
116
129
  /**
117
130
  * Append a filename to the registry (no-op if already present).
118
131
  */
@@ -185,3 +198,63 @@ export async function purgeRegisteredDbFiles(
185
198
  }
186
199
  }
187
200
  }
201
+
202
+ /**
203
+ * What a failed delete means: the file is already gone (expo-sqlite throws
204
+ * "Database ... not found" for it, on Android and iOS alike) or it is still there.
205
+ */
206
+ function alreadyGone(error: unknown): boolean {
207
+ return /not found/i.test(error instanceof Error ? error.message : String(error))
208
+ }
209
+
210
+ /**
211
+ * Delete Wallet with profiles: every wallet profile has its own identity and so
212
+ * its own registry, one per network. Purges every file this identity's registry
213
+ * knows on every network — the other profiles are not open at logout, so there
214
+ * is no current `dbName` to anchor on as `purgeRegisteredDbFiles` does.
215
+ * Best-effort per file, for the same reasons as that function.
216
+ *
217
+ * Resolves true when every file is gone. By default a file that could not be
218
+ * deleted is unregistered anyway: after Delete Wallet the registry must not point
219
+ * a rebuilt wallet back at it (XQ-008).
220
+ *
221
+ * `keepFailed` is for removing one profile, which has a retry at every startup
222
+ * (core/profiles/purgeProfile) and that retry finds the files only through this
223
+ * registry: an entry dropped with its file still on disk would leave the removed
224
+ * profile's plaintext history there for good. So an entry stays when its file
225
+ * could not be deleted, and goes when the file is gone, whether this call or an
226
+ * earlier one deleted it.
227
+ */
228
+ export async function purgeIdentityDbFiles(
229
+ keySuffix: string,
230
+ deleteFile: (filename: string) => Promise<void>,
231
+ options: { keepFailed?: boolean } = {}
232
+ ): Promise<boolean> {
233
+ let clean = true
234
+ for (const chain of WALLET_DB_CHAINS) {
235
+ let filenames: string[] = []
236
+ try {
237
+ filenames = await getRegisteredDbs(keySuffix, chain)
238
+ } catch {
239
+ clean = false
240
+ continue
241
+ }
242
+ for (const filename of filenames) {
243
+ let deleted = true
244
+ try {
245
+ await deleteFile(filename)
246
+ } catch (error) {
247
+ // Best-effort — see purgeRegisteredDbFiles.
248
+ deleted = alreadyGone(error)
249
+ if (!deleted) clean = false
250
+ }
251
+ if (options.keepFailed && !deleted) continue
252
+ try {
253
+ await unregisterDb(keySuffix, chain, filename)
254
+ } catch {
255
+ // Best-effort — see purgeRegisteredDbFiles.
256
+ }
257
+ }
258
+ }
259
+ return clean
260
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -40,9 +40,8 @@ async function generateQRCodeSVG(data: string, size: number = 180): Promise<stri
40
40
  *
41
41
  * `only`, when given, renders a single page (share index `only` of `shares`,
42
42
  * still labelled "Share <only+1> of <shares.length>") as a standalone
43
- * one-page document instead of every share in one multi-page document. See
44
- * printRecoveryShares.ts (XR-110): the default flow calls this once per
45
- * share so no single print job carries more than one of the threshold.
43
+ * one-page document instead of every share in one multi-page document.
44
+ * printRecoveryShares.ts no longer uses it (XR-110 reverted, see there).
46
45
  */
47
46
  export async function generatePrintHTML(
48
47
  shares: string[],