@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
package/README.md CHANGED
@@ -171,7 +171,9 @@ configureToolbox({
171
171
  arcApiKey: process.env.EXPO_PUBLIC_ARC_API_KEY,
172
172
  chaintracksUrl: process.env.EXPO_PUBLIC_CHAINTRACKS_URL,
173
173
  whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY,
174
- taalApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY
174
+ // A distinct key: TAAL and WhatsOnChain are different origins, and this
175
+ // one is never used as a fallback for the other.
176
+ taalApiKey: process.env.EXPO_PUBLIC_TAAL_API_KEY
175
177
  }
176
178
  }
177
179
  })
@@ -560,6 +562,57 @@ are required — both hard-won during this package's extraction:
560
562
 
561
563
  ## Breaking changes
562
564
 
565
+ **0.10.0:** `verifyFramePayment` takes `{ wallet, chainTracker }`
566
+ (`FrameVerifyDeps`) as its first argument instead of a single wallet, and
567
+ `DerivingWallet` no longer includes `getServices()`. Pass the permissions
568
+ manager as `wallet` and `await storage.getServices().getChainTracker()` as
569
+ `chainTracker`. The 0.8.0 note below about `DerivingWallet` gaining
570
+ `getServices()` no longer applies.
571
+
572
+ **0.9.0:** `useWallet().logout` now returns `Promise<boolean>` (it was
573
+ `() => void`). It resolves once teardown has finished, and resolves to
574
+ `false` when the secrets layer could not confirm erasure. Await it before
575
+ treating sign-out or Delete Wallet as complete. The
576
+ `@bsv/wallet-toolbox-mobile` peer range moves to ^2.14.3, and hosts must copy
577
+ `patches/@bsv+wallet-toolbox-mobile+2.14.3.patch` in place of the 2.14.0
578
+ patch. 0.8.0 was never published, so hosts upgrading from 0.7.0 get its
579
+ breaking changes below as well.
580
+
581
+ **0.8.0:** three API points break. `DerivingWallet` (the interface
582
+ `core/localpay/verify.ts`'s `verifyFramePayment` accepts) gains a required
583
+ `getServices(): { getChainTracker(): Promise<ChainTracker> | ChainTracker }`
584
+ — a host that built its own object against the old, narrower shape (just
585
+ `getPublicKey`) must add it before its build will typecheck.
586
+ `RestoreWalletDeps` gains a required `hasStoredIdentity(): Promise<boolean>`
587
+ and `RestorePrompts` gains a required `confirmReplace(): Promise<'replace' |
588
+ 'keep'>` — a host supplying its own `RestoreWalletDeps`, or building its own
589
+ `RestorePrompts` instead of using `ui/recoveryPrompts.ts`'s
590
+ `restorePrompts(t)`, must implement both. `core/storage/LocalStorageAdapter.ts`
591
+ and its exports (`initializeLocalStorage`, `isLocalStorage`,
592
+ `getStorageDisplayName`, `LocalStorageConfig`) are removed — dead code with
593
+ no real caller in this app, but a host that imported these names directly
594
+ gets a build error.
595
+
596
+ `restoreWallet`/`recoverWallet` also change host-visible behaviour for
597
+ anything that goes through them (the app's own mnemonic and scan-shares
598
+ screens, and any host reusing the `core/recovery/` module directly):
599
+ recovering or importing over an already-built wallet now rebuilds instead of
600
+ silently no-op'ing, storing one secret kind now deletes the other (exactly
601
+ one secret survives a restore), a failed backup replay's "skip" now also
602
+ works for hex/WIF imports, an attestation failure after a successful build
603
+ is reported non-fatally instead of failing the whole attempt, and
604
+ `recoverWallet` now asks the new `confirmReplace` prompt before overwriting
605
+ a secret already on the device — declining cancels before anything is
606
+ written. An external pairing deep link no longer auto-connects from
607
+ Connections; it now lands on `/pair` and requires the same explicit
608
+ Approve/Reject tap a scanned QR gets. `validateShareCompatibility` is
609
+ deprecated (still works, returns English prose) in favour of
610
+ `checkShareCompatibility`, which returns a code for the caller to translate.
611
+ See the CHANGELOG's 0.8.0 entry for the full list, including the additive
612
+ review-fix changes (Nearby/QR payment verification, offline-drain and
613
+ declined-payment handling, auto-approve bounds, exchange-rate/header/backup
614
+ fixes, and more) that ship alongside these three breaking points.
615
+
563
616
  **0.4.0:** the package no longer reads `process.env` at all. `DEFAULT_BACKUP_URL`
