@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The transport-independent conformance cases (spec 6.14 item 7, "Shared conformance cases"): all 28 methods
3
+ * round-trip, wallet errors map to `WireError`, and the request and response size caps. A transport's tests run
4
+ * them against its own executor through `CaseContext.call`, so the HTTP router (Android) and any later transport
5
+ * share one definition. The HTTP-only cases (status table, CORS, Host check) stay in the router tests.
6
+ *
7
+ * Contract of the wallet under test (the executor wires its fake wallet this way):
8
+ * - every method answers `{ echo: <method> }`;
9
+ * - `{ __fail: kind }` makes the wallet throw: `invalid-parameter` (a `WERR_INVALID_PARAMETER`), `insufficient-funds`
10
+ * (`WERR_INSUFFICIENT_FUNDS`), `hmac` (`code: 'ERR_INVALID_HMAC'`), `signature` (`code: 'ERR_INVALID_SIGNATURE'`),
11
+ * `unknown` (a plain `Error`);
12
+ * - `{ __respondBytes: n }` makes the wallet answer a string of `n` characters.
13
+ *
14
+ * `call` returns the dispatcher `Outcome`, or an `HttpResult` when the executor is an HTTP responder. For an
15
+ * `HttpResult` the cases read the JSON body, not the status: a body with `isError: true` is a wallet error, a
16
+ * body with `domain: 'brc185'` is a connection error, anything else is the result.
17
+ */
18
+ import type { Outcome } from '../dispatcher'
19
+ import { MAX_BRIDGE_REQUEST_BYTES } from '../protocol/limits'
20
+ import { BRIDGE_METHODS, type WalletMethodName } from '../protocol/methods'
21
+ import type { ConnectionErrorCode, Delivery } from '../protocol/connectionError'
22
+ import type { WireError } from '../protocol/errorCodec'
23
+
24
+ export type { Outcome }
25
+
26
+ export interface HttpResult {
27
+ status: number
28
+ headers: [string, string][]
29
+ body: string
30
+ }
31
+
32
+ export interface CaseContext {
33
+ call(method: string, args: unknown): Promise<Outcome | HttpResult>
34
+ }
35
+
36
+ export interface ConformanceCase {
37
+ id: string
38
+ method?: WalletMethodName
39
+ /** Throws on failure. */
40
+ run(ctx: CaseContext): Promise<void>
41
+ }
42
+
43
+ type Normalised =
44
+ | { kind: 'ok'; result: unknown }
45
+ | { kind: 'wallet'; wire: Partial<WireError> }
46
+ | { kind: 'connection'; code: ConnectionErrorCode; delivery?: Delivery }
47
+
48
+ function isHttp(r: Outcome | HttpResult): r is HttpResult {
49
+ return typeof (r as HttpResult).status === 'number' && typeof (r as HttpResult).body === 'string'
50
+ }
51
+
52
+ function normalise(r: Outcome | HttpResult): Normalised {
53
+ if (!isHttp(r)) {
54
+ if (r.ok) return { kind: 'ok', result: r.result }
55
+ if ('walletError' in r) return { kind: 'wallet', wire: r.walletError }
56
+ return { kind: 'connection', code: r.connectionError.code, delivery: r.connectionError.delivery }
57
+ }
58
+ let body: unknown
59
+ try {
60
+ body = JSON.parse(r.body)
61
+ } catch {
62
+ throw new Error(`HTTP ${r.status} body is not JSON`)
63
+ }
64
+ const o = body as Record<string, unknown> | null
65
+ if (o !== null && typeof o === 'object') {
66
+ if (o.isError === true) return { kind: 'wallet', wire: o as Partial<WireError> }
67
+ if (o.domain === 'brc185') {
68
+ return { kind: 'connection', code: o.code as ConnectionErrorCode, delivery: o.delivery as Delivery | undefined }
69
+ }
70
+ }
71
+ if (r.status < 200 || r.status > 299)
72
+ throw new Error(`HTTP ${r.status} with a body that is neither a wire nor a connection error`)
73
+ return { kind: 'ok', result: body }
74
+ }
75
+
76
+ function fail(msg: string): never {
77
+ throw new Error(msg)
78
+ }
79
+
80
+ function sameJson(a: unknown, b: unknown): boolean {
81
+ return JSON.stringify(a) === JSON.stringify(b)
82
+ }
83
+
84
+ const methodCases: ConformanceCase[] = (Object.keys(BRIDGE_METHODS) as WalletMethodName[]).map(method => ({
85
+ id: `method:${method}`,
86
+ method,
87
+ async run(ctx) {
88
+ const n = normalise(await ctx.call(method, {}))
89
+ if (n.kind !== 'ok') fail(`${method}: expected a result, got ${JSON.stringify(n)}`)
90
+ if (!sameJson(n.result, { echo: method })) fail(`${method}: result did not round-trip: ${JSON.stringify(n.result)}`)
91
+ }
92
+ }))
93
+
94
+ const ERROR_KINDS: Array<{ kind: string; code: number; name: string }> = [
95
+ { kind: 'invalid-parameter', code: 6, name: 'WERR_INVALID_PARAMETER' },
96
+ { kind: 'insufficient-funds', code: 7, name: 'WERR_INSUFFICIENT_FUNDS' },
97
+ { kind: 'hmac', code: 3, name: 'ERR_INVALID_HMAC' },
98
+ { kind: 'signature', code: 4, name: 'ERR_INVALID_SIGNATURE' },
99
+ { kind: 'unknown', code: 1, name: 'WERR_UNKNOWN' }
100
+ ]
101
+
102
+ const errorCases: ConformanceCase[] = ERROR_KINDS.map(({ kind, code, name }) => ({
103
+ id: `error-codec:${kind}`,
104
+ async run(ctx) {
105
+ const n = normalise(await ctx.call('getPublicKey', { __fail: kind }))
106
+ if (n.kind !== 'wallet') fail(`${kind}: expected a wallet error, got ${JSON.stringify(n)}`)
107
+ if (n.wire.isError !== true || n.wire.code !== code || n.wire.name !== name) {
108
+ fail(`${kind}: expected wire code ${code} ${name}, got ${JSON.stringify(n.wire)}`)
109
+ }
110
+ const msg = n.wire.message
111
+ if (typeof msg !== 'string' || msg.includes('\n at ')) fail(`${kind}: wire message missing or carries a stack`)
112
+ }
113
+ }))
114
+
115
+ const capCases: ConformanceCase[] = [
116
+ {
117
+ id: 'request-cap:over',
118
+ async run(ctx) {
119
+ const n = normalise(await ctx.call('listActions', { pad: 'a'.repeat(MAX_BRIDGE_REQUEST_BYTES + 1) }))
120
+ if (n.kind !== 'connection' || n.code !== 'RESOURCE_LIMIT')
121
+ fail(`expected RESOURCE_LIMIT, got ${JSON.stringify(n)}`)
122
+ if (n.delivery !== undefined && n.delivery !== 'not-sent') fail('an over-cap request must be not-sent')
123
+ }
124
+ },
125
+ {
126
+ id: 'response-cap:over',
127
+ async run(ctx) {
128
+ const n = normalise(await ctx.call('listActions', { __respondBytes: MAX_BRIDGE_REQUEST_BYTES + 1 }))
129
+ if (n.kind !== 'connection' || n.code !== 'RESOURCE_LIMIT')
130
+ fail(`expected RESOURCE_LIMIT, got ${JSON.stringify(n)}`)
131
+ if (n.delivery !== undefined && n.delivery !== 'unknown') fail('an over-cap response must be delivery unknown')
132
+ }
133
+ },
134
+ {
135
+ id: 'response-cap:under',
136
+ async run(ctx) {
137
+ const n = normalise(await ctx.call('listActions', { __respondBytes: 1024 }))
138
+ if (n.kind !== 'ok' || typeof n.result !== 'string' || n.result.length !== 1024) {
139
+ fail(`a small response must pass through, got ${JSON.stringify(n).slice(0, 200)}`)
140
+ }
141
+ }
142
+ }
143
+ ]
144
+
145
+ export const TRANSPORT_INDEPENDENT_CASES: ReadonlyArray<ConformanceCase> = Object.freeze([
146
+ ...methodCases,
147
+ ...errorCases,
148
+ ...capCases
149
+ ])
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The page-client contract a transport's stand-in client implements (BRC-185 section 4.2, spec 6.16): discover,
3
+ * connect, invoke. Types only, copied from the iOS kit's `src/testing/pageClient.ts` with one change:
4
+ * `DiscoveredProvider.handle` is `unknown`, because the handle is transport-specific (a page-side announce handle on
5
+ * Safari, an endpoint set on Android loopback). The iOS copy is left as is. No imports from the app.
6
+ */
7
+ import type { WalletInterface } from '@bsv/sdk'
8
+ import { isConnectionError, type ConnectionError, type ConnectionErrorCode } from '../protocol/connectionError'
9
+ import type { Descriptor } from '../protocol/descriptor'
10
+ import type { CloseReason } from '../protocol/envelopes'
11
+
12
+ export { isConnectionError }
13
+ export type { ConnectionError, ConnectionErrorCode, CloseReason }
14
+
15
+ export interface DiscoveredProvider {
16
+ requestId: string
17
+ /** Transport-specific; opaque to shared code. */
18
+ handle: unknown
19
+ descriptor: Descriptor
20
+ }
21
+
22
+ export interface RejectedProvider {
23
+ requestId: string
24
+ reason: string
25
+ error?: unknown
26
+ }
27
+
28
+ export interface Connection {
29
+ epoch: string
30
+ provider: DiscoveredProvider
31
+ wallet: WalletInterface
32
+ /** Reasons delivered to `onClose`, in order. */
33
+ closed: CloseReason[]
34
+ disconnect(): Promise<void>
35
+ }
36
+
37
+ export interface PageClient {
38
+ /** Collect, describe and verify each provider. */
39
+ discover(): Promise<{ providers: DiscoveredProvider[]; rejected: RejectedProvider[] }>
40
+ /** Connect to a verified provider with a fresh epoch. `onClose` also receives the reason in `Connection.closed`. */
41
+ connect(provider: DiscoveredProvider, onClose?: (reason: CloseReason) => void): Promise<Connection>
42
+ /** `connection.wallet[method](args)`. */
43
+ invoke(connection: Connection, method: keyof WalletInterface, args?: unknown): Promise<unknown>
44
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The permissions manager for unverified (unattested) browser origins (spec 6.5).
3
+ *
4
+ * The same class as the attested manager, configured differently: its prompt settings come from
5
+ * the effective unverified policy, the token modules refuse, and it reads a site's manifest from
6
+ * the real hostname rather than the `<hostname>.<grantTag>.unverified.invalid` namespace name it
7
+ * sees as the originator. The caller applies the same wrapper stack as the attested manager.
8
+ */
9
+ import type { WalletInterface } from '@bsv/sdk'
10
+ import { SigningPolicyPermissionsManager, isAskEveryTimeProtocol } from '../services/signingPermissionPolicy'
11
+ import type { SeekFlags } from './permissionPolicy'
12
+ import { hostnameOfUnattested, isUnattestedOriginator } from './unverifiedOriginator'
13
+
14
+ /** A token module that refuses everything: these modules move tokens and keep their own
15
+ * approval sessions per originator, which a forging local app could ride. */
16
+ export const refusingModule = {
17
+ onRequest: async () => {
18
+ const error = new Error('Token modules are not available to unverified origins') as Error & { code: string }
19
+ error.code = 'ERR_PERMISSION_DENIED'
20
+ throw error
21
+ },
22
+ onResponse: async (res: unknown) => res
23
+ }
24
+
25
+ const SPECIAL_SUFFIXES = ['.localhost', '.local', '.internal', '.lan', '.home.arpa', '.test', '.example', '.onion']
26
+
27
+ /** Hosts whose manifest proves nothing or must never be fetched on a site's say-so (spec 6.5). */
28
+ export function isUnreadableManifestHost(host: string): boolean {
29
+ if (host === 'localhost' || !host.includes('.')) return true
30
+ if (/^[0-9]+$/.test(host.slice(host.lastIndexOf('.') + 1))) return true
31
+ return SPECIAL_SUFFIXES.some(s => host.endsWith(s))
32
+ }
33
+
34
+ interface Manifest {
35
+ groupPermissions: Record<string, any> | null
36
+ counterpartyPermissions: Record<string, any> | null
37
+ }
38
+
39
+ /** A token-module name: raw, exact-case `p <scheme> …`, the form the manager routes on. */
40
+ function routesToTokenModule(name: unknown): boolean {
41
+ if (typeof name !== 'string' || !name.startsWith('p ')) return false
42
+ const scheme = name.split(' ')[1]
43
+ return scheme === 'btms' || scheme === 'color'
44
+ }
45
+
46
+ /** Fresh shallow copies; the delegate's objects are never edited. */
47
+ export function filterUnverifiedManifest(manifest: Manifest): Manifest {
48
+ const { groupPermissions, counterpartyPermissions } = manifest
49
+ let group: Manifest['groupPermissions'] = null
50
+ if (groupPermissions != null) {
51
+ const { spendingAuthorization: _dropped, ...rest } = groupPermissions
52
+ group = { ...rest }
53
+ if (Array.isArray(rest.protocolPermissions)) {
54
+ group.protocolPermissions = rest.protocolPermissions.filter(
55
+ (p: any) => !routesToTokenModule(p?.protocolID?.[1]) && !isAskEveryTimeProtocol(p?.protocolID)
56
+ )
57
+ }
58
+ if (Array.isArray(rest.basketAccess)) {
59
+ group.basketAccess = rest.basketAccess.filter((b: any) => !routesToTokenModule(b?.basket))
60
+ }
61
+ }
62
+ let counterparty: Manifest['counterpartyPermissions'] = null
63
+ if (counterpartyPermissions != null) {
64
+ counterparty = { ...counterpartyPermissions }
65
+ if (Array.isArray(counterpartyPermissions.protocols)) {
66
+ counterparty.protocols = counterpartyPermissions.protocols.filter(
67
+ (p: any) =>
68
+ !routesToTokenModule(p?.protocolID?.[1] ?? p?.protocolName) && !isAskEveryTimeProtocol(p?.protocolID)
69
+ )
70
+ }
71
+ }
72
+ return { groupPermissions: group, counterpartyPermissions: counterparty }
73
+ }
74
+
75
+ export function buildUnverifiedPermissionsManager(
76
+ wallet: WalletInterface,
77
+ adminOriginator: string,
78
+ flags: SeekFlags
79
+ ): SigningPolicyPermissionsManager {
80
+ const manager = new SigningPolicyPermissionsManager(wallet, adminOriginator, {
81
+ differentiatePrivilegedOperations: true,
82
+ ...flags,
83
+ permissionModules: { btms: refusingModule, color: refusingModule }
84
+ } as any)
85
+
86
+ // Instance-level override of the manager's (type-private) fetch: the attested manager is
87
+ // untouched, and this manager's own manifest cache is keyed by the real hostname.
88
+ const internals = manager as unknown as { fetchManifestPermissions(originator: string): Promise<Manifest> }
89
+ const fetchManifest = internals.fetchManifestPermissions.bind(manager)
90
+ internals.fetchManifestPermissions = async originator => {
91
+ if (!isUnattestedOriginator(originator)) return { groupPermissions: null, counterpartyPermissions: null }
92
+ const host = hostnameOfUnattested(originator)
93
+ if (isUnreadableManifestHost(host)) return { groupPermissions: null, counterpartyPermissions: null }
94
+ return filterUnverifiedManifest(await fetchManifest(host))
95
+ }
96
+ return manager
97
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The unverified originator namespace (spec 6.3, 6.5). Dependency-free so the Safari extension
3
+ * bundle, the dispatcher and the permissions layer all agree on one grammar.
4
+ *
5
+ * An unattested origin never reaches the wallet under its own name. It is rewritten to
6
+ * `<hostname>.<grantTag>.unverified.invalid`: the `.invalid` TLD never resolves, so no external
7
+ * input can produce the name, and a fresh grant tag per approval means permissions granted under
8
+ * one approval are not inherited by the next (6.4).
9
+ */
10
+ import { GRANT_TAG_PREFIX, GRANT_TAG_RANDOM_CHARS } from './protocol/limits'
11
+
12
+ export class OriginRefused extends Error {
13
+ constructor(message: string) {
14
+ super(message)
15
+ this.name = 'OriginRefused'
16
+ }
17
+ }
18
+
19
+ const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567'
20
+ const UNVERIFIED_SUFFIX = '.unverified.invalid'
21
+ const GRANT_TAG_RE = new RegExp(`^${GRANT_TAG_PREFIX}[a-z2-7]{${GRANT_TAG_RANDOM_CHARS}}$`)
22
+ const LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/
23
+
24
+ /** The SDK's originator limit, in bytes. */
25
+ export const MAX_ORIGINATOR_BYTES = 250
26
+ /** `.` + 11-char tag + `.unverified.invalid` leaves this much for the hostname. */
27
+ export const MAX_UNVERIFIED_HOSTNAME_BYTES =
28
+ MAX_ORIGINATOR_BYTES - (1 + (1 + GRANT_TAG_RANDOM_CHARS) + UNVERIFIED_SUFFIX.length)
29
+
30
+ /**
31
+ * Lowercase LDH labels of 1–63 characters, at most `maxLength` in total, no empty label (so no
32
+ * trailing dot), and a last label that is not purely numeric (which also rules out IPv4 literals).
33
+ */
34
+ export function isLdhHostname(host: unknown, maxLength: number): host is string {
35
+ if (typeof host !== 'string' || host.length === 0 || host.length > maxLength) return false
36
+ const labels = host.split('.')
37
+ for (const l of labels) if (l.length > 63 || !LABEL_RE.test(l)) return false
38
+ return !/^[0-9]+$/.test(labels[labels.length - 1])
39
+ }
40
+
41
+ export function isGrantTag(tag: unknown): tag is string {
42
+ return typeof tag === 'string' && GRANT_TAG_RE.test(tag)
43
+ }
44
+
45
+ /** `g` followed by 10 lowercase base32 characters, from a CSPRNG. */
46
+ export function mintGrantTag(): string {
47
+ const bytes = new Uint8Array(GRANT_TAG_RANDOM_CHARS)
48
+ globalThis.crypto.getRandomValues(bytes)
49
+ let out = GRANT_TAG_PREFIX
50
+ // 256 is a multiple of 32, so masking the low five bits is unbiased.
51
+ for (const b of bytes) out += BASE32[b & 31]
52
+ return out
53
+ }
54
+
55
+ export function unverifiedOriginator(hostname: string, grantTag: string): string {
56
+ if (!isGrantTag(grantTag)) throw new OriginRefused('invalid grant tag')
57
+ if (!isLdhHostname(hostname, MAX_UNVERIFIED_HOSTNAME_BYTES) || hostname.split('.').pop() === 'invalid') {
58
+ throw new OriginRefused('hostname cannot be placed in the unverified namespace')
59
+ }
60
+ return `${hostname}.${grantTag}${UNVERIFIED_SUFFIX}`
61
+ }
62
+
63
+ /** Exactly `<hostname>.g<10 base32>.unverified.invalid`, nothing looser. */
64
+ export function isUnattestedOriginator(o: unknown): boolean {
65
+ if (typeof o !== 'string' || !o.endsWith(UNVERIFIED_SUFFIX)) return false
66
+ const rest = o.slice(0, -UNVERIFIED_SUFFIX.length)
67
+ const dot = rest.lastIndexOf('.')
68
+ if (dot < 1) return false
69
+ const host = rest.slice(0, dot)
70
+ if (!isGrantTag(rest.slice(dot + 1))) return false
71
+ if (!isLdhHostname(host, MAX_UNVERIFIED_HOSTNAME_BYTES)) return false
72
+ return host.split('.').pop() !== 'invalid'
73
+ }
74
+
75
+ export function hostnameOfUnattested(o: string): string {
76
+ if (!isUnattestedOriginator(o)) throw new OriginRefused('not an unverified originator')
77
+ const rest = o.slice(0, -UNVERIFIED_SUFFIX.length)
78
+ return rest.slice(0, rest.lastIndexOf('.'))
79
+ }
package/core/config.tsx CHANGED
@@ -43,19 +43,4 @@ export const DEFAULT_MESSAGEBOX_URL = NETWORKS.main.messageBoxUrl
43
43
  * every request fail authentication.
44
44
  */
45
45
  export const DEFAULT_CHAIN: AppChain = 'main'
46
- /**
47
- * Internal authority label passed only by the wallet shell.
48
- *
49
- * The permissions manager grants this originator administrative access, so it
50
- * must be a name no external caller can present. It used to sit outside the
51
- * hostname namespace altogether (`urn:bsv-wallet:internal-admin`), but
52
- * @bsv/sdk 2.8 accepts only canonical hostnames as originators. It now lives
53
- * in the RFC 6761 `.invalid` TLD, which never resolves, so no host can be
54
- * served from it, and `parseExternalOrigin` refuses that whole TLD at the
55
- * external trust boundary. An ordinary DNS name would let whoever controls
56
- * that host acquire the same authority through a paired connection.
57
- */
58
- export const ADMIN_ORIGINATOR = 'internal-admin.bsv-wallet.invalid'
59
-
60
- /** The label before @bsv/sdk 2.8, still found in data persisted by older builds. */
61
- export const LEGACY_ADMIN_ORIGINATOR = 'urn:bsv-wallet:internal-admin'
46
+ export { ADMIN_ORIGINATOR, LEGACY_ADMIN_ORIGINATOR } from './bridge/protocol/constants'
@@ -13,13 +13,19 @@
13
13
  * window, not full history: an old inbound payment outside it will not
14
14
  * surface here. Documented limitation (see the 2026-09-18 spec) rather
15
15
  * than a silent one.
16
- * 3. Token transfers — EXACT, via `token_settlements.counterpartyKey`
17
- * (`idx_token_settlements_counterpartyKey`).
16
+ * 3. Token transfers — EXACT, via the `color_transfers` journal's
17
+ * `counterpartyKey` (plan 07 W1). Units are exact `bigint`s read from the
18
+ * journal's canonical decimal TEXT, never a number. A received row's key
19
+ * is the sender's key as the hand-over named it (blinded A′ by default,
20
+ * spec D2), so an inbound blinded payment matches no contact; that is the
21
+ * blinding working, not a gap.
18
22
  *
19
23
  * The address rail is never attributable to a contact (no key in its label)
20
24
  * and is excluded here the same way it is everywhere else in the app.
21
25
  */
26
+ import { parseDecimalAmount } from '@bsv/mandala'
22
27
  import { counterpartyOf } from '../pay/counterparty'
28
+ import type { ColorTransferRole, ColorTransferState } from '../mandala/types'
23
29
 
24
30
  /** The recent-window size for source (2) above. */
25
31
  export const RECENT_WINDOW = 200
@@ -44,14 +50,15 @@ export interface ContactActivityWallet {
44
50
  ): Promise<{ actions: ContactBsvAction[] }>
45
51
  }
