@bsv/expo-wallet-toolbox 0.22.0 → 0.24.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 (137) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +10 -9
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  16. package/core/bridge/bindings.ts +459 -0
  17. package/core/bridge/conformance.ts +222 -0
  18. package/core/bridge/consent.ts +494 -0
  19. package/core/bridge/consentSheetSource.ts +98 -0
  20. package/core/bridge/dispatcher.ts +621 -0
  21. package/core/bridge/inbox.ts +569 -0
  22. package/core/bridge/index.ts +48 -0
  23. package/core/bridge/loopback/cors.ts +57 -0
  24. package/core/bridge/loopback/endpoints.ts +11 -0
  25. package/core/bridge/loopback/hostCheck.ts +25 -0
  26. package/core/bridge/loopback/index.ts +7 -0
  27. package/core/bridge/loopback/launchProof.ts +166 -0
  28. package/core/bridge/loopback/router.ts +770 -0
  29. package/core/bridge/loopback/routerTypes.ts +115 -0
  30. package/core/bridge/loopback/status.ts +52 -0
  31. package/core/bridge/memoryInboxStore.ts +231 -0
  32. package/core/bridge/permissionPolicy.ts +247 -0
  33. package/core/bridge/policy.ts +72 -0
  34. package/core/bridge/protocol/base64url.ts +64 -0
  35. package/core/bridge/protocol/connectionError.ts +79 -0
  36. package/core/bridge/protocol/constants.ts +21 -0
  37. package/core/bridge/protocol/continuity.ts +21 -0
  38. package/core/bridge/protocol/descriptor.ts +395 -0
  39. package/core/bridge/protocol/envelopes.ts +188 -0
  40. package/core/bridge/protocol/errorCodec.ts +164 -0
  41. package/core/bridge/protocol/json.ts +237 -0
  42. package/core/bridge/protocol/limits.ts +43 -0
  43. package/core/bridge/protocol/methods.ts +55 -0
  44. package/core/bridge/protocol/origin.ts +130 -0
  45. package/core/bridge/runtime.ts +642 -0
  46. package/core/bridge/runtimeFlags.ts +34 -0
  47. package/core/bridge/testing/conformanceCases.ts +149 -0
  48. package/core/bridge/testing/pageClient.ts +44 -0
  49. package/core/bridge/unverifiedManager.ts +97 -0
  50. package/core/bridge/unverifiedOriginator.ts +79 -0
  51. package/core/config.tsx +1 -16
  52. package/core/constants.ts +7 -11
  53. package/core/context/WalletConnectionContext.tsx +92 -49
  54. package/core/context/WalletContext.tsx +288 -165
  55. package/core/context/sessionTeardown.ts +46 -0
  56. package/core/context/usePairingAttempt.ts +31 -0
  57. package/core/e2e/broadcaster.ts +25 -0
  58. package/core/e2e/consentFixture.ts +46 -0
  59. package/core/e2e/mode.ts +42 -0
  60. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  61. package/core/headers/headerConsensus.ts +230 -0
  62. package/core/headers/headerStore.ts +344 -122
  63. package/core/headers/prewarm.ts +4 -7
  64. package/core/headers/syncHeaders.ts +82 -12
  65. package/core/hooks/usePermissionQueue.ts +89 -34
  66. package/core/i18n/translations.tsx +958 -24
  67. package/core/identity/handleRegistry/client.ts +4 -2
  68. package/core/identity/handleRegistry/resolver.ts +7 -11
  69. package/core/index.ts +17 -0
  70. package/core/localpay/pending.ts +39 -4
  71. package/core/network/boundedFetch.ts +101 -0
  72. package/core/networks.ts +11 -13
  73. package/core/pay/rails/address.ts +5 -4
  74. package/core/pay/rails/handle.ts +3 -1
  75. package/core/pay/rails/sweep.ts +791 -0
  76. package/core/peerpay/brc29.ts +4 -0
  77. package/core/peerpay/handleResendRequests.ts +15 -2
  78. package/core/peerpay/outbox.ts +115 -2
  79. package/core/profiles/assertProfileEmpty.ts +2 -2
  80. package/core/profiles/profileStore.ts +3 -2
  81. package/core/services/arcadeBroadcastProvider.ts +260 -114
  82. package/core/services/autoApprovePolicy.ts +7 -1
  83. package/core/services/capWalletArgs.ts +2 -1
  84. package/core/services/permissionPrompts.ts +132 -0
  85. package/core/services/secrets/kek.ts +5 -0
  86. package/core/services/secrets/migration.ts +27 -2
  87. package/core/services/secrets/policy.ts +6 -0
  88. package/core/services/signingPermissionPolicy.ts +230 -2
  89. package/core/services/vault/VaultKeyService.ts +5 -2
  90. package/core/services/vault/ceremony.ts +2 -2
  91. package/core/services/vault/ceremonyHost.ts +1 -1
  92. package/core/services/vault/guard.ts +20 -0
  93. package/core/services/vault/outputAuthority.ts +76 -0
  94. package/core/services/vault/transfers.ts +52 -28
  95. package/core/services/vault/vaultStore.ts +60 -14
  96. package/core/services/walletArgLimits.ts +17 -2
  97. package/core/services/walletConnectionValidation.ts +13 -1
  98. package/core/services/walletServiceConfig.ts +8 -7
  99. package/core/storage/encryptedDbImage.ts +325 -0
  100. package/core/stores/ConnectionStore.ts +17 -0
  101. package/core/toolboxConfig.ts +78 -2
  102. package/expo-module.config.json +5 -0
  103. package/ios/BoundedBody.swift +15 -0
  104. package/ios/BsvBoundedFetch.podspec +17 -0
  105. package/ios/BsvBoundedFetchModule.swift +121 -0
  106. package/package.json +12 -8
  107. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  108. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  109. package/ui/components/pay/AddressReceive.tsx +6 -2
  110. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  111. package/ui/components/pay/PayCellRow.tsx +3 -1
  112. package/ui/components/pay/PayForm.tsx +12 -2
  113. package/ui/components/pay/RecipientField.tsx +1 -0
  114. package/ui/components/pay/RequestHub.tsx +1 -0
  115. package/ui/components/pay/UniversalSend.tsx +110 -42
  116. package/ui/components/ui/ListRow.tsx +10 -2
  117. package/ui/components/ui/PermissionSheet.tsx +534 -158
  118. package/ui/components/ui/Sheet.tsx +59 -7
  119. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  120. package/ui/components/vault/KeyChooser.tsx +1 -1
  121. package/ui/components/wallet/AmountInput.tsx +4 -1
  122. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  123. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  124. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  125. package/ui/components/wallet/ProfileButton.tsx +1 -0
  126. package/ui/exportDatabases.ts +94 -5
  127. package/ui/hooks/useExportWalletData.ts +37 -24
  128. package/ui/importDatabases.ts +154 -34
  129. package/ui/index.ts +4 -0
  130. package/ui/screens/ConnectionsScreen.tsx +12 -3
  131. package/ui/screens/PairScreen.tsx +10 -3
  132. package/ui/screens/PayScreen.tsx +1 -0
  133. package/ui/screens/TrustScreen.tsx +6 -3
  134. package/ui/screens/VaultScreen.tsx +13 -3
  135. package/ui/screens/VaultTransferScreen.tsx +6 -3
  136. package/ui/screens/WalletConfigScreen.tsx +30 -3
  137. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -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,231 @@
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
+ recordCreatedAt: number
29
+ sealedRecord?: Uint8Array
30
+ sealedResult?: Uint8Array
31
+ resultAt?: number
32
+ /** True once the result is acknowledged or purged. */
33
+ gone?: boolean
34
+ claimBootId?: string
35
+ }
36
+
37
+ interface Shared {
38
+ key: SymmetricKey
39
+ entries: Map<string, Entry>
40
+ events: Array<{ closeSeq: number; at: number; sealed: Uint8Array }>
41
+ /** Highest `closeSeq` retention has trimmed. */
42
+ evictedThrough: number
43
+ }
44
+
45
+ export interface MemoryInboxStore extends InboxStore {
46
+ /** The same persisted state under a new boot id: what a process restart looks like. */
47
+ restart(bootId?: string): MemoryInboxStore
48
+ /** Everything held at rest, for the contract suite's plaintext-marker test (via the harness). */
49
+ rawBytes(): Uint8Array[]
50
+ }
51
+
52
+ export interface MemoryInboxStoreOptions {
53
+ now?: () => number
54
+ bootId?: string
55
+ /** Event retention: at most this many events (default 1024, spec 6.4). */
56
+ maxEvents?: number
57
+ /** Event retention: events older than this are trimmed (default 24 h). */
58
+ maxEventAgeMs?: number
59
+ }
60
+
61
+ const DEFAULT_MAX_EVENTS = 1024
62
+ const DEFAULT_MAX_EVENT_AGE_MS = 24 * 60 * 60 * 1000
63
+
64
+ let bootCounter = 0
65
+
66
+ export function createMemoryInboxStore(opts: MemoryInboxStoreOptions = {}): MemoryInboxStore {
67
+ const shared: Shared = { key: SymmetricKey.fromRandom(), entries: new Map(), events: [], evictedThrough: 0 }
68
+ return open(
69
+ shared,
70
+ opts.now ?? Date.now,
71
+ opts.bootId ?? `boot-${++bootCounter}`,
72
+ opts.maxEvents ?? DEFAULT_MAX_EVENTS,
73
+ opts.maxEventAgeMs ?? DEFAULT_MAX_EVENT_AGE_MS
74
+ )
75
+ }
76
+
77
+ function open(
78
+ shared: Shared,
79
+ now: () => number,
80
+ boot: string,
81
+ maxEvents: number,
82
+ maxEventAgeMs: number
83
+ ): MemoryInboxStore {
84
+ const seal = (bytes: Uint8Array): Uint8Array => Uint8Array.from(shared.key.encrypt(Array.from(bytes)) as number[])
85
+ const unseal = (bytes: Uint8Array): Uint8Array => Uint8Array.from(shared.key.decrypt(Array.from(bytes)) as number[])
86
+
87
+ /** Time-based purge: results after 15 minutes, whole tombstones after their window. */
88
+ function sweep() {
89
+ const t = now()
90
+ for (const [id, e] of shared.entries) {
91
+ if (e.sealedResult && e.resultAt !== undefined && t - e.resultAt > INBOX_RESULT_TTL_MS) {
92
+ e.sealedResult = undefined
93
+ e.gone = true
94
+ }
95
+ if (t - e.createdAt > TOMBSTONE_MS && e.state === 'done') shared.entries.delete(id)
96
+ }
97
+ }
98
+
99
+ /** Event retention (count and age); remembers the highest trimmed `closeSeq`. */
100
+ function trimEvents() {
101
+ const t = now()
102
+ const keep = shared.events.filter(e => t - e.at <= maxEventAgeMs)
103
+ const kept = keep.length > maxEvents ? keep.slice(keep.length - maxEvents) : keep
104
+ if (kept.length === shared.events.length) return
105
+ const keptSet = new Set(kept)
106
+ for (const e of shared.events)
107
+ if (!keptSet.has(e)) shared.evictedThrough = Math.max(shared.evictedThrough, e.closeSeq)
108
+ shared.events = kept
109
+ }
110
+
111
+ const store: MemoryInboxStore = {
112
+ async create(id, bytes) {
113
+ sweep()
114
+ if (shared.entries.has(id)) return false
115
+ let recordCreatedAt = now()
116
+ try {
117
+ const value = JSON.parse(Utils.toUTF8(Array.from(bytes)))?.createdAt
118
+ if (typeof value === 'number' && Number.isFinite(value)) recordCreatedAt = value
119
+ } catch { /* malformed records are refused by the processor */ }
120
+ shared.entries.set(id, {
121
+ state: 'pending',
122
+ size: bytes.byteLength,
123
+ createdAt: now(),
124
+ recordCreatedAt,
125
+ sealedRecord: seal(bytes)
126
+ })
127
+ return true
128
+ },
129
+
130
+ async stat(id): Promise<InboxStat | undefined> {
131
+ const e = shared.entries.get(id)
132
+ if (!e) return undefined
133
+ return { size: e.size, state: e.state, ...(e.claimBootId !== undefined ? { claimBootId: e.claimBootId } : {}) }
134
+ },
135
+
136
+ async read(id) {
137
+ const e = shared.entries.get(id)
138
+ return e?.sealedRecord ? unseal(e.sealedRecord) : undefined
139
+ },
140
+
141
+ async accept(id) {
142
+ const e = shared.entries.get(id)
143
+ if (!e || e.state !== 'pending') return false
144
+ e.state = 'accepted'
145
+ return true
146
+ },
147
+
148
+ async release(id) {
149
+ const e = shared.entries.get(id)
150
+ if (!e || e.state !== 'accepted') return false
151
+ e.state = 'pending'
152
+ return true
153
+ },
154
+
155
+ async claim(id, digest): Promise<ClaimOutcome> {
156
+ const e = shared.entries.get(id)
157
+ if (!e || e.state !== 'accepted' || !e.sealedRecord) return 'not-accepted'
158
+ if (inboxDigest(unseal(e.sealedRecord)) !== digest) return 'digest-mismatch'
159
+ e.state = 'claimed'
160
+ e.claimBootId = boot
161
+ // Arguments are deleted at claim; the record is never read again.
162
+ e.sealedRecord = undefined
163
+ return 'claimed'
164
+ },
165
+
166
+ async writeResult(id, bytes) {
167
+ const e = shared.entries.get(id)
168
+ if (!e || e.state === 'done') return false
169
+ e.state = 'done'
170
+ e.sealedRecord = undefined
171
+ e.sealedResult = seal(bytes)
172
+ e.resultAt = now()
173
+ return true
174
+ },
175
+
176
+ async readResult(id): Promise<ResultRead> {
177
+ sweep()
178
+ const e = shared.entries.get(id)
179
+ if (!e || e.state !== 'done') return { kind: 'none' }
180
+ if (!e.sealedResult) return { kind: 'purged' }
181
+ return { kind: 'result', bytes: unseal(e.sealedResult) }
182
+ },
183
+
184
+ async ack(id) {
185
+ const e = shared.entries.get(id)
186
+ if (!e || e.state !== 'done') return
187
+ e.sealedRecord = undefined
188
+ e.sealedResult = undefined
189
+ e.gone = true
190
+ },
191
+
192
+ async writeEvent(ev: InboxCloseEvent) {
193
+ shared.events.push({
194
+ closeSeq: ev.closeSeq,
195
+ at: now(),
196
+ sealed: seal(Uint8Array.from(Utils.toArray(JSON.stringify(ev), 'utf8')))
197
+ })
198
+ shared.events.sort((a, b) => a.closeSeq - b.closeSeq)
199
+ trimEvents()
200
+ },
201
+
202
+ async readEventsAfter(seq) {
203
+ trimEvents()
204
+ const events = shared.events
205
+ .filter(e => e.closeSeq > seq)
206
+ .map(e => JSON.parse(Utils.toUTF8(Array.from(unseal(e.sealed)))) as InboxCloseEvent)
207
+ return { events, gap: seq < shared.evictedThrough }
208
+ },
209
+
210
+ bootId: () => boot,
211
+
212
+ async list(state) {
213
+ sweep()
214
+ const entries = [...shared.entries].filter(([, e]) => e.state === state)
215
+ if (state === 'pending') entries.sort((a, b) => a[1].recordCreatedAt - b[1].recordCreatedAt)
216
+ return entries.map(([id]) => id)
217
+ },
218
+
219
+ rawBytes() {
220
+ const out: Uint8Array[] = shared.events.map(e => e.sealed)
221
+ for (const e of shared.entries.values()) {
222
+ if (e.sealedRecord) out.push(e.sealedRecord)
223
+ if (e.sealedResult) out.push(e.sealedResult)
224
+ }
225
+ return out
226
+ },
227
+
228
+ restart: bootId => open(shared, now, bootId ?? `boot-${++bootCounter}`, maxEvents, maxEventAgeMs)
229
+ }
230
+ return store
231
+ }
@@ -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
+ }