@bsv/expo-wallet-toolbox 0.25.1 → 0.26.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 (43) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/core/context/WalletContext.tsx +3 -1
  3. package/core/i18n/translations.tsx +221 -36
  4. package/core/identity/handleRegistry/client.ts +110 -16
  5. package/core/identity/handleRegistry/registration.ts +115 -17
  6. package/core/profiles/profileStore.ts +4 -1
  7. package/core/services/groupSpendingLimit.ts +26 -0
  8. package/core/services/signingPermissionPolicy.ts +14 -8
  9. package/core/services/vault/ceremony.ts +13 -0
  10. package/core/services/vault/ceremonyHost.ts +58 -0
  11. package/core/services/vault/failedVaultSpend.ts +40 -0
  12. package/core/services/vault/outputAuthority.ts +13 -6
  13. package/core/services/vault/transfers.ts +56 -12
  14. package/core/storage/encryptedDbImage.ts +11 -2
  15. package/core/theme/tokens.ts +26 -12
  16. package/package.json +2 -1
  17. package/ui/components/QRScanner.tsx +24 -22
  18. package/ui/components/pay/MessageBoxConfig.tsx +10 -16
  19. package/ui/components/pay/NearbyAdvisoryModal.tsx +6 -13
  20. package/ui/components/pay/NearbyFlow.tsx +72 -35
  21. package/ui/components/pay/PayForm.tsx +27 -19
  22. package/ui/components/pay/PaymentSuccessOverlay.tsx +8 -6
  23. package/ui/components/pay/UniversalSend.tsx +4 -1
  24. package/ui/components/ui/AlertCard.tsx +3 -2
  25. package/ui/components/ui/BalancedText.tsx +117 -0
  26. package/ui/components/ui/ErrorBoundary.tsx +31 -14
  27. package/ui/components/ui/GroupedList.tsx +28 -22
  28. package/ui/components/ui/ListRow.tsx +126 -35
  29. package/ui/components/ui/PermissionSheet.tsx +31 -24
  30. package/ui/components/ui/PresenceRow.tsx +15 -23
  31. package/ui/components/ui/Sheet.tsx +11 -17
  32. package/ui/components/ui/Toast.tsx +13 -17
  33. package/ui/components/vault/EnrollWizard.tsx +446 -196
  34. package/ui/components/vault/KeyChooser.tsx +7 -20
  35. package/ui/components/vault/VaultCeremonySheet.tsx +44 -36
  36. package/ui/components/wallet/AmountInput.tsx +11 -17
  37. package/ui/components/wallet/BiometricAdvisoryModal.tsx +13 -17
  38. package/ui/index.ts +1 -1
  39. package/ui/screens/TrustScreen.tsx +49 -61
  40. package/ui/screens/VaultScreen.tsx +99 -60
  41. package/ui/screens/VaultTransferScreen.tsx +34 -27
  42. package/ui/screens/WalletCheckScreen.tsx +25 -24
  43. package/ui/screens/WalletConfigScreen.tsx +66 -72
@@ -35,6 +35,18 @@ export type AvailabilityResult =
35
35
  | { kind: 'failed' }
36
36
 
37
37
  /** `rejected` is the server answering no; `failed` is not having an answer. */
38
+ /**
39
+ * The App Store or Google Play subscription that pays for a custom handle, as
40
+ * the registry verifies it: `token` is the StoreKit 2 signed transaction or
41
+ * Google's purchase token.
42
+ */
43
+ export interface StorePurchase {
44
+ store: 'app-store' | 'google-play'
45
+ productId: string
46
+ transactionId: string
47
+ token: string | null
48
+ }
49
+
38
50
  export type PutResult =
39
51
  | { kind: 'created' }
40
52
  | { kind: 'ok' }
@@ -50,13 +62,42 @@ export type PutResult =
50
62
  */
51
63
  export type ProfileLookup = { kind: 'found'; profile: RegistryProfile } | { kind: 'none' } | { kind: 'failed' }
52
64
 
