@bsv/expo-wallet-toolbox 0.5.0 → 0.7.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 (90) hide show
  1. package/CHANGELOG.md +255 -0
  2. package/README.md +19 -0
  3. package/core/amountFormatHelpers.ts +238 -34
  4. package/core/backup/RemoteSyncReader.ts +2 -5
  5. package/core/backup/codec.ts +2 -2
  6. package/core/backup/push.ts +1 -1
  7. package/core/config.tsx +12 -5
  8. package/core/contacts/contactActivity.ts +153 -0
  9. package/core/contacts/contactCache.ts +41 -0
  10. package/core/contacts/contactsStore.ts +183 -0
  11. package/core/context/WalletContext.tsx +55 -10
  12. package/core/demo/demoAssets.ts +60 -0
  13. package/core/demo/demoLedger.ts +240 -0
  14. package/core/demo/demoMandalaRuntime.ts +96 -0
  15. package/core/demo/demoMode.ts +38 -0
  16. package/core/demo/demoWallet.ts +25 -0
  17. package/core/demo/index.ts +26 -0
  18. package/core/demo/useDemo.ts +59 -0
  19. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  20. package/core/headers/headerStore.ts +7 -10
  21. package/core/i18n/translations.tsx +1234 -74
  22. package/core/identity/contactLink.ts +36 -0
  23. package/core/identity/handleRegistry/client.ts +285 -0
  24. package/core/identity/handleRegistry/profileCert.ts +254 -0
  25. package/core/identity/handleRegistry/registration.ts +559 -0
  26. package/core/identity/handleRegistry/resolver.ts +247 -0
  27. package/core/identity/handleRegistry/rules.ts +104 -0
  28. package/core/index.ts +20 -2
  29. package/core/localpay/pendingAborts.ts +5 -1
  30. package/core/monitor/MonitorSupervisor.ts +121 -0
  31. package/core/monitor/TaskBackupPush.ts +1 -1
  32. package/core/monitor/TaskCreditInbox.ts +1 -1
  33. package/core/monitor/TaskDrainOutbox.ts +1 -1
  34. package/core/monitor/TaskSendOffline.ts +1 -1
  35. package/core/net/online.ts +49 -0
  36. package/core/numberFormat.ts +19 -0
  37. package/core/offline/plan.ts +1 -1
  38. package/core/pay/recordProof.ts +2 -6
  39. package/core/services/arcadeBroadcastProvider.ts +1 -4
  40. package/core/services/exchangeRate.ts +1 -1
  41. package/core/services/externalOrigin.ts +5 -2
  42. package/core/services/vault/transfers.ts +2 -2
  43. package/core/services/walletServiceConfig.ts +31 -20
  44. package/core/storage/StorageExpoSQLite.ts +41 -34
  45. package/core/storage/methods/findSql.ts +3 -0
  46. package/core/storage/methods/listActionsSql.ts +8 -5
  47. package/core/storage/methods/listOutputsSql.ts +2 -2
  48. package/core/storage/methods/processOfflineActions.ts +2 -3
  49. package/core/storage/methods/reviewStatusSql.ts +7 -2
  50. package/core/storage/schema/createTables.ts +29 -0
  51. package/core/toolboxConfig.ts +70 -0
  52. package/core/toolboxTypes.ts +40 -0
  53. package/core/userAvatar.ts +79 -0
  54. package/core/walletMonitor.ts +8 -3
  55. package/package.json +7 -7
  56. package/ui/activityFilter.ts +115 -0
  57. package/ui/components/pay/PaymentSuccessOverlay.tsx +46 -6
  58. package/ui/components/pay/RecipientField.tsx +84 -70
  59. package/ui/components/pay/StepBar.tsx +32 -0
  60. package/ui/components/pay/UniversalSend.tsx +677 -149
  61. package/ui/components/ui/PencilEditField.tsx +109 -0
  62. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  63. package/ui/components/wallet/ActivityRow.tsx +222 -120
  64. package/ui/components/wallet/AmountInput.tsx +18 -6
  65. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  66. package/ui/components/wallet/ContactSigil.tsx +49 -0
  67. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  68. package/ui/components/wallet/FitAmount.tsx +148 -0
  69. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  70. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  71. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  72. package/ui/components/wallet/ProfileButton.tsx +62 -0
  73. package/ui/components/wallet/UserAvatar.tsx +85 -0
  74. package/ui/components/wallet/avatarIcons.ts +122 -0
  75. package/ui/hooks/useContactsStore.ts +10 -0
  76. package/ui/hooks/useMandala.ts +18 -1
  77. package/ui/hooks/useOnline.ts +65 -20
  78. package/ui/index.ts +26 -1
  79. package/ui/screens/ContactScreen.tsx +289 -0
  80. package/ui/screens/ContactsScreen.tsx +373 -0
  81. package/ui/screens/IdentifierScreen.tsx +234 -0
  82. package/ui/screens/NewContactScreen.tsx +362 -0
  83. package/ui/screens/PayScreen.tsx +20 -7
  84. package/ui/screens/ProfileScreen.tsx +783 -0
  85. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  86. package/ui/screens/TrustScreen.tsx +1 -1
  87. package/ui/screens/WalletConfigScreen.tsx +42 -0
  88. package/ui/screens/WalletHomeScreen.tsx +528 -83
  89. package/ui/tokenStatus.ts +21 -0
  90. package/ui/txStatus.ts +43 -5
