@bsv/expo-wallet-toolbox 0.23.0 → 0.24.1

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 (86) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +1 -4
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/inbox.ts +169 -64
  16. package/core/bridge/memoryInboxStore.ts +10 -1
  17. package/core/constants.ts +7 -11
  18. package/core/context/WalletConnectionContext.tsx +85 -48
  19. package/core/context/WalletContext.tsx +30 -32
  20. package/core/context/usePairingAttempt.ts +31 -0
  21. package/core/e2e/broadcaster.ts +25 -0
  22. package/core/e2e/consentFixture.ts +46 -0
  23. package/core/e2e/mode.ts +42 -0
  24. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  25. package/core/headers/headerConsensus.ts +230 -0
  26. package/core/headers/headerStore.ts +344 -122
  27. package/core/headers/prewarm.ts +4 -7
  28. package/core/headers/syncHeaders.ts +82 -12
  29. package/core/i18n/translations.tsx +47 -12
  30. package/core/identity/handleRegistry/client.ts +4 -2
  31. package/core/identity/handleRegistry/resolver.ts +7 -11
  32. package/core/index.ts +2 -0
  33. package/core/localpay/pending.ts +39 -4
  34. package/core/network/boundedFetch.ts +101 -0
  35. package/core/networks.ts +11 -13
  36. package/core/pay/rails/address.ts +5 -4
  37. package/core/pay/rails/handle.ts +3 -1
  38. package/core/pay/rails/sweep.ts +791 -0
  39. package/core/peerpay/brc29.ts +4 -0
  40. package/core/peerpay/handleResendRequests.ts +15 -2
  41. package/core/peerpay/outbox.ts +115 -2
  42. package/core/profiles/assertProfileEmpty.ts +2 -2
  43. package/core/profiles/profileStore.ts +3 -2
  44. package/core/services/arcadeBroadcastProvider.ts +260 -114
  45. package/core/services/secrets/kek.ts +5 -0
  46. package/core/services/secrets/migration.ts +27 -2
  47. package/core/services/secrets/policy.ts +6 -0
  48. package/core/services/vault/VaultKeyService.ts +5 -2
  49. package/core/services/vault/ceremony.ts +2 -2
  50. package/core/services/vault/ceremonyHost.ts +1 -1
  51. package/core/services/vault/guard.ts +10 -0
  52. package/core/services/vault/outputAuthority.ts +76 -0
  53. package/core/services/vault/transfers.ts +52 -28
  54. package/core/services/vault/vaultStore.ts +60 -14
  55. package/core/services/walletConnectionValidation.ts +13 -1
  56. package/core/services/walletServiceConfig.ts +8 -7
  57. package/core/stores/ConnectionStore.ts +17 -0
  58. package/core/toolboxConfig.ts +60 -1
  59. package/expo-module.config.json +5 -0
  60. package/ios/BoundedBody.swift +15 -0
  61. package/ios/BsvBoundedFetch.podspec +17 -0
  62. package/ios/BsvBoundedFetchModule.swift +134 -0
  63. package/package.json +7 -3
  64. package/ui/components/pay/AddressReceive.tsx +6 -2
  65. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  66. package/ui/components/pay/PayCellRow.tsx +3 -1
  67. package/ui/components/pay/PayForm.tsx +12 -2
  68. package/ui/components/pay/RecipientField.tsx +1 -0
  69. package/ui/components/pay/RequestHub.tsx +1 -0
  70. package/ui/components/pay/UniversalSend.tsx +110 -42
  71. package/ui/components/ui/ListRow.tsx +10 -2
  72. package/ui/components/vault/KeyChooser.tsx +1 -1
  73. package/ui/components/wallet/AmountInput.tsx +4 -1
  74. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  75. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  76. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  77. package/ui/components/wallet/ProfileButton.tsx +1 -0
  78. package/ui/importDatabases.ts +31 -6
  79. package/ui/screens/ConnectionsScreen.tsx +12 -3
  80. package/ui/screens/PairScreen.tsx +10 -3
  81. package/ui/screens/PayScreen.tsx +1 -0
  82. package/ui/screens/TrustScreen.tsx +6 -3
  83. package/ui/screens/VaultScreen.tsx +13 -3
  84. package/ui/screens/VaultTransferScreen.tsx +6 -3
  85. package/ui/screens/WalletConfigScreen.tsx +17 -2
  86. package/ui/screens/WalletHomeScreen.tsx +7 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,153 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.24.1
