@bsv/expo-wallet-toolbox 0.25.1 → 0.27.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 (59) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/core/context/WalletContext.tsx +23 -2
  3. package/core/i18n/translations.tsx +245 -36
  4. package/core/identity/handleRegistry/classify.ts +74 -0
  5. package/core/identity/handleRegistry/client.ts +110 -16
  6. package/core/identity/handleRegistry/registration.ts +115 -17
  7. package/core/identity/handleRegistry/resolver.ts +77 -34
  8. package/core/identity/handleRegistry/rules.ts +4 -0
  9. package/core/index.ts +7 -0
  10. package/core/monitor/TaskDrainOutbox.ts +13 -3
  11. package/core/pay/paymail/address.ts +19 -0
  12. package/core/pay/paymail/client.ts +177 -0
  13. package/core/pay/paymail/networkCheck.ts +56 -0
  14. package/core/pay/rails/handle.ts +46 -9
  15. package/core/pay/rails/paymail.ts +542 -0
  16. package/core/peerpay/handleResendRequests.ts +6 -6
  17. package/core/peerpay/outbox.ts +185 -17
  18. package/core/peerpay/rebuildToken.ts +2 -2
  19. package/core/profiles/profileStore.ts +4 -1
  20. package/core/services/groupSpendingLimit.ts +26 -0
  21. package/core/services/signingPermissionPolicy.ts +14 -8
  22. package/core/services/vault/ceremony.ts +13 -0
  23. package/core/services/vault/ceremonyHost.ts +58 -0
  24. package/core/services/vault/failedVaultSpend.ts +40 -0
  25. package/core/services/vault/outputAuthority.ts +13 -6
  26. package/core/services/vault/transfers.ts +56 -12
  27. package/core/storage/encryptedDbImage.ts +11 -2
  28. package/core/theme/tokens.ts +26 -12
  29. package/package.json +2 -1
  30. package/ui/components/QRScanner.tsx +24 -22
  31. package/ui/components/pay/ImportedOutboxApproval.tsx +23 -2
  32. package/ui/components/pay/MessageBoxConfig.tsx +10 -16
  33. package/ui/components/pay/NearbyAdvisoryModal.tsx +6 -13
  34. package/ui/components/pay/NearbyFlow.tsx +72 -35
  35. package/ui/components/pay/PayForm.tsx +27 -19
  36. package/ui/components/pay/PaymentSuccessOverlay.tsx +8 -6
  37. package/ui/components/pay/UniversalSend.tsx +79 -5
  38. package/ui/components/ui/AlertCard.tsx +3 -2
  39. package/ui/components/ui/BalancedText.tsx +117 -0
  40. package/ui/components/ui/ErrorBoundary.tsx +31 -14
  41. package/ui/components/ui/GroupedList.tsx +28 -22
  42. package/ui/components/ui/ListRow.tsx +126 -35
  43. package/ui/components/ui/PermissionSheet.tsx +31 -24
  44. package/ui/components/ui/PresenceRow.tsx +15 -23
  45. package/ui/components/ui/Sheet.tsx +11 -17
  46. package/ui/components/ui/Toast.tsx +13 -17
  47. package/ui/components/vault/EnrollWizard.tsx +446 -196
  48. package/ui/components/vault/KeyChooser.tsx +7 -20
  49. package/ui/components/vault/VaultCeremonySheet.tsx +44 -36
  50. package/ui/components/wallet/AmountInput.tsx +11 -17
  51. package/ui/components/wallet/BiometricAdvisoryModal.tsx +13 -17
  52. package/ui/index.ts +1 -1
  53. package/ui/screens/TrustScreen.tsx +49 -61
  54. package/ui/screens/VaultScreen.tsx +99 -60
  55. package/ui/screens/VaultTransferScreen.tsx +34 -27
  56. package/ui/screens/WalletCheckScreen.tsx +25 -24
  57. package/ui/screens/WalletConfigScreen.tsx +66 -72
  58. package/ui/screens/WalletHomeScreen.tsx +104 -4
  59. package/ui/txStatus.ts +1 -1
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Classify a paymail domain by its capability map.
3
+ *
4
+ * `peerpay`: the domain runs the profile lookup (`0ace65da5987`), so it is a
5
+ * MessageBox registry. `legacy`: it serves the paymail P2P pair that HandCash
6
+ * serves, so it can be paid by `sendViaPaymail`. `unsupported`: the document
7
+ * loaded and has neither, or the SRV answer was not authenticated. `failed`:
8
+ * DNS or HTTP gave no answer.
9
+ */
10
+ import { isPublicHttpsUrl } from '../../net/publicDestination'
11
+ import { BRFC_LOOKUP, BRFC_P2P_DESTINATION, BRFC_P2P_RECEIVE_BEEF, looksLikeDomain } from './rules'
12
+ import type { RegistryResolver } from './resolver'
13
+
14
+ export type PaymailClass = 'peerpay' | 'legacy' | 'unsupported' | 'failed'
15
+ export type UnsupportedReason = 'unsecured' | 'no_capabilities'
16
+ export interface PaymailClassification {
17
+ kind: PaymailClass
18
+ /** Only when `kind` is `unsupported`. */
19
+ reason?: UnsupportedReason
20
+ }
21
+ export interface ClassifyArgs {
22
+ resolver: Pick<RegistryResolver, 'discoverCapabilities'>
23
+ ownDomains: readonly string[]
24
+ }
25
+
26
+ const LEGACY_PLACEHOLDERS = ['{alias}', '{domain.tld}'] as const
27
+
28
+ /**
29
+ * A string that starts with `https://`, holds every placeholder, has none in
30
+ * the authority (a placeholder in the host would let user input choose the
31
+ * host), and passes `isPublicHttpsUrl`.
32
+ */
33
+ export function isLegacyCapabilityUrl(value: unknown, placeholders: readonly string[]): value is string {
34
+ if (typeof value !== 'string' || !value.startsWith('https://')) return false
35
+ if (!placeholders.every(p => value.includes(p))) return false
36
+ const rest = value.slice('https://'.length)
37
+ const end = rest.search(/[/?#]/)
38
+ const authority = end === -1 ? rest : rest.slice(0, end)
39
+ if (placeholders.some(p => authority.includes(p))) return false
40
+ return isPublicHttpsUrl(value)
41
+ }
42
+
43
+ export async function classifyPaymailDomainDetailed(
44
+ args: ClassifyArgs,
45
+ domain: string
46
+ ): Promise<PaymailClassification> {
47
+ const d = domain.trim().toLowerCase()
48
+ if (args.ownDomains.some(own => own.toLowerCase() === d)) return { kind: 'peerpay' }
49
+ if (!looksLikeDomain(d)) return { kind: 'unsupported', reason: 'no_capabilities' }
50
+ const found = await args.resolver.discoverCapabilities(d)
51
+ switch (found.kind) {
52
+ case 'failed':
53
+ return { kind: 'failed' }
54
+ case 'unsecured':
55
+ return { kind: 'unsupported', reason: 'unsecured' }
56
+ case 'none':
57
+ return { kind: 'unsupported', reason: 'no_capabilities' }
58
+ case 'ok': {
59
+ const caps = found.capabilities
60
+ if (typeof caps[BRFC_LOOKUP] === 'string') return { kind: 'peerpay' }
61
+ if (
62
+ isLegacyCapabilityUrl(caps[BRFC_P2P_DESTINATION], LEGACY_PLACEHOLDERS) &&
63
+ isLegacyCapabilityUrl(caps[BRFC_P2P_RECEIVE_BEEF], LEGACY_PLACEHOLDERS)
64
+ ) {
65
+ return { kind: 'legacy' }
66
+ }
67
+ return { kind: 'unsupported', reason: 'no_capabilities' }
68
+ }
69
+ }
70
+ }
71
+
72
+ export async function classifyPaymailDomain(args: ClassifyArgs, domain: string): Promise<PaymailClass> {
73
+ return (await classifyPaymailDomainDetailed(args, domain)).kind
74
+ }
@@ -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
  }