@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,36 @@
1
+ /**
2
+ * The profile QR / add-contact deep link: `bsv-wallet://contact/add?identityKey=<hex>`
3
+ * (2026-09-18 design ruling — a deep link straight to this app's add-contact
4
+ * screen, never a bare key and never `peerpay:`).
5
+ *
6
+ * `app/+native-intent.ts` already strips the `bsv-wallet://`/`bsv-browser://`
7
+ * scheme and hands the remainder to Expo Router as a route, so an OS-level
8
+ * scan resolves on its own. `parseContactAddLink` below is for the OTHER
9
+ * path — the in-app QR scanner on the Contacts header, which hands this
10
+ * module raw scanned text rather than navigating anywhere.
11
+ */
12
+
13
+ const COMPRESSED_KEY = /^0[23][0-9a-fA-F]{64}$/
14
+
15
+ export function contactAddLinkFor(identityKey: string): string {
16
+ return `bsv-wallet://contact/add?identityKey=${identityKey.toLowerCase()}`
17
+ }
18
+
19
+ /** Whether a string is a 66-hex compressed public key — the shape of an Identifier. */
20
+ export function isCompressedIdentityKey(s: string): boolean {
21
+ return COMPRESSED_KEY.test(s.trim())
22
+ }
23
+
24
+ /**
25
+ * The identity key out of a scanned code, or undefined when the text names
26
+ * neither a contact-add link nor a bare compressed key. Accepts a bare key
27
+ * too — a QR carrying just the identifier is not wrong, only less specific.
28
+ */
29
+ export function parseIdentityKeyFromScan(text: string): string | undefined {
30
+ const trimmed = text.trim()
31
+ if (COMPRESSED_KEY.test(trimmed)) return trimmed.toLowerCase()
32
+ const query = trimmed.split('?')[1]
33
+ if (!query) return undefined
34
+ const key = new URLSearchParams(query).get('identityKey')
35
+ return key && COMPRESSED_KEY.test(key) ? key.toLowerCase() : undefined
36
+ }
@@ -0,0 +1,314 @@
1
+ /**
2
+ * The registry's four routes.
3
+ *
4
+ * Two of the four have contracts inherited from the identity code they stand
5
+ * in for, and they are opposites on purpose: `search` THROWS on a transport
6
+ * failure, because Pay's error banner is raised from a catch and an empty
7
+ * array would read as "nobody by that name"; `lookupIdentityKey` NEVER throws,
8
+ * because an unknown peer and an unreachable registry get the same UI and a
9
+ * profile lookup may never be the reason a screen fails to render.
10
+ *
11
+ * Writes only ever go to the pinned registry — a foreign domain is somewhere
12
+ * to read from, never somewhere to publish to — and the clock skew that
13
+ * `serverNow` corrects by is only ever taken from a pinned response, for the
14
+ * same reason.
15
+ */
16
+ import {
17
+ MAX_SEARCH_RESULTS,
18
+ SEARCH_MIN_QUERY_LENGTH,
19
+ isRoutableSearchQuery,
20
+ isValidHandleFormat,
21
+ looksLikeDomain
22
+ } from './rules'
23
+ import { verifyProfileCertificate, type ProfileCertJson, type RegistryProfile } from './profileCert'
24
+ import { createRegistryResolver, fetchWithTimeout, type RegistryPin, type RegistryResolver } from './resolver'
25
+ import { createKeyPinStore, type KeyPinStore } from './keyPinStore'
26
+
27
+ /** Why a handle is not free. The server's `stale` arrives as `cooldown`. */
28
+ export type AvailabilityReason = 'taken' | 'too_similar' | 'reserved' | 'invalid' | 'cooldown'
29
+
30
+ export type AvailabilityResult =
31
+ | { kind: 'available' }
32
+ | { kind: 'unavailable'; reason: AvailabilityReason }
33
+ | { kind: 'failed' }
34
+
35
+ /** `rejected` is the server answering no; `failed` is not having an answer. */
36
+ export type PutResult =
37
+ | { kind: 'created' }
38
+ | { kind: 'ok' }
39
+ | { kind: 'rejected'; code: string; description: string }
40
+ | { kind: 'failed'; message: string }
41
+
42
+ /**
43
+ * `none` means the registry answered and holds nothing believable for that key;
44
+ * `failed` means there was no answer at all. A caller that only renders can
45
+ * flatten both to "no handle" — `lookupIdentityKey` does. A caller that WRITES
46
+ * the answer into a cache cannot: blanking a contact's handle because the
47
+ * device happened to be offline is the opposite of a cache.
48
+ */
49
+ export type ProfileLookup = { kind: 'found'; profile: RegistryProfile } | { kind: 'none' } | { kind: 'failed' }
50
+
51
+ export interface HandleRegistryClient {
52
+ /** The pinned domain: what a bare handle is registered under. */
53
+ readonly domain: string
54
+ checkAvailability(handle: string): Promise<AvailabilityResult>
55
+ putCertificate(cert: ProfileCertJson): Promise<PutResult>
56
+ /** Throws on transport failure — the contract `searchIdentities` already has. */
57
+ search(query: string): Promise<RegistryProfile[]>
58
+ /** Never throws. The full verdict, for callers that cache the answer. */
59
+ lookupProfile(identityKey: string, domain?: string): Promise<ProfileLookup>
60
+ /** Never throws — the contract `resolveIdentity` already has. */
61
+ lookupIdentityKey(identityKey: string, domain?: string): Promise<RegistryProfile | null>
62
+ /** The device clock, corrected by the skew the pinned registry last reported. */
63
+ serverNow(): Date
64
+ }
65
+
66
+ function reasonOf(raw: unknown): AvailabilityReason | null {
67
+ switch (raw) {
68
+ case 'taken':
69
+ case 'too_similar':
70
+ case 'reserved':
71
+ case 'invalid':
72
+ case 'cooldown':
73
+ return raw
74
+ // A released row whose stored issuedAt has not passed yet: a certificate
75
+ // dated now cannot beat it, so to the person typing this is a cooldown.
76
+ case 'stale':
77
+ return 'cooldown'
78
+ default:
79
+ return null
80
+ }
81
+ }
82
+
83
+ export function createHandleRegistryClient(args: {
84
+ pinned: RegistryPin
85
+ fetchImpl?: typeof fetch
86
+ now?: () => number
87
+ resolver?: RegistryResolver
88
+ pinStore?: KeyPinStore
89
+ }): HandleRegistryClient {
90
+ const fetchImpl = args.fetchImpl ?? ((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init))
91
+ const now = args.now ?? (() => Date.now())
92
+ const domain = args.pinned.domain.trim().toLowerCase()
93
+ const origin = args.pinned.url.trim().replace(/\/+$/, '')
94
+ const resolver = args.resolver ?? createRegistryResolver({ pinned: args.pinned, fetchImpl, now })
95
+ const pinStore = args.pinStore ?? createKeyPinStore()
96
+ let skewMs = 0
97
+
98
+ /**
99
+ * XR-071: the registry a certificate came from — pinned or foreign — is not
100
+ * a naming authority, so a structurally valid, self-signed certificate is
101
+ * only as trustworthy as "nobody has shown us a different key for this
102
+ * paymail before". The first key ever seen for a paymail is remembered;
103
+ * a later certificate for the same paymail under a DIFFERENT key is refused
104
+ * rather than treated as an update, because from a static check alone that
105
+ * is indistinguishable from a compromised or malicious registry redirecting
106
+ * the paymail to an attacker.
107
+ */
108
+ async function pinnedOrNull(profile: RegistryProfile): Promise<RegistryProfile | null> {
109
+ const known = await pinStore.get(profile.paymail)
110
+ if (known === null) {
111
+ await pinStore.set(profile.paymail, profile.identityKey)
112
+ return profile
113
+ }
114
+ return known.toLowerCase() === profile.identityKey.toLowerCase() ? profile : null
115
+ }
116
+
117
+ /** Only ever from the registry we write to: a foreign host's clock is not
118
+ * the one our `issuedAt` has to beat. */
119
+ function notePinnedSkew(res: Response): void {
120
+ const header = res.headers?.get?.('date')
121
+ const at = header ? Date.parse(header) : NaN
122
+ if (Number.isFinite(at)) skewMs = at - now()
123
+ }
124
+
125
+ async function errorBody(res: Response): Promise<{ code: string; description: string }> {
126
+ try {
127
+ const body = (await res.json()) as { code?: unknown; description?: unknown } | undefined
128
+ return {
129
+ code: typeof body?.code === 'string' ? body.code : `ERR_HTTP_${res.status}`,
130
+ description: typeof body?.description === 'string' ? body.description : `registry HTTP ${res.status}`
131
+ }
132
+ } catch {
133
+ return { code: `ERR_HTTP_${res.status}`, description: `registry HTTP ${res.status}` }
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Which registry answers this query, what to send it, and whether the user
139
+ * typed a complete address rather than a fragment.
140
+ *
141
+ * `paymail` is set only for a complete `handle@domain`. The trust model then
142
+ * requires that only a row with exactly that paymail be offered — the
143
+ * server's search is a prefix, skeleton and substring search, so without this
144
+ * a typed `dee@deggen.com` would be answered with `dee2`, `deeanna` and a
145
+ * look-alike, any of which the user might take for the person they named.
146
+ *
147
+ * Complete means the domain is finished AND the local part could be a handle.
148
+ * That second half is a choice: `de@deggen.com` can name nobody, because no
149
+ * registered handle is two characters, so it is read as the fragment it is
150
+ * and the prefix neighbours are still offered as suggestions — the strict
151
+ * reading would answer an address that cannot exist with nothing at all.
152
+ *
153
+ * `isRoutableSearchQuery` is the server's own gate restated: over 32
154
+ * characters, outside `[a-z0-9._-]`, or a path its route table claims (the
155
+ * literal `available`, which answers `400 ERR_INVALID_LOOKUP` and would
156
+ * otherwise surface as an outage) costs no request at all.
157
+ *
158
+ * `transient` marks the one place those two readings overlap — see the
159
+ * comment on the prefix branch.
160
+ */
161
+ function routeFor(raw: string): { domain: string; query: string; paymail?: string; transient?: boolean } | null {
162
+ const text = raw.trim().toLowerCase()
163
+ const at = text.indexOf('@')
164
+ if (at < 0) return isRoutableSearchQuery(text) ? { domain, query: text } : null
165
+ const local = text.slice(0, at)
166
+ const typed = text.slice(at + 1)
167
+ if (local.length < SEARCH_MIN_QUERY_LENGTH || !isRoutableSearchQuery(local)) return null
168
+ // A domain still being typed is a prefix of ours: still our registry, and
169
+ // still a fragment — the user has not finished naming anybody yet.
170
+ //
171
+ // A prefix that is ITSELF a complete domain is not that. `.co` is a prefix
172
+ // of `.com`, so for essentially any pinned `x.com` a finished, real,
173
+ // different registry would be answered by ours — with the exact-paymail
174
+ // rule switched off, because the address would be read as a fragment. A
175
+ // typed `alice@deggen.co` would come back as every `*@deggen.com`
176
+ // neighbour, squatter included, and never as the person named.
177
+ if (typed === domain || (domain.startsWith(typed) && !looksLikeDomain(typed))) {
178
+ const complete = typed === domain && isValidHandleFormat(local)
179
+ return { domain, query: local, ...(complete ? { paymail: `${local}@${domain}` } : {}) }
180
+ }
181
+ if (!looksLikeDomain(typed)) return null
182
+ const complete = isValidHandleFormat(local)
183
+ return {
184
+ domain: typed,
185
+ query: local,
186
+ ...(complete ? { paymail: `${local}@${typed}` } : {}),
187
+ // Every character of our own domain is typed through on the way to it, so
188
+ // a prefix of ours that resolves nowhere is a half-typed address rather
189
+ // than an outage to raise a banner about mid-keystroke.
190
+ ...(domain.startsWith(typed) ? { transient: true } : {})
191
+ }
192
+ }
193
+
194
+ /** A free function rather than a method: `lookupIdentityKey` delegates to it,
195
+ * and a destructured `const { lookupIdentityKey } = client` must still work. */
196
+ async function lookupProfile(identityKey: string, forDomain?: string): Promise<ProfileLookup> {
197
+ const key = identityKey.trim().toLowerCase()
198
+ const target = (forDomain ?? domain).trim().toLowerCase()
199
+ try {
200
+ const endpoints = await resolver.resolve(target)
201
+ if (!endpoints) return { kind: 'failed' }
202
+ const res = await fetchWithTimeout(fetchImpl, endpoints.reverse(key), {
203
+ headers: { accept: 'application/json' }
204
+ })
205
+ if (endpoints.pinned) notePinnedSkew(res)
206
+ // Only a 404 is the registry saying "this key holds nothing". Every other
207
+ // refusal is the registry not having answered the question at all, and a
208
+ // caller that caches the answer has to be able to tell those apart.
209
+ if (res.status === 404) return { kind: 'none' }
210
+ if (!res.ok) return { kind: 'failed' }
211
+ const profile = await verifyProfileCertificate(await res.json(), { domain: target, identityKey: key })
212
+ const pinned = profile ? await pinnedOrNull(profile) : null
213
+ return pinned ? { kind: 'found', profile: pinned } : { kind: 'none' }
214
+ } catch {
215
+ return { kind: 'failed' }
216
+ }
217
+ }
218
+
219
+ return {
220
+ domain,
221
+
222
+ async checkAvailability(handle) {
223
+ const wanted = handle.trim().toLowerCase()
224
+ // Checked here first so a half-typed handle costs no request and gets an
225
+ // answer on the keystroke rather than after the round trip.
226
+ if (!isValidHandleFormat(wanted)) return { kind: 'unavailable', reason: 'invalid' }
227
+ try {
228
+ const res = await fetchWithTimeout(fetchImpl, `${origin}/api/handle/available/${encodeURIComponent(wanted)}`, {
229
+ headers: { accept: 'application/json' }
230
+ })
231
+ notePinnedSkew(res)
232
+ if (!res.ok) return { kind: 'failed' }
233
+ const body = (await res.json()) as { available?: unknown; reason?: unknown } | undefined
234
+ if (body?.available === true) return { kind: 'available' }
235
+ const reason = reasonOf(body?.reason)
236
+ return reason ? { kind: 'unavailable', reason } : { kind: 'failed' }
237
+ } catch {
238
+ return { kind: 'failed' }
239
+ }
240
+ },
241
+
242
+ async putCertificate(cert) {
243
+ let res: Response
244
+ try {
245
+ res = await fetchWithTimeout(fetchImpl, `${origin}/api/handle`, {
246
+ method: 'PUT',
247
+ headers: { 'content-type': 'application/json' },
248
+ body: JSON.stringify(cert)
249
+ })
250
+ } catch (e) {
251
+ return { kind: 'failed', message: e instanceof Error ? e.message : String(e) }
252
+ }
253
+ notePinnedSkew(res)
254
+ if (res.status === 201) return { kind: 'created' }
255
+ if (res.status === 200) return { kind: 'ok' }
256
+ // Rate limiting and a server fault are both "ask again later"; every
257
+ // other status is the registry having read the certificate and refused.
258
+ if (res.status === 429 || res.status >= 500) return { kind: 'failed', message: `registry HTTP ${res.status}` }
259
+ const { code, description } = await errorBody(res)
260
+ return { kind: 'rejected', code, description }
261
+ },
262
+
263
+ async search(query) {
264
+ const route = routeFor(query)
265
+ if (!route) return []
266
+ const endpoints = await resolver.resolve(route.domain)
267
+ if (!endpoints) {
268
+ if (route.transient) return []
269
+ throw new Error(`handleRegistry: no registry for ${route.domain}`)
270
+ }
271
+ const res = await fetchWithTimeout(fetchImpl, endpoints.search(route.query), {
272
+ headers: { accept: 'application/json' }
273
+ })
274
+ if (endpoints.pinned) notePinnedSkew(res)
275
+ if (!res.ok) throw new Error(`handleRegistry: search failed with HTTP ${res.status}`)
276
+ const body = (await res.json()) as unknown
277
+ if (!Array.isArray(body)) return []
278
+ const verified = await Promise.all(
279
+ // Capped before a single signature is checked. The route's contract is
280
+ // ten rows and our own server enforces it, but a complete foreign
281
+ // domain the user typed is answered by a host bound by nothing — and
282
+ // each row is one ECDSA verification on the thread the recipient field
283
+ // is drawn from, so an uncapped answer is a freeze, not a long list.
284
+ //
285
+ // `expect.paymail` is what enforces "a complete address names one
286
+ // person": set, every other row the server volunteered is dropped.
287
+ body.slice(0, MAX_SEARCH_RESULTS).map(row =>
288
+ verifyProfileCertificate(row, {
289
+ domain: route.domain,
290
+ ...(route.paymail ? { paymail: route.paymail } : {})
291
+ })
292
+ )
293
+ )
294
+ const certified = verified.filter((profile): profile is RegistryProfile => profile !== null)
295
+ // Each row is checked against this device's own key-pin history
296
+ // (XR-071) — a row whose certificate verifies but whose key contradicts
297
+ // one already accepted for that paymail is dropped like any other row
298
+ // that failed verification.
299
+ const pinned = await Promise.all(certified.map(profile => pinnedOrNull(profile)))
300
+ return pinned.filter((profile): profile is RegistryProfile => profile !== null)
301
+ },
302
+
303
+ lookupProfile,
304
+
305
+ async lookupIdentityKey(identityKey, forDomain) {
306
+ const result = await lookupProfile(identityKey, forDomain)
307
+ return result.kind === 'found' ? result.profile : null
308
+ },
309
+
310
+ serverNow() {
311
+ return new Date(now() + skewMs)
312
+ }
313
+ }
314
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Trust-on-first-use for paymail → identityKey.
3
+ *
4
+ * A profile certificate only proves the subject signed it as its own
5
+ * certifier — it says nothing about who is entitled to a paymail. A registry
6
+ * (any registry, including our pinned one) that turns malicious or is
7
+ * compromised can therefore mint a fresh, self-signed certificate for
8
+ * `victim@domain` under an attacker key, and `verifyProfileCertificate` has
9
+ * no naming authority to check it against (XR-071 / SEC2-079).
10
+ *
11
+ * What we CAN check is continuity: once this device has resolved a key for a
12
+ * paymail, a different key showing up later for the same paymail is either a
13
+ * real, rare re-key or an attack, and the two are indistinguishable from a
14
+ * static check alone — so a later different key is refused rather than
15
+ * silently accepted. This is deliberately per-device, not synced through
16
+ * backup: it protects against what the paymail's OWN registry does after the
17
+ * fact, so it must not be something a compromised backup or that same
18
+ * registry could also rewrite.
19
+ */
20
+ import AsyncStorage from '@react-native-async-storage/async-storage'
21
+
22
+ const STORAGE_KEY = 'handleRegistry.keyPins.v1'
23
+
24
+ export interface KeyPinStore {
25
+ /** The identityKey this device has previously accepted for `paymail`, or null. */
26
+ get(paymail: string): Promise<string | null>
27
+ /** Records `identityKey` as the accepted key for `paymail`, if none is pinned yet. */
28
+ set(paymail: string, identityKey: string): Promise<void>
29
+ }
30
+
31
+ let pins: Record<string, string> | null = null
32
+
33
+ async function load(): Promise<Record<string, string>> {
34
+ if (pins) return pins
35
+ try {
36
+ const raw = await AsyncStorage.getItem(STORAGE_KEY)
37
+ const parsed: unknown = raw ? JSON.parse(raw) : {}
38
+ pins = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, string>) : {}
39
+ } catch {
40
+ pins = {}
41
+ }
42
+ return pins
43
+ }
44
+
45
+ /** One store, backed by the same on-device AsyncStorage every client instance
46
+ * shares — a paymail resolved from one screen must still be pinned the next
47
+ * time any other screen resolves it. */
48
+ export function createKeyPinStore(): KeyPinStore {
49
+ return {
50
+ async get(paymail) {
51
+ const table = await load()
52
+ return table[paymail] ?? null
53
+ },
54
+ async set(paymail, identityKey) {
55
+ const table = await load()
56
+ if (table[paymail] === identityKey) return
57
+ table[paymail] = identityKey
58
+ try {
59
+ await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(table))
60
+ } catch (e) {
61
+ console.warn('[handleRegistry] failed to persist a key pin', e)
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ /** Test-only: forget every pin and the in-memory cache. */
68
+ export function resetKeyPinsForTests(): void {
69
+ pins = null
70
+ }
@@ -0,0 +1,254 @@
1
+ /**
2
+ * The profile certificate: mint one, and decide whether one handed to us is
3
+ * worth believing.
4
+ *
5
+ * The registry is a directory, not an authority on what a profile says, so
6
+ * every certificate read from any host passes `verifyProfileCertificate`
7
+ * before a single field of it is shown or used. `Certificate.verify()` alone
8
+ * is not that decision: it proves the certificate was signed by the key it
9
+ * NAMES as certifier, which for a self-signed profile is only meaningful once
10
+ * `subject === certifier` has been checked separately — otherwise a third
11
+ * party's well-formed signature over someone else's subject verifies happily.
12
+ *
13
+ * Nothing here touches a network; `client.ts` does that and calls in here.
14
+ */
15
+ import { Certificate, Random, Utils, type ProtoWallet } from '@bsv/sdk'
16
+ import {
17
+ MAX_CERT_BODY_BYTES,
18
+ MAX_FIELDS,
19
+ MAX_FIELD_NAME_BYTES,
20
+ MAX_FIELD_VALUE_BYTES,
21
+ PROFILE_CERT_TYPE,
22
+ ZERO_OUTPOINT,
23
+ parsePaymail,
24
+ utf8ByteLength
25
+ } from './rules'
26
+
27
+ /** The seven-member BRC-52 wire shape, exactly as the registry serves it. */
28
+ export interface ProfileCertJson {
29
+ type: string
30
+ serialNumber: string
31
+ subject: string
32
+ certifier: string
33
+ revocationOutpoint: string
34
+ fields: Record<string, string>
35
+ signature: string
36
+ }
37
+
38
+ /**
39
+ * The two `WalletInterface` methods `Certificate.sign` reaches for.
40
+ *
41
+ * Callers pass the wallet wrapped with `bindOriginator(wallet, adminOriginator)`
42
+ * (core/mandala/createRuntime.ts) so signing the user's own profile never
43
+ * raises a permission prompt.
44
+ *
45
+ * `counterparty` is optional because the SDK never sends one: `Certificate.sign`
46
+ * passes `data`, `protocolID` and `keyID` alone. The wallet's own default of
47
+ * `'anyone'` is what the certificate then verifies against, since
48
+ * `Certificate.verify()` is an `'anyone'` ProtoWallet checking the signature
49
+ * against `certifier`. Declaring it required would describe a contract the SDK
50
+ * does not honour.
51
+ */
52
+ export interface ProfileSigner {
53
+ getPublicKey(args: { identityKey: true }, originator?: string): Promise<{ publicKey: string }>
54
+ createSignature(
55
+ args: { data: number[]; protocolID: [number, string]; keyID: string; counterparty?: string },
56
+ originator?: string
57
+ ): Promise<{ signature: number[] }>
58
+ }
59
+
60
+ /** A certificate that passed every rule in the trust model. */
61
+ export interface RegistryProfile {
62
+ identityKey: string
63
+ paymail: string
64
+ handle: string
65
+ domain: string
66
+ displayName?: string
67
+ issuedAt: Date
68
+ certificate: ProfileCertJson
69
+ }
70
+
71
+ export async function buildProfileCertificate(args: {
72
+ signer: ProfileSigner
73
+ paymail: string
74
+ issuedAt: Date
75
+ displayName?: string
76
+ released?: boolean
77
+ }): Promise<ProfileCertJson> {
78
+ const parsed = parsePaymail(args.paymail)
79
+ if (!parsed) throw new Error(`handleRegistry: not a valid paymail: ${args.paymail}`)
80
+ if (!Number.isFinite(args.issuedAt.getTime())) throw new Error('handleRegistry: issuedAt is not a date')
81
+
82
+ const fields: Record<string, string> = {
83
+ paymail: `${parsed.handle}@${parsed.domain}`,
84
+ issuedAt: args.issuedAt.toISOString()
85
+ }
86
+ const displayName = args.displayName?.trim() ?? ''
87
+ if (displayName !== '') fields.displayName = displayName
88
+ if (args.released === true) fields.released = 'true'
89
+ assertWithinLimits(fields)
90
+
91
+ const { publicKey } = await args.signer.getPublicKey({ identityKey: true })
92
+ const certificate = new Certificate(
93
+ PROFILE_CERT_TYPE,
94
+ Utils.toBase64(Random(32)),
95
+ publicKey,
96
+ publicKey,
97
+ ZERO_OUTPOINT,
98
+ fields
99
+ )
100
+ // `sign` is typed against ProtoWallet; structurally it needs only the two
101
+ // methods ProfileSigner names, and the wallet this app passes is the
102
+ // originator-bound PermissionsManager, not a ProtoWallet.
103
+ await certificate.sign(args.signer as unknown as ProtoWallet)
104
+
105
+ const json: ProfileCertJson = {
106
+ type: certificate.type,
107
+ serialNumber: certificate.serialNumber,
108
+ subject: certificate.subject,
109
+ certifier: certificate.certifier,
110
+ revocationOutpoint: certificate.revocationOutpoint,
111
+ fields: certificate.fields,
112
+ signature: certificate.signature ?? ''
113
+ }
114
+ if (json.signature === '') throw new Error('handleRegistry: signing produced no signature')
115
+ if (utf8ByteLength(JSON.stringify(json)) > MAX_CERT_BODY_BYTES) {
116
+ throw new Error('handleRegistry: certificate exceeds the 16 KB body limit')
117
+ }
118
+ return json
119
+ }
120
+
121
+ /** Refused here rather than at the server, so a too-long name is an immediate
122
+ * message about the field the user is typing, not a 400 two seconds later. */
123
+ function assertWithinLimits(fields: Record<string, string>): void {
124
+ const names = Object.keys(fields)
125
+ if (names.length > MAX_FIELDS) throw new Error(`handleRegistry: more than ${MAX_FIELDS} certificate fields`)
126
+ for (const name of names) {
127
+ if (utf8ByteLength(name) >= MAX_FIELD_NAME_BYTES) throw new Error(`handleRegistry: field name too long: ${name}`)
128
+ if (utf8ByteLength(fields[name]) > MAX_FIELD_VALUE_BYTES) {
129
+ throw new Error(`handleRegistry: field value too long: ${name}`)
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * The trust model, in order. Answers a profile or null; never throws, because
136
+ * every caller is rendering a list and a bad row is a row to leave out.
137
+ */
138
+ export async function verifyProfileCertificate(
139
+ cert: unknown,
140
+ expect: { domain: string; paymail?: string; identityKey?: string }
141
+ ): Promise<RegistryProfile | null> {
142
+ try {
143
+ const json = asProfileCertJson(cert)
144
+ if (!json) return drop('not a certificate object')
145
+ if (json.type !== PROFILE_CERT_TYPE) return drop('wrong certificate type')
146
+ if (json.subject.toLowerCase() !== json.certifier.toLowerCase()) return drop('subject is not the certifier')
147
+ if (json.revocationOutpoint !== ZERO_OUTPOINT) return drop('revocation outpoint is not the zero outpoint')
148
+ if (utf8ByteLength(JSON.stringify(json)) > MAX_CERT_BODY_BYTES) return drop('over the body limit')
149
+
150
+ const names = Object.keys(json.fields)
151
+ if (names.length > MAX_FIELDS) return drop('too many fields')
152
+ for (const name of names) {
153
+ if (utf8ByteLength(name) >= MAX_FIELD_NAME_BYTES) return drop('field name over the limit')
154
+ if (utf8ByteLength(json.fields[name]) > MAX_FIELD_VALUE_BYTES) return drop('field value over the limit')
155
+ }
156
+ if (json.fields.released === 'true') return drop('released')
157
+
158
+ const paymail = json.fields.paymail
159
+ if (typeof paymail !== 'string' || paymail !== paymail.trim().toLowerCase()) {
160
+ return drop('paymail is not exact lowercase')
161
+ }
162
+ const parsed = parsePaymail(paymail)
163
+ if (!parsed) return drop('paymail is not handle@domain')
164
+ if (parsed.domain !== expect.domain.trim().toLowerCase()) return drop('paymail is for another domain')
165
+ if (expect.paymail !== undefined && paymail !== expect.paymail.trim().toLowerCase()) {
166
+ return drop('not the paymail that was asked for')
167
+ }
168
+ if (expect.identityKey !== undefined && json.subject.toLowerCase() !== expect.identityKey.trim().toLowerCase()) {
169
+ return drop('not the key that was asked for')
170
+ }
171
+
172
+ const issuedAtMs = Date.parse(json.fields.issuedAt ?? '')
173
+ if (!Number.isFinite(issuedAtMs)) return drop('issuedAt is missing or unparseable')
174
+
175
+ const verified = await new Certificate(
176
+ json.type,
177
+ json.serialNumber,
178
+ json.subject,
179
+ json.certifier,
180
+ json.revocationOutpoint,
181
+ json.fields,
182
+ json.signature
183
+ ).verify()
184
+ // Since @bsv/sdk 2.8 `verify` answers false for a forged or malformed
185
+ // signature instead of throwing, so this is where a forgery is refused.
186
+ if (!verified) return drop('signature does not verify')
187
+
188
+ const displayName = json.fields.displayName?.trim()
189
+ return {
190
+ identityKey: json.subject,
191
+ paymail,
192
+ handle: parsed.handle,
193
+ domain: parsed.domain,
194
+ ...(displayName ? { displayName } : {}),
195
+ issuedAt: new Date(issuedAtMs),
196
+ certificate: json
197
+ }
198
+ } catch (e) {
199
+ // Every throw shares one reason, because the text is the SDK's and some of
200
+ // it is shaped by the certificate: one bad character in `serialNumber`
201
+ // reaches the base64 decoder, which names the index it failed at — a
202
+ // different sentence per position, and enough of them to spend the budget
203
+ // below and silence every real reason afterwards. The first one still
204
+ // reports its own words, which is what a broken registry is diagnosed from.
205
+ return drop('certificate threw during verification', e instanceof Error ? e.message : String(e))
206
+ }
207
+ }
208
+
209
+ /**
210
+ * One line per reason, then silence.
211
+ *
212
+ * A failed certificate is never shown, and a registry serving ten junk rows on
213
+ * every debounced keystroke must not be able to fill the log either — so a
214
+ * reason already reported is not reported again. Every reason is one of this
215
+ * module's own literals; the cap is there so that a reason built one day from
216
+ * text the registry supplied still cannot grow the set without bound.
217
+ */
218
+ const droppedReasons = new Set<string>()
219
+ function drop(why: string, detail?: string): null {
220
+ if (!droppedReasons.has(why) && droppedReasons.size < 32) {
221
+ droppedReasons.add(why)
222
+ const line = detail === undefined ? why : `${why}: ${detail}`
223
+ console.log('handleRegistry: dropped a profile certificate —', line, '(further reports suppressed)')
224
+ }
225
+ return null
226
+ }
227
+
228
+ /** Test-only: forget which reasons have been reported. */
229
+ export function resetDroppedLog(): void {
230
+ droppedReasons.clear()
231
+ }
232
+
233
+ function asProfileCertJson(value: unknown): ProfileCertJson | null {
234
+ if (!value || typeof value !== 'object') return null
235
+ const candidate = value as Record<string, unknown>
236
+ for (const key of ['type', 'serialNumber', 'subject', 'certifier', 'revocationOutpoint', 'signature'] as const) {
237
+ if (typeof candidate[key] !== 'string') return null
238
+ }
239
+ if (!candidate.fields || typeof candidate.fields !== 'object' || Array.isArray(candidate.fields)) return null
240
+ const fields: Record<string, string> = {}
241
+ for (const [name, fieldValue] of Object.entries(candidate.fields as Record<string, unknown>)) {
242
+ if (typeof fieldValue !== 'string') return null
243
+ fields[name] = fieldValue
244
+ }
245
+ return {
246
+ type: candidate.type as string,
247
+ serialNumber: candidate.serialNumber as string,
248
+ subject: candidate.subject as string,
249
+ certifier: candidate.certifier as string,
250
+ revocationOutpoint: candidate.revocationOutpoint as string,
251
+ fields,
252
+ signature: candidate.signature as string
253
+ }
254
+ }