@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  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/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Which host answers for a domain.
3
+ *
4
+ * Our own domain is pinned by configuration: the host was stated by the build,
5
+ * so asking DNS about it would only add a way to be told something else. Every
6
+ * other domain resolves the way Paymail does — DNSSEC-authenticated SRV, then
7
+ * the well-known capability document — because a foreign domain is the one
8
+ * place this feature trusts an answer it did not bring with it.
9
+ *
10
+ * The AD requirement has one exception, and it is not a loophole: an SRV whose
11
+ * target IS the domain names no new host, so an unauthenticated answer moves
12
+ * nothing that `https://<domain>` would not already have reached.
13
+ */
14
+ import { BRFC_LOOKUP, BRFC_REVERSE_LOOKUP, looksLikeDomain } from './rules'
15
+ import { isPublicHttpsUrl } from '../../net/publicDestination'
16
+
17
+ /** The domain this build's own handles live under, and the host serving it. */
18
+ export interface RegistryPin {
19
+ readonly domain: string
20
+ readonly url: string
21
+ }
22
+
23
+ /** The two routes, already substituted and encoded. */
24
+ export interface RegistryEndpoints {
25
+ readonly domain: string
26
+ search(query: string): string
27
+ reverse(pubkey: string): string
28
+ /** True for the configured domain, which skipped discovery entirely. */
29
+ readonly pinned: boolean
30
+ }
31
+
32
+ export interface RegistryResolver {
33
+ resolve(domain: string): Promise<RegistryEndpoints | null>
34
+ /** Test seam, and the way a "try again" control forgets a failed lookup. */
35
+ clearCache(): void
36
+ }
37
+
38
+ export const REGISTRY_TIMEOUT_MS = 8000
39
+ export const RESOLVER_SUCCESS_TTL_MS = 10 * 60 * 1000
40
+ export const RESOLVER_FAILURE_TTL_MS = 60 * 1000
41
+ export const DOH_ENDPOINTS: readonly string[] = ['https://cloudflare-dns.com/dns-query', 'https://dns.google/resolve']
42
+ /**
43
+ * Comfortably over ten capped profile certificates (MAX_SEARCH_RESULTS *
44
+ * MAX_CERT_BODY_BYTES, ~160 KiB) plus JSON overhead — nothing this feature
45
+ * legitimately reads is anywhere near this large (XR-077 / SEC2-027).
46
+ */
47
+ export const REGISTRY_MAX_BODY_BYTES = 256 * 1024
48
+
49
+ const SRV_TYPE = 33
50
+ const NOERROR = 0
51
+ const NXDOMAIN = 3
52
+
53
+ /**
54
+ * Reads a body no bigger than `maxBytes`, in whatever way the runtime allows.
55
+ * A declared `Content-Length` over the cap is refused before anything is
56
+ * read; otherwise, when the runtime exposes the body as a stream, chunks are
57
+ * counted as they arrive and the read is aborted the instant the running
58
+ * total crosses the cap — an untrusted host cannot make this allocate more
59
+ * than the cap regardless of what it claims or how it paces the bytes
60
+ * (XR-077 / SEC2-027). `fallback` (the original, unbounded `response.json`)
61
+ * is used only when the runtime gives no stream to count from at all, which
62
+ * this feature's own test doubles do — a floor, not a firewall, on a runtime
63
+ * where nothing better is available.
64
+ */
65
+ async function readBoundedJson(res: Response, fallback: () => Promise<unknown>, url: string): Promise<unknown> {
66
+ const declared = res.headers?.get?.('content-length')
67
+ if (declared) {
68
+ const n = Number(declared)
69
+ if (Number.isFinite(n) && n > REGISTRY_MAX_BODY_BYTES) {
70
+ throw new Error(`handleRegistry: ${url} declared ${n} bytes, over the ${REGISTRY_MAX_BODY_BYTES} byte limit`)
71
+ }
72
+ }
73
+ const reader = (res as { body?: ReadableStream<Uint8Array> | null }).body?.getReader?.()
74
+ if (!reader) return await fallback()
75
+ const chunks: Uint8Array[] = []
76
+ let total = 0
77
+ for (;;) {
78
+ const { done, value } = await reader.read()
79
+ if (done) break
80
+ if (!value) continue
81
+ total += value.byteLength
82
+ if (total > REGISTRY_MAX_BODY_BYTES) {
83
+ await reader.cancel().catch(() => {})
84
+ throw new Error(`handleRegistry: ${url} exceeded the ${REGISTRY_MAX_BODY_BYTES} byte limit while streaming`)
85
+ }
86
+ chunks.push(value)
87
+ }
88
+ const merged = new Uint8Array(total)
89
+ let offset = 0
90
+ for (const chunk of chunks) {
91
+ merged.set(chunk, offset)
92
+ offset += chunk.byteLength
93
+ }
94
+ return JSON.parse(new TextDecoder().decode(merged))
95
+ }
96
+
97
+ /**
98
+ * One attempt, bounded — headers AND body. There is no shared fetch helper in
99
+ * this codebase — every call site hand-rolls this — so this feature's two
100
+ * networking modules share exactly one copy of it rather than two.
101
+ *
102
+ * A caller's own signal is composed, not replaced: the deadline is ours to add,
103
+ * but a screen that cancels on unmount must still cancel the request rather than
104
+ * hold it to the full eight seconds. `core/backup/client.ts` links the two the
105
+ * same way — and, for the same reason it does, the deadline outlives the
106
+ * headers: every caller in this feature reads a JSON body, and a connection
107
+ * that delivers headers and then stalls (a captive portal, a half-closed load
108
+ * balancer, a mobile link that drops mid-body) leaves `json()` pending for
109
+ * ever. `registration.ts` serialises every write behind one promise, so a
110
+ * single stalled body would wedge every later write for the life of the
111
+ * process, with no toast and no timeout.
112
+ */
113
+ export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, init?: RequestInit): Promise<Response> {
114
+ const controller = new AbortController()
115
+ const caller = init?.signal ?? null
116
+ const onAbort = () => controller.abort(caller?.reason)
117
+ if (caller?.aborted) onAbort()
118
+ caller?.addEventListener('abort', onAbort)
119
+ const release = () => caller?.removeEventListener('abort', onAbort)
120
+ const startedAt = Date.now()
121
+ const timer = setTimeout(() => controller.abort(), REGISTRY_TIMEOUT_MS)
122
+ let response: Response
123
+ try {
124
+ response = await fetchImpl(url, { ...init, signal: controller.signal })
125
+ } catch (e) {
126
+ release()
127
+ throw e
128
+ } finally {
129
+ clearTimeout(timer)
130
+ }
131
+ const readJson = typeof response.json === 'function' ? response.json.bind(response) : null
132
+ const hasBody = !!(response as { body?: unknown }).body
133
+ if (!readJson && !hasBody) {
134
+ release()
135
+ return response
136
+ }
137
+ const fallback = readJson ?? (() => Promise.reject(new Error(`handleRegistry: ${url} has no json() and no body`)))
138
+ // Rebinding the reader rather than buffering the body here: what each caller
139
+ // asks for is all that is ever allocated. The abort is what stops a real
140
+ // stalled stream; the rejection is what stops a transport that ignores it.
141
+ response.json = async () => {
142
+ let bodyTimer: ReturnType<typeof setTimeout> | undefined
143
+ try {
144
+ return await new Promise((resolve, reject) => {
145
+ bodyTimer = setTimeout(
146
+ () => {
147
+ controller.abort()
148
+ reject(new Error(`handleRegistry: no body from ${url} after ${REGISTRY_TIMEOUT_MS}ms`))
149
+ },
150
+ Math.max(0, REGISTRY_TIMEOUT_MS - (Date.now() - startedAt))
151
+ )
152
+ void readBoundedJson(response, fallback, url).then(resolve, reject)
153
+ })
154
+ } finally {
155
+ if (bodyTimer !== undefined) clearTimeout(bodyTimer)
156
+ release()
157
+ }
158
+ }
159
+ return response
160
+ }
161
+
162
+ interface SrvRecord {
163
+ priority: number
164
+ weight: number
165
+ port: number
166
+ target: string
167
+ }
168
+
169
+ interface DohAnswer {
170
+ type?: number
171
+ data?: string
172
+ }
173
+
174
+ interface DohResponse {
175
+ Status?: number
176
+ AD?: boolean
177
+ Answer?: DohAnswer[]
178
+ }
179
+
180
+ function parseSrv(data: string): SrvRecord | null {
181
+ const parts = data.trim().split(/\s+/)
182
+ if (parts.length < 4) return null
183
+ const priority = Number(parts[0])
184
+ const weight = Number(parts[1])
185
+ const port = Number(parts[2])
186
+ const target = parts[3].replace(/\.$/, '').toLowerCase()
187
+ if (!Number.isFinite(priority) || !Number.isFinite(weight) || target === '') return null
188
+ // A port that cannot be dialled does not belong in a URL: `:70000`, `:-1` and
189
+ // `:44.3` are each read by some parser as something other than a port.
190
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null
191
+ return { priority, weight, port, target }
192
+ }
193
+
194
+ /**
195
+ * A foreign domain's own `.well-known/bsvalias` document names WHERE its
196
+ * search/reverse routes live — nothing binds that to the domain the request
197
+ * was made about. Without a host-class check, a foreign domain (no DNSSEC
198
+ * spoofing needed against anyone else — an attacker publishing this for their
199
+ * own domain is enough) could advertise a capability template rooted at a
200
+ * loopback or private address and have every later search/reverse request
201
+ * this feature makes land there instead (XR-073 / SEC2-057, SEC2-076).
202
+ */
203
+ function templateOf(value: unknown, placeholder: string): string | null {
204
+ if (typeof value !== 'string' || !value.startsWith('https://')) return null
205
+ if (!value.includes(placeholder)) return null
206
+ return isPublicHttpsUrl(value) ? value : null
207
+ }
208
+
209
+ export function createRegistryResolver(args: {
210
+ pinned?: RegistryPin
211
+ fetchImpl?: typeof fetch
212
+ now?: () => number
213
+ dohEndpoints?: readonly string[]
214
+ }): RegistryResolver {
215
+ const fetchImpl = args.fetchImpl ?? ((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init))
216
+ const now = args.now ?? (() => Date.now())
217
+ const dohEndpoints = args.dohEndpoints ?? DOH_ENDPOINTS
218
+ const pinnedDomain = args.pinned?.domain.trim().toLowerCase() ?? ''
219
+ const pinnedOrigin = args.pinned?.url.trim().replace(/\/+$/, '') ?? ''
220
+ const cache = new Map<string, { at: number; value: RegistryEndpoints | null }>()
221
+
222
+ const pinnedEndpoints: RegistryEndpoints | null =
223
+ pinnedDomain !== '' && pinnedOrigin !== ''
224
+ ? {
225
+ domain: pinnedDomain,
226
+ search: query => `${pinnedOrigin}/api/handle/${encodeURIComponent(query)}`,
227
+ reverse: pubkey => `${pinnedOrigin}/api/identityKey/${encodeURIComponent(pubkey)}`,
228
+ pinned: true
229
+ }
230
+ : null
231
+
232
+ /**
233
+ * The SRV answer, or the Paymail fallback, or null when DNS said nothing usable.
234
+ *
235
+ * Only NOERROR and NXDOMAIN are answers. Any other status — SERVFAIL, which
236
+ * is what a resolver returns for a DNSSEC-bogus zone under `do=1`, or REFUSED
237
+ * — carries no Answer either, so treating it as "no SRV" would quietly turn a
238
+ * DNSSEC failure into `https://<domain>`. It is a failure of that resolver
239
+ * instead, and the next one gets the question.
240
+ */
241
+ async function lookupSrv(domain: string): Promise<{ target: string; port: number } | null> {
242
+ const fallback = { target: domain, port: 443 }
243
+ for (const endpoint of dohEndpoints) {
244
+ let body: DohResponse
245
+ try {
246
+ const url = `${endpoint}?name=${encodeURIComponent(`_bsvalias._tcp.${domain}`)}&type=SRV&do=1`
247
+ const res = await fetchWithTimeout(fetchImpl, url, { headers: { accept: 'application/dns-json' } })
248
+ if (!res.ok) continue
249
+ body = (await res.json()) as DohResponse
250
+ } catch {
251
+ continue
252
+ }
253
+ if (body.Status !== NOERROR && body.Status !== NXDOMAIN) continue
254
+ const records = (body.Answer ?? [])
255
+ .filter(answer => answer.type === SRV_TYPE && typeof answer.data === 'string')
256
+ .map(answer => parseSrv(answer.data as string))
257
+ .filter((record): record is SrvRecord => record !== null)
258
+ if (body.Status === NXDOMAIN || records.length === 0) return fallback
259
+ records.sort((a, b) => a.priority - b.priority || b.weight - a.weight)
260
+ const best = records[0]
261
+ if (body.AD !== true && best.target !== domain) return null
262
+ return { target: best.target, port: best.port }
263
+ }
264
+ return null
265
+ }
266
+
267
+ async function discover(domain: string): Promise<RegistryEndpoints | null> {
268
+ const host = await lookupSrv(domain)
269
+ if (!host) return null
270
+ const origin = `https://${host.target}${host.port === 443 ? '' : `:${host.port}`}`
271
+ // An SRV target is ordinarily just a hostname, but nothing stops one from
272
+ // being an IP literal, `localhost`, or a `.local` name — and DNSSEC only
273
+ // authenticates that the domain's own zone said so, not that it is a
274
+ // sensible destination (XR-073 / SEC2-057, SEC2-076).
275
+ if (!isPublicHttpsUrl(`${origin}/`)) return null
276
+ let capabilities: Record<string, unknown>
277
+ try {
278
+ const res = await fetchWithTimeout(fetchImpl, `${origin}/.well-known/bsvalias`, {
279
+ headers: { accept: 'application/json' }
280
+ })
281
+ if (!res.ok) return null
282
+ const body = (await res.json()) as { capabilities?: Record<string, unknown> }
283
+ capabilities = body?.capabilities ?? {}
284
+ } catch {
285
+ return null
286
+ }
287
+ const searchTemplate = templateOf(capabilities[BRFC_LOOKUP], '{query}')
288
+ const reverseTemplate = templateOf(capabilities[BRFC_REVERSE_LOOKUP], '{pubkey}')
289
+ if (!searchTemplate || !reverseTemplate) return null
290
+ return {
291
+ domain,
292
+ search: query => searchTemplate.replace('{query}', encodeURIComponent(query)),
293
+ reverse: pubkey => reverseTemplate.replace('{pubkey}', encodeURIComponent(pubkey)),
294
+ pinned: false
295
+ }
296
+ }
297
+
298
+ return {
299
+ async resolve(rawDomain) {
300
+ const domain = rawDomain.trim().toLowerCase()
301
+ if (pinnedEndpoints && domain === pinnedDomain) return pinnedEndpoints
302
+ // Ahead of the cache, not inside discovery: a half-typed domain is not an
303
+ // answer, and the cache has no eviction — search resolves as the user types.
304
+ if (!looksLikeDomain(domain)) return null
305
+ const hit = cache.get(domain)
306
+ if (hit && now() - hit.at < (hit.value ? RESOLVER_SUCCESS_TTL_MS : RESOLVER_FAILURE_TTL_MS)) return hit.value
307
+ const value = await discover(domain)
308
+ cache.set(domain, { at: now(), value })
309
+ return value
310
+ },
311
+ clearCache() {
312
+ cache.clear()
313
+ }
314
+ }
315
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Handle-registry rules — the constants, and the string checks that are pure.
3
+ *
4
+ * Every value here mirrors a rule the registry enforces on write
5
+ * (go-message-box-server `pkg/handles`, `pkg/profilecert`). Restating them on
6
+ * this side is not distrust of the server: a client that cannot tell a valid
7
+ * handle from an invalid one has to ask the network what the user just typed,
8
+ * once per keystroke.
9
+ *
10
+ * "Handle" already names the identity-key pay rail in this codebase
11
+ * (`RailId 'handle'`, core/pay/rails/handle.ts). Nothing here reuses that word
12
+ * as a rail — a handle is the local part of a `handle@domain` paymail.
13
+ */
14
+ import { Utils } from '@bsv/sdk'
15
+
16
+ /** base64(SHA-256("public profile lookup")) — the profile certificate's type. */
17
+ export const PROFILE_CERT_TYPE = 'SbatVXXssDW3AO0J9bxIljkHGbPBGCVAXg94gXFf0cE='
18
+ /** BRFC id of the `public profile lookup` capability — search. */
19
+ export const BRFC_LOOKUP = '0ace65da5987'
20
+ /** BRFC id of the `public profile reverse lookup` capability — key → profile. */
21
+ export const BRFC_REVERSE_LOOKUP = '43dcf83ddc5f'
22
+ /** There is no on-chain revocation: a profile is replaced or tombstoned. */
23
+ export const ZERO_OUTPOINT = `${'0'.repeat(64)}.0`
24
+
25
+ export const MAX_FIELDS = 32
26
+ /** Exclusive — go-sdk's own `CertificateFieldNameUnder50Bytes`. */
27
+ export const MAX_FIELD_NAME_BYTES = 50
28
+ export const MAX_FIELD_VALUE_BYTES = 1024
29
+ export const MAX_CERT_BODY_BYTES = 16384
30
+
31
+ /** Shorter than this and the search route answers nothing at all. */
32
+ export const SEARCH_MIN_QUERY_LENGTH = 2
33
+ /** Longer than this and the search route answers nothing at all. */
34
+ export const MAX_SEARCH_QUERY_LENGTH = 32
35
+ /**
36
+ * The most rows the search route ever answers with (`searchLimit` in
37
+ * go-message-box-server's own handler).
38
+ *
39
+ * Restated on this side because the host that answers a search is not always
40
+ * ours: a complete foreign domain the user typed is resolved and asked, and
41
+ * nothing binds it to our server's limit. Every row costs one ECDSA
42
+ * verification on the only thread the recipient field has, so an uncapped
43
+ * answer is an unbounded freeze rather than a long list.
44
+ */
45
+ export const MAX_SEARCH_RESULTS = 10
46
+
47
+ const HANDLE_FORMAT = /^[a-z0-9][a-z0-9._-]{1,30}[a-z0-9]$/
48
+ const DOMAIN_FORMAT = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/
49
+ const SEARCH_QUERY_FORMAT = /^[a-z0-9._-]+$/
50
+
51
+ /**
52
+ * Path segments a query must never become, because the search route never sees
53
+ * them. `GET /api/handle/available` is mounted ahead of
54
+ * `GET /api/handle/{query}` and answers `400 ERR_INVALID_LOOKUP`; `..` does not
55
+ * even leave the device intact, since the URL parser collapses a double-dot
56
+ * segment (`https://host/api/handle/..` is `https://host/api/`, which nothing
57
+ * serves) and encoding cannot rescue it — the spec reads `%2e%2e` as the same
58
+ * segment. Either one `search` would surface as "the registry is down", for an
59
+ * ordinary English word or for two dots. A lone `.` is already too short.
60
+ */
61
+ const RESERVED_QUERY_PATHS = new Set(['available', '..'])
62
+
63
+ /** 3-32 characters of a-z 0-9 . _ - beginning and ending with a letter or digit. */
64
+ export function isValidHandleFormat(handle: string): boolean {
65
+ return HANDLE_FORMAT.test(handle)
66
+ }
67
+
68
+ /** A dotted, all-lowercase domain. Says nothing about whether it resolves. */
69
+ export function looksLikeDomain(text: string): boolean {
70
+ return DOMAIN_FORMAT.test(text.trim().toLowerCase())
71
+ }
72
+
73
+ /**
74
+ * Whether the registry would actually search for this, rather than answer an
75
+ * empty array or a 400. Restating the server's own gate here is what keeps a
76
+ * routine word — a too-long paste, an accent, a slash — from costing a request
77
+ * and, for the reserved paths, from raising an outage banner.
78
+ */
79
+ export function isRoutableSearchQuery(query: string): boolean {
80
+ if (query.length < SEARCH_MIN_QUERY_LENGTH || query.length > MAX_SEARCH_QUERY_LENGTH) return false
81
+ if (!SEARCH_QUERY_FORMAT.test(query)) return false
82
+ return !RESERVED_QUERY_PATHS.has(query)
83
+ }
84
+
85
+ /**
86
+ * `handle@domain`, trimmed and lowercased, or null when it is not one.
87
+ *
88
+ * Lowercasing here is what makes a typed `Dee@Example.com` comparable with the
89
+ * exact-lowercase `paymail` field the registry stores — the comparison the
90
+ * trust model turns on.
91
+ */
92
+ export function parsePaymail(text: string): { handle: string; domain: string } | null {
93
+ const parts = text.trim().toLowerCase().split('@')
94
+ if (parts.length !== 2) return null
95
+ const [handle, domain] = parts
96
+ if (!isValidHandleFormat(handle) || !looksLikeDomain(domain)) return null
97
+ return { handle, domain }
98
+ }
99
+
100
+ /** UTF-8 length, the unit every server-side size limit counts in. `Buffer` does
101
+ * not exist in React Native, so this goes through the SDK's own encoder. */
102
+ export function utf8ByteLength(text: string): number {
103
+ return Utils.toArray(text, 'utf8').length
104
+ }
package/core/index.ts CHANGED
@@ -12,7 +12,8 @@ export { configureNewHeaderPolling } from './walletMonitor'
12
12
  export { TaskSendOffline } from './monitor/TaskSendOffline'
13
13
  export { TaskCreditInbox } from './monitor/TaskCreditInbox'
14
14
  export { TaskDrainOutbox, drainUnsentEntries } from './monitor/TaskDrainOutbox'
15
- export { getOnline, subscribeOnline } from './net/online'
15
+ export { getOnline, subscribeOnline, probeOnline } from './net/online'
16
+ export { validateArcUrl } from './net/validateArcUrl'
16
17
  export * from './logging'
17
18
  export * from './diskSpace'
18
19
  export type { AppChain, WalletChain } from './config'
@@ -33,12 +34,14 @@ export {
33
34
  getBackupUrl,
34
35
  getServiceConfig,
35
36
  getMandalaEndpoints,
37
+ getHandleRegistryConfig,
38
+ isAllowedServiceOrigin,
36
39
  isMandalaAvailable,
37
40
  isVaultEnabled,
38
41
  isVaultAvailable,
39
42
  resetToolboxConfig
40
43
  } from './toolboxConfig'
41
- export type { ToolboxConfig, ToolboxServiceConfig, MandalaEndpointConfig } from './toolboxConfig'
44
+ export type { ToolboxConfig, ToolboxServiceConfig, MandalaEndpointConfig, HandleRegistryConfig } from './toolboxConfig'
42
45
 
43
46
  // Theme tokens and providers
44
47
  export { ThemeProvider, useTheme } from './theme/ThemeContext'
@@ -52,16 +55,19 @@ export { useThemeStyles } from './theme/useThemeStyles'
52
55
  export {
53
56
  formatAmount,
54
57
  formatAmountParts,
58
+ splitAmountFraction,
55
59
  formatAmountInInputUnit,
56
60
  formatSatoshisAsFiat,
57
61
  formatSatoshisAsBsv,
62
+ formatSatoshisExact,
58
63
  formatSatoshisAsBsvDecimal,
59
64
  parseDisplayToSatoshis,
60
65
  getUnitLabel,
61
66
  formatSatoshis,
62
67
  isFiatCurrency,
63
68
  satoshisPerFiatUnit,
64
- fiatFractionDigits
69
+ fiatFractionDigits,
70
+ decimalSeparator
65
71
  } from './amountFormatHelpers'
66
72
  export type { UsdToFiat, AmountFormatOptions } from './amountFormatHelpers'
67
73
 
@@ -101,6 +107,7 @@ export * from './offline/payerHold'
101
107
  export * from './offline/tokenFrames'
102
108
  export {
103
109
  cancelParkedPayment,
110
+ chainAlreadyKnows,
104
111
  type CancelParkedOutcome,
105
112
  type CancelParkedStorage,
106
113
  type CancelParkedWallet,
@@ -168,12 +175,13 @@ export {
168
175
  type CoverVerifier
169
176
  } from './mandala/bundle'
170
177
 
178
+ // Contacts
179
+ export { mergeContactCache, type ContactCache } from './contacts/contactCache'
180
+
171
181
  // Local SQLite storage layer
172
182
  export { StorageExpoSQLite } from './storage/StorageExpoSQLite'
173
183
  export type { StorageExpoSQLiteOptions, TokenTransactionRepair } from './storage/StorageExpoSQLite'
174
184
  export { createTables, ensureOfflineActionsColumns, ensureTokenSettlementColumns } from './storage/schema/createTables'
175
- export { initializeLocalStorage, isLocalStorage, getStorageDisplayName } from './storage/LocalStorageAdapter'
176
- export type { LocalStorageConfig } from './storage/LocalStorageAdapter'
177
185
  export { findOfflineActions, findOfflineActionByTxid, updateOfflineAction } from './storage/methods/offlineActions'
178
186
  export type { OfflineActionRow, OfflineActionStatus, BindValue } from './storage/methods/offlineActions'
179
187
  export { readWalletBalance } from './storage/methods/walletBalanceSql'
@@ -189,6 +197,10 @@ export {
189
197
  LocalStorageContext,
190
198
  type LocalStorageContextType
191
199
  } from './context/LocalStorageProvider'
200
+ // XR-114: lets a consent screen check, before it promises biometric
201
+ // protection, whether provisioning would actually land on a disclosed
202
+ // (non-biometric) policy for this device/build.
203
+ export { resolveProvisioningPolicy, type ResolvedPolicy } from './services/secrets/policy'
192
204
 
193
205
  // User context and native handlers
194
206
  export { UserContextProvider, UserContext } from './context/UserContext'
@@ -210,6 +222,7 @@ export type { FiatCurrency } from './displayCurrencies'
210
222
 
211
223
  // Pay rails
212
224
  export * from './pay/rails'
225
+ export * from './pay/rails/nativeIntent'
213
226
  export * from './pay/beefRepair'
214
227
  export * from './pay/creditErrors'
215
228
  export * from './pay/creditInbox'
@@ -273,6 +286,14 @@ export {
273
286
  touchWatched,
274
287
  unwatchAddress
275
288
  } from './pay/watchlist'
289
+ // receiveHistory.ts's own KVStorage is omitted for the same reason watchlist.ts's is above.
290
+ export {
291
+ RECEIVE_HISTORY_KEY,
292
+ MAX_RECEIVE_HISTORY,
293
+ recordIssuedDate,
294
+ getIssuedDates,
295
+ setIssuedDates
296
+ } from './pay/receiveHistory'
276
297
  // isCompressedPublicKey is omitted here because './pay/rails' above already
277
298
  // re-exports the same binding; naming it twice trips eslint's import/export rule.
278
299
  export {
@@ -310,6 +331,7 @@ export * from './services/arcadeBroadcastProvider'
310
331
  export * from './services/walletArgLimits'
311
332
  export * from './services/capWalletArgs'
312
333
  export * from './services/externalOrigin'
334
+ export * from './services/arcTokenStorage'
313
335
 
314
336
  // Encrypted wallet backup log
315
337
  export * from './backup/RemoteSyncReader'
@@ -327,6 +349,18 @@ export * from './backup/restoreOnImport'
327
349
  export * from './walletRepair/runWalletCheck'
328
350
  export { TaskBackupPush } from './monitor/TaskBackupPush'
329
351
 
352
+ // Wallet recovery and creation: headless orchestration behind the mnemonic /
353
+ // shares screens (store secret → build → attest), the share primitives, and the
354
+ // hook that wires them to the providers. Screens only render the outcomes.
355
+ export * from './recovery/shares'
356
+ export * from './recovery/secret'
357
+ export * from './recovery/shareCollector'
358
+ export * from './recovery/backupMaterial'
359
+ export * from './recovery/restoreWallet'
360
+ export * from './recovery/recoverWallet'
361
+ export * from './recovery/createWallet'
362
+ export * from './recovery/useRecoveryDeps'
363
+
330
364
  // Hardware vault: YubiKey PIV custody (1-of-N P-256 comb vault, spec
331
365
  // docs/superpowers/specs/2026-09-09-r1-comb-vault-design.md), ceremony state
332
366
  // machine, the r1comb template module, session helper, transfers
@@ -345,6 +379,7 @@ export * from './services/vault/session'
345
379
  export * from './services/vault/random'
346
380
  export * from './services/vault/r1comb'
347
381
  export * from './services/vault/vaultStore'
382
+ export * from './services/vault/metaAuthority'
348
383
  export * from './services/vault/mockYubiKey'
349
384
  export * from './services/vault/devMock'
350
385
  export * from './services/vault/guard'
@@ -354,6 +389,7 @@ export * from './services/vault/ceremonyHost'
354
389
  export * from './services/vault/VaultKeyService'
355
390
  export * from './services/vault/pivReset'
356
391
  export * from './services/vault/transfers'
392
+ export * from './services/vault/chainRecovery'
357
393
 
358
394
  // Connection/pairing state (QR-paired desktop sessions), the vault ceremony
359
395
  // context (React face of the ceremonyHost singleton), and the shared
@@ -401,3 +437,15 @@ export {
401
437
  } from './context/WalletContext'
402
438
  export type { WalletManagersSlice, WalletStatusSlice } from './context/WalletContext'
403
439
  export { usePermissionQueue } from './hooks/usePermissionQueue'
440
+
441
+ export { getNumberLocale } from './numberFormat'
442
+
443
+ export {
444
+ getUserAvatarIcon,
445
+ loadUserAvatarIcon,
446
+ setUserAvatarIcon,
447
+ subscribeUserAvatar,
448
+ useUserAvatarIcon,
449
+ type AvatarIcon,
450
+ type AvatarIconFamily
451
+ } from './userAvatar'