65
+ /** A profile as `search` returns it. */
66
+ export type HandleProfile = RegistryProfile
67
+
68
+ /**
69
+ * What a complete address resolves to, against the key this device pinned for
70
+ * it. `changed` is a valid certificate under another key: the pin does not move
71
+ * until `acceptKey`. `failed` is not having an answer, `none` is the registry
72
+ * saying nobody holds the handle.
73
+ */
74
+ export type ResolveResult =
75
+ | { kind: 'found'; profile: HandleProfile }
76
+ | { kind: 'changed'; profile: HandleProfile; pinnedKey: string }
77
+ | { kind: 'none' }
78
+ | { kind: 'failed' }
79
+
53
80
  export interface HandleRegistryClient {
54
81
  /** The pinned domain: what a bare handle is registered under. */
55
82
  readonly domain: string
56
83
  checkAvailability(handle: string): Promise<AvailabilityResult>
57
- putCertificate(cert: ProfileCertJson): Promise<PutResult>
58
- /** Throws on transport failure — the contract `searchIdentities` already has. */
59
- search(query: string): Promise<RegistryProfile[]>
84
+ /**
85
+ * `purchase` pays for a custom handle; it goes as `{certificate, purchase}`.
86
+ * `fallback` is the certificate of the generated handle the wallet becomes
87
+ * when the subscription lapses; it goes as a third member, and only with a
88
+ * purchase (the registry ignores it on a free claim).
89
+ */
90
+ putCertificate(cert: ProfileCertJson, purchase?: StorePurchase, fallback?: ProfileCertJson): Promise<PutResult>
91
+ /**
92
+ * Throws on transport failure — the contract `searchIdentities` already has.
93
+ * A complete address whose key differs from the pin comes back with
94
+ * `changedFrom` (the pinned key); a partial query still drops that row.
95
+ */
96
+ search(query: string): Promise<Array<HandleProfile & { changedFrom?: string }>>
97
+ /** Never throws. One complete address, checked against this device's key pin. */
98
+ resolveHandle(paymail: string): Promise<ResolveResult>
99
+ /** Replaces the pin for `paymail`: the payer has accepted its new key. */
100
+ acceptKey(paymail: string, identityKey: string): Promise<void>
60
101
  /** Never throws. The full verdict, for callers that cache the answer. */
61
102
  lookupProfile(identityKey: string, domain?: string): Promise<ProfileLookup>
62
103
  /** Never throws — the contract `resolveIdentity` already has. */
@@ -108,13 +149,17 @@ export function createHandleRegistryClient(args: {
108
149
  * is indistinguishable from a compromised or malicious registry redirecting
109
150
  * the paymail to an attacker.
110
151
  */
111
- async function pinnedOrNull(profile: RegistryProfile): Promise<RegistryProfile | null> {
152
+ async function checkPin(profile: RegistryProfile): Promise<{ kind: 'match' } | { kind: 'mismatch'; pinnedKey: string }> {
112
153
  const known = await pinStore.get(profile.paymail)
113
154
  if (known === null) {
114
155
  await pinStore.set(profile.paymail, profile.identityKey)
115
- return profile
156
+ return { kind: 'match' }
116
157
  }
117
- return known.toLowerCase() === profile.identityKey.toLowerCase() ? profile : null
158
+ return known.toLowerCase() === profile.identityKey.toLowerCase() ? { kind: 'match' } : { kind: 'mismatch', pinnedKey: known }
159
+ }
160
+
161
+ async function pinnedOrNull(profile: RegistryProfile): Promise<RegistryProfile | null> {
162
+ return (await checkPin(profile)).kind === 'match' ? profile : null
118
163
  }
119
164
 
120
165
  /** Only ever from the registry we write to: a foreign host's clock is not
@@ -167,6 +212,13 @@ export function createHandleRegistryClient(args: {
167
212
  if (at < 0) return isRoutableSearchQuery(text) ? { domain, query: text } : null
168
213
  const local = text.slice(0, at)
169
214
  const typed = text.slice(at + 1)
215
+ // A one-character handle is a real, exact address: `r@domain` asks the
216
+ // registry for that one handle. Anything shorter than a search query is
217
+ // read this way only when the domain is finished; typed as a fragment it
218
+ // is still nothing to ask about.
219
+ if (/^[a-z0-9]$/.test(local) && (typed === domain || looksLikeDomain(typed))) {
220
+ return { domain: typed, query: local, paymail: `${local}@${typed}` }
221
+ }
170
222
  if (local.length < SEARCH_MIN_QUERY_LENGTH || !isRoutableSearchQuery(local)) return null
171
223
  // A domain still being typed is a prefix of ours: still our registry, and
172
224
  // still a fragment — the user has not finished naming anybody yet.
@@ -242,14 +294,18 @@ export function createHandleRegistryClient(args: {
242
294
  }
243
295
  },
244
296
 
245
- async putCertificate(cert) {
246
- let res: Response
247
- try {
248
- res = await fetchWithTimeout(fetchImpl, `${origin}/api/handle`, {
297
+ async putCertificate(cert, purchase, fallback) {
298
+ const put = (body: unknown) =>
299
+ fetchWithTimeout(fetchImpl, `${origin}/api/handle`, {
249
300
  method: 'PUT',
250
301
  headers: { 'content-type': 'application/json' },
251
- body: JSON.stringify(cert)
302
+ body: JSON.stringify(body)
252
303
  })
304
+ let res: Response
305
+ try {
306
+ res = await put(purchase ? { certificate: cert, purchase, ...(fallback ? { fallback } : {}) } : cert)
307
+ // No bare retry after ERR_INVALID_CERTIFICATE: the registry verifies
308
+ // purchases now, and a bare certificate would claim a paid handle free.
253
309
  } catch (e) {
254
310
  return { kind: 'failed', message: e instanceof Error ? e.message : String(e) }
255
311
  }
@@ -296,11 +352,49 @@ export function createHandleRegistryClient(args: {
296
352
  )
297
353
  const certified = verified.filter((profile): profile is RegistryProfile => profile !== null)
298
354
  // Each row is checked against this device's own key-pin history
299
- // (XR-071) — a row whose certificate verifies but whose key contradicts
300
- // one already accepted for that paymail is dropped like any other row
301
- // that failed verification.
302
- const pinned = await Promise.all(certified.map(profile => pinnedOrNull(profile)))
303
- return pinned.filter((profile): profile is RegistryProfile => profile !== null)
355
+ // (XR-071). A row whose certificate verifies but whose key contradicts
356
+ // one already accepted for that paymail is dropped from a partial query;
357
+ // for a complete address it is the answer, flagged with the pinned key,
358
+ // so the caller can warn instead of showing nobody.
359
+ const rows = await Promise.all(
360
+ certified.map(async (profile): Promise<(HandleProfile & { changedFrom?: string }) | null> => {
361
+ const pin = await checkPin(profile)
362
+ if (pin.kind === 'mismatch') return route.paymail ? { ...profile, changedFrom: pin.pinnedKey } : null
363
+ return profile
364
+ })
365
+ )
366
+ return rows.filter((profile): profile is HandleProfile & { changedFrom?: string } => profile !== null)
367
+ },
368
+
369
+ async resolveHandle(paymail) {
370
+ try {
371
+ const route = routeFor(paymail)
372
+ if (!route?.paymail) return { kind: 'none' }
373
+ const endpoints = await resolver.resolve(route.domain)
374
+ if (!endpoints) return { kind: 'failed' }
375
+ const res = await fetchWithTimeout(fetchImpl, endpoints.search(route.query), {
376
+ headers: { accept: 'application/json' }
377
+ })
378
+ if (endpoints.pinned) notePinnedSkew(res)
379
+ if (res.status === 404) return { kind: 'none' }
380
+ if (!res.ok) return { kind: 'failed' }
381
+ const body = (await res.json()) as unknown
382
+ if (!Array.isArray(body)) return { kind: 'none' }
383
+ for (const row of body.slice(0, MAX_SEARCH_RESULTS)) {
384
+ const profile = await verifyProfileCertificate(row, { domain: route.domain, paymail: route.paymail })
385
+ if (!profile) continue
386
+ const pin = await checkPin(profile)
387
+ if (pin.kind === 'mismatch') return { kind: 'changed', profile, pinnedKey: pin.pinnedKey }
388
+ return { kind: 'found', profile }
389
+ }
390
+ return { kind: 'none' }
391
+ } catch {
392
+ return { kind: 'failed' }
393
+ }
394
+ },
395
+
396
+ async acceptKey(paymail, identityKey) {
397
+ await pinStore.set(paymail.trim().toLowerCase(), identityKey)
304
398
  },
305
399
 
306
400
  lookupProfile,
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import { parsePaymail } from './rules'
19
19
  import { buildProfileCertificate, type ProfileCertJson, type ProfileSigner } from './profileCert'
20
- import type { HandleRegistryClient } from './client'
20
+ import type { HandleRegistryClient, StorePurchase } from './client'
21
21
 
22
22
  /** The in-flight journal. One at a time; a second intent replaces it. */
23
23
  export const PENDING_JOURNAL_KEY = 'profile_handle_pending'
@@ -30,6 +30,9 @@ export const ISSUED_AT_KV_KEY = 'profile_handle_issued_at'
30
30
  */
31
31
  export const MAX_ISSUED_AT_LEAD_MS = 240_000
32
32
 
33
+ /** The registry's refusal of a fallback handle that is taken or too similar. */
34
+ const FALLBACK_UNAVAILABLE = 'ERR_FALLBACK_UNAVAILABLE'
35
+
33
36
  /** Structurally satisfied by `StorageExpoSQLite`. */
34
37
  export interface RegistrationStorage {
35
38
  getKeyValue(key: string): Promise<string | undefined>
@@ -42,6 +45,10 @@ export interface PendingStep {
42
45
  kind: 'release' | 'claim'
43
46
  paymail: string
44
47
  cert: ProfileCertJson
48
+ /** the store subscription a paid claim is sent with */
49
+ purchase?: StorePurchase
50
+ /** the generated handle's certificate a paid claim reserves, signed after the claim */
51
+ fallback?: ProfileCertJson
45
52
  }
46
53
 
47
54
  /**
@@ -69,15 +76,21 @@ export interface PendingJournal {
69
76
  export type RegistrationFailureCode = 'invalid_handle' | 'wrong_domain' | 'same_handle' | 'clock_ahead'
70
77
 
71
78
  export type RegistrationResult =
72
- | { kind: 'registered'; paymail: string }
79
+ /** `fallback`: the bare free handle the claim reserved, when it went with one */
80
+ | { kind: 'registered'; paymail: string; fallback?: string }
73
81
  | { kind: 'updated'; paymail: string }
74
- | { kind: 'changed'; paymail: string }
82
+ | { kind: 'changed'; paymail: string; fallback?: string }
75
83
  /** The handle was tombstoned and nothing was claimed in its place. */
76
84
  | { kind: 'released'; paymail: string }
77
85
  /** `attempted` is the handle that was lost; `paymail` is the one kept. */
78
86
  | { kind: 'rolled_back'; paymail: string; attempted?: string }
79
87
  | { kind: 'pending' }
80
- | { kind: 'rejected'; code: string; description: string }
88
+ /**
89
+ * `notRestored`: a change's claim was refused AND the reclaim of the old
90
+ * handle (`notRestored`, handle@domain) was refused too, so the wallet holds
91
+ * no handle. `code` and `description` are then the reclaim's.
92
+ */
93
+ | { kind: 'rejected'; code: string; description: string; notRestored?: string }
81
94
  | { kind: 'failed'; message: string; code?: RegistrationFailureCode }
82
95
  | { kind: 'unavailable' }
83
96
  | { kind: 'idle' }
@@ -236,12 +249,63 @@ async function alreadyApplied(
236
249
  return mine === null || mine.paymail !== step.paymail
237
250
  }
238
251
 
252
+ /**
253
+ * The fallback's certificate for a paid claim, dated strictly after `after`
254
+ * (the claim, or in a change the later of the release and the claim). Null
255
+ * with no purchase: the registry reads `fallback` on a paid claim only.
256
+ */
257
+ async function buildFallback(
258
+ deps: RegistrationDeps,
259
+ client: HandleRegistryClient,
260
+ args: { purchase?: StorePurchase; fallbackHandle?: string },
261
+ after: Date
262
+ ): Promise<ProfileCertJson | null> {
263
+ if (!args.purchase || !args.fallbackHandle) return null
264
+ const paymail = `${args.fallbackHandle.trim().toLowerCase()}@${client.domain}`
265
+ if (!parsePaymail(paymail)) throw new InvalidFallback(args.fallbackHandle)
266
+ const issuedAt = await nextIssuedAt(deps, client, after)
267
+ // The ceiling can leave no room above the claim; a fallback dated at or
268
+ // before it would be refused as stale after the claim had been paid for.
269
+ if (issuedAt.getTime() <= after.getTime()) throw new ClockAhead()
270
+ return await buildProfileCertificate({ signer: deps.signer, paymail, issuedAt })
271
+ }
272
+
273
+ class InvalidFallback extends Error {
274
+ constructor(handle: string) {
275
+ super(`handleRegistry: not a valid fallback handle: ${handle}`)
276
+ }
277
+ }
278
+
279
+ class ClockAhead extends Error {
280
+ constructor() {
281
+ super('handleRegistry: the clock is too far ahead to reserve a fallback handle yet')
282
+ }
283
+ }
284
+
285
+ /** A failure this module reached on its own, in the shape callers read. */
286
+ function failureOf(e: unknown): RegistrationResult {
287
+ if (e instanceof InvalidFallback) return { kind: 'failed', code: 'invalid_handle', message: e.message }
288
+ if (e instanceof ClockAhead) return { kind: 'failed', code: 'clock_ahead', message: e.message }
289
+ return { kind: 'failed', message: messageOf(e) }
290
+ }
291
+
239
292
  /** The `issuedAt` a step was minted with, as the journal carries it. */
240
293
  function issuedAtOf(step: PendingStep | undefined): Date | undefined {
241
294
  const ms = Date.parse(step?.cert.fields.issuedAt ?? '')
242
295
  return Number.isFinite(ms) ? new Date(ms) : undefined
243
296
  }
244
297
 
298
+ /** The bare handle a claim step reserved as its fallback, when it had one. */
299
+ function fallbackOf(step: PendingStep | undefined): string | undefined {
300
+ const paymail = step?.fallback?.fields.paymail
301
+ return typeof paymail === 'string' ? paymail.split('@')[0] : undefined
302
+ }
303
+
304
+ /** A reclaim the registry refused: the old handle is not back. */
305
+ function notRestored(back: RegistrationResult, paymail: string): RegistrationResult {
306
+ return back.kind === 'rejected' ? { ...back, notRestored: paymail } : back
307
+ }
308
+
245
309
  /**
246
310
  * The handle to put the user back on, when the step the registry just refused
247
311
  * is the claim of a change that has already tombstoned the old one.
@@ -271,7 +335,7 @@ async function runJournal(
271
335
  ): Promise<RegistrationResult> {
272
336
  for (let i = 0; i < journal.steps.length; i++) {
273
337
  const step = journal.steps[i]
274
- const outcome = await client.putCertificate(step.cert)
338
+ const outcome = await client.putCertificate(step.cert, step.purchase, step.fallback)
275
339
  if (outcome.kind === 'created' || outcome.kind === 'ok') continue
276
340
  // No answer: the journal stays, and the next mount or an explicit retry
277
341
  // re-sends the same bytes.
@@ -290,14 +354,27 @@ async function runJournal(
290
354
  // their tombstone ahead of ours — any device a few minutes fast does —
291
355
  // and is the same hazard as the handle being taken. Replaying cannot
292
356
  // win, but the reclaim still can.
293
- if (reclaim) return await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
357
+ if (reclaim) return notRestored(await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted), reclaim.paymail)
294
358
  // Replaying a certificate the registry calls stale can never win, so
295
359
  // keeping the journal would only retry it on every mount, forever.
296
360
  await clearJournal(deps.storage)
297
361
  return { kind: 'failed', message: outcome.description }
298
362
  }
299
- if (reclaim) return await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
363
+ if (reclaim) {
364
+ const back = await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
365
+ // The reserve failed before anything was claimed, so the caller has to
366
+ // see that code to pick another fallback: the old handle is back, and
367
+ // the refusal is what is reported.
368
+ if (outcome.code === FALLBACK_UNAVAILABLE && back.kind === 'rolled_back') {
369
+ return { kind: 'rejected', code: outcome.code, description: outcome.description }
370
+ }
371
+ return notRestored(back, reclaim.paymail)
372
+ }
300
373
  await clearJournal(deps.storage)
374
+ // a rollback journal resumed on a later start: its one step reclaims the old handle
375
+ if (journal.intent === 'change' && journal.steps.length === 1 && journal.previousPaymail === step.paymail) {
376
+ return { kind: 'rejected', code: outcome.code, description: outcome.description, notRestored: step.paymail }
377
+ }
301
378
  return { kind: 'rejected', code: outcome.code, description: outcome.description }
302
379
  }
303
380
  await clearJournal(deps.storage)
@@ -313,10 +390,12 @@ async function runJournal(
313
390
  ...(journal.attemptedPaymail ? { attempted: journal.attemptedPaymail } : {})
314
391
  }
315
392
  }
393
+ // the fallback is the journal's, which may not be the one the caller of this run chose
394
+ const fallback = fallbackOf(journal.steps[journal.steps.length - 1])
316
395
  if (journal.intent === 'update') return { kind: 'updated', paymail }
317
- if (journal.intent === 'change') return { kind: 'changed', paymail }
396
+ if (journal.intent === 'change') return { kind: 'changed', paymail, ...(fallback ? { fallback } : {}) }
318
397
  if (journal.intent === 'release') return { kind: 'released', paymail }
319
- return { kind: 'registered', paymail }
398
+ return { kind: 'registered', paymail, ...(fallback ? { fallback } : {}) }
320
399
  }
321
400
 
322
401
  /**
@@ -398,9 +477,9 @@ async function finishOutstanding(
398
477
 
399
478
  export function registerHandle(
400
479
  deps: RegistrationDeps,
401
- args: { handle: string; displayName?: string }
480
+ args: { handle: string; displayName?: string; purchase?: StorePurchase; fallbackHandle?: string }
402
481
  ): Promise<RegistrationResult> {
403
- return share(`register:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}`, async () => {
482
+ return share(`register:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}:${args.fallbackHandle ?? ''}`, async () => {
404
483
  const client = deps.client
405
484
  if (!client) return { kind: 'unavailable' }
406
485
  try {
@@ -416,16 +495,25 @@ export function registerHandle(
416
495
  issuedAt,
417
496
  displayName: args.displayName
418
497
  })
498
+ const fallback = await buildFallback(deps, client, args, issuedAt)
419
499
  const journal: PendingJournal = {
420
500
  v: 1,
421
501
  intent: 'register',
422
- steps: [{ kind: 'claim', paymail, cert }],
502
+ steps: [
503
+ {
504
+ kind: 'claim',
505
+ paymail,
506
+ cert,
507
+ ...(args.purchase ? { purchase: args.purchase } : {}),
508
+ ...(fallback ? { fallback } : {})
509
+ }
510
+ ],
423
511
  startedAt: issuedAt.toISOString()
424
512
  }
425
513
  await writeJournal(deps.storage, journal)
426
514
  return await runJournal(deps, client, journal)
427
515
  } catch (e) {
428
- return { kind: 'failed', message: messageOf(e) }
516
+ return failureOf(e)
429
517
  }
430
518
  })
431
519
  }
@@ -472,9 +560,9 @@ export function updateProfile(
472
560
 
473
561
  export function changeHandle(
474
562
  deps: RegistrationDeps,
475
- args: { previousPaymail: string; handle: string; displayName?: string }
563
+ args: { previousPaymail: string; handle: string; displayName?: string; purchase?: StorePurchase; fallbackHandle?: string }
476
564
  ): Promise<RegistrationResult> {
477
- const key = `change:${args.previousPaymail.trim().toLowerCase()}:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}`
565
+ const key = `change:${args.previousPaymail.trim().toLowerCase()}:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}:${args.fallbackHandle ?? ''}`
478
566
  return share(key, async () => {
479
567
  const client = deps.client
480
568
  if (!client) return { kind: 'unavailable' }
@@ -530,12 +618,22 @@ export function changeHandle(
530
618
  issuedAt: claimAt,
531
619
  displayName: args.displayName
532
620
  })
621
+ // dated after the release and the claim both, so it beats the tombstone
622
+ // of a fallback handle that is the one being released
623
+ const fallback = await buildFallback(deps, client, args, claimAt)
533
624
  const journal: PendingJournal = {
534
625
  v: 1,
535
626
  intent: 'change',
536
627
  steps: [
537
628
  { kind: 'release', paymail: previousPaymail, cert: release },
538
- { kind: 'claim', paymail, cert: claim }
629
+ // the new handle's subscription and its fallback go with its claim; a release needs neither
630
+ {
631
+ kind: 'claim',
632
+ paymail,
633
+ cert: claim,
634
+ ...(args.purchase ? { purchase: args.purchase } : {}),
635
+ ...(fallback ? { fallback } : {})
636
+ }
539
637
  ],
540
638
  previousPaymail,
541
639
  startedAt: releaseAt.toISOString()
@@ -543,7 +641,7 @@ export function changeHandle(
543
641
  await writeJournal(deps.storage, journal)
544
642
  return await runJournal(deps, client, journal)
545
643
  } catch (e) {
546
- return { kind: 'failed', message: messageOf(e) }
644
+ return failureOf(e)
547
645
  }
548
646
  })
549
647
  }
@@ -79,7 +79,10 @@ export function normalizeRestorePending(raw: unknown): AppChain[] | undefined {
79
79
  }
80
80
 
81
81
  export function defaultProfilesState(): ProfilesState {
82
- return { active: 0, profiles: [{ index: 0, network: e2eSafeChain(DEFAULT_CHAIN) }] }
82
+ // E2E builds set this before the toolbox loads (index.js). A fresh install
83
+ // then starts on testnet. Production never sets it, so the default stays main.
84
+ const network = (globalThis as { __BSV_E2E_CHAIN?: string }).__BSV_E2E_CHAIN === 'test' ? 'test' : DEFAULT_CHAIN
85
+ return { active: 0, profiles: [{ index: 0, network: e2eSafeChain(network) }] }
83
86
  }
84
87
 
85
88
  /** Trim and cap a profile name; undefined when nothing is left (the default label applies). */
@@ -0,0 +1,26 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage'
2
+ import { AUTO_APPROVE_STORAGE_KEY, DEFAULT_AUTO_APPROVE_THRESHOLD } from '../constants'
3
+ import { profileScopedKey } from '../profiles/profileStore'
4
+
5
+ /**
6
+ * The most a site's one-time group grant may let it spend each month: what it could spend without asking,
7
+ * per payment (the stored auto-approve threshold). 0 means the user wants every payment asked about.
8
+ */
9
+ export async function groupSpendingLimit(): Promise<number> {
10
+ const v = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY)).catch(() => null)
11
+ return v === null ? DEFAULT_AUTO_APPROVE_THRESHOLD : Number(v) || 0
12
+ }
13
+
14
+ /** The same group with its spending limited to `limit`; with a limit of 0 or less, with no spending at all. */
15
+ export function clampGroupSpending<T extends { spendingAuthorization?: { amount: number; description?: string } }>(
16
+ group: T,
17
+ limit: number
18
+ ): T {
19
+ const spending = group.spendingAuthorization
20
+ if (!spending) return group
21
+ if (!(limit > 0)) {
22
+ const { spendingAuthorization: _removed, ...rest } = group
23
+ return rest as T
24
+ }
25
+ return spending.amount <= limit ? group : { ...group, spendingAuthorization: { ...spending, amount: limit } }
26
+ }
@@ -1,5 +1,6 @@
1
1
  import { Hash, Utils } from '@bsv/sdk'
2
2
  import { WalletPermissionsManager, type GroupedPermissions } from '@bsv/wallet-toolbox-mobile'
3
+ import { groupSpendingLimit } from './groupSpendingLimit'
3
4
 
4
5
  /** A site's manifest group request (BRC-73), as the Connect sheet shows it and `mintGroupedPermissions` mints it. */
5
6
  export type GroupPermissions = GroupedPermissions
@@ -118,13 +119,13 @@ const isObject = (v: unknown): v is Record<string, any> => v !== null && typeof
118
119
  * the manifest, so every entry is checked: one that does not have the shape the manager reads is
119
120
  * left out, and what remains is both what the Connect sheet shows and what Connect mints.
120
121
  */
121
- function sanitizeGroup(raw: unknown): GroupPermissions | null {
122
+ export function sanitizeGroup(raw: unknown, limit: number): GroupPermissions | null {
122
123
  if (!isObject(raw)) return null
123
124
  const group: GroupPermissions = {}
124
125
  if (typeof raw.description === 'string') group.description = raw.description
125
126
  const spending = raw.spendingAuthorization
126
- if (isObject(spending) && Number.isSafeInteger(spending.amount) && spending.amount > 0) {
127
- group.spendingAuthorization = { amount: spending.amount, description: str(spending.description) }
127
+ if (isObject(spending) && Number.isSafeInteger(spending.amount) && spending.amount > 0 && limit > 0) {
128
+ group.spendingAuthorization = { amount: Math.min(spending.amount, limit), description: str(spending.description) }
128
129
  }
129
130
  const list = (v: unknown): any[] => (Array.isArray(v) ? v.filter(isObject) : [])
130
131
  group.protocolPermissions = list(raw.protocolPermissions)
@@ -327,7 +328,7 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
327
328
  try {
328
329
  const { normalized } = this.internals.prepareOriginator(originator)
329
330
  const { groupPermissions } = await this.internals.fetchManifestPermissions(normalized)
330
- return sanitizeGroup(groupPermissions)
331
+ return sanitizeGroup(groupPermissions, await groupSpendingLimit())
331
332
  } catch {
332
333
  return null
333
334
  }
@@ -347,19 +348,24 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
347
348
  protocolPermissions: (group.protocolPermissions ?? []).filter(p => !isAskEveryTimeProtocol(p.protocolID))
348
349
  }
349
350
  const todo = await i.filterAlreadyGrantedPermissions(normalized, wanted)
351
+ const limit = await groupSpendingLimit()
352
+ const spend =
353
+ todo.spendingAuthorization != null && limit > 0
354
+ ? { ...todo.spendingAuthorization, amount: Math.min(todo.spendingAuthorization.amount, limit) }
355
+ : null
350
356
  const lookup = i.buildOriginatorLookupValues(originator, normalized)
351
357
  const toCreate: MintItem[] = []
352
358
  const toRenew: MintItem[] = []
353
- if (todo.spendingAuthorization != null) {
359
+ if (spend != null) {
354
360
  toCreate.push({
355
361
  request: {
356
362
  type: 'spending',
357
363
  originator: normalized,
358
- spending: { satoshis: todo.spendingAuthorization.amount },
359
- reason: todo.spendingAuthorization.description
364
+ spending: { satoshis: spend.amount },
365
+ reason: spend.description
360
366
  },
361
367
  expiry: 0,
362
- amount: todo.spendingAuthorization.amount
368
+ amount: spend.amount
363
369
  })
364
370
  }
365
371
  for (const p of todo.protocolPermissions ?? []) {
@@ -269,6 +269,19 @@ export class CeremonyController {
269
269
  return () => this.subscribers.delete(cb)
270
270
  }
271
271
 
272
+ /** Whether `signer` is still the armed one: not released by its caller, by
273
+ * cancel(), by a detach or by the retention ceiling. Read by a shared signer
274
+ * session (ceremonyHost.openVaultSignerSession) before it reuses a signer. */
275
+ holds(signer: VaultSigner): boolean {
276
+ return this.activeHandle === signer
277
+ }
278
+
279
+ /** Whether cancel() ended the ceremony most recently asked for. requestSigner
280
+ * resets it, so it speaks only for that ceremony. */
281
+ get wasCancelled(): boolean {
282
+ return this.cancelled
283
+ }
284
+
272
285
  /** Ask for the chosen key as a signer. Every overlapping request is refused:
273
286
  * one caller must have sole ownership of both the signer and the process-wide
274
287
  * native discovery/session object through release and teardown. */
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { CeremonyController, VaultProgress, VaultSigner } from './ceremony'
9
9
  import { getVaultDriver } from './driver'
10
+ import { VaultError } from './types'
10
11
  import { vaultStore } from './vaultStore'
11
12
 
12
13
  /** How long an armed signer stays usable before it relocks — refreshed by
@@ -50,3 +51,60 @@ export function requestVaultSigner(reason: string, chosenSerial: string): Promis
50
51
  export function noteVaultProgress(p: VaultProgress): void {
51
52
  ceremony.noteProgress(p)
52
53
  }
54
+
55
+ /**
56
+ * One key session for a whole spend that also creates a Vault output (a
57
+ * withdrawal with a re-vaulted remainder, a re-lock): one PIN entry and one
58
+ * tap cover both the new output's possession proof and the input signatures.
59
+ * Before this, each step opened its own ceremony, so the person entered the
60
+ * PIN and tapped twice for one transfer.
61
+ *
62
+ * The session is a local of ONE operation and is closed in that operation's
63
+ * finally. It is never module state (see VaultSigner).
64
+ *
65
+ * - `acquire` arms the chosen key the first time. Later calls return the same
66
+ * signer while it is still armed. If the key left or the retention window
67
+ * closed in between (the proof is signed before the transaction is built, so
68
+ * the session stays open through the build), it asks for a fresh ceremony:
69
+ * the old two-tap behaviour, never a failed transfer. A session the person
70
+ * cancelled stays cancelled (`user-cancelled`).
71
+ * - `close` releases the signer. Idempotent, as VaultSigner.release() is, so
72
+ * the spend may release the signer itself as soon as the last input is
73
+ * signed and the operation's finally may close again.
74
+ */
75
+ export interface VaultSignerSession {
76
+ acquire(reason: string, chosenSerial: string): Promise<VaultSigner>
77
+ close(): void
78
+ }
79
+
80
+ export function openVaultSignerSession(
81
+ deps: {
82
+ request: (reason: string, chosenSerial: string) => Promise<VaultSigner>
83
+ holds: (signer: VaultSigner) => boolean
84
+ cancelled: () => boolean
85
+ } = {
86
+ request: requestVaultSigner,
87
+ holds: signer => ceremony.holds(signer),
88
+ cancelled: () => ceremony.wasCancelled
89
+ }
90
+ ): VaultSignerSession {
91
+ let held: VaultSigner | undefined
92
+ return {
93
+ async acquire(reason, chosenSerial) {
94
+ if (held && held.serial === chosenSerial && deps.holds(held)) return held
95
+ if (held) {
96
+ const ended = held
97
+ held = undefined
98
+ ended.release()
99
+ if (deps.cancelled()) throw new VaultError('user-cancelled', 'Vault key session was cancelled')
100
+ }
101
+ held = await deps.request(reason, chosenSerial)
102
+ return held
103
+ },
104
+ close() {
105
+ const signer = held
106
+ held = undefined
107
+ signer?.release()
108
+ }
109
+ }
110
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Which FAILED Vault spends (withdrawals, re-locks) hold a pending key removal
3
+ * open in finalizeVaultKeyRemoval.
4
+ *
5
+ * The tombstone exists so that no output the removed key can still open is
6
+ * missed. A failed spend is a risk to that only if it may yet be on the
7
+ * network, creating an output committed to the old key set. Refusing on every
8
+ * failed spend ever recorded (the earlier rule) could never clear: a failed
9
+ * action stays in the wallet's history for good, so one aborted re-lock
10
+ * attempt, or one failed withdrawal months before, kept the removal pending
11
+ * after its re-lock was mined.
12
+ *
13
+ * A failed spend blocks only when BOTH hold:
14
+ *
15
+ * 1. It has a transaction ID. A Vault input is signed by the card and by
16
+ * nothing else, and the wallet assigns the ID at signAction. A spend with
17
+ * none was aborted before any signature: no transaction with its inputs can
18
+ * exist.
19
+ * 2. It began at or after the removal did. finalize clears the tombstone only
20
+ * with an ACCEPTED re-lock and two scans that find no output authorizing
21
+ * the removed key, so every output an earlier spend could have consumed is
22
+ * spent by an accepted transaction: the earlier one can no longer confirm.
23
+ * (Should an accepted re-lock still be dropped, its sources return as
24
+ * outputs committed to the removed key, which the coverage badge offers to
25
+ * re-lock: the owner decision recorded at ACCEPTED_ACTION_STATUSES.)
26
+ *
27
+ * Fail closed where the spend cannot be placed in time: a signed spend with no
28
+ * readable creation time, or a removal with no readable start, blocks.
29
+ */
30
+ export function failedVaultSpendBlocksRemoval(
31
+ action: { txid?: string; created_at?: string | Date | number },
32
+ removalStartedAt: number
33
+ ): boolean {
34
+ if (typeof action.txid !== 'string' || action.txid === '') return false
35
+ const at = action.created_at
36
+ const created =
37
+ at instanceof Date ? at.getTime() : typeof at === 'number' ? at : typeof at === 'string' ? Date.parse(at) : NaN
38
+ if (!Number.isFinite(created) || !Number.isFinite(removalStartedAt)) return true
39
+ return created >= removalStartedAt
40
+ }