564
617
  is removed, and the `EXPO_PUBLIC_*` service reads in `walletServiceConfig` are
565
618
  gone. The host supplies these through `configureToolbox({ backupUrl, services })`
@@ -428,10 +428,26 @@ export const formatAmountInInputUnit = (
428
428
  return formatSatoshisLocale(Math.abs(Math.round(n)))
429
429
  }
430
430
 
431
+ /**
432
+ * The character the active locale uses for a decimal point (e.g. ',' for
433
+ * de-DE), read off a real formatted number rather than hardcoded — a
434
+ * comma-decimal locale typing '3,50' must not have it silently truncated at
435
+ * the comma by `parseFloat`, which only ever recognizes '.'.
436
+ */
437
+ export const decimalSeparator = (): string => {
438
+ try {
439
+ const part = new Intl.NumberFormat(locale()).formatToParts(1.1).find(p => p.type === 'decimal')
440
+ return part?.value ?? '.'
441
+ } catch {
442
+ return '.'
443
+ }
444
+ }
445
+
431
446
  /**
432
447
  * Convert a user-entered display value back to integer satoshis.
433
448
  * - BSV mode: input is satoshi integers, passthrough
434
- * - fiat mode: input is a decimal amount in that currency
449
+ * - fiat mode: input is a decimal amount in that currency, typed with the
450
+ * active locale's own decimal separator
435
451
  */