6
+
7
+ One fix: the iOS native fetch. Hosts must rebuild their native apps.
8
+
9
+ ### Fixed
10
+
11
+ - **iOS: `BsvBoundedFetch` refused every request** with `ERR_INVALID_REQUEST`
12
+ ("Invalid bounded HTTPS request"). The module read `maxBytes` from an untyped
13
+ dictionary with `as? Int`; over JSI the value is a Swift `Double`, and that
14
+ cast is always nil. Backup, handle registry and trust-list requests all go
15
+ through this module, so none of them worked on iOS in 0.24.0. The value is
16
+ now read as a whole number from either representation. Android was not
17
+ affected (it uses a typed record).
18
+
19
+ ## 0.24.0
20
+
21
+ BSV Broadcaster as the broadcast path (#97), sweep of external keys (#93), the
22
+ security review fixes (#72 to #92) and an end-to-end harness mode (#67). Hosts
23
+ must rebuild their native apps: the package now ships a native module.
24
+
25
+ ### Breaking / host action
26
+
27
+ - **The package ships a native Expo module, `BsvBoundedFetch` (#72, #79).**
28
+ `android/`, `ios/` and `expo-module.config.json` are now published, and
29
+ `expo-modules-core` ~57.0.0 is a new peer. Expo autolinking picks the module
30
+ up; hosts must rebuild the native apps (a JS-only update is not enough).
31
+ Backup, handle registry and trust-list requests go through it so that the
32
+ response size is capped in native code before JS sees a byte. There is no
33
+ fallback to the global `fetch`: without the module those requests throw.
34
+ Redirects are returned as 3xx and are not followed.
35
+ - **Taal is removed** (#97): `taalArcUrl`, `taalApiKey` and
36
+ `createTaalBroadcastService`. See Removed.
37
+ - **Wallet guard** (#77): `revealCounterpartyKeyLinkage` is refused for every
38
+ originator but the admin, and the wallet database export protocol is a
39
+ reserved namespace that only the admin may use.
40
+ - **Vault deposits need a hardware key** (#83). Before a new vault output is
41
+ funded, one enrolled key must sign a challenge bound to that output
42
+ (`requireVaultOutputKeyPossession`). A deposit with no key present fails
43
+ with `VaultError` `not-enrolled` or `wrong-key`.
44
+ - **Imported databases hold their outgoing PeerPay payments** (#92).
45
+ `importDatabases` quarantines the imported outbox; nothing is sent again
46
+ until the user approves each payment in `UniversalSend`
47
+ (`ImportedOutboxApproval`). Approval is bound to the signed recipient output.
48
+ - **Legacy secret migration refuses to overwrite an existing wallet** (#84).
49
+ The result can now be `{ outcome: 'failed', stage: 'existing-identity' }`,
50
+ `retryable: true` when the store could not be read and `false` when an
51
+ envelope identity or KEK is already there.
52
+
53
+ ### Security
54
+
55
+ - **Backup** (#72, #73): response bytes are capped in the native receiver.
56
+ Writers now produce v2 envelopes that authenticate the log position (device,
57
+ generation, sequence, predecessor digest) and the snapshot head inside the
58
+ AEAD. Legacy entries still decode, but they cannot prove that a recovery
59
+ snapshot is complete.
60
+ - **Headers** (#81, #85): linked headers are checked for difficulty
61
+ transitions and accumulated work, an interrupted branch replacement is
62
+ recovered, and a remote payment root is accepted only when its header is an
63
+ anchored member of the validated chain.
64
+ - **Wallet connections** (#78, #80, #87, #88): the replay floor survives
65
+ pairing a topic again; revocation cancels pairing attempts that are still in
66
+ progress (`usePairingAttempt`); in-flight wallet requests are revoked when
67
+ the relay socket closes; and the session response must match the approved
68
+ topic, backend identity key and protocol at the claimed HTTPS origin.
69
+ `parseRelayResponse(raw, expected?)` takes the expected tuple.
70
+ - **Database import** (#82): every `sqlite_master` object is compared with the
71
+ reference schema. Names that start with `sqlite` are no longer exempt.
72
+ - **Secrets** (#86): a biometric upgrade reads the new key back through its
73
+ access control before the session unlocks.
74
+ - **Vault** (#91): metadata mutations (rename, key removal, recovery) are
75
+ bound to the authenticated snapshot.
76
+ - **Safari bridge inbox** (#74): queue limits are enforced in the native
77
+ store, results are kept under queue pressure and pending calls are closed on
78
+ disposal.
79
+ - **Nearby payments** (#76): a received description is cut at a complete
80
+ UTF-8 boundary, so it stays within its byte limit.
81
+
82
+ ### Added: end-to-end harness mode (#67)
83
+
84
+ - `configureToolbox({ e2e: { broadcasterUrl } })`, for test builds only. It
85
+ locks the wallet off mainnet, stores keys without a biometric prompt and
86
+ points Pay at a mock broadcaster on a loopback or private address.
87
+ `configureToolbox` throws when an E2E config also has a backup URL, the
88
+ vault, a push adapter or mainnet services. Never set it in a build that can
89
+ hold funds.
90
+ - Exports `isE2eBuild`, `getE2eBroadcasterUrl` and `e2eSafeChain`. Pay and
91
+ Home controls gained `testID`s for Maestro.
92
+
93
+ ### Changed
94
+
95
+ - BSV Broadcaster (`broadcast.bsvblockchain.tech`) is now the primary
96
+ broadcast, SSE and chaintracks endpoint on all 4 networks (main, test,
97
+ teratest, scaletest).
98
+ - Broadcast provider order: BSV Broadcaster, GorillaPool, WhatsOnChain,
99
+ Bitails. Each is registered only where the network table says it serves
100
+ that network.
101
+ - Each provider gets a flat 30 s budget (`postBeefUntilSuccessSoftTimeoutMs`
102
+ 30000, per-KB 0, max 30000). The walk inside a provider ends 2 s earlier
103
+ (28 s), so its results arrive before the soft timeout; a post does not
104
+ start with less than 1 s left. Transactions not reached get retryable
105
+ errors.
106
+ - Every unconfirmed transaction of a BEEF is posted as EF, parents first.
107
+ An ancestor that cannot be built as EF gets a retryable error, as do its
108
+ descendants.
109
+ - Only BSV Broadcaster validator answers HTTP 400 with the posted txid and
110
+ ARC code 461 or 464 (number or string) are final rejections. Every other
111
+ non-success answer is retryable.
112
+
113
+ ### Removed
114
+
115
+ - Taal: `taalArcUrl`, `taalApiKey` and `createTaalBroadcastService`. Hosts
116
+ that pass `taalApiKey` must drop it.
117
+
118
+ ### Added: sweep external keys (`core/pay/rails/sweep.ts`)
119
+
120
+ Move coins that an external key controls into this wallet. Each sweep has a
121
+ preview step (WhatsOnChain reads only) and an execute step.
122
+
123
+ - **WIF:** `parseWif` / `isWif` (mainnet and testnet, compressed and
124
+ uncompressed), `planWifSweep` (preview), `sweepWif` (execute).
125
+ - **Recovery phrase:** `scanMnemonic` (preview: gap-limit scan of each path's
126
+ receive chain; the change chain only when the receive chain shows use),
127
+ `sweepMnemonic` (execute, with per-path totals). The path list
128
+ (`paths`, default `DEFAULT_SWEEP_PATHS`, a placeholder) and the gap limit
129
+ (`gapLimit`, default 20) are parameters.
130
+ - **Import decision:** `decideMnemonicImport` returns `restore` (backup cache
131
+ hit), `sweep` (no backup, coins found) or `empty` (restore as this wallet's
132
+ root). A failed cache lookup throws; it never falls through to a sweep.
133
+ - The spend is the wallet's own `createAction` with the external outpoints as
134
+ inputs and no outputs, then `signAction` with locally signed inputs. The
135
+ wallet sets the fee, adds change to the default basket and broadcasts.
136
+ Batches of at most `maxInputsPerTx` (default 100) inputs per transaction.
137
+ - Never spent: 1-sat outputs (`token`), outputs below their own input fee
138
+ (`dust`), outputs whose real script is not plain P2PKH (`nonstandard`). All
139
+ are reported in `skipped`. A batch is aborted when the wallet adds an input
140
+ of its own or the fee rate exceeds `maxFeeRate` (default 1000 sat/kB).
141
+ - `wocFetch` in `pay/rails/address.ts` is now exported.
142
+
143
+ ### Fixed
144
+
145
+ - **The ARC and WhatsOnChain broadcasters now post every transaction in a multi-transaction BEEF.** They previously
146
+ converted the BEEF to a single transaction (`Transaction.fromBEEF` returns the last one) and returned one result, so in
147
+ a `sendWith` batch of chained transactions only the last was posted, and the earlier ones reached the network only if
148
+ a later provider in the chain posted the whole BEEF. Each requested
149
+ txid is now posted on its own, parents first (`Beef.sortTxs`), with one result per txid in the caller's order. A
150
+ child whose parent was not accepted is not posted and is reported as a retryable service error.
151
+
5
152
  ## 0.23.0
6
153
 
7
154
  Peer floors raised to the latest `@bsv` releases, the browser wallet bridge
package/README.md CHANGED
@@ -187,10 +187,7 @@ configureToolbox({
187
187
  arcUrl: process.env.EXPO_PUBLIC_ARC_URL,
188
188
  arcApiKey: process.env.EXPO_PUBLIC_ARC_API_KEY,
189
189
  chaintracksUrl: process.env.EXPO_PUBLIC_CHAINTRACKS_URL,
190
- whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY,
191
- // A distinct key: TAAL and WhatsOnChain are different origins, and this
192
- // one is never used as a fallback for the other.
193
- taalApiKey: process.env.EXPO_PUBLIC_TAAL_API_KEY
190
+ whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY
194
191
  }
195
192
  }
196
193
  })
@@ -0,0 +1,15 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'org.bsv'
7
+ version = '0.0.0'
8
+
9
+ android {
10
+ namespace 'org.bsv.boundedfetch'
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName '0.0.0'
14
+ }
15
+ }
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET" />
3
+ </manifest>
@@ -0,0 +1,19 @@
1
+ package org.bsv.boundedfetch;
2
+
3
+ import java.io.ByteArrayOutputStream;
4
+ import java.io.IOException;
5
+
6
+ /** Counts decoded response bytes before they enter the accumulated body. */
7
+ public final class BoundedBody {
8
+ private final int limit;
9
+ private final ByteArrayOutputStream body = new ByteArrayOutputStream();
10
+
11
+ public BoundedBody(int limit) { this.limit = limit; }
12
+
13
+ public void append(byte[] chunk, int count) throws IOException {
14
+ if (count > limit - body.size()) throw new IOException("ERR_RESPONSE_TOO_LARGE");
15
+ body.write(chunk, 0, count);
16
+ }
17
+
18
+ public byte[] bytes() { return body.toByteArray(); }
19
+ }
@@ -0,0 +1,28 @@
1
+ package org.bsv.boundedfetch;
2
+
3
+ import java.io.IOException;
4
+ import java.net.HttpURLConnection;
5
+ import java.util.concurrent.atomic.AtomicBoolean;
6
+
7
+ /** Cancellation remains effective even before HttpURLConnection is connected. */
8
+ public final class BoundedConnection {
9
+ private final HttpURLConnection connection;
10
+ private final AtomicBoolean cancelled = new AtomicBoolean();
11
+
12
+ public BoundedConnection(HttpURLConnection connection) { this.connection = connection; }
13
+
14
+ public void cancel() {
15
+ cancelled.set(true);
16
+ connection.disconnect();
17
+ }
18
+
19
+ public void checkActive() throws IOException {
20
+ if (cancelled.get()) throw new IOException("Bounded request aborted");
21
+ }
22
+
23
+ public void connect() throws IOException {
24
+ checkActive();
25
+ connection.connect();
26
+ checkActive();
27
+ }
28
+ }
@@ -0,0 +1,114 @@
1
+ package org.bsv.boundedfetch
2
+
3
+ import android.util.Base64
4
+ import expo.modules.kotlin.Promise
5
+ import expo.modules.kotlin.modules.Module
6
+ import expo.modules.kotlin.modules.ModuleDefinition
7
+ import expo.modules.kotlin.records.Field
8
+ import expo.modules.kotlin.records.Record
9
+ import java.net.HttpURLConnection
10
+ import java.net.URL
11
+ import java.util.concurrent.ConcurrentHashMap
12
+ import java.util.concurrent.Executors
13
+ import java.util.zip.GZIPInputStream
14
+
15
+ class BoundedRequestOptions : Record {
16
+ @Field var id: String = ""
17
+ @Field var url: String = ""
18
+ @Field var method: String = "GET"
19
+ @Field var headers: List<List<String>> = emptyList()
20
+ @Field var body: String? = null
21
+ @Field var maxBytes: Int = -1
22
+ }
23
+
24
+ class BsvBoundedFetchModule : Module() {
25
+ private val requests = ConcurrentHashMap<String, BoundedConnection>()
26
+ private val workers = Executors.newCachedThreadPool()
27
+
28
+ override fun definition() = ModuleDefinition {
29
+ Name("BsvBoundedFetch")
30
+
31
+ // Register synchronously on the module queue before scheduling network I/O.
32
+ // The subsequent cancel call uses the same queue and sees the receiver.
33
+ AsyncFunction("request") { options: BoundedRequestOptions, promise: Promise ->
34
+ try {
35
+ val url = URL(options.url)
36
+ require(url.protocol == "https" && options.maxBytes in 0..67108864) { "Invalid bounded HTTPS request" }
37
+ val connection = url.openConnection() as HttpURLConnection
38
+ connection.instanceFollowRedirects = false
39
+ connection.useCaches = false
40
+ connection.connectTimeout = 30000
41
+ connection.readTimeout = 30000
42
+ connection.requestMethod = options.method
43
+ options.headers.forEach { header ->
44
+ require(header.size == 2) { "Invalid header" }
45
+ connection.setRequestProperty(header[0], header[1])
46
+ }
47
+ // Explicit encoding disables Android's implicit decompression; count the
48
+ // decoded stream below, including when the server ignores identity.
49
+ connection.setRequestProperty("Accept-Encoding", "identity")
50
+ val receiver = BoundedConnection(connection)
51
+ requests[options.id] = receiver
52
+ workers.execute {
53
+ try {
54
+ receiver.checkActive()
55
+ val upload = options.body?.let { Base64.decode(it, Base64.DEFAULT) }
56
+ if (upload != null) {
57
+ connection.doOutput = true
58
+ connection.setFixedLengthStreamingMode(upload.size)
59
+ }
60
+ receiver.connect()
61
+ if (upload != null) {
62
+ receiver.checkActive()
63
+ connection.outputStream.use { it.write(upload) }
64
+ }
65
+ receiver.checkActive()
66
+ val status = connection.responseCode
67
+ val declaredLength = connection.getHeaderField("Content-Length")?.toLongOrNull()
68
+ if (declaredLength != null && declaredLength > options.maxBytes) {
69
+ throw java.io.IOException("ERR_RESPONSE_TOO_LARGE")
70
+ }
71
+ val body = BoundedBody(options.maxBytes)
72
+ val raw = if (status >= 400) connection.errorStream else connection.inputStream
73
+ raw?.use {
74
+ val stream = when (connection.contentEncoding?.lowercase()) {
75
+ null, "identity" -> it
76
+ "gzip" -> GZIPInputStream(it)
77
+ else -> throw java.io.IOException("Unsupported response encoding")
78
+ }
79
+ stream.use { decoded ->
80
+ val chunk = ByteArray(8192)
81
+ while (true) {
82
+ receiver.checkActive()
83
+ val count = decoded.read(chunk)
84
+ if (count < 0) break
85
+ // Reject BEFORE appending, with no native-to-JS chunk queue.
86
+ body.append(chunk, count)
87
+ }
88
+ }
89
+ }
90
+ val headers = connection.headerFields.entries.filter { it.key != null }
91
+ .flatMap { entry -> entry.value.map { listOf(entry.key, it) } }
92
+ promise.resolve(mapOf("status" to status, "headers" to headers,
93
+ "body" to Base64.encodeToString(body.bytes(), Base64.NO_WRAP)))
94
+ } catch (error: Exception) {
95
+ promise.reject("ERR_BOUNDED_FETCH", error.message ?: "Bounded request failed", error)
96
+ } finally {
97
+ requests.remove(options.id)
98
+ connection.disconnect()
99
+ }
100
+ }
101
+ } catch (error: Exception) {
102
+ promise.reject("ERR_BOUNDED_FETCH", error.message ?: "Invalid bounded request", error)
103
+ }
104
+ }
105
+
106
+ AsyncFunction("cancel") { id: String -> requests[id]?.cancel(); Unit }
107
+
108
+ OnDestroy {
109
+ requests.values.forEach { it.cancel() }
110
+ requests.clear()
111
+ workers.shutdownNow()
112
+ }
113
+ }
114
+ }
@@ -33,10 +33,11 @@ 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. */
36
+ /** One decoded entry retained across authentication and replay, bounded independently of log size. */
38
37
  private decodedCache: { seq: number; decoded: DecodedEntry } | null = null
39
38
  private verifiedCompletePromise: Promise<boolean> | null = null
39
+ private authenticationPromise: Promise<boolean> | null = null
40
+ private authenticatedLog = false
40
41
  /** The most recent (i.e. furthest along in replay order) appData snapshot seen on any
41
42
  * entry so far — see the `appData` getter below. */
42
43
  private lastAppData: AppDataSnapshot | undefined
@@ -48,7 +49,8 @@ export class RemoteSyncReader {
48
49
  private readonly deviceId: string,
49
50
  private readonly generation: number,
50
51
  private readonly settings: TableSettings,
51
- private readonly expectedHeadSeq?: number
52
+ private readonly expectedHeadSeq?: number,
53
+ private readonly onActivity?: () => void
52
54
  ) {}
53
55
 
54
56
  /** Settings for the storage being restored into. */
@@ -57,9 +59,8 @@ export class RemoteSyncReader {
57
59
  }
58
60
 
59
61
  /**
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).
62
+ * Fetch and check server-index consistency, once. Authenticated membership is
63
+ * checked separately against the encrypted positions before replay.
63
64
  */
64
65
  private async ensureIndex(): Promise<LogEntry[]> {
65
66
  if (this.entries == null) {
@@ -101,15 +102,8 @@ export class RemoteSyncReader {
101
102
  } else {
102
103
  ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
103
104
  }
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.
105
+ // These checks detect corrupted transport bytes. The encrypted v2 position
106
+ // below is the authority for log membership, not this server-owned index.
113
107
  if (ciphertext.length !== entry.size) {
114
108
  throw new BackupChainError(
115
109
  `backup blob at sequence ${entry.seq} is ${ciphertext.length} bytes but the index recorded ${entry.size}`
@@ -119,7 +113,18 @@ export class RemoteSyncReader {
119
113
  if (digest !== entry.sha256) {
120
114
  throw new BackupChainError(`backup blob at sequence ${entry.seq} does not match the index's recorded digest`)
121
115
  }
122
- return await decodeEntry(this.wallet, Array.from(ciphertext), this.chain)
116
+ const decoded = await decodeEntry(this.wallet, Array.from(ciphertext), this.chain)
117
+ const position = decoded.position
118
+ if (
119
+ position &&
120
+ (position.deviceId !== this.deviceId ||
121
+ position.generation !== this.generation ||
122
+ position.seq !== entry.seq ||
123
+ position.prevSha256 !== (entry.prevSha256 ?? undefined))
124
+ ) {
125
+ throw new BackupChainError(`authenticated backup position does not match sequence ${entry.seq}`)
126
+ }
127
+ return decoded
123
128
  }
124
129
 
125
130
  /**
@@ -134,7 +139,7 @@ export class RemoteSyncReader {
134
139
  * rides alongside a chunk rather than replacing it, so nothing here needs to be swallowed.
135
140
  */
136
141
  async getSyncChunk(_args: RequestSyncChunkArgs): Promise<SyncChunk> {
137
- await this.ensureIndex()
142
+ await this.authenticateLog()
138
143
  const entries = this.entries!
139
144
 
140
145
  if (this.next >= entries.length) {
@@ -149,7 +154,9 @@ export class RemoteSyncReader {
149
154
  // own log (unlike restoreOnImport's cross-device merge). An entry that predates this
150
155
  // feature, or one written while there was genuinely nothing app-owned to add, carries no
151
156
  // `appData` at all and must not erase a still-current snapshot from an earlier entry.
152
- if (decoded.appData !== undefined) this.lastAppData = decoded.appData
157
+ // Legacy snapshots are reorderable by the service and must not overwrite
158
+ // live pending payments, outbox entries, contacts or issued dates.
159
+ if (this.authenticatedLog && decoded.appData !== undefined) this.lastAppData = decoded.appData
153
160
  // Advance only after successful download AND decryption. Retrying this
154
161
  // reader after either fails must retry the same entry rather than lose it.
155
162
  this.next++
@@ -192,21 +199,9 @@ export class RemoteSyncReader {
192
199
  }
193
200
 
194
201
  /**
195
- * Whether this generation's log, as it stands right now, is provably complete — i.e. this
196
- * device itself once confirmed the generation's initial snapshot was whole, independent of
197
- * anything the server's index metadata alone reports (see codec.ts's DecodedEntry and
198
- * push.ts's own seal docs).
199
- *
200
- * True only when the NEWEST entry carries a seal for THIS generation whose
201
- * `initialChunkCount` is no greater than the number of entries in the log — i.e. every
202
- * chunk of the initial snapshot the seal refers to is present. Cheap by design: only that
203
- * one entry is decrypted here, never the whole log — replay (getSyncChunk) still decodes
204
- * every entry as it goes and is what actually enforces the chain end to end.
205
- *
206
- * Because every chunk appended after the initial window closes carries the SAME seal (see
207
- * push.ts's pushOnce), this stays true as further deltas land, rather than flipping back to
208
- * false the moment a new chunk becomes the newest entry — a generation is not "un-verified"
209
- * by continuing to receive backups.
202
+ * True only after all v2 positions and the ordered initial-snapshot head
203
+ * commitment verify. A complete authentic old log can still be replayed by a
204
+ * server: freshness requires an independent trusted head anchor.
210
205
  */
211
206
  async verifiedComplete(): Promise<boolean> {
212
207
  if (this.verifiedCompletePromise == null) {
@@ -216,23 +211,53 @@ export class RemoteSyncReader {
216
211
  }
217
212
 
218
213
  private async computeVerifiedComplete(): Promise<boolean> {
219
- const entries = await this.ensureIndex()
220
- if (entries.length === 0) return false
221
-
222
- const last = entries[entries.length - 1]
223
- let decoded: DecodedEntry
224
214
  try {
225
- decoded = await this.fetchAndDecode(last)
215
+ if (!(await this.authenticateLog())) return false
216
+ return this.decodedCache?.decoded.seal != null
226
217
  } catch {
227
- // A last entry that fails to download or decrypt cannot be trusted as sealed —
228
- // treat the generation as unverified rather than throwing out of a check that
229
- // pickTarget uses purely to rank candidates.
218
+ // Ranking may skip a corrupt candidate. Its cached authentication failure
219
+ // is still rethrown before replay if the legacy fallback selects it.
230
220
  return false
231
221
  }
232
- this.decodedCache = { seq: last.seq, decoded }
233
- const seal = decoded.seal
234
- if (seal == null) return false
235
- return seal.generation === this.generation && seal.initialChunkCount <= entries.length
222
+ }
223
+
224
+ private authenticateLog(): Promise<boolean> {
225
+ if (this.authenticationPromise == null) {
226
+ this.authenticationPromise = this.checkAuthenticatedLog().catch(error => {
227
+ // Transient download failures must remain retryable at the same position.
228
+ this.authenticationPromise = null
229
+ throw error
230
+ })
231
+ }
232
+ return this.authenticationPromise
233
+ }
234
+
235
+ private async checkAuthenticatedLog(): Promise<boolean> {
236
+ const entries = await this.ensureIndex()
237
+ if (entries.length === 0) return false
238
+ const first = entries[0]
239
+ const decoded = await this.fetchAndDecode(first)
240
+ this.decodedCache = { seq: first.seq, decoded }
241
+ // Keep legacy entity recovery available, explicitly unverified. Its count-
242
+ // only seals prove neither ordered membership nor snapshot completeness.
243
+ if (!decoded.position) return false
244
+
245
+ // Preflight every authenticated position before returning ANY recovery
246
+ // state. Keep only one decoded entry cached so large backups stay bounded.
247
+ for (const entry of entries) {
248
+ const current = await this.fetchAndDecode(entry)
249
+ if (!current.position) throw new BackupChainError('backup generation mixes legacy and authenticated positions')
250
+ if (entry.seq === entries.length) this.decodedCache = { seq: entry.seq, decoded: current }
251
+ const seal = current.seal
252
+ if (seal && entries[seal.initialChunkCount - 1]?.sha256 !== seal.initialHeadSha256) {
253
+ throw new BackupChainError('authenticated initial snapshot head does not match the backup log')
254
+ }
255
+ // Authentication can take longer than the rebuild's inactivity deadline.
256
+ // Report work without exposing any recovery data before the whole log verifies.
257
+ this.onActivity?.()
258
+ }
259
+ this.authenticatedLog = true
260
+ return true
236
261
  }
237
262
 
238
263
  /**
@@ -32,6 +32,7 @@ import {
32
32
  } from '@bsv/backup-cache-client'
33
33
  import { MAX_RESTORE_RESPONSE_BYTES, type BackupChain } from './constants'
34
34
  import { deriveBackupWallet } from './derive'
35
+ import { createBoundedNativeFetch } from '../network/boundedFetch'
35
36
 
36
37
  export { BackupHttpError, ERR_BLOB_TOO_LARGE, ERR_SEQ_CONFLICT }
37
38
  export type { DeviceSummary, Limits, LogEntry }
@@ -53,13 +54,13 @@ export class BackupClient extends BackupCacheClient {
53
54
  * @param primaryKey the wallet's m/0'/0' key, from which the pseudonym is derived.
54
55
  * @param chain the network this client serves. Each chain derives a different
55
56
  * pseudonym, so each network's log lives in its own server account.
56
- * @param fetchImpl injectable transport for tests; defaults to global fetch.
57
+ * @param fetchImpl trusted injectable transport for tests; production uses the native receive cap.
57
58
  */
58
59
  constructor(baseUrl: string, primaryKey: number[], chain: BackupChain, fetchImpl?: typeof fetch) {
59
60
  super({
60
61
  baseUrl,
61
62
  wallet: deriveBackupWallet(primaryKey, chain),
62
- fetch: withBackupRequestTimeout(fetchImpl ?? ((input, init) => fetch(input, init)))
63
+ fetch: withBackupRequestTimeout(fetchImpl ?? createBoundedNativeFetch(MAX_RESTORE_RESPONSE_BYTES))
63
64
  })
64
65
  }
65
66
 
@@ -80,13 +81,9 @@ export class BackupClient extends BackupCacheClient {
80
81
  }
81
82
 
82
83
  /**
83
- * Bound the request and the body readers used by BackupCacheClient with one
84
- * deadline. React Native's XHR fetch resolves after the download, but its
85
- * Blob/FileReader conversion is still asynchronous; browser fetch can resolve
86
- * before any body bytes arrive. Neither phase may strand the monitor.
87
- *
88
- * Wrap the existing readers instead of rebuilding/cloning the Response: a
89
- * large backup still allocates only the buffer the package itself requests.
84
+ * Apply one deadline to transport and body decoding. The production transport
85
+ * bounds actual received bytes natively before this wrapper receives a Response;
86
+ * Content-Length here is only an advisory early rejection for injected transports.
90
87
  */
91
88
  export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch {
92
89
  return async (input, init) => {
@@ -135,12 +132,6 @@ export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch
135
132
  }
136
133
 
137
134
  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
135
  const declaredLength = Number(response.headers.get('content-length'))
145
136
  if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_RESPONSE_BYTES) {
146
137
  throw new BackupHttpError(