46
52
 
47
- /** The slice of `token_settlements` this module reads. */
48
- export interface ContactSettlementRow {
53
+ /** The slice of a `color_transfers` row this module reads. */
54
+ export interface ContactTransferRow {
49
55
  txid: string
50
- role: 'sent' | 'received'
56
+ role: ColorTransferRole
51
57
  assetId: string
52
- state: string
58
+ state: ColorTransferState
53
59
  counterpartyKey?: string
54
- amountBaseUnits?: number
60
+ /** Exact token units; absent when the stored text does not read back exactly (no figure beats a wrong one). */
61
+ units?: bigint
55
62
  createdAt: string
56
63
  }
57
64
 
@@ -59,7 +66,7 @@ export interface ContactSettlementsDb {
59
66
  getAllAsync(sql: string, params: (string | number | null)[]): Promise<unknown[]>
60
67
  }
61
68
 
62
- export type ContactActivityItem = ({ kind: 'bsv' } & ContactBsvAction) | ({ kind: 'token' } & ContactSettlementRow)
69
+ export type ContactActivityItem = ({ kind: 'bsv' } & ContactBsvAction) | ({ kind: 'token' } & ContactTransferRow)
63
70
 
64
71
  function timeOf(item: ContactActivityItem): number {
65
72
  const raw = item.kind === 'bsv' ? item.created_at : item.createdAt
@@ -68,40 +75,53 @@ function timeOf(item: ContactActivityItem): number {
68
75
  return Number.isNaN(ts) ? 0 : ts
69
76
  }
70
77
 
71
- /** Token transfers with this counterparty. Exported separately so it can be
72
- * unit-tested against a real in-memory SQLite (see `mandala/settlementStore.ts`'s
73
- * own test pattern) without a wallet in the loop. */
74
- export async function listTokenSettlementsByCounterparty(
78
+ /** How many journal rows one contact page reads; the newest are the ones a person looks for. */
79
+ export const TRANSFER_WINDOW = 500
80
+
81
+ /**
82
+ * Token transfers with this counterparty, newest first, from the
83
+ * `color_transfers` journal. A cancelled send is left out: that money never
84
+ * moved (the same rule the runtime's activity list keeps). Exported separately
85
+ * so it can be unit-tested against a real in-memory SQLite without a wallet in
86
+ * the loop.
87
+ */
88
+ export async function listTokenTransfersByCounterparty(
75
89
  db: ContactSettlementsDb,
76
90
  counterpartyKey: string
77
- ): Promise<ContactSettlementRow[]> {
91
+ ): Promise<ContactTransferRow[]> {
78
92
  const rows = (await db.getAllAsync(
79
- 'SELECT txid, role, assetId, state, counterpartyKey, amountBaseUnits, createdAt FROM token_settlements WHERE counterpartyKey = ? ORDER BY createdAt DESC',
80
- [counterpartyKey]
93
+ `SELECT txid, role, assetId, units, state, counterpartyKey, createdAt FROM color_transfers
94
+ WHERE counterpartyKey = ? AND state <> 'cancelled' ORDER BY createdAt DESC, rowid DESC LIMIT ?`,
95
+ [counterpartyKey, TRANSFER_WINDOW]
81
96
  )) as {
82
97
  txid: string
83
98
  role: string
84
99
  assetId: string
100
+ units: unknown
85
101
  state: string
86
102
  counterpartyKey: string | null
87
- amountBaseUnits: number | null
88
103
  createdAt: string
89
104
  }[]
90
- return rows.map(r => ({
91
- txid: r.txid,
92
- role: r.role as 'sent' | 'received',
93
- assetId: r.assetId,
94
- state: r.state,
95
- counterpartyKey: r.counterpartyKey ?? undefined,
96
- amountBaseUnits: r.amountBaseUnits ?? undefined,
97
- createdAt: r.createdAt
98
- }))
105
+ return rows.map(r => {
106
+ const row: ContactTransferRow = {
107
+ txid: r.txid,
108
+ role: r.role as ColorTransferRole,
109
+ assetId: r.assetId,
110
+ state: r.state as ColorTransferState,
111
+ createdAt: r.createdAt
112
+ }
113
+ if (r.counterpartyKey) row.counterpartyKey = r.counterpartyKey
114
+ const units = parseDecimalAmount(r.units)
115
+ if (units !== null) row.units = units
116
+ return row
117
+ })
99
118
  }
100
119
 
101
120
  /**
102
121
  * Every activity item with `identityKey`, merged and sorted newest first.
103
122
  *
104
- * `wallet` and `settlementsDb` are both optional so a caller that only has
123
+ * `wallet` and `settlementsDb` (the wallet database holding `color_transfers`)
124
+ * are both optional so a caller that only has
105
125
  * one half built (e.g. a token-less wallet) still gets what it can — same
106
126
  * fail-open posture as `resolveIdentity.ts`.
107
127
  */
@@ -142,8 +162,8 @@ export async function getContactActivity(args: {
142
162
 
143
163
  if (settlementsDb) {
144
164
  try {
145
- const settlements = await listTokenSettlementsByCounterparty(settlementsDb, identityKey)
146
- for (const row of settlements) items.push({ kind: 'token', ...row })
165
+ const transfers = await listTokenTransfersByCounterparty(settlementsDb, identityKey)
166
+ for (const row of transfers) items.push({ kind: 'token', ...row })
147
167
  } catch {
148
168
  // Same posture as above.
149
169
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `ContactsStore` over the toolbox's own SQLite connection.
3
3
  *
4
- * Deliberately logic-free, same spirit as `mandala/settlementStore.ts`: every
4
+ * Deliberately logic-free, same spirit as `mandala/transferJournal.ts`: every
5
5
  * decision (what counts as a match, how activity is aggregated) lives in the
6
6
  * callers of this module. What is here is statements.
7
7
  *
@@ -10,7 +10,7 @@
10
10
  * `renameContact`, which exists for exactly that. A background identity
11
11
  * refresh calls `refreshContactCache` instead, which never touches `name`.
12
12
  *
13
- * Access pattern matches `settlementStore.ts`: the caller hands in
13
+ * Access pattern matches `transferJournal.ts`: the caller hands in
14
14
  * `storage.sqliteDb` and this module only ever issues parameterised statements
15
15
  * against it.
16
16
  */
@@ -4,6 +4,7 @@ import * as SecureStore from 'expo-secure-store'
4
4
  import { WalletClient, PrivateKey, ProtoWallet, Utils } from '@bsv/sdk'
5
5
  import type { WalletProtocol } from '@bsv/sdk'
6
6
  import connectionStore from '../stores/ConnectionStore'
7
+ import { registerSessionTeardown } from './sessionTeardown'
7
8
  import type { Connection } from '../stores/ConnectionStore'
8
9
  import {
9
10
  buildPairingSignatureMessage,
@@ -214,7 +215,9 @@ export function useWalletConnection() {
214
215
  let activeDisconnect: (() => void) | null = null
215
216
 
216
217
  /** Tear down any live paired RPC socket. No-op if no WalletConnectionProvider
217
- * is mounted or no session is currently connected. */
218
+ * is mounted or no session is currently connected. Shim kept for existing
219
+ * callers and tests; WalletContext now goes through runSessionTeardown, where
220
+ * the provider registers this same disconnect for logout and profile. */
218
221
  export function disconnectActivePairedSession(): void {
219
222
  activeDisconnect?.()
220
223
  }
@@ -315,7 +318,10 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
315
318
  // unmount stops a stale/unmounted provider's disconnect from being called.
316
319
  useEffect(() => {
317
320
  activeDisconnect = disconnect
321
+ // A network switch keeps the identity, so pairings survive it.
322
+ const unregister = registerSessionTeardown(['logout', 'profile'], () => disconnect())
318
323
  return () => {
324
+ unregister()
319
325
  if (activeDisconnect === disconnect) activeDisconnect = null
320
326
  }
321
327
  }, [disconnect])