436
452
  export const parseDisplayToSatoshis = (
437
453
  displayValue: string,
@@ -443,7 +459,9 @@ export const parseDisplayToSatoshis = (
443
459
  if (!cleaned) return 0
444
460
 
445
461
  if (isFiatCurrency(currency)) {
446
- const amount = parseFloat(cleaned)
462
+ const sep = decimalSeparator()
463
+ const normalized = sep === '.' ? cleaned : cleaned.replace(sep, '.')
464
+ const amount = parseFloat(normalized)
447
465
  if (isNaN(amount)) return 0
448
466
  const per = satoshisPerFiatUnit(currency, satoshisPerUSD, usdToFiat)
449
467
  if (!(per > 0)) return 0
@@ -6,11 +6,11 @@
6
6
  * toolbox at all. `WalletStorageManager.syncFromReader` drives this exactly as it would
7
7
  * drive a live remote storage provider.
8
8
  */
9
- import type { CompletedProtoWallet } from '@bsv/sdk'
9
+ import { Hash, Utils, type CompletedProtoWallet } from '@bsv/sdk'
10
10
  import type { TableSettings } from '@bsv/wallet-toolbox-mobile'
11
11
  import type { BackupClient, LogEntry } from './client'
12
- import { decodeChunk, emptyChunk } from './codec'
13
- import type { BackupChain } from './constants'
12
+ import { decodeEntry, emptyChunk, type AppDataSnapshot, type DecodedEntry } from './codec'
13
+ import { MAX_INDEX_ENTRIES, type BackupChain } from './constants'
14
14
  import type { RequestSyncChunkArgs, SyncChunk } from '../toolboxTypes'
15
15
 
16
16
  export class BackupChainError extends Error {
@@ -33,6 +33,13 @@ export class RemoteSyncReader {
33
33
  private entries: LogEntry[] | null = null
34
34
  private next = 0
35
35
  private prefetched: { seq: number, result: Promise<BlobResult> } | null = null
36
+ /** Decoded once, keyed by seq, so verifiedComplete's own look-ahead at the newest entry
37
+ * never re-fetches or re-decrypts it when replay later reaches that same entry. */
38
+ private decodedCache: { seq: number, decoded: DecodedEntry } | null = null
39
+ private verifiedCompletePromise: Promise<boolean> | null = null
40
+ /** The most recent (i.e. furthest along in replay order) appData snapshot seen on any
41
+ * entry so far — see the `appData` getter below. */
42
+ private lastAppData: AppDataSnapshot | undefined
36
43
 
37
44
  constructor (
38
45
  private readonly client: BackupClient,
@@ -50,20 +57,22 @@ export class RemoteSyncReader {
50
57
  }
51
58
 
52
59
  /**
53
- * Return the next chunk in sequence.
54
- *
55
- * `args` is ignored deliberately: a live reader would honour `since` and `offsets`, but a
56
- * log is an ordered recording of chunks that were already produced against those very
57
- * arguments. Replaying them in order reproduces the original stream exactly, and second
58
- * -guessing it would risk skipping records.
60
+ * Fetch and verify the index, once. Shared by getSyncChunk (which needs every entry to
61
+ * replay) and verifiedComplete (which only needs to know how many entries exist and what
62
+ * the last one is).
59
63
  */
60
- async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
64
+ private async ensureIndex (): Promise<LogEntry[]> {
61
65
  if (this.entries == null) {
62
66
  const entries: LogEntry[] = []
63
67
  let page = await this.client.index(this.deviceId, this.generation)
64
68
  for (;;) {
65
69
  const pageStart = entries.length
66
70
  entries.push(...page)
71
+ // A malicious/compromised backup host could otherwise keep paging forever — nothing
72
+ // else in this loop depends on the server ever running out of entries to offer.
73
+ if (entries.length > MAX_INDEX_ENTRIES) {
74
+ throw new BackupChainError(`backup index has grown past ${MAX_INDEX_ENTRIES} entries without completing`)
75
+ }
67
76
  this.verifyChain(entries, pageStart)
68
77
  const missingHead = this.expectedHeadSeq != null && entries.length < this.expectedHeadSeq
69
78
  if (page.length === 0) {
@@ -77,12 +86,11 @@ export class RemoteSyncReader {
77
86
  // let a retry skip verification or mistake a partial index for completion.
78
87
  this.entries = entries
79
88
  }
89
+ return this.entries
90
+ }
80
91
 
81
- if (this.next >= this.entries.length) {
82
- return emptyChunk(this.deviceId, this.settings.storageIdentityKey, '')
83
- }
84
-
85
- const entry = this.entries[this.next]
92
+ private async fetchAndDecode (entry: LogEntry): Promise<DecodedEntry> {
93
+ if (this.decodedCache?.seq === entry.seq) return this.decodedCache.decoded
86
94
  let ciphertext: Uint8Array
87
95
  if (this.prefetched?.seq === entry.seq) {
88
96
  const pending = this.prefetched
@@ -93,13 +101,62 @@ export class RemoteSyncReader {
93
101
  } else {
94
102
  ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
95
103
  }
96
- const chunk = await decodeChunk(this.wallet, Array.from(ciphertext), this.chain)
104
+ // The index is itself server-supplied, but it is fetched from a separate endpoint than
105
+ // the blob body — a malicious or compromised service can serve the wrong (though still
106
+ // authentic, same-wallet) ciphertext at a given sequence while its own index entry for
107
+ // that sequence still carries the digest/size of what that sequence actually holds.
108
+ // Decryption alone cannot catch this: the AEAD envelope authenticates only
109
+ // {chain, chunk, seal} (see codec.ts), never the position a chunk was appended at.
110
+ // Checking the downloaded bytes against the index's own claim for THIS entry, before
111
+ // ever decrypting them, rejects a substituted or reordered blob outright instead of
112
+ // silently replaying it mislabeled.
113
+ if (ciphertext.length !== entry.size) {
114
+ throw new BackupChainError(
115
+ `backup blob at sequence ${entry.seq} is ${ciphertext.length} bytes but the index recorded ${entry.size}`
116
+ )
117
+ }
118
+ const digest = Utils.toHex(Hash.sha256(Array.from(ciphertext)))
119
+ if (digest !== entry.sha256) {
120
+ throw new BackupChainError(`backup blob at sequence ${entry.seq} does not match the index's recorded digest`)
121
+ }
122
+ return await decodeEntry(this.wallet, Array.from(ciphertext), this.chain)
123
+ }
124
+
125
+ /**
126
+ * Return the next chunk in sequence.
127
+ *
128
+ * `args` is ignored deliberately: a live reader would honour `since` and `offsets`, but a
129
+ * log is an ordered recording of chunks that were already produced against those very
130
+ * arguments. Replaying them in order reproduces the original stream exactly, and second
131
+ * -guessing it would risk skipping records.
132
+ *
133
+ * Every entry is an ordinary chunk (see codec.ts's DecodedEntry) — a seal, when present,
134
+ * rides alongside a chunk rather than replacing it, so nothing here needs to be swallowed.
135
+ */
136
+ async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
137
+ await this.ensureIndex()
138
+ const entries = this.entries!
139
+
140
+ if (this.next >= entries.length) {
141
+ return emptyChunk(this.deviceId, this.settings.storageIdentityKey, '')
142
+ }
143
+
144
+ const entry = entries[this.next]
145
+ const decoded = await this.fetchAndDecode(entry)
146
+ // Every appData-carrying chunk is a full snapshot as of its own push (see
147
+ // backup/appData.ts's captureAppDataSnapshot), so the LAST one seen while replaying in
148
+ // order is authoritative — never merged with an earlier one within this same device's
149
+ // own log (unlike restoreOnImport's cross-device merge). An entry that predates this
150
+ // feature, or one written while there was genuinely nothing app-owned to add, carries no
151
+ // `appData` at all and must not erase a still-current snapshot from an earlier entry.
152
+ if (decoded.appData !== undefined) this.lastAppData = decoded.appData
97
153
  // Advance only after successful download AND decryption. Retrying this
98
154
  // reader after either fails must retry the same entry rather than lose it.
99
155
  this.next++
100
- const following = this.entries[this.next]
156
+ const following = entries[this.next]
101
157
  if (following && entry.size > 0 && entry.size <= PREFETCH_MAX_BYTES &&
102
- following.size > 0 && following.size <= PREFETCH_MAX_BYTES) {
158
+ following.size > 0 && following.size <= PREFETCH_MAX_BYTES &&
159
+ this.decodedCache?.seq !== following.seq) {
103
160
  this.prefetched = {
104
161
  seq: following.seq,
105
162
  // Store failures as values until consumed, so a stopped replay never
@@ -109,7 +166,8 @@ export class RemoteSyncReader {
109
166
  )
110
167
  }
111
168
  }
112
- return chunk
169
+
170
+ return decoded.chunk
113
171
  }
114
172
 
115
173
  /** Number of chunks in this generation, once the index has been read. */
@@ -117,6 +175,60 @@ export class RemoteSyncReader {
117
175
  return this.entries?.length ?? 0
118
176
  }
119
177
 
178
+ /**
179
+ * The most recent appData snapshot seen across every entry replayed through getSyncChunk
180
+ * so far (XR-011). Read by restore.ts once this device's log is fully drained, so it
181
+ * reflects the newest chunk that carried the field — undefined for a log written entirely
182
+ * before this feature shipped, or one with genuinely nothing app-owned to carry.
183
+ */
184
+ get appData (): AppDataSnapshot | undefined {
185
+ return this.lastAppData
186
+ }
187
+
188
+ /**
189
+ * Whether this generation's log, as it stands right now, is provably complete — i.e. this
190
+ * device itself once confirmed the generation's initial snapshot was whole, independent of
191
+ * anything the server's index metadata alone reports (see codec.ts's DecodedEntry and
192
+ * push.ts's own seal docs).
193
+ *
194
+ * True only when the NEWEST entry carries a seal for THIS generation whose
195
+ * `initialChunkCount` is no greater than the number of entries in the log — i.e. every
196
+ * chunk of the initial snapshot the seal refers to is present. Cheap by design: only that
197
+ * one entry is decrypted here, never the whole log — replay (getSyncChunk) still decodes
198
+ * every entry as it goes and is what actually enforces the chain end to end.
199
+ *
200
+ * Because every chunk appended after the initial window closes carries the SAME seal (see
201
+ * push.ts's pushOnce), this stays true as further deltas land, rather than flipping back to
202
+ * false the moment a new chunk becomes the newest entry — a generation is not "un-verified"
203
+ * by continuing to receive backups.
204
+ */
205
+ async verifiedComplete (): Promise<boolean> {
206
+ if (this.verifiedCompletePromise == null) {
207
+ this.verifiedCompletePromise = this.computeVerifiedComplete()
208
+ }
209
+ return await this.verifiedCompletePromise
210
+ }
211
+
212
+ private async computeVerifiedComplete (): Promise<boolean> {
213
+ const entries = await this.ensureIndex()
214
+ if (entries.length === 0) return false
215
+
216
+ const last = entries[entries.length - 1]
217
+ let decoded: DecodedEntry
218
+ try {
219
+ decoded = await this.fetchAndDecode(last)
220
+ } catch {
221
+ // A last entry that fails to download or decrypt cannot be trusted as sealed —
222
+ // treat the generation as unverified rather than throwing out of a check that
223
+ // pickTarget uses purely to rank candidates.
224
+ return false
225
+ }
226
+ this.decodedCache = { seq: last.seq, decoded }
227
+ const seal = decoded.seal
228
+ if (seal == null) return false
229
+ return seal.generation === this.generation && seal.initialChunkCount <= entries.length
230
+ }
231
+
120
232
  /**
121
233
  * Reject a log with a gap or a fork before any of it is replayed.
122
234
  *
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The app-owned recovery-critical rows that ride alongside a pushed sync chunk, as the
3
+ * additive `appData` envelope field (see codec.ts's encodeChunk/decodeEntry).
4
+ *
5
+ * XR-011: `codec.ts`'s twelve CHUNK_ENTITIES are all toolbox-owned tables — nothing here ever
6
+ * touches key_value_store, so a receiver's acknowledged-but-not-yet-internalized Nearby/QR
7
+ * PaymentFrame (localpay_pending) and an outbound PeerPay token's delivery checkpoint
8
+ * (peerpay_outbox) were never backed up at all: a device loss before internalize/delivery
9
+ * completed stranded them permanently, even with a perfect seed+backup restore of everything
10
+ * else. XR-055 adds a third row, the durable issued-conventional-receive-date history
11
+ * (pay/receiveHistory.ts), for the same reason: it also lives only in key_value_store.
12
+ *
13
+ * This module is the ONLY place these rows cross from local storage into the backup log and
14
+ * back. It deliberately knows nothing about how to internalize a payment, retry a delivery,
15
+ * or sweep an address — `applyAppData` does exactly one thing, write rows back to
16
+ * key_value_store, so a replayed row is picked up by the SAME existing consumers (the
17
+ * background pending-queue effect, the outbox's own retry UI, the recovery sweep) through
18
+ * their own existing guards, exactly as if this device had written the row itself while
19
+ * briefly offline. Nothing here ever calls internalizeAction, broadcasts, or releases an
20
+ * input.
21
+ *
22
+ * Deferred out of this pass (see XR-011's ledger row): `offline_actions` and
23
+ * `token_linkage_payloads` are real SQL tables, not key_value_store blobs — replaying them
24
+ * needs a userId remap (their FK is device-local) and, for offline_actions, a decision on
25
+ * how a restored row's local `seq` should interleave with whatever this fresh device's own
26
+ * autoincrement has already assigned. Both are tractable but are a separate, larger change
27
+ * from the three KV rows here, which is why they are not included yet.
28
+ *
29
+ * KNOWN, STILL-OPEN GAP (see XR-011's reviewer follow-up): a row written here is only ever
30
+ * actually PERSISTED to the backup log on a push whose CHUNK already carries a real toolbox-
31
+ * entity change — see push.ts's own comment at its `captureAppDataSnapshot` call and
32
+ * codec.ts's encodeChunk docs for why (an appData-only entry, with every entity array empty,
33
+ * would trip the toolbox's own processSyncChunk completion sentinel for a downstream reader
34
+ * that doesn't yet understand this field). That means the row's own headline scenario — an
35
+ * acknowledged Nearby/QR payment, a PeerPay delivery checkpoint, or an issued receive date,
36
+ * with NOTHING ELSE touching an entity table in that same window — is NOT covered: the row
37
+ * stays local-only until some unrelated entity-bearing push happens to close a later window,
38
+ * which may never occur before the device is lost. This is pinned end-to-end (not merely at
39
+ * the pushOnce-unit level) by
40
+ * __tests__/backup/appDataIsolatedActivity.test.ts. Closing it for real needs either a
41
+ * dedicated appData-only log-entry shape — safe only once every device in the fleet is known
42
+ * to run a build that understands it — or a separate backup-server channel outside the
43
+ * per-device chunk log; both are wire/server changes shared with other devices, not a
44
+ * same-device code fix, so they are recorded here as an open design delta rather than
45
+ * attempted.
46
+ */
47
+ import { OUTBOX_KEY } from '../peerpay/outbox'
48
+ import { PENDING_KEY } from '../localpay/pending'
49
+ import { getIssuedDates, setIssuedDates } from '../pay/receiveHistory'
50
+ import type { AppDataSnapshot } from './codec'
51
+
52
+ export interface KVStorage {
53
+ getKeyValue (k: string): Promise<string | undefined>
54
+ setKeyValue (k: string, v: string): Promise<void>
55
+ }
56
+
57
+ /** True for `undefined` or a snapshot carrying nothing at all — the common "nothing queued,
58
+ * nothing to add" case, which must produce no `appData` field at all (see codec.ts's
59
+ * encodeChunk docs on why an unsealed/appData-less chunk must serialise byte-for-byte as the
60
+ * old-format envelope). */
61
+ export function isEmptyAppData (appData: AppDataSnapshot | undefined): boolean {
62
+ return (
63
+ appData == null ||
64
+ (appData.localpayPending === undefined &&
65
+ appData.peerpayOutbox === undefined &&
66
+ (appData.receiveIssuedDates?.length ?? 0) === 0)
67
+ )
68
+ }
69
+
70
+ /**
71
+ * Read the current value of every app-owned recovery-critical row, straight off local
72
+ * storage, for pushOnce to fold into the same envelope as whatever chunk it is about to
73
+ * send. Never called on its own cadence — see codec.ts's encodeChunk docs on why appData
74
+ * only ever rides an already-non-empty chunk.
75
+ */
76
+ export async function captureAppDataSnapshot (storage: KVStorage): Promise<AppDataSnapshot> {
77
+ const [localpayPending, peerpayOutbox, receiveIssuedDates] = await Promise.all([
78
+ storage.getKeyValue(PENDING_KEY),
79
+ storage.getKeyValue(OUTBOX_KEY),
80
+ getIssuedDates(storage)
81
+ ])
82
+ const snapshot: AppDataSnapshot = {}
83
+ if (localpayPending !== undefined) snapshot.localpayPending = localpayPending
84
+ if (peerpayOutbox !== undefined) snapshot.peerpayOutbox = peerpayOutbox
85
+ if (receiveIssuedDates.length > 0) snapshot.receiveIssuedDates = receiveIssuedDates
86
+ return snapshot
87
+ }
88
+
89
+ /**
90
+ * Apply a decoded snapshot to local storage. The ONLY effect of a restore replaying appData
91
+ * — three plain key_value_store writes, nothing else. Skips a field the snapshot did not
92
+ * carry (rather than overwriting with nothing), so replaying an OLDER chunk's appData after
93
+ * a newer one already landed (e.g. re-running an interrupted restore) can never regress a
94
+ * row that a later chunk already updated in this same pass.
95
+ */
96
+ export async function applyAppData (storage: KVStorage, snapshot: AppDataSnapshot): Promise<void> {
97
+ if (snapshot.localpayPending !== undefined) await storage.setKeyValue(PENDING_KEY, snapshot.localpayPending)
98
+ if (snapshot.peerpayOutbox !== undefined) await storage.setKeyValue(OUTBOX_KEY, snapshot.peerpayOutbox)
99
+ if (snapshot.receiveIssuedDates !== undefined && snapshot.receiveIssuedDates.length > 0) {
100
+ await setIssuedDates(storage, snapshot.receiveIssuedDates)
101
+ }
102
+ }
103
+
104
+ /** Parses a KV row's raw JSON text into an array of plain objects, never throwing — a
105
+ * corrupt or missing blob merges as if it were empty rather than failing the whole restore. */
106
+ function parseJsonArray (raw: string | undefined): Array<Record<string, unknown>> { // eslint-disable-line @typescript-eslint/array-type
107
+ if (raw === undefined) return []
108
+ try {
109
+ const parsed = JSON.parse(raw) as unknown
110
+ return Array.isArray(parsed) ? (parsed as Array<Record<string, unknown>>) : [] // eslint-disable-line @typescript-eslint/array-type
111
+ } catch {
112
+ return []
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Union two same-shaped `id`-keyed JSON-array KV blobs (localpay_pending / peerpay_outbox),
118
+ * keeping every distinct entry from both sides. Used only when restoring more than one
119
+ * device's own backup log into the same storage (XR-015): each device's own queue is an
120
+ * independent, non-overlapping history exactly like the toolbox's own entity tables are —
121
+ * restoring only the highest-ranked device's snapshot would silently drop whatever a second
122
+ * device alone was still holding (e.g. a Nearby payment received on a phone that was never
123
+ * the "primary" device in the manifest).
124
+ *
125
+ * On an id collision the FIRST side's entry wins, matching restoreOnImport's own device
126
+ * iteration order (primary device folded in first) — irrelevant in practice, since two
127
+ * devices sharing a seed cannot mint the same PaymentPending/OutboxEntry id (both are
128
+ * `${timestamp}_${keyPrefix}`-derived per device), but keeps the merge total rather than
129
+ * throwing on a theoretical collision.
130
+ */
131
+ function mergeJsonArrayById (a: string | undefined, b: string | undefined): string | undefined {
132
+ if (a === undefined) return b
133
+ if (b === undefined) return a
134
+ const merged = new Map<string, Record<string, unknown>>()
135
+ for (const item of [...parseJsonArray(a), ...parseJsonArray(b)]) {
136
+ const id = typeof item.id === 'string' ? item.id : JSON.stringify(item)
137
+ if (!merged.has(id)) merged.set(id, item)
138
+ }
139
+ return JSON.stringify([...merged.values()])
140
+ }
141
+
142
+ /**
143
+ * Merge two snapshots — see mergeJsonArrayById for why this is a union rather than a
144
+ * last-write-wins overwrite. `restoreOnImport` folds every device's own final appData
145
+ * together this way before the single `applyAppData` call that actually reaches storage, so
146
+ * no one device's snapshot can clobber another's.
147
+ */
148
+ export function mergeAppData (a: AppDataSnapshot | undefined, b: AppDataSnapshot | undefined): AppDataSnapshot {
149
+ return {
150
+ localpayPending: mergeJsonArrayById(a?.localpayPending, b?.localpayPending),
151
+ peerpayOutbox: mergeJsonArrayById(a?.peerpayOutbox, b?.peerpayOutbox),
152
+ receiveIssuedDates:
153
+ a?.receiveIssuedDates === undefined && b?.receiveIssuedDates === undefined
154
+ ? undefined
155
+ : [...new Set([...(a?.receiveIssuedDates ?? []), ...(b?.receiveIssuedDates ?? [])])].sort()
156
+ }
157
+ }
@@ -30,7 +30,7 @@ import {
30
30
  type Limits,
31
31
  type LogEntry
32
32
  } from '@bsv/backup-cache-client'
33
- import type { BackupChain } from './constants'
33
+ import { MAX_RESTORE_RESPONSE_BYTES, type BackupChain } from './constants'
34
34
  import { deriveBackupWallet } from './derive'
35
35
 
36
36
  export { BackupHttpError, ERR_BLOB_TOO_LARGE, ERR_SEQ_CONFLICT }
@@ -135,6 +135,20 @@ export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch
135
135
  }
136
136
 
137
137
  const response = await bounded(() => transport(input, { ...init, signal: controller.signal }))
138
+ // Refuse before EITHER reader is ever wrapped, let alone called: on this platform fetch
139
+ // has no incremental/streaming read mode (see this function's own docstring), so a
140
+ // declared-oversized body can only be bounded here, never partway through reading it.
141
+ // A response that omits Content-Length entirely passes through unchanged — a documented
142
+ // residual gap (see MAX_RESTORE_RESPONSE_BYTES), not a false rejection of ordinary
143
+ // traffic that happens not to declare a length.
144
+ const declaredLength = Number(response.headers.get('content-length'))
145
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_RESPONSE_BYTES) {
146
+ throw new BackupHttpError(
147
+ response.status,
148
+ 'ERR_RESPONSE_TOO_LARGE',
149
+ `response declared ${declaredLength} bytes, over the ${MAX_RESTORE_RESPONSE_BYTES}-byte restore cap`
150
+ )
151
+ }
138
152
  const readJson = response.json.bind(response)
139
153
  const readArrayBuffer = response.arrayBuffer.bind(response)
140
154
  response.json = () => bounded(readJson)