@bsv/expo-wallet-toolbox 0.22.0 → 0.24.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 (137) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +10 -9
  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/BrowserBridgeProvider.tsx +273 -0
  16. package/core/bridge/bindings.ts +459 -0
  17. package/core/bridge/conformance.ts +222 -0
  18. package/core/bridge/consent.ts +494 -0
  19. package/core/bridge/consentSheetSource.ts +98 -0
  20. package/core/bridge/dispatcher.ts +621 -0
  21. package/core/bridge/inbox.ts +569 -0
  22. package/core/bridge/index.ts +48 -0
  23. package/core/bridge/loopback/cors.ts +57 -0
  24. package/core/bridge/loopback/endpoints.ts +11 -0
  25. package/core/bridge/loopback/hostCheck.ts +25 -0
  26. package/core/bridge/loopback/index.ts +7 -0
  27. package/core/bridge/loopback/launchProof.ts +166 -0
  28. package/core/bridge/loopback/router.ts +770 -0
  29. package/core/bridge/loopback/routerTypes.ts +115 -0
  30. package/core/bridge/loopback/status.ts +52 -0
  31. package/core/bridge/memoryInboxStore.ts +231 -0
  32. package/core/bridge/permissionPolicy.ts +247 -0
  33. package/core/bridge/policy.ts +72 -0
  34. package/core/bridge/protocol/base64url.ts +64 -0
  35. package/core/bridge/protocol/connectionError.ts +79 -0
  36. package/core/bridge/protocol/constants.ts +21 -0
  37. package/core/bridge/protocol/continuity.ts +21 -0
  38. package/core/bridge/protocol/descriptor.ts +395 -0
  39. package/core/bridge/protocol/envelopes.ts +188 -0
  40. package/core/bridge/protocol/errorCodec.ts +164 -0
  41. package/core/bridge/protocol/json.ts +237 -0
  42. package/core/bridge/protocol/limits.ts +43 -0
  43. package/core/bridge/protocol/methods.ts +55 -0
  44. package/core/bridge/protocol/origin.ts +130 -0
  45. package/core/bridge/runtime.ts +642 -0
  46. package/core/bridge/runtimeFlags.ts +34 -0
  47. package/core/bridge/testing/conformanceCases.ts +149 -0
  48. package/core/bridge/testing/pageClient.ts +44 -0
  49. package/core/bridge/unverifiedManager.ts +97 -0
  50. package/core/bridge/unverifiedOriginator.ts +79 -0
  51. package/core/config.tsx +1 -16
  52. package/core/constants.ts +7 -11
  53. package/core/context/WalletConnectionContext.tsx +92 -49
  54. package/core/context/WalletContext.tsx +288 -165
  55. package/core/context/sessionTeardown.ts +46 -0
  56. package/core/context/usePairingAttempt.ts +31 -0
  57. package/core/e2e/broadcaster.ts +25 -0
  58. package/core/e2e/consentFixture.ts +46 -0
  59. package/core/e2e/mode.ts +42 -0
  60. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  61. package/core/headers/headerConsensus.ts +230 -0
  62. package/core/headers/headerStore.ts +344 -122
  63. package/core/headers/prewarm.ts +4 -7
  64. package/core/headers/syncHeaders.ts +82 -12
  65. package/core/hooks/usePermissionQueue.ts +89 -34
  66. package/core/i18n/translations.tsx +958 -24
  67. package/core/identity/handleRegistry/client.ts +4 -2
  68. package/core/identity/handleRegistry/resolver.ts +7 -11
  69. package/core/index.ts +17 -0
  70. package/core/localpay/pending.ts +39 -4
  71. package/core/network/boundedFetch.ts +101 -0
  72. package/core/networks.ts +11 -13
  73. package/core/pay/rails/address.ts +5 -4
  74. package/core/pay/rails/handle.ts +3 -1
  75. package/core/pay/rails/sweep.ts +791 -0
  76. package/core/peerpay/brc29.ts +4 -0
  77. package/core/peerpay/handleResendRequests.ts +15 -2
  78. package/core/peerpay/outbox.ts +115 -2
  79. package/core/profiles/assertProfileEmpty.ts +2 -2
  80. package/core/profiles/profileStore.ts +3 -2
  81. package/core/services/arcadeBroadcastProvider.ts +260 -114
  82. package/core/services/autoApprovePolicy.ts +7 -1
  83. package/core/services/capWalletArgs.ts +2 -1
  84. package/core/services/permissionPrompts.ts +132 -0
  85. package/core/services/secrets/kek.ts +5 -0
  86. package/core/services/secrets/migration.ts +27 -2
  87. package/core/services/secrets/policy.ts +6 -0
  88. package/core/services/signingPermissionPolicy.ts +230 -2
  89. package/core/services/vault/VaultKeyService.ts +5 -2
  90. package/core/services/vault/ceremony.ts +2 -2
  91. package/core/services/vault/ceremonyHost.ts +1 -1
  92. package/core/services/vault/guard.ts +20 -0
  93. package/core/services/vault/outputAuthority.ts +76 -0
  94. package/core/services/vault/transfers.ts +52 -28
  95. package/core/services/vault/vaultStore.ts +60 -14
  96. package/core/services/walletArgLimits.ts +17 -2
  97. package/core/services/walletConnectionValidation.ts +13 -1
  98. package/core/services/walletServiceConfig.ts +8 -7
  99. package/core/storage/encryptedDbImage.ts +325 -0
  100. package/core/stores/ConnectionStore.ts +17 -0
  101. package/core/toolboxConfig.ts +78 -2
  102. package/expo-module.config.json +5 -0
  103. package/ios/BoundedBody.swift +15 -0
  104. package/ios/BsvBoundedFetch.podspec +17 -0
  105. package/ios/BsvBoundedFetchModule.swift +121 -0
  106. package/package.json +12 -8
  107. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  108. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  109. package/ui/components/pay/AddressReceive.tsx +6 -2
  110. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  111. package/ui/components/pay/PayCellRow.tsx +3 -1
  112. package/ui/components/pay/PayForm.tsx +12 -2
  113. package/ui/components/pay/RecipientField.tsx +1 -0
  114. package/ui/components/pay/RequestHub.tsx +1 -0
  115. package/ui/components/pay/UniversalSend.tsx +110 -42
  116. package/ui/components/ui/ListRow.tsx +10 -2
  117. package/ui/components/ui/PermissionSheet.tsx +534 -158
  118. package/ui/components/ui/Sheet.tsx +59 -7
  119. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  120. package/ui/components/vault/KeyChooser.tsx +1 -1
  121. package/ui/components/wallet/AmountInput.tsx +4 -1
  122. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  123. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  124. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  125. package/ui/components/wallet/ProfileButton.tsx +1 -0
  126. package/ui/exportDatabases.ts +94 -5
  127. package/ui/hooks/useExportWalletData.ts +37 -24
  128. package/ui/importDatabases.ts +154 -34
  129. package/ui/index.ts +4 -0
  130. package/ui/screens/ConnectionsScreen.tsx +12 -3
  131. package/ui/screens/PairScreen.tsx +10 -3
  132. package/ui/screens/PayScreen.tsx +1 -0
  133. package/ui/screens/TrustScreen.tsx +6 -3
  134. package/ui/screens/VaultScreen.tsx +13 -3
  135. package/ui/screens/VaultTransferScreen.tsx +6 -3
  136. package/ui/screens/WalletConfigScreen.tsx +30 -3
  137. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -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(
@@ -140,16 +140,23 @@ function unpackBytes(value: unknown, key?: string): unknown {
140
140
  }
141
141
 
142
142
  /**
143
- * A seal's own payload: the generation it vouches for, and how many chunks made up that
144
- * generation's initial snapshot — the count the reader needs to see before it can call the
145
- * generation whole. Carried as an extra field on an ORDINARY chunk envelope (see
146
- * encodeChunk), never as a separate log entry: an old build's decodeChunk ignores a field it
147
- * has never heard of, so a chunk carrying a seal is byte-for-byte a chunk to any reader that
148
- * predates sealing.
143
+ * The initial snapshot's ordered ciphertext head and count. V2 readers verify
144
+ * both against a fully position-authenticated generation. Legacy count-only
145
+ * seals remain decodable but cannot establish completeness.
149
146
  */
150
147
  export interface BackupSeal {
151
148
  generation: number
152
149
  initialChunkCount: number
150
+ /** V2: digest of the final ciphertext in the ordered initial snapshot. */
151
+ initialHeadSha256?: string
152
+ }
153
+
154
+ /** Position authenticated inside the encrypted v2 envelope, never by the server index. */
155
+ export interface BackupLogPosition {
156
+ deviceId: string
157
+ generation: number
158
+ seq: number
159
+ prevSha256?: string
153
160
  }
154
161
 
155
162
  /**
@@ -181,10 +188,19 @@ export interface AppDataSnapshot {
181
188
  * has ever appended — this type exists mainly so RemoteSyncReader can read `seal`/`appData`
182
189
  * off an entry without re-decoding it a second time.
183
190
  */
184
- export type DecodedEntry = { kind: 'chunk'; chunk: SyncChunk; seal?: BackupSeal; appData?: AppDataSnapshot }
191
+ export type DecodedEntry = {
192
+ kind: 'chunk'
193
+ chunk: SyncChunk
194
+ seal?: BackupSeal
195
+ appData?: AppDataSnapshot
196
+ position?: BackupLogPosition
197
+ }
185
198
 
186
199
  /**
187
- * Serialise and encrypt a sync chunk, optionally sealing a generation in the same envelope.
200
+ * Serialise and encrypt a sync chunk. Production writers supply `position`,
201
+ * selecting v2 and binding the device, generation, sequence and predecessor
202
+ * digest inside the AEAD envelope. Omitting it retains legacy codec support;
203
+ * legacy entries can recover entities but cannot authenticate recovery snapshots.
188
204
  *
189
205
  * `counterparty: 'self'` is the entire zero-knowledge property. With 'self' the symmetric
190
206
  * key comes from the wallet's own key material and nobody else can derive it; naming the
@@ -214,9 +230,13 @@ export async function encodeChunk(
214
230
  chunk: SyncChunk,
215
231
  chain: BackupChain,
216
232
  seal?: BackupSeal,
217
- appData?: AppDataSnapshot
233
+ appData?: AppDataSnapshot,
234
+ position?: BackupLogPosition
218
235
  ): Promise<number[]> {
219
- const json = stringifyJsonRpc({ chain, chunk: packBytes(chunk), seal, appData }, true)
236
+ const json = stringifyJsonRpc(
237
+ { version: position ? 2 : undefined, chain, chunk: packBytes(chunk), seal, appData, position },
238
+ true
239
+ )
220
240
  const { ciphertext } = await wallet.encrypt({
221
241
  plaintext: Utils.toArray(json, 'utf8'),
222
242
  protocolID: BACKUP_PROTOCOL,
@@ -248,6 +268,8 @@ export async function decodeEntry(
248
268
  counterparty: 'self'
249
269
  })
250
270
  const envelope = parseJsonRpc(Utils.toUTF8(plaintext), true) as {
271
+ version?: unknown
272
+ position?: unknown
251
273
  chain?: unknown
252
274
  chunk?: unknown
253
275
  seal?: unknown
@@ -258,16 +280,59 @@ export async function decodeEntry(
258
280
  `backup blob is labeled for chain '${String(envelope?.chain)}' but '${chain}' was expected — refusing to restore across networks`
259
281
  )
260
282
  }
283
+ if (envelope.version !== undefined && envelope.version !== 2) throw new Error('unsupported backup envelope version')
284
+ const position = envelope.version === 2 ? decodePosition(envelope.position) : undefined
261
285
  let seal: BackupSeal | undefined
262
286
  if (envelope.seal != null) {
263
- const s = envelope.seal as { generation?: unknown; initialChunkCount?: unknown }
287
+ const s = envelope.seal as { generation?: unknown; initialChunkCount?: unknown; initialHeadSha256?: unknown }
264
288
  if (typeof s.generation !== 'number' || typeof s.initialChunkCount !== 'number') {
265
289
  throw new Error('backup seal is malformed')
266
290
  }
267
- seal = { generation: s.generation, initialChunkCount: s.initialChunkCount }
291
+ if (
292
+ position &&
293
+ (!Number.isSafeInteger(s.initialChunkCount) ||
294
+ s.initialChunkCount < 1 ||
295
+ !isDigest(s.initialHeadSha256) ||
296
+ s.generation !== position.generation ||
297
+ s.initialChunkCount >= position.seq)
298
+ ) {
299
+ throw new Error('authenticated backup seal is malformed')
300
+ }
301
+ seal = {
302
+ generation: s.generation,
303
+ initialChunkCount: s.initialChunkCount,
304
+ ...(position ? { initialHeadSha256: s.initialHeadSha256 as string } : {})
305
+ }
268
306
  }
269
307
  const appData = decodeAppData(envelope.appData)
270
- return { kind: 'chunk', chunk: unpackBytes(envelope.chunk) as SyncChunk, seal, appData }
308
+ return {
309
+ kind: 'chunk',
310
+ chunk: unpackBytes(envelope.chunk) as SyncChunk,
311
+ seal,
312
+ appData,
313
+ ...(position ? { position } : {})
314
+ }
315
+ }
316
+
317
+ function isDigest(value: unknown): value is string {
318
+ return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value)
319
+ }
320
+
321
+ function decodePosition(raw: unknown): BackupLogPosition {
322
+ const p = raw as Partial<BackupLogPosition> | null
323
+ if (
324
+ !p ||
325
+ typeof p.deviceId !== 'string' ||
326
+ !/^[0-9a-f]{32}$/.test(p.deviceId) ||
327
+ !Number.isSafeInteger(p.generation) ||
328
+ p.generation! < 1 ||
329
+ !Number.isSafeInteger(p.seq) ||
330
+ p.seq! < 1 ||
331
+ (p.seq === 1 ? p.prevSha256 !== undefined : !isDigest(p.prevSha256))
332
+ ) {
333
+ throw new Error('authenticated backup position is malformed')
334
+ }
335
+ return { deviceId: p.deviceId, generation: p.generation!, seq: p.seq!, prevSha256: p.prevSha256 }
271
336
  }
272
337
 
273
338
  /** Validates a decrypted envelope's `appData` field. Throws rather than silently dropping a
@@ -82,15 +82,9 @@ export const MIN_PUSH_INTERVAL_MS = 60_000
82
82
  export const MAX_BLOB_BYTES = 1 << 20
83
83
 
84
84
  /**
85
- * Hard ceiling on a single restore-side HTTP response body, enforced against the
86
- * Content-Length header before any transport call materializes it.
87
- *
88
- * Independent of the server's own advertised cap (`client.limits().maxBlobBytes`, up to
89
- * 200 MiB) — this exists so a malicious or compromised backup host cannot exhaust mobile
90
- * memory merely by declaring (and then sending) an oversized body. React Native's fetch has
91
- * no incremental/streaming read mode (see client.ts's withBackupRequestTimeout), so the
92
- * only point at which an oversized body can be bounded at all is before it is ever
93
- * requested to be read — hence the check runs on the header, not the bytes.
85
+ * Hard ceiling on decoded bytes in any backup HTTP response, enforced inside
86
+ * the native receiver before accumulation, base64 conversion or JSON parsing.
87
+ * The server's advertised blob cap does not override this device memory bound.
94
88
  */
95
89
  export const MAX_RESTORE_RESPONSE_BYTES = 64 * 1024 * 1024
96
90
 
@@ -51,6 +51,10 @@ export const ENTITY_TO_CHUNK_ARRAY: Record<EntityName, string> = {
51
51
  }
52
52
 
53
53
  export interface PushCursor {
54
+ /** Undefined on legacy logs, which must rotate before writing authenticated positions. */
55
+ formatVersion?: 2
56
+ /** Authenticated initial snapshot commitment, fixed when the first window closes. */
57
+ initialHeadSha256?: string
54
58
  /** ISO timestamp; only records updated at or after this are considered. */
55
59
  since?: string
56
60
  /** Per-entity consumed counts within the current `since` window. */
@@ -88,6 +92,8 @@ export interface PushCursor {
88
92
 
89
93
  export function freshCursor(generation = 1): PushCursor {
90
94
  return {
95
+ formatVersion: 2,
96
+ initialHeadSha256: undefined,
91
97
  since: undefined,
92
98
  offsets: zeroOffsets(),
93
99
  maxUpdatedAt: undefined,
@@ -119,6 +125,8 @@ export async function loadCursor(chain: BackupChain, pseudonym: string, deviceId
119
125
  try {
120
126
  const parsed = JSON.parse(raw) as Partial<PushCursor>
121
127
  return {
128
+ formatVersion: parsed.formatVersion,
129
+ initialHeadSha256: parsed.initialHeadSha256,
122
130
  since: parsed.since,
123
131
  // Merge over a zeroed base so a cursor written by an older build, before a new
124
132
  // entity existed, does not produce an undefined offset.
@@ -15,6 +15,7 @@
15
15
  * are `since`-based and replay is idempotent, so a torn read corrects itself on the next
16
16
  * pass.
17
17
  */
18
+ import { Hash, Utils } from '@bsv/sdk'
18
19
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
19
20
  import { captureAppDataSnapshot, isEmptyAppData } from './appData'
20
21
  import { captureContacts } from './contactsBackup'
@@ -98,6 +99,15 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
98
99
  const deviceId = deps.deviceId ?? (await getDeviceId())
99
100
 
100
101
  let cursor = await loadCursor(deps.chain, pseudonym, deviceId)
102
+ // Old ciphertext has no authenticated position. A new snapshot is required;
103
+ // claiming an existing unbound generation is now authenticated is unsafe.
104
+ if (
105
+ cursor.formatVersion !== 2 ||
106
+ (cursor.seq > 0 && !/^[0-9a-f]{64}$/.test(cursor.prevSha256 ?? '')) ||
107
+ (cursor.initialChunkCount != null && !/^[0-9a-f]{64}$/.test(cursor.initialHeadSha256 ?? ''))
108
+ ) {
109
+ cursor = rotate(cursor)
110
+ }
101
111
 
102
112
  // Clock-regression guard: `since` only ever advances forward via nextInstant, and the
103
113
  // column comparison is `>=`, so a record stamped BELOW a window this cursor already
@@ -118,16 +128,6 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
118
128
  cursor.maxObservedWallClock != null && cursor.maxObservedWallClock > nowIso ? cursor.maxObservedWallClock : nowIso
119
129
  }
120
130
 
121
- // Back-fill: this cursor's window closed at least once (since is set) with real chunks
122
- // pushed (chunksInGeneration > 0), but under an older build that predates sealing —
123
- // initialChunkCount was never set. Set it now, purely locally: the log through the
124
- // current seq is already a coherent complete state, so nothing needs re-uploading. No
125
- // network round trip and no new entry — the NEXT real chunk this device appends (whenever
126
- // that is) carries the seal referencing this count, same as any other sealed generation.
127
- if (cursor.since != null && cursor.initialChunkCount === undefined && cursor.chunksInGeneration > 0) {
128
- cursor = { ...cursor, initialChunkCount: cursor.chunksInGeneration }
129
- }
130
-
131
131
  const chunk = await deps.storage.getSyncChunk({
132
132
  identityKey: deps.identityKey,
133
133
  fromStorageIdentityKey: deps.identityKey,
@@ -164,7 +164,8 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
164
164
  // the seal always references the original initial snapshot, which is what lets
165
165
  // verifiedComplete stay true as further deltas land (see RemoteSyncReader).
166
166
  initialChunkCount:
167
- cursor.initialChunkCount ?? (cursor.chunksInGeneration > 0 ? cursor.chunksInGeneration : undefined)
167
+ cursor.initialChunkCount ?? (cursor.chunksInGeneration > 0 ? cursor.chunksInGeneration : undefined),
168
+ initialHeadSha256: cursor.initialHeadSha256 ?? (cursor.chunksInGeneration > 0 ? cursor.prevSha256 : undefined)
168
169
  }
169
170
 
170
171
  const rotated = shouldRotate(advanced)
@@ -227,15 +228,24 @@ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
227
228
  // module's own docstring on why a dedicated marker is unsafe for an old reader).
228
229
  const seal: BackupSeal | undefined =
229
230
  cursor.initialChunkCount != null
230
- ? { generation: cursor.generation, initialChunkCount: cursor.initialChunkCount }
231
+ ? {
232
+ generation: cursor.generation,
233
+ initialChunkCount: cursor.initialChunkCount,
234
+ initialHeadSha256: cursor.initialHeadSha256
235
+ }
231
236
  : undefined
232
- const ciphertext = await encodeChunk(wallet, chunk, deps.chain, seal, appDataToSend)
233
-
234
237
  const seq = cursor.seq + 1
238
+ const ciphertext = await encodeChunk(wallet, chunk, deps.chain, seal, appDataToSend, {
239
+ deviceId,
240
+ generation: cursor.generation,
241
+ seq,
242
+ prevSha256: cursor.prevSha256
243
+ })
235
244
  let sha: string
236
245
  try {
237
- const r = await client.append(deviceId, cursor.generation, seq, cursor.prevSha256, ciphertext)
238
- sha = r.sha256
246
+ await client.append(deviceId, cursor.generation, seq, cursor.prevSha256, ciphertext)
247
+ // The server's append response is not an authenticated commitment.
248
+ sha = Utils.toHex(Hash.sha256(ciphertext))
239
249
  } catch (e) {
240
250
  if (e instanceof BackupHttpError && e.code === ERR_SEQ_CONFLICT) {
241
251
  // The server and the cursor disagree about the head. Resynchronise from the server's
@@ -39,8 +39,9 @@ export interface RestoreDeps {
39
39
  onProgress?: (chunks: number, total: number) => void
40
40
  /**
41
41
  * Called whenever the restore finishes a step that is not a chunk: ranking a candidate
42
- * generation, and each page of the post-replay proof reconciliation. Carries nothing; it
43
- * only says the restore is still working, so a caller waiting on it can tell a slow
42
+ * generation, authenticating each entry, and each page of the post-replay proof
43
+ * reconciliation. Carries nothing; it only says the restore is still working,
44
+ * so a caller waiting on it can tell a slow
44
45
  * restore from a stuck one.
45
46
  */
46
47
  onActivity?: () => void
@@ -51,8 +52,8 @@ export interface RestoreResult {
51
52
  deviceId: string
52
53
  generation: number
53
54
  /**
54
- * True when the replayed generation's newest entry carries a seal proving, to this
55
- * device, that its initial snapshot is fully present — see codec.ts's DecodedEntry and
55
+ * True when every v2 position and the newest seal's ordered snapshot head
56
+ * commitment verify — see codec.ts's DecodedEntry and
56
57
  * push.ts's pushOnce. False means either an explicit device/generation override was
57
58
  * chosen with no seal, or no candidate anywhere in the manifest was sealed and today's
58
59
  * newest-only fallback was used instead. See P1-backup-incomplete-generation.
@@ -260,7 +261,7 @@ export async function pickTarget(
260
261
  }
261
262
 
262
263
  const readerFor = (d: DeviceSummary): RemoteSyncReader =>
263
- new RemoteSyncReader(client, wallet, chain, d.deviceId, d.generation, settings, d.headSeq)
264
+ new RemoteSyncReader(client, wallet, chain, d.deviceId, d.generation, settings, d.headSeq, onActivity)
264
265
 
265
266
  if (generation != null) {
266
267
  const exact = candidates.find(d => d.generation === generation)
@@ -0,0 +1,273 @@
1
+ /**
2
+ * BrowserBridgeProvider publishes the open wallet to the bridge runtime (spec 6.9).
3
+ *
4
+ * Mount it inside `WalletContextProvider` (opt-in; without it every bridge request fails
5
+ * `CONFIGURATION_ERROR`). It follows the `DirectPayProvider` template: once the wallet is built it
6
+ * reads the identity key from that wallet's manager, derives the account context from it and the
7
+ * network, and keeps the result keyed on the manager's object identity so a rebuilt wallet never
8
+ * publishes the last one's context.
9
+ *
10
+ * It reports, in one place: the attested manager, the unverified one when an unattested transport
11
+ * was registered at build time, readiness, network and account context. What the runtime does with
12
+ * a replaced manager (revision bump, binding close, prompt withdrawal) is in `runtime.ts`.
13
+ *
14
+ * Wiring: as soon as the runtime is loaded it builds the `ConsentStore`, installs the dispatcher
15
+ * on it, registers the store's withdrawal with the runtime and hands the store to the
16
+ * PermissionSheet's `connection` kind. The dispatcher is installed whether or not a wallet is
17
+ * built, so a request that arrives while the wallet is still building parks (6.6) instead of
18
+ * failing. The store reaches the admin-scoped wallet (wrapped exactly as `PairScreen` wraps it for
19
+ * `connectionAuthority`) through a lookup that always reads the current one, and the dispatcher
20
+ * only touches the store once readiness is `ready`. A wallet replacement settles pending consent
21
+ * through the binding close (`account-changed`), not by declining it; unmount withdraws the
22
+ * requests and uninstalls all of it.
23
+ *
24
+ * Readiness: `blocked` while the secrets layer is locked, `ready` once a manager and its account
25
+ * context are in hand, `building` while a build runs or the context is still being derived, and
26
+ * `none` otherwise.
27
+ */
28
+ import React, { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
29
+ import AsyncStorage from '@react-native-async-storage/async-storage'
30
+ import type { WalletInterface } from '@bsv/sdk'
31
+ import { profileScopedKey } from '../profiles/profileStore'
32
+ import { capWalletArgs } from '../services/capWalletArgs'
33
+ import { guardVaultAccess } from '../services/vault/guard'
34
+ import { getUnlockState, subscribeUnlockState } from '../services/secrets'
35
+ import { useWallet, useWalletManagers, useWalletStatus } from '../context/WalletContext'
36
+ import type { SigningPolicyPermissionsManager } from '../services/signingPermissionPolicy'
37
+ import { createConsentStore, type HmacCapableWallet } from './consent'
38
+ import { mintGrantTag, unverifiedOriginator, isUnattestedOriginator } from './unverifiedOriginator'
39
+ import { createDispatcher, installDispatcher } from './dispatcher'
40
+ import { setConsentSheetSource } from './consentSheetSource'
41
+ import { loadStoredPolicy, resolvePermissionPolicy, type PermissionPolicy } from './permissionPolicy'
42
+ import {
43
+ attachBridgeHost,
44
+ computeAccountContext,
45
+ initBridgeRuntime,
46
+ publish,
47
+ registerConsentWithdrawal,
48
+ setActiveConsent,
49
+ getBridgeSnapshot,
50
+ getPublishedManagers,
51
+ setBridgeBaseVersion,
52
+ type BridgeManager,
53
+ type BridgeReadiness
54
+ } from './runtime'
55
+
56
+ const ACCOUNT_CONTEXT_RETRY_MS = 1000
57
+ const ACCOUNT_CONTEXT_RETRY_MAX_MS = 30_000
58
+
59
+ interface ContextFor {
60
+ signing: SigningPolicyPermissionsManager
61
+ network: string
62
+ value: string
63
+ }
64
+
65
+ export const BrowserBridgeProvider: React.FC<{ children?: React.ReactNode; baseVersion?: string }> = ({
66
+ children,
67
+ baseVersion
68
+ }) => {
69
+ const { managers, adminOriginator } = useWalletManagers()
70
+ const { walletBuilt, walletBuilding, selectedNetwork } = useWalletStatus()
71
+ const { withdrawPrompts, configStatus } = useWallet()
72
+ const unlock = useSyncExternalStore(subscribeUnlockState, getUnlockState, getUnlockState)
73
+
74
+ // The context value changes on every queue change; teardown needs the current function.
75
+ const withdrawRef = useRef(withdrawPrompts)
76
+ withdrawRef.current = withdrawPrompts
77
+
78
+ // Cold start: until the wallet shell has read its stored config (`configStatus` leaves 'initial'
79
+ // for the first time) it is not yet known whether this install has a wallet, so the bridge
80
+ // reports `building`, never `none` (spec 6.15 item 9). A later 'initial' (after logout) is not a
81
+ // cold start: the ref is cleared for good.
82
+ const coldStartRef = useRef(true)
83
+ if (configStatus !== 'initial') coldStartRef.current = false
84
+ const awaitingConfig = coldStartRef.current
85
+
86
+ const [loaded, setLoaded] = useState(false)
87
+ useEffect(() => {
88
+ let current = true
89
+ const detach = attachBridgeHost({ withdrawPrompts: old => withdrawRef.current(old), hasWallet: true })
90
+ initBridgeRuntime().then(
91
+ () => {
92
+ if (current) setLoaded(true)
93
+ },
94
+ e => console.warn('[BrowserBridgeProvider] runtime did not load:', e instanceof Error ? e.message : String(e))
95
+ )
96
+ return () => {
97
+ current = false
98
+ detach()
99
+ }
100
+ }, [])
101
+
102
+ useEffect(() => {
103
+ if (baseVersion !== undefined) setBridgeBaseVersion(baseVersion)
104
+ }, [baseVersion])
105
+
106
+ const signing = managers.signingPermissionsManager
107
+ const wallet = managers.permissionsManager as unknown as (WalletInterface & object) | undefined
108
+
109
+ // The account context of the wallet it was derived from, never of its predecessor. A failed
110
+ // derivation (a locked keychain, a transient secure-store error) is retried with a growing
111
+ // delay; readiness stays `building` meanwhile, so requests park and the dispatcher's own
112
+ // `wallet-not-ready` nudge stays true.
113
+ const [contextFor, setContextFor] = useState<ContextFor | undefined>(undefined)
114
+ const [contextAttempt, setContextAttempt] = useState(0)
115
+ const contextFailures = useRef(0)
116
+ useEffect(() => {
117
+ if (!loaded || !walletBuilt || !signing || !wallet) return
118
+ let current = true
119
+ let retry: ReturnType<typeof setTimeout> | undefined
120
+ wallet
121
+ .getPublicKey({ identityKey: true }, adminOriginator)
122
+ .then(({ publicKey }) => computeAccountContext(publicKey, selectedNetwork))
123
+ .then(value => {
124
+ contextFailures.current = 0
125
+ if (current) setContextFor({ signing, network: selectedNetwork, value })
126
+ })
127
+ .catch(e => {
128
+ console.warn('[BrowserBridgeProvider] No account context:', e instanceof Error ? e.message : String(e))
129
+ if (!current) return
130
+ const delay = Math.min(
131
+ ACCOUNT_CONTEXT_RETRY_MAX_MS,
132
+ ACCOUNT_CONTEXT_RETRY_MS * 2 ** Math.min(contextFailures.current++, 8)
133
+ )
134
+ retry = setTimeout(() => setContextAttempt(n => n + 1), delay)
135
+ })
136
+ return () => {
137
+ current = false
138
+ if (retry !== undefined) clearTimeout(retry)
139
+ }
140
+ }, [loaded, walletBuilt, signing, wallet, adminOriginator, selectedNetwork, contextAttempt, unlock.status])
141
+
142
+ // The admin-scoped wallet the consent store authenticates with. Read through `adminRef`, so the
143
+ // one store (below) always uses the current wallet and never a stale one.
144
+ const adminWallet = useMemo(
145
+ () => (wallet ? capWalletArgs(guardVaultAccess(wallet, adminOriginator)) : undefined),
146
+ [wallet, adminOriginator]
147
+ )
148
+ const adminRef = useRef(adminWallet)
149
+ adminRef.current = adminWallet
150
+
151
+ // The user's stored prompt policy, as the wallet was built with it: what the sheet discloses.
152
+ const storedPolicyRef = useRef<PermissionPolicy | undefined>(undefined)
153
+ useEffect(() => {
154
+ storedPolicyRef.current = undefined
155
+ if (!loaded || !adminWallet) return
156
+ let current = true
157
+ loadStoredPolicy(profileScopedKey(''), adminWallet, adminOriginator).then(
158
+ p => {
159
+ if (current) storedPolicyRef.current = p
160
+ },
161
+ () => undefined
162
+ )
163
+ return () => {
164
+ current = false
165
+ }
166
+ }, [loaded, adminWallet, adminOriginator])
167
+
168
+ // Consent store and dispatcher, installed once the runtime is loaded and kept across wallet
169
+ // replacements. The store's records are tagged by the admin key, so a different wallet never
170
+ // shares one; the profile key is read live, so the store notices a profile switch that has not
171
+ // yet produced a new wallet.
172
+ useEffect(() => {
173
+ if (!loaded) return
174
+ const lookup = (): HmacCapableWallet => {
175
+ const w = adminRef.current
176
+ if (!w) throw new Error('No wallet is available')
177
+ return w
178
+ }
179
+ const lazyAdmin: HmacCapableWallet = {
180
+ createHmac: (args, originator) => lookup().createHmac(args, originator),
181
+ verifyHmac: (args, originator) => lookup().verifyHmac(args, originator)
182
+ }
183
+ const store = createConsentStore({
184
+ storage: AsyncStorage,
185
+ adminWallet: lazyAdmin,
186
+ adminOriginator,
187
+ profileKey: () => profileScopedKey(''),
188
+ now: () => Date.now(),
189
+ randomBytes: n => globalThis.crypto.getRandomValues(new Uint8Array(n)),
190
+ // The manager that will check the group: the unverified one for an unverified originator.
191
+ mint: async (originator, group) => {
192
+ const published = getPublishedManagers()
193
+ const manager = isUnattestedOriginator(originator) ? published.unverified : published.attested
194
+ if (manager === undefined) throw new Error('No permissions manager to mint under')
195
+ await manager.signing.mintGroupedPermissions(originator, group)
196
+ }
197
+ })
198
+ const unregister = registerConsentWithdrawal(() => store.withdrawAll())
199
+ const unregisterActive = setActiveConsent({
200
+ store,
201
+ adminWallet: lazyAdmin,
202
+ adminOriginator,
203
+ profileKey: () => profileScopedKey('')
204
+ })
205
+ const dispatcher = createDispatcher({
206
+ consent: store,
207
+ previewGroup: async binding => {
208
+ const host = /^https?:\/\/([^/:]+)(?::\d+)?$/.exec(binding.applicationOrigin)?.[1]
209
+ if (host === undefined) return null
210
+ const published = getPublishedManagers()
211
+ // An unverified site's real originator carries a grant tag minted at approval; the
212
+ // preview needs only the hostname, which the unverified manager reads the manifest from.
213
+ const preview =
214
+ binding.attestation === 'unattested'
215
+ ? { manager: published.unverified, originator: unverifiedOriginator(host, mintGrantTag()) }
216
+ : { manager: published.attested, originator: host }
217
+ return (await preview.manager?.signing.peekGroupPermissions(preview.originator)) ?? null
218
+ }
219
+ })
220
+ installDispatcher(dispatcher)
221
+ setConsentSheetSource({
222
+ store,
223
+ context: () => ({ walletRevision: Number(getBridgeSnapshot().walletRevision), profileKey: profileScopedKey('') }),
224
+ // The policy the unverified manager was built with (WalletContext): the host's statement
225
+ // plus the user's stored policy.
226
+ policy: () => resolvePermissionPolicy(storedPolicyRef.current)
227
+ })
228
+ return () => {
229
+ store.withdrawAll()
230
+ unregister()
231
+ unregisterActive()
232
+ setConsentSheetSource(undefined)
233
+ installDispatcher(undefined)
234
+ }
235
+ }, [loaded, adminOriginator])
236
+
237
+ const unverifiedSigning = managers.unverifiedSigningPermissionsManager
238
+ const unverifiedWallet = managers.unverifiedPermissionsManager as unknown as WalletInterface | undefined
239
+
240
+ useEffect(() => {
241
+ if (!loaded) return
242
+ const haveWallet = walletBuilt && !!signing && !!wallet
243
+ const accountContext =
244
+ haveWallet && contextFor?.signing === signing && contextFor.network === selectedNetwork ? contextFor.value : ''
245
+ const status = unlock.status
246
+ let readiness: BridgeReadiness
247
+ if (status === 'locked' || status === 'unlocking' || status === 'cancelled') readiness = 'blocked'
248
+ else if (haveWallet && accountContext) readiness = 'ready'
249
+ else if (walletBuilding || haveWallet || awaitingConfig) readiness = 'building'
250
+ else readiness = 'none'
251
+
252
+ const attestedManager: BridgeManager | undefined = haveWallet ? { wallet: wallet!, signing: signing! } : undefined
253
+ const unverifiedManager: BridgeManager | undefined =
254
+ haveWallet && unverifiedSigning && unverifiedWallet
255
+ ? { wallet: unverifiedWallet, signing: unverifiedSigning }
256
+ : undefined
257
+ publish({ attestedManager, unverifiedManager, readiness, network: selectedNetwork, accountContext })
258
+ }, [
259
+ loaded,
260
+ walletBuilt,
261
+ walletBuilding,
262
+ awaitingConfig,
263
+ signing,
264
+ wallet,
265
+ unverifiedSigning,
266
+ unverifiedWallet,
267
+ selectedNetwork,
268
+ contextFor,
269
+ unlock.status
270
+ ])
271
+
272
+ return <>{children}</>
273
+ }