@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,115 @@
1
+ /**
2
+ * Port types of the loopback router (spec 6.5, 6.7). Defined once here: the router consumes them and the Android
3
+ * kit's controller implements them. Type-only imports keep this file (and the loopback barrel) free of the
4
+ * runtime, so the pure modules still bundle into the page-side stand-in client.
5
+ */
6
+ import type { BindingRegistry } from '../bindings'
7
+ import type { dispatch } from '../dispatcher'
8
+ import type { ContinuityHandle } from '../protocol/continuity'
9
+ import type { BridgeSnapshot } from '../runtime'
10
+ import type { LoopbackBound } from './hostCheck'
11
+
12
+ /** One request as Kotlin hands it over. Header names are lowercased; `body` is the UTF-8 text of the body. */
13
+ export interface RawRequest {
14
+ id: string
15
+ method: string
16
+ target: string
17
+ headers: [string, string][]
18
+ body: string
19
+ }
20
+
21
+ export interface RouteResponse {
22
+ status: number
23
+ headers: [string, string][]
24
+ body: string
25
+ }
26
+
27
+ /** Answer now, or hold the socket open until `settled` resolves (RPC and parked connects). */
28
+ export type RoutePlan =
29
+ | ({ kind: 'respond' } & RouteResponse)
30
+ | { kind: 'hold'; id: string; settled: Promise<RouteResponse> }
31
+
32
+ /** A live launch record as the router sees it: plain data, no Buffer. `n` is base64url. */
33
+ export interface LaunchRecordView {
34
+ epoch: string
35
+ k: Uint8Array
36
+ n: string
37
+ }
38
+
39
+ export interface HelloQuery {
40
+ hello: string
41
+ origin: string
42
+ challenge: string
43
+ host: string
44
+ }
45
+
46
+ export interface LaunchesPort {
47
+ /** The live unused record whose hello MAC matches, if any. Consumes nothing. */
48
+ matchHello(p: HelloQuery): LaunchRecordView | undefined
49
+ /** Marks the record used before returning it; undefined if used, expired or unknown. */
50
+ take(epoch: string): LaunchRecordView | undefined
51
+ }
52
+
53
+ export interface UnsettledGatePort {
54
+ /** True when the origin has no unsettled binding, so a connect may proceed. */
55
+ check(origin: string): boolean
56
+ claim(origin: string, epoch: string): void
57
+ release(epoch: string): void
58
+ }
59
+
60
+ export interface TokenOutboxPort {
61
+ take(epoch: string): string | undefined
62
+ confirmWritten(epoch: string): void
63
+ drop(epoch: string): void
64
+ }
65
+
66
+ /** `unavailable` and `dropped` answer 503 CONFIGURATION_ERROR not-sent; `full` answers 429. */
67
+ export type ParkResult = 'resume' | 'unavailable' | 'dropped' | 'full'
68
+
69
+ export interface SessionPort {
70
+ readiness(): 'park' | 'none-fail' | 'go'
71
+ parkConnect(id: string, origin: string, epoch: string): Promise<ParkResult>
72
+ onConnect(epoch: string): void
73
+ onBindingClosed(epoch: string): void
74
+ }
75
+
76
+ /** The router consumes `secret`, `touch`, `inFlight` and `isGone`; the session and controller consume the rest. */
77
+ export interface BindingLedgerPort {
78
+ /** Opens the epoch with `settled` false. */
79
+ open(epoch: string, origin: string, secret: Uint8Array): void
80
+ secret(epoch: string): Uint8Array | undefined
81
+ origin(epoch: string): string | undefined
82
+ touch(epoch: string): void
83
+ inFlight(epoch: string, delta: 1 | -1): void
84
+ parked(epoch: string, delta: 1 | -1): void
85
+ markSettled(epoch: string): void
86
+ isSettled(epoch: string): boolean
87
+ markGone(connId: string): void
88
+ isGone(connId: string): boolean
89
+ clearGone(connId: string): void
90
+ /** Undefined while parked or in flight. */
91
+ idleSince(epoch: string): number | undefined
92
+ epochsForOrigin(origin: string): string[]
93
+ close(epoch: string): void
94
+ }
95
+
96
+ export interface RouterEnv {
97
+ transportId: string
98
+ bound(): LoopbackBound
99
+ identity(origin: string): Promise<ContinuityHandle>
100
+ descriptorBase: { name: string; vendor: string; icon?: string; instanceLabel: string }
101
+ launches: LaunchesPort
102
+ unsettledGate: UnsettledGatePort
103
+ tokenOutbox: TokenOutboxPort
104
+ session: SessionPort
105
+ ledger: BindingLedgerPort
106
+ registry: BindingRegistry
107
+ connectExplicit: BindingRegistry['connectExplicit']
108
+ snapshot(): BridgeSnapshot
109
+ dispatch: typeof dispatch
110
+ allowLocalhostHttp(): boolean
111
+ }
112
+
113
+ export interface LoopbackRouter {
114
+ handle(req: RawRequest): Promise<RoutePlan>
115
+ }
@@ -0,0 +1,52 @@
1
+ /** The HTTP status table (spec 6.6.2). Pages discriminate by body; statuses are for logs and generic clients. */
2
+ import type { ConnectionError } from '../protocol/connectionError'
3
+
4
+ export const STATUS = Object.freeze({
5
+ ok: 200,
6
+ noContent: 204,
7
+ walletError: 400,
8
+ protocolError: 400,
9
+ notFound: 404,
10
+ forbidden: 403,
11
+ userCancelled: 403,
12
+ launchProof: 403,
13
+ methodNotAllowed: 405,
14
+ providerChanged: 412,
15
+ connectionClosed: 410,
16
+ lengthRequired: 411,
17
+ bodyTooLarge: 413,
18
+ unsupportedMediaType: 415,
19
+ resourceLimit: 429,
20
+ notBuilt: 503,
21
+ tooManyConnections: 503,
22
+ oversizeResponse: 502,
23
+ internal: 500
24
+ } as const)
25
+
26
+ export type StatusKey = keyof typeof STATUS
27
+
28
+ /**
29
+ * The status for a connection error. The code decides unless the caller names a `situation` that the code alone
30
+ * cannot express (launch proof refusal, oversize response, internal error, oversize request).
31
+ */
32
+ export function statusForConnectionError(e: ConnectionError, situation?: StatusKey): number {
33
+ if (situation !== undefined) return STATUS[situation]
34
+ switch (e.code) {
35
+ case 'PROTOCOL_ERROR':
36
+ return STATUS.protocolError
37
+ case 'PROVIDER_CHANGED':
38
+ return STATUS.providerChanged
39
+ case 'CONNECTION_CLOSED':
40
+ return STATUS.connectionClosed
41
+ case 'RESOURCE_LIMIT':
42
+ return STATUS.resourceLimit
43
+ case 'USER_CANCELLED':
44
+ return STATUS.userCancelled
45
+ case 'CONFIGURATION_ERROR':
46
+ return STATUS.notBuilt
47
+ default:
48
+ // Page-side codes (SELECTION_REQUIRED, DISCOVERY_BLOCKED, PAIRING_*, DISCONNECTED) are never emitted by the
49
+ // server; if one reaches here it is an internal error.
50
+ return STATUS.internal
51
+ }
52
+ }
@@ -0,0 +1,222 @@
1
+ /**
2
+ * In-memory `InboxStore` (spec 6.8): the reference adapter and the one the tests run. Project 2's
3
+ * App Group adapter must pass the same contract suite (`__tests__/bridge/inboxContract.ts`).
4
+ *
5
+ * Everything held is sealed with AES-GCM (the SDK's `SymmetricKey`, pure JS so it works on every
6
+ * runtime) under a key that lives only in the shared state, so the contract harness's `rawBytes` is a
7
+ * meaningful view of "what is at rest". Sizes and states are metadata, not payload.
8
+ */
9
+ import { SymmetricKey, Utils } from '@bsv/sdk'
10
+ import {
11
+ inboxDigest,
12
+ type ClaimOutcome,
13
+ type InboxState,
14
+ type InboxStat,
15
+ type InboxStore,
16
+ type ResultRead
17
+ } from './inbox'
18
+ import type { InboxCloseEvent } from './protocol/envelopes'
19
+ import { INBOX_CLOCK_SKEW_MS, INBOX_MAX_VALIDITY_MS, INBOX_RESULT_TTL_MS } from './protocol/limits'
20
+
21
+ /** An id tombstone outlives the longest `notAfter` window, the skew allowance and a result's life. */
22
+ const TOMBSTONE_MS = INBOX_MAX_VALIDITY_MS + INBOX_CLOCK_SKEW_MS + INBOX_RESULT_TTL_MS + 5 * 60 * 1000
23
+
24
+ interface Entry {
25
+ state: InboxState
26
+ size: number
27
+ createdAt: number
28
+ sealedRecord?: Uint8Array
29
+ sealedResult?: Uint8Array
30
+ resultAt?: number
31
+ /** True once the result is acknowledged or purged. */
32
+ gone?: boolean
33
+ claimBootId?: string
34
+ }
35
+
36
+ interface Shared {
37
+ key: SymmetricKey
38
+ entries: Map<string, Entry>
39
+ events: Array<{ closeSeq: number; at: number; sealed: Uint8Array }>
40
+ /** Highest `closeSeq` retention has trimmed. */
41
+ evictedThrough: number
42
+ }
43
+
44
+ export interface MemoryInboxStore extends InboxStore {
45
+ /** The same persisted state under a new boot id: what a process restart looks like. */
46
+ restart(bootId?: string): MemoryInboxStore
47
+ /** Everything held at rest, for the contract suite's plaintext-marker test (via the harness). */
48
+ rawBytes(): Uint8Array[]
49
+ }
50
+
51
+ export interface MemoryInboxStoreOptions {
52
+ now?: () => number
53
+ bootId?: string
54
+ /** Event retention: at most this many events (default 1024, spec 6.4). */
55
+ maxEvents?: number
56
+ /** Event retention: events older than this are trimmed (default 24 h). */
57
+ maxEventAgeMs?: number
58
+ }
59
+
60
+ const DEFAULT_MAX_EVENTS = 1024
61
+ const DEFAULT_MAX_EVENT_AGE_MS = 24 * 60 * 60 * 1000
62
+
63
+ let bootCounter = 0
64
+
65
+ export function createMemoryInboxStore(opts: MemoryInboxStoreOptions = {}): MemoryInboxStore {
66
+ const shared: Shared = { key: SymmetricKey.fromRandom(), entries: new Map(), events: [], evictedThrough: 0 }
67
+ return open(
68
+ shared,
69
+ opts.now ?? Date.now,
70
+ opts.bootId ?? `boot-${++bootCounter}`,
71
+ opts.maxEvents ?? DEFAULT_MAX_EVENTS,
72
+ opts.maxEventAgeMs ?? DEFAULT_MAX_EVENT_AGE_MS
73
+ )
74
+ }
75
+
76
+ function open(
77
+ shared: Shared,
78
+ now: () => number,
79
+ boot: string,
80
+ maxEvents: number,
81
+ maxEventAgeMs: number
82
+ ): MemoryInboxStore {
83
+ const seal = (bytes: Uint8Array): Uint8Array => Uint8Array.from(shared.key.encrypt(Array.from(bytes)) as number[])
84
+ const unseal = (bytes: Uint8Array): Uint8Array => Uint8Array.from(shared.key.decrypt(Array.from(bytes)) as number[])
85
+
86
+ /** Time-based purge: results after 15 minutes, whole tombstones after their window. */
87
+ function sweep() {
88
+ const t = now()
89
+ for (const [id, e] of shared.entries) {
90
+ if (e.sealedResult && e.resultAt !== undefined && t - e.resultAt > INBOX_RESULT_TTL_MS) {
91
+ e.sealedResult = undefined
92
+ e.gone = true
93
+ }
94
+ if (t - e.createdAt > TOMBSTONE_MS && e.state === 'done') shared.entries.delete(id)
95
+ }
96
+ }
97
+
98
+ /** Event retention (count and age); remembers the highest trimmed `closeSeq`. */
99
+ function trimEvents() {
100
+ const t = now()
101
+ const keep = shared.events.filter(e => t - e.at <= maxEventAgeMs)
102
+ const kept = keep.length > maxEvents ? keep.slice(keep.length - maxEvents) : keep
103
+ if (kept.length === shared.events.length) return
104
+ const keptSet = new Set(kept)
105
+ for (const e of shared.events)
106
+ if (!keptSet.has(e)) shared.evictedThrough = Math.max(shared.evictedThrough, e.closeSeq)
107
+ shared.events = kept
108
+ }
109
+
110
+ const store: MemoryInboxStore = {
111
+ async create(id, bytes) {
112
+ sweep()
113
+ if (shared.entries.has(id)) return false
114
+ shared.entries.set(id, {
115
+ state: 'pending',
116
+ size: bytes.byteLength,
117
+ createdAt: now(),
118
+ sealedRecord: seal(bytes)
119
+ })
120
+ return true
121
+ },
122
+
123
+ async stat(id): Promise<InboxStat | undefined> {
124
+ const e = shared.entries.get(id)
125
+ if (!e) return undefined
126
+ return { size: e.size, state: e.state, ...(e.claimBootId !== undefined ? { claimBootId: e.claimBootId } : {}) }
127
+ },
128
+
129
+ async read(id) {
130
+ const e = shared.entries.get(id)
131
+ return e?.sealedRecord ? unseal(e.sealedRecord) : undefined
132
+ },
133
+
134
+ async accept(id) {
135
+ const e = shared.entries.get(id)
136
+ if (!e || e.state !== 'pending') return false
137
+ e.state = 'accepted'
138
+ return true
139
+ },
140
+
141
+ async release(id) {
142
+ const e = shared.entries.get(id)
143
+ if (!e || e.state !== 'accepted') return false
144
+ e.state = 'pending'
145
+ return true
146
+ },
147
+
148
+ async claim(id, digest): Promise<ClaimOutcome> {
149
+ const e = shared.entries.get(id)
150
+ if (!e || e.state !== 'accepted' || !e.sealedRecord) return 'not-accepted'
151
+ if (inboxDigest(unseal(e.sealedRecord)) !== digest) return 'digest-mismatch'
152
+ e.state = 'claimed'
153
+ e.claimBootId = boot
154
+ // Arguments are deleted at claim; the record is never read again.
155
+ e.sealedRecord = undefined
156
+ return 'claimed'
157
+ },
158
+
159
+ async writeResult(id, bytes) {
160
+ const e = shared.entries.get(id)
161
+ if (!e || e.state === 'done') return false
162
+ e.state = 'done'
163
+ e.sealedRecord = undefined
164
+ e.sealedResult = seal(bytes)
165
+ e.resultAt = now()
166
+ return true
167
+ },
168
+
169
+ async readResult(id): Promise<ResultRead> {
170
+ sweep()
171
+ const e = shared.entries.get(id)
172
+ if (!e || e.state !== 'done') return { kind: 'none' }
173
+ if (!e.sealedResult) return { kind: 'purged' }
174
+ return { kind: 'result', bytes: unseal(e.sealedResult) }
175
+ },
176
+
177
+ async ack(id) {
178
+ const e = shared.entries.get(id)
179
+ if (!e || e.state !== 'done') return
180
+ e.sealedRecord = undefined
181
+ e.sealedResult = undefined
182
+ e.gone = true
183
+ },
184
+
185
+ async writeEvent(ev: InboxCloseEvent) {
186
+ shared.events.push({
187
+ closeSeq: ev.closeSeq,
188
+ at: now(),
189
+ sealed: seal(Uint8Array.from(Utils.toArray(JSON.stringify(ev), 'utf8')))
190
+ })
191
+ shared.events.sort((a, b) => a.closeSeq - b.closeSeq)
192
+ trimEvents()
193
+ },
194
+
195
+ async readEventsAfter(seq) {
196
+ trimEvents()
197
+ const events = shared.events
198
+ .filter(e => e.closeSeq > seq)
199
+ .map(e => JSON.parse(Utils.toUTF8(Array.from(unseal(e.sealed)))) as InboxCloseEvent)
200
+ return { events, gap: seq < shared.evictedThrough }
201
+ },
202
+
203
+ bootId: () => boot,
204
+
205
+ async list(state) {
206
+ sweep()
207
+ return [...shared.entries].filter(([, e]) => e.state === state).map(([id]) => id)
208
+ },
209
+
210
+ rawBytes() {
211
+ const out: Uint8Array[] = shared.events.map(e => e.sealed)
212
+ for (const e of shared.entries.values()) {
213
+ if (e.sealedRecord) out.push(e.sealedRecord)
214
+ if (e.sealedResult) out.push(e.sealedResult)
215
+ }
216
+ return out
217
+ },
218
+
219
+ restart: bootId => open(shared, now, bootId ?? `boot-${++bootCounter}`, maxEvents, maxEventAgeMs)
220
+ }
221
+ return store
222
+ }
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Which permission prompts each kind of browser origin gets (spec 6.5).
3
+ *
4
+ * The permissions managers take their `seek*` settings from here instead of a literal in
5
+ * WalletContext. `verified` is exactly what the attested manager has always used; `unverified`
6
+ * can only be stricter, because an unverified origin is one a local app could be claiming.
7
+ *
8
+ * Pure policy: nothing here imports React or the permissions manager. The stored user policy
9
+ * is HMAC-tagged by the admin-scoped wallet (like `connectionAuthority.ts`), so a raw
10
+ * AsyncStorage edit cannot loosen prompts.
11
+ */
12
+ import AsyncStorage from '@react-native-async-storage/async-storage'
13
+ import type { WalletInterface, WalletProtocol } from '@bsv/sdk'
14
+ import { ADMIN_ORIGINATOR } from './protocol/constants'
15
+ import { getBrowserBridgeConfig } from '../toolboxConfig'
16
+
17
+ export interface SeekFlags {
18
+ seekBasketInsertionPermissions: boolean
19
+ seekBasketListingPermissions: boolean
20
+ seekBasketRemovalPermissions: boolean
21
+ seekCertificateAcquisitionPermissions: boolean
22
+ seekCertificateDisclosurePermissions: boolean
23
+ seekCertificateRelinquishmentPermissions: boolean
24
+ seekCertificateListingPermissions: boolean
25
+ seekGroupedPermission: boolean
26
+ seekPermissionsForIdentityKeyRevelation: boolean
27
+ seekPermissionsForIdentityResolution: boolean
28
+ seekPermissionsForKeyLinkageRevelation: boolean
29
+ seekPermissionsForPublicKeyRevelation: boolean
30
+ seekPermissionWhenApplyingActionLabels: boolean
31
+ seekPermissionWhenListingActionsByLabel: boolean
32
+ seekProtocolPermissionsForEncrypting: boolean
33
+ seekProtocolPermissionsForHMAC: boolean
34
+ seekProtocolPermissionsForSigning: boolean
35
+ seekSpendingPermissions: boolean
36
+ }
37
+
38
+ export interface PermissionPolicy {
39
+ verified: SeekFlags
40
+ unverified: SeekFlags
41
+ }
42
+
43
+ /** What a host may state in `configureToolbox`: any subset of either half. */
44
+ export interface PermissionPolicyOverride {
45
+ verified?: Partial<SeekFlags>
46
+ unverified?: Partial<SeekFlags>
47
+ }
48
+
49
+ export const SEEK_FLAG_KEYS: ReadonlyArray<keyof SeekFlags> = [
50
+ 'seekBasketInsertionPermissions',
51
+ 'seekBasketListingPermissions',
52
+ 'seekBasketRemovalPermissions',
53
+ 'seekCertificateAcquisitionPermissions',
54
+ 'seekCertificateDisclosurePermissions',
55
+ 'seekCertificateRelinquishmentPermissions',
56
+ 'seekCertificateListingPermissions',
57
+ 'seekGroupedPermission',
58
+ 'seekPermissionsForIdentityKeyRevelation',
59
+ 'seekPermissionsForIdentityResolution',
60
+ 'seekPermissionsForKeyLinkageRevelation',
61
+ 'seekPermissionsForPublicKeyRevelation',
62
+ 'seekPermissionWhenApplyingActionLabels',
63
+ 'seekPermissionWhenListingActionsByLabel',
64
+ 'seekProtocolPermissionsForEncrypting',
65
+ 'seekProtocolPermissionsForHMAC',
66
+ 'seekProtocolPermissionsForSigning',
67
+ 'seekSpendingPermissions'
68
+ ]
69
+
70
+ /**
71
+ * The attested manager's configuration, moved verbatim from WalletContext.
72
+ * Changing any value here changes what every attested site is asked.
73
+ */
74
+ export const DEFAULT_VERIFIED_SEEK_FLAGS: SeekFlags = {
75
+ seekBasketInsertionPermissions: false,
76
+ seekBasketListingPermissions: false,
77
+ seekBasketRemovalPermissions: false,
78
+ seekCertificateAcquisitionPermissions: false,
79
+ seekCertificateDisclosurePermissions: false,
80
+ seekCertificateRelinquishmentPermissions: false,
81
+ seekCertificateListingPermissions: false,
82
+ // A site whose manifest declares metanet.groupPermissions is asked for them all in one sheet
83
+ // during waitForAuthentication. The request holds that origin's permission lock until
84
+ // answered, so it MUST be handled (onGroupedPermissionRequested) or the site hangs.
85
+ seekGroupedPermission: true,
86
+ seekPermissionsForIdentityKeyRevelation: false,
87
+ seekPermissionsForIdentityResolution: false,
88
+ seekPermissionsForKeyLinkageRevelation: false,
89
+ seekPermissionsForPublicKeyRevelation: false,
90
+ seekPermissionWhenApplyingActionLabels: false,
91
+ seekPermissionWhenListingActionsByLabel: false,
92
+ seekProtocolPermissionsForEncrypting: false,
93
+ seekProtocolPermissionsForHMAC: false,
94
+ // On, unlike Metanet Desktop: the vault guard no longer refuses external BRC-29
95
+ // ([2,'3241645161d8']) signing outright, and that namespace also derives this wallet's own
96
+ // address-rail keys (counterparty 'anyone'), so a site signing under it must be asked first
97
+ // -- for BRC-29, on every signature. BRC-103/104 auth signing is exempt
98
+ // (SigningPolicyPermissionsManager).
99
+ seekProtocolPermissionsForSigning: true,
100
+ seekSpendingPermissions: true
101
+ }
102
+
103
+ /** Unverified origins are also asked before they touch baskets. */
104
+ export const DEFAULT_UNVERIFIED_SEEK_FLAGS: SeekFlags = {
105
+ ...DEFAULT_VERIFIED_SEEK_FLAGS,
106
+ seekBasketInsertionPermissions: true,
107
+ seekBasketListingPermissions: true,
108
+ seekBasketRemovalPermissions: true
109
+ }
110
+
111
+ /** The flags an unverified origin can never be spared, whatever the policy says. */
112
+ const FORCED_UNVERIFIED: ReadonlyArray<keyof SeekFlags> = [
113
+ 'seekSpendingPermissions',
114
+ 'seekProtocolPermissionsForSigning',
115
+ 'seekGroupedPermission'
116
+ ]
117
+
118
+ /**
119
+ * The flags the unverified manager is actually built from: verified OR unverified for each
120
+ * flag, so it can only be stricter than the attested one, with the forced three always on.
121
+ */
122
+ export function effectiveUnverified(p: PermissionPolicy): SeekFlags {
123
+ const out = {} as SeekFlags
124
+ for (const key of SEEK_FLAG_KEYS) out[key] = p.verified[key] === true || p.unverified[key] === true
125
+ for (const key of FORCED_UNVERIFIED) out[key] = true
126
+ return out
127
+ }
128
+
129
+ /**
130
+ * Connection-sheet wording for each flag (i18n keys): `off` is the line shown when the flag is
131
+ * false (the site is NOT asked), `on` when it is true (asked first). Keyed by `SeekFlags`, so
132
+ * adding a flag without wording fails to compile.
133
+ */
134
+ export const SEEK_FLAG_DISCLOSURE: Record<keyof SeekFlags, { off: string; on: string }> = Object.fromEntries(
135
+ SEEK_FLAG_KEYS.map(key => [key, { off: `bridge.policy.${key}.off`, on: `bridge.policy.${key}.on` }])
136
+ ) as Record<keyof SeekFlags, { off: string; on: string }>
137
+
138
+ function mergeFlags(base: SeekFlags, over: Partial<SeekFlags> | undefined): SeekFlags {
139
+ const out = { ...base }
140
+ if (over === undefined || over === null || typeof over !== 'object') return out
141
+ for (const key of SEEK_FLAG_KEYS) {
142
+ const v = over[key]
143
+ if (typeof v === 'boolean') out[key] = v
144
+ }
145
+ return out
146
+ }
147
+
148
+ /**
149
+ * Defaults, then the host's statement from `configureToolbox`, then the user's stored policy.
150
+ * `stored` must already have passed `loadStoredPolicy` (which authenticates it).
151
+ */
152
+ export function resolvePermissionPolicy(stored?: PermissionPolicy): PermissionPolicy {
153
+ const host = getBrowserBridgeConfig().permissionPolicy
154
+ const hosted: PermissionPolicy = {
155
+ verified: mergeFlags(DEFAULT_VERIFIED_SEEK_FLAGS, host?.verified),
156
+ unverified: mergeFlags(DEFAULT_UNVERIFIED_SEEK_FLAGS, host?.unverified)
157
+ }
158
+ if (stored === undefined) return hosted
159
+ return {
160
+ verified: mergeFlags(hosted.verified, stored.verified),
161
+ unverified: mergeFlags(hosted.unverified, stored.unverified)
162
+ }
163
+ }
164
+
165
+ // ---- Stored user policy -------------------------------------------------------------------
166
+
167
+ type PolicyTagWallet = Pick<WalletInterface, 'createHmac' | 'verifyHmac'>
168
+
169
+ /** Reserved in `core/services/vault/guard.ts`: no connected origin may mint or verify this tag. */
170
+ export const BRIDGE_SITE_AUTHORITY_PROTOCOL_ID: WalletProtocol = [2, 'bridge site authority']
171
+ const POLICY_KEY_ID = 'permission-policy'
172
+ const POLICY_DOMAIN = 'bsv-wallet-bridge-permission-policy-v1'
173
+
174
+ const storageKey = (profileKey: string) => `bsv-bridge-permission-policy:${profileKey}`
175
+
176
+ function isFlags(v: unknown): v is SeekFlags {
177
+ if (v === null || typeof v !== 'object') return false
178
+ return SEEK_FLAG_KEYS.every(k => typeof (v as Record<string, unknown>)[k] === 'boolean')
179
+ }
180
+
181
+ function policyMessage(profileKey: string, p: PermissionPolicy): number[] {
182
+ // Fixed key order, so the bytes do not depend on how the record was serialized.
183
+ const bits = (f: SeekFlags) => SEEK_FLAG_KEYS.map(k => (f[k] ? '1' : '0')).join('')
184
+ return Array.from(
185
+ new TextEncoder().encode(`${POLICY_DOMAIN}|${profileKey}|${bits(p.verified)}|${bits(p.unverified)}`)
186
+ )
187
+ }
188
+
189
+ async function computeTag(wallet: PolicyTagWallet, originator: string, profileKey: string, p: PermissionPolicy) {
190
+ const { hmac } = await wallet.createHmac(
191
+ {
192
+ protocolID: BRIDGE_SITE_AUTHORITY_PROTOCOL_ID,
193
+ keyID: POLICY_KEY_ID,
194
+ counterparty: 'self',
195
+ data: policyMessage(profileKey, p)
196
+ },
197
+ originator
198
+ )
199
+ return Buffer.from(hmac).toString('base64url')
200
+ }
201
+
202
+ /** The user's stored policy for a profile, or undefined when absent, malformed or not authentic. */
203
+ export async function loadStoredPolicy(
204
+ profileKey: string,
205
+ adminWallet: PolicyTagWallet,
206
+ adminOriginator: string = ADMIN_ORIGINATOR
207
+ ): Promise<PermissionPolicy | undefined> {
208
+ try {
209
+ const raw = await AsyncStorage.getItem(storageKey(profileKey))
210
+ if (raw === null) return undefined
211
+ const parsed = JSON.parse(raw) as { policy?: { verified?: unknown; unverified?: unknown }; tag?: unknown }
212
+ const policy = parsed?.policy
213
+ if (!policy || !isFlags(policy.verified) || !isFlags(policy.unverified) || typeof parsed.tag !== 'string') {
214
+ return undefined
215
+ }
216
+ const checked: PermissionPolicy = { verified: policy.verified, unverified: policy.unverified }
217
+ const { valid } = await adminWallet.verifyHmac(
218
+ {
219
+ protocolID: BRIDGE_SITE_AUTHORITY_PROTOCOL_ID,
220
+ keyID: POLICY_KEY_ID,
221
+ counterparty: 'self',
222
+ data: policyMessage(profileKey, checked),
223
+ hmac: Array.from(Buffer.from(parsed.tag, 'base64url'))
224
+ },
225
+ adminOriginator
226
+ )
227
+ return valid === true ? checked : undefined
228
+ } catch {
229
+ // verifyHmac rejects on a mismatch; storage and JSON failures land here too. All mean "no policy".
230
+ return undefined
231
+ }
232
+ }
233
+
234
+ /** Stores the policy with its tag. Takes effect from the next wallet build. */
235
+ export async function saveStoredPolicy(
236
+ profileKey: string,
237
+ policy: PermissionPolicy,
238
+ adminWallet: PolicyTagWallet,
239
+ adminOriginator: string = ADMIN_ORIGINATOR
240
+ ): Promise<void> {
241
+ const clean: PermissionPolicy = {
242
+ verified: mergeFlags(DEFAULT_VERIFIED_SEEK_FLAGS, policy.verified),
243
+ unverified: mergeFlags(DEFAULT_UNVERIFIED_SEEK_FLAGS, policy.unverified)
244
+ }
245
+ const tag = await computeTag(adminWallet, adminOriginator, profileKey, clean)
246
+ await AsyncStorage.setItem(storageKey(profileKey), JSON.stringify({ policy: clean, tag }))
247
+ }