@bsv/expo-wallet-toolbox 0.22.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 (64) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +9 -5
  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/context/WalletConnectionContext.tsx +7 -1
  41. package/core/context/WalletContext.tsx +258 -133
  42. package/core/context/sessionTeardown.ts +46 -0
  43. package/core/hooks/usePermissionQueue.ts +89 -34
  44. package/core/i18n/translations.tsx +911 -12
  45. package/core/index.ts +15 -0
  46. package/core/services/autoApprovePolicy.ts +7 -1
  47. package/core/services/capWalletArgs.ts +2 -1
  48. package/core/services/permissionPrompts.ts +132 -0
  49. package/core/services/signingPermissionPolicy.ts +230 -2
  50. package/core/services/vault/guard.ts +10 -0
  51. package/core/services/walletArgLimits.ts +17 -2
  52. package/core/storage/encryptedDbImage.ts +325 -0
  53. package/core/toolboxConfig.ts +18 -1
  54. package/package.json +6 -6
  55. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  56. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  57. package/ui/components/ui/PermissionSheet.tsx +534 -158
  58. package/ui/components/ui/Sheet.tsx +59 -7
  59. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  60. package/ui/exportDatabases.ts +94 -5
  61. package/ui/hooks/useExportWalletData.ts +37 -24
  62. package/ui/importDatabases.ts +123 -28
  63. package/ui/index.ts +4 -0
  64. package/ui/screens/WalletConfigScreen.tsx +13 -1
@@ -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'
@@ -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])