@@ -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,285 @@
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
+
26
+ /** Why a handle is not free. The server's `stale` arrives as `cooldown`. */
27
+ export type AvailabilityReason = 'taken' | 'too_similar' | 'reserved' | 'invalid' | 'cooldown'
28
+
29
+ export type AvailabilityResult =
30
+ | { kind: 'available' }
31
+ | { kind: 'unavailable'; reason: AvailabilityReason }
32
+ | { kind: 'failed' }
33
+
34
+ /** `rejected` is the server answering no; `failed` is not having an answer. */
35
+ export type PutResult =
36
+ | { kind: 'created' }
37
+ | { kind: 'ok' }
38
+ | { kind: 'rejected'; code: string; description: string }
39
+ | { kind: 'failed'; message: string }
40
+
41
+ /**
42
+ * `none` means the registry answered and holds nothing believable for that key;
43
+ * `failed` means there was no answer at all. A caller that only renders can
44
+ * flatten both to "no handle" — `lookupIdentityKey` does. A caller that WRITES
45
+ * the answer into a cache cannot: blanking a contact's handle because the
46
+ * device happened to be offline is the opposite of a cache.
47
+ */
48
+ export type ProfileLookup = { kind: 'found'; profile: RegistryProfile } | { kind: 'none' } | { kind: 'failed' }
49
+
50
+ export interface HandleRegistryClient {
51
+ /** The pinned domain: what a bare handle is registered under. */
52
+ readonly domain: string
53
+ checkAvailability(handle: string): Promise<AvailabilityResult>
54
+ putCertificate(cert: ProfileCertJson): Promise<PutResult>
55
+ /** Throws on transport failure — the contract `searchIdentities` already has. */
56
+ search(query: string): Promise<RegistryProfile[]>
57
+ /** Never throws. The full verdict, for callers that cache the answer. */
58
+ lookupProfile(identityKey: string, domain?: string): Promise<ProfileLookup>
59
+ /** Never throws — the contract `resolveIdentity` already has. */
60
+ lookupIdentityKey(identityKey: string, domain?: string): Promise<RegistryProfile | null>
61
+ /** The device clock, corrected by the skew the pinned registry last reported. */
62
+ serverNow(): Date
63
+ }
64
+
65
+ function reasonOf(raw: unknown): AvailabilityReason | null {
66
+ switch (raw) {
67
+ case 'taken':
68
+ case 'too_similar':
69
+ case 'reserved':
70
+ case 'invalid':
71
+ case 'cooldown':
72
+ return raw
73
+ // A released row whose stored issuedAt has not passed yet: a certificate
74
+ // dated now cannot beat it, so to the person typing this is a cooldown.
75
+ case 'stale':
76
+ return 'cooldown'
77
+ default:
78
+ return null
79
+ }
80
+ }
81
+
82
+ export function createHandleRegistryClient(args: {
83
+ pinned: RegistryPin
84
+ fetchImpl?: typeof fetch
85
+ now?: () => number
86
+ resolver?: RegistryResolver
87
+ }): HandleRegistryClient {
88
+ const fetchImpl = args.fetchImpl ?? ((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init))
89
+ const now = args.now ?? (() => Date.now())
90
+ const domain = args.pinned.domain.trim().toLowerCase()
91
+ const origin = args.pinned.url.trim().replace(/\/+$/, '')
92
+ const resolver = args.resolver ?? createRegistryResolver({ pinned: args.pinned, fetchImpl, now })
93
+ let skewMs = 0
94
+
95
+ /** Only ever from the registry we write to: a foreign host's clock is not
96
+ * the one our `issuedAt` has to beat. */
97
+ function notePinnedSkew(res: Response): void {
98
+ const header = res.headers?.get?.('date')
99
+ const at = header ? Date.parse(header) : NaN
100
+ if (Number.isFinite(at)) skewMs = at - now()
101
+ }
102
+
103
+ async function errorBody(res: Response): Promise<{ code: string; description: string }> {
104
+ try {
105
+ const body = (await res.json()) as { code?: unknown; description?: unknown } | undefined
106
+ return {
107
+ code: typeof body?.code === 'string' ? body.code : `ERR_HTTP_${res.status}`,
108
+ description: typeof body?.description === 'string' ? body.description : `registry HTTP ${res.status}`
109
+ }
110
+ } catch {
111
+ return { code: `ERR_HTTP_${res.status}`, description: `registry HTTP ${res.status}` }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Which registry answers this query, what to send it, and whether the user
117
+ * typed a complete address rather than a fragment.
118
+ *
119
+ * `paymail` is set only for a complete `handle@domain`. The trust model then
120
+ * requires that only a row with exactly that paymail be offered — the
121
+ * server's search is a prefix, skeleton and substring search, so without this
122
+ * a typed `dee@deggen.com` would be answered with `dee2`, `deeanna` and a
123
+ * look-alike, any of which the user might take for the person they named.
124
+ *
125
+ * Complete means the domain is finished AND the local part could be a handle.
126
+ * That second half is a choice: `de@deggen.com` can name nobody, because no
127
+ * registered handle is two characters, so it is read as the fragment it is
128
+ * and the prefix neighbours are still offered as suggestions — the strict
129
+ * reading would answer an address that cannot exist with nothing at all.
130
+ *
131
+ * `isRoutableSearchQuery` is the server's own gate restated: over 32
132
+ * characters, outside `[a-z0-9._-]`, or a path its route table claims (the
133
+ * literal `available`, which answers `400 ERR_INVALID_LOOKUP` and would
134
+ * otherwise surface as an outage) costs no request at all.
135
+ *
136
+ * `transient` marks the one place those two readings overlap — see the
137
+ * comment on the prefix branch.
138
+ */
139
+ function routeFor(raw: string): { domain: string; query: string; paymail?: string; transient?: boolean } | null {
140
+ const text = raw.trim().toLowerCase()
141
+ const at = text.indexOf('@')
142
+ if (at < 0) return isRoutableSearchQuery(text) ? { domain, query: text } : null
143
+ const local = text.slice(0, at)
144
+ const typed = text.slice(at + 1)
145
+ if (local.length < SEARCH_MIN_QUERY_LENGTH || !isRoutableSearchQuery(local)) return null
146
+ // A domain still being typed is a prefix of ours: still our registry, and
147
+ // still a fragment — the user has not finished naming anybody yet.
148
+ //
149
+ // A prefix that is ITSELF a complete domain is not that. `.co` is a prefix
150
+ // of `.com`, so for essentially any pinned `x.com` a finished, real,
151
+ // different registry would be answered by ours — with the exact-paymail
152
+ // rule switched off, because the address would be read as a fragment. A
153
+ // typed `alice@deggen.co` would come back as every `*@deggen.com`
154
+ // neighbour, squatter included, and never as the person named.
155
+ if (typed === domain || (domain.startsWith(typed) && !looksLikeDomain(typed))) {
156
+ const complete = typed === domain && isValidHandleFormat(local)
157
+ return { domain, query: local, ...(complete ? { paymail: `${local}@${domain}` } : {}) }
158
+ }
159
+ if (!looksLikeDomain(typed)) return null
160
+ const complete = isValidHandleFormat(local)
161
+ return {
162
+ domain: typed,
163
+ query: local,
164
+ ...(complete ? { paymail: `${local}@${typed}` } : {}),
165
+ // Every character of our own domain is typed through on the way to it, so
166
+ // a prefix of ours that resolves nowhere is a half-typed address rather
167
+ // than an outage to raise a banner about mid-keystroke.
168
+ ...(domain.startsWith(typed) ? { transient: true } : {})
169
+ }
170
+ }
171
+
172
+ /** A free function rather than a method: `lookupIdentityKey` delegates to it,
173
+ * and a destructured `const { lookupIdentityKey } = client` must still work. */
174
+ async function lookupProfile(identityKey: string, forDomain?: string): Promise<ProfileLookup> {
175
+ const key = identityKey.trim().toLowerCase()
176
+ const target = (forDomain ?? domain).trim().toLowerCase()
177
+ try {
178
+ const endpoints = await resolver.resolve(target)
179
+ if (!endpoints) return { kind: 'failed' }
180
+ const res = await fetchWithTimeout(fetchImpl, endpoints.reverse(key), {
181
+ headers: { accept: 'application/json' }
182
+ })
183
+ if (endpoints.pinned) notePinnedSkew(res)
184
+ // Only a 404 is the registry saying "this key holds nothing". Every other
185
+ // refusal is the registry not having answered the question at all, and a
186
+ // caller that caches the answer has to be able to tell those apart.
187
+ if (res.status === 404) return { kind: 'none' }
188
+ if (!res.ok) return { kind: 'failed' }
189
+ const profile = await verifyProfileCertificate(await res.json(), { domain: target, identityKey: key })
190
+ return profile ? { kind: 'found', profile } : { kind: 'none' }
191
+ } catch {
192
+ return { kind: 'failed' }
193
+ }
194
+ }
195
+
196
+ return {
197
+ domain,
198
+
199
+ async checkAvailability(handle) {
200
+ const wanted = handle.trim().toLowerCase()
201
+ // Checked here first so a half-typed handle costs no request and gets an
202
+ // answer on the keystroke rather than after the round trip.
203
+ if (!isValidHandleFormat(wanted)) return { kind: 'unavailable', reason: 'invalid' }
204
+ try {
205
+ const res = await fetchWithTimeout(fetchImpl, `${origin}/api/handle/available/${encodeURIComponent(wanted)}`, {
206
+ headers: { accept: 'application/json' }
207
+ })
208
+ notePinnedSkew(res)
209
+ if (!res.ok) return { kind: 'failed' }
210
+ const body = (await res.json()) as { available?: unknown; reason?: unknown } | undefined
211
+ if (body?.available === true) return { kind: 'available' }
212
+ const reason = reasonOf(body?.reason)
213
+ return reason ? { kind: 'unavailable', reason } : { kind: 'failed' }
214
+ } catch {
215
+ return { kind: 'failed' }
216
+ }
217
+ },
218
+
219
+ async putCertificate(cert) {
220
+ let res: Response
221
+ try {
222
+ res = await fetchWithTimeout(fetchImpl, `${origin}/api/handle`, {
223
+ method: 'PUT',
224
+ headers: { 'content-type': 'application/json' },
225
+ body: JSON.stringify(cert)
226
+ })
227
+ } catch (e) {
228
+ return { kind: 'failed', message: e instanceof Error ? e.message : String(e) }
229
+ }
230
+ notePinnedSkew(res)
231
+ if (res.status === 201) return { kind: 'created' }
232
+ if (res.status === 200) return { kind: 'ok' }
233
+ // Rate limiting and a server fault are both "ask again later"; every
234
+ // other status is the registry having read the certificate and refused.
235
+ if (res.status === 429 || res.status >= 500) return { kind: 'failed', message: `registry HTTP ${res.status}` }
236
+ const { code, description } = await errorBody(res)
237
+ return { kind: 'rejected', code, description }
238
+ },
239
+
240
+ async search(query) {
241
+ const route = routeFor(query)
242
+ if (!route) return []
243
+ const endpoints = await resolver.resolve(route.domain)
244
+ if (!endpoints) {
245
+ if (route.transient) return []
246
+ throw new Error(`handleRegistry: no registry for ${route.domain}`)
247
+ }
248
+ const res = await fetchWithTimeout(fetchImpl, endpoints.search(route.query), {
249
+ headers: { accept: 'application/json' }
250
+ })
251
+ if (endpoints.pinned) notePinnedSkew(res)
252
+ if (!res.ok) throw new Error(`handleRegistry: search failed with HTTP ${res.status}`)
253
+ const body = (await res.json()) as unknown
254
+ if (!Array.isArray(body)) return []
255
+ const verified = await Promise.all(
256
+ // Capped before a single signature is checked. The route's contract is
257
+ // ten rows and our own server enforces it, but a complete foreign
258
+ // domain the user typed is answered by a host bound by nothing — and
259
+ // each row is one ECDSA verification on the thread the recipient field
260
+ // is drawn from, so an uncapped answer is a freeze, not a long list.
261
+ //
262
+ // `expect.paymail` is what enforces "a complete address names one
263
+ // person": set, every other row the server volunteered is dropped.
264
+ body.slice(0, MAX_SEARCH_RESULTS).map(row =>
265
+ verifyProfileCertificate(row, {
266
+ domain: route.domain,
267
+ ...(route.paymail ? { paymail: route.paymail } : {})
268
+ })
269
+ )
270
+ )
271
+ return verified.filter((profile): profile is RegistryProfile => profile !== null)
272
+ },
273
+
274
+ lookupProfile,
275
+
276
+ async lookupIdentityKey(identityKey, forDomain) {
277
+ const result = await lookupProfile(identityKey, forDomain)
278
+ return result.kind === 'found' ? result.profile : null
279
+ },
280
+
281
+ serverNow() {
282
+ return new Date(now() + skewMs)
283
+ }
284
+ }
285
+ }
@@ -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
+ }