@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.
- package/CHANGELOG.md +222 -0
- package/README.md +82 -13
- package/core/bridge/BrowserBridgeProvider.tsx +273 -0
- package/core/bridge/bindings.ts +459 -0
- package/core/bridge/conformance.ts +222 -0
- package/core/bridge/consent.ts +494 -0
- package/core/bridge/consentSheetSource.ts +98 -0
- package/core/bridge/dispatcher.ts +621 -0
- package/core/bridge/inbox.ts +464 -0
- package/core/bridge/index.ts +48 -0
- package/core/bridge/loopback/cors.ts +57 -0
- package/core/bridge/loopback/endpoints.ts +11 -0
- package/core/bridge/loopback/hostCheck.ts +25 -0
- package/core/bridge/loopback/index.ts +7 -0
- package/core/bridge/loopback/launchProof.ts +166 -0
- package/core/bridge/loopback/router.ts +770 -0
- package/core/bridge/loopback/routerTypes.ts +115 -0
- package/core/bridge/loopback/status.ts +52 -0
- package/core/bridge/memoryInboxStore.ts +222 -0
- package/core/bridge/permissionPolicy.ts +247 -0
- package/core/bridge/policy.ts +72 -0
- package/core/bridge/protocol/base64url.ts +64 -0
- package/core/bridge/protocol/connectionError.ts +79 -0
- package/core/bridge/protocol/constants.ts +21 -0
- package/core/bridge/protocol/continuity.ts +21 -0
- package/core/bridge/protocol/descriptor.ts +395 -0
- package/core/bridge/protocol/envelopes.ts +188 -0
- package/core/bridge/protocol/errorCodec.ts +164 -0
- package/core/bridge/protocol/json.ts +237 -0
- package/core/bridge/protocol/limits.ts +43 -0
- package/core/bridge/protocol/methods.ts +55 -0
- package/core/bridge/protocol/origin.ts +130 -0
- package/core/bridge/runtime.ts +642 -0
- package/core/bridge/runtimeFlags.ts +34 -0
- package/core/bridge/testing/conformanceCases.ts +149 -0
- package/core/bridge/testing/pageClient.ts +44 -0
- package/core/bridge/unverifiedManager.ts +97 -0
- package/core/bridge/unverifiedOriginator.ts +79 -0
- package/core/config.tsx +1 -16
- package/core/contacts/contactActivity.ts +48 -28
- package/core/contacts/contactsStore.ts +2 -2
- package/core/context/WalletConnectionContext.tsx +7 -1
- package/core/context/WalletContext.tsx +420 -348
- package/core/context/sessionTeardown.ts +46 -0
- package/core/demo/demoAssets.ts +8 -10
- package/core/demo/demoLedger.ts +32 -38
- package/core/demo/demoMandalaRuntime.ts +67 -49
- package/core/demo/index.ts +1 -1
- package/core/hooks/usePermissionQueue.ts +89 -34
- package/core/i18n/translations.tsx +983 -12
- package/core/index.ts +70 -37
- package/core/localpay/build.ts +110 -569
- package/core/localpay/codec.ts +190 -93
- package/core/localpay/pending.ts +217 -202
- package/core/localpay/session.ts +99 -25
- package/core/localpay/types.ts +6 -5
- package/core/localpay/verify.ts +118 -173
- package/core/mandala/abortGuard.ts +97 -120
- package/core/mandala/accessPolicy.ts +133 -0
- package/core/mandala/assets.ts +370 -0
- package/core/mandala/colorGuard.ts +178 -0
- package/core/mandala/colorModule.ts +82 -0
- package/core/mandala/createRuntime.ts +483 -2392
- package/core/mandala/handle.ts +694 -0
- package/core/mandala/kvStore.ts +105 -0
- package/core/mandala/nearby.ts +185 -0
- package/core/mandala/receipt.ts +121 -0
- package/core/mandala/runtime.ts +166 -312
- package/core/mandala/settle.ts +540 -0
- package/core/mandala/transferJournal.ts +395 -0
- package/core/mandala/types.ts +61 -311
- package/core/networks.ts +5 -5
- package/core/offline/cancelParked.ts +80 -63
- package/core/offline/payerHold.ts +52 -118
- package/core/parsePeerPayURI.ts +25 -12
- package/core/pay/rails/handle.ts +15 -14
- package/core/pay/rails/index.ts +5 -3
- package/core/pay/rails/nearby.ts +25 -87
- package/core/profiles/assertProfileEmpty.ts +19 -10
- package/core/services/autoApprovePolicy.ts +7 -1
- package/core/services/capWalletArgs.ts +2 -1
- package/core/services/permissionPrompts.ts +132 -0
- package/core/services/signingPermissionPolicy.ts +230 -2
- package/core/services/vault/guard.ts +15 -4
- package/core/services/walletArgLimits.ts +17 -2
- package/core/storage/StorageExpoSQLite.ts +93 -229
- package/core/storage/encryptedDbImage.ts +325 -0
- package/core/storage/methods/processOfflineActions.ts +86 -136
- package/core/storage/schema/createTables.ts +9 -184
- package/core/toolboxConfig.ts +18 -1
- package/package.json +9 -8
- package/ui/bridgeSheet/ContextRelay.tsx +86 -0
- package/ui/bridgeSheet/relayedContexts.ts +21 -0
- package/ui/components/pay/AssetPicker.tsx +2 -2
- package/ui/components/pay/HandleReceive.tsx +4 -4
- package/ui/components/pay/NearbyFlow.tsx +324 -239
- package/ui/components/pay/RequestHub.tsx +10 -0
- package/ui/components/pay/UniversalSend.tsx +31 -28
- package/ui/components/pay/useRecipientInput.ts +2 -2
- package/ui/components/ui/PermissionSheet.tsx +625 -315
- package/ui/components/ui/Sheet.tsx +59 -7
- package/ui/components/ui/colorPrompt.ts +236 -0
- package/ui/components/ui/sheetResumeSignal.ts +19 -0
- package/ui/components/wallet/AmountInput.tsx +9 -6
- package/ui/components/wallet/AssetAmount.tsx +6 -6
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ContactActivityList.tsx +10 -13
- package/ui/components/wallet/tokenEviction.ts +9 -9
- package/ui/exportDatabases.ts +94 -5
- package/ui/hooks/useExportWalletData.ts +37 -24
- package/ui/hooks/useMandala.ts +6 -6
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/importDatabases.ts +124 -29
- package/ui/index.ts +4 -0
- package/ui/screens/PayScreen.tsx +14 -20
- package/ui/screens/SettingsScreen.tsx +3 -1
- package/ui/screens/WalletCheckScreen.tsx +7 -2
- package/ui/screens/WalletConfigScreen.tsx +13 -1
- package/ui/screens/WalletHomeScreen.tsx +40 -14
- package/ui/screens/tokenRowTitle.ts +28 -15
- package/ui/tokenFormat.ts +133 -69
- package/ui/tokenStatus.ts +5 -8
- package/core/localpay/settlementAck.ts +0 -155
- package/core/mandala/basketMigration.ts +0 -166
- package/core/mandala/bundle.ts +0 -244
- package/core/mandala/drain.ts +0 -754
- package/core/mandala/inboxPrehold.ts +0 -193
- package/core/mandala/permissionModule.ts +0 -931
- package/core/mandala/resendTransfer.ts +0 -178
- package/core/mandala/settlementStore.ts +0 -434
- package/core/mandala/token.ts +0 -45
- package/core/offline/tokenFrames.ts +0 -197
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dispatch pipeline (spec 6.6): one BRC-185 request in, one `Outcome` out.
|
|
3
|
+
*
|
|
4
|
+
* Order, as in the spec: transport bounds, binding, method, probes, arguments, wallet state and
|
|
5
|
+
* consent, readiness again, a synchronous re-check, the call, the result. Steps 6 and 7 may park a
|
|
6
|
+
* request for as long as it takes (BRC-219 sets no timeout on a pending prompt); a parked request
|
|
7
|
+
* wakes on two signals, a snapshot change and the close of its own binding, so a profile switch
|
|
8
|
+
* settles it instead of letting it proceed onto the new wallet.
|
|
9
|
+
*
|
|
10
|
+
* `Outcome.walletError` carries `delivery`, which the plan's type omitted but spec 6.11 assigns:
|
|
11
|
+
* `not-sent` for a refusal before the call, and for a call that failed on a read-only method
|
|
12
|
+
* (nothing can have changed); `unknown` for a call that failed on a mutating method.
|
|
13
|
+
*
|
|
14
|
+
* The `ConsentStore` needs the admin-scoped wallet, so it is not created here: `BrowserBridgeProvider`
|
|
15
|
+
* creates it per wallet, hands it to `createDispatcher`, then `installDispatcher`.
|
|
16
|
+
*/
|
|
17
|
+
import { WERR_INVALID_PARAMETER, normalizeBRC100WalletByteFields, stringifyBRC100 } from '@bsv/sdk'
|
|
18
|
+
import { snapshotWalletResultRequest, validateWalletArgs, validateWalletResult } from '@bsv/sdk'
|
|
19
|
+
import type { WalletInterface } from '@bsv/sdk'
|
|
20
|
+
import { WalletArgTooLarge, capWalletArgs, tierLimits } from '../services/capWalletArgs'
|
|
21
|
+
import { checkWalletArgs, type WalletArgLimits } from '../services/walletArgLimits'
|
|
22
|
+
import type { Binding } from './bindings'
|
|
23
|
+
import type { ConsentStore, GroupPermissions } from './consent'
|
|
24
|
+
import { findTokenModuleVariant, isValidVersionString } from './policy'
|
|
25
|
+
import { encodeWalletError, type WireError } from './protocol/errorCodec'
|
|
26
|
+
import { connectionError, isConnectionError, type ConnectionError, type Delivery } from './protocol/connectionError'
|
|
27
|
+
import {
|
|
28
|
+
MAX_BRIDGE_REQUEST_BYTES,
|
|
29
|
+
MAX_IN_FLIGHT_BYTES,
|
|
30
|
+
MAX_IN_FLIGHT_PER_BINDING,
|
|
31
|
+
MAX_IN_FLIGHT_TOTAL
|
|
32
|
+
} from './protocol/limits'
|
|
33
|
+
import { BRIDGE_METHODS, isBridgeMethod, type WalletMethodName } from './protocol/methods'
|
|
34
|
+
import { assertCanonicalOriginator } from './protocol/origin'
|
|
35
|
+
import type { CloseEvent } from './bindings'
|
|
36
|
+
import {
|
|
37
|
+
assertBridgeHost,
|
|
38
|
+
getBindingRegistry,
|
|
39
|
+
getBridgeSnapshot,
|
|
40
|
+
getPublishedManagers,
|
|
41
|
+
getTransport,
|
|
42
|
+
onBindingClosed,
|
|
43
|
+
onSnapshotChange,
|
|
44
|
+
type AttentionReason
|
|
45
|
+
} from './runtime'
|
|
46
|
+
|
|
47
|
+
export interface DispatchRequest {
|
|
48
|
+
epoch: string
|
|
49
|
+
instanceId: string
|
|
50
|
+
continuityKey: string
|
|
51
|
+
origin: string
|
|
52
|
+
accountContext?: string
|
|
53
|
+
method: string
|
|
54
|
+
args: unknown
|
|
55
|
+
sizeBytes: number
|
|
56
|
+
/**
|
|
57
|
+
* Awaited once, after consent and before the final readiness wait and the synchronous re-check.
|
|
58
|
+
* The durable inbox claims its record here (spec 6.8): the claim is the at-most-once point, and
|
|
59
|
+
* the re-check then runs after it. A rejection with a `ConnectionError` settles the request with
|
|
60
|
+
* it; the wallet is not called.
|
|
61
|
+
*/
|
|
62
|
+
beforeCall?: () => Promise<void>
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type Outcome =
|
|
66
|
+
| { ok: true; result: unknown }
|
|
67
|
+
| { ok: false; walletError: WireError; delivery: Delivery }
|
|
68
|
+
| { ok: false; connectionError: ConnectionError }
|
|
69
|
+
|
|
70
|
+
export interface DispatcherDeps {
|
|
71
|
+
consent: ConsentStore
|
|
72
|
+
/** Defaults to the device tier's limits, the same ones `capWalletArgs` applies. */
|
|
73
|
+
walletArgLimits?: WalletArgLimits
|
|
74
|
+
/** Nudges the backup log after a mutating call. Defaults to `TaskBackupPush.noteChanged`. */
|
|
75
|
+
noteChanged?: () => void
|
|
76
|
+
/**
|
|
77
|
+
* The manifest group to show on the Connect sheet, from the manager that will check it. Awaited
|
|
78
|
+
* under a short timeout before the sheet is raised; a failure, a timeout or an empty manifest
|
|
79
|
+
* all resolve to null, which gives the plain sheet.
|
|
80
|
+
*/
|
|
81
|
+
previewGroup?: (binding: Binding) => Promise<GroupPermissions | null>
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** How long the Connect sheet waits for the manifest preview before showing without it. */
|
|
85
|
+
export const PREVIEW_GROUP_TIMEOUT_MS = 2000
|
|
86
|
+
|
|
87
|
+
export interface Dispatcher {
|
|
88
|
+
dispatch(input: { transport: string | { id: string }; request: DispatchRequest }): Promise<Outcome>
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A settled outcome reached mid-pipeline. */
|
|
92
|
+
class Early {
|
|
93
|
+
constructor(readonly outcome: Outcome) {}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const refuse = (e: ConnectionError): Early => new Early({ ok: false, connectionError: e })
|
|
97
|
+
const walletRefusal = (wire: WireError): Early => new Early({ ok: false, walletError: wire, delivery: 'not-sent' })
|
|
98
|
+
|
|
99
|
+
function permissionDenied(message: string): Early {
|
|
100
|
+
const error = Object.assign(new Error(message), { code: 'ERR_PERMISSION_DENIED' })
|
|
101
|
+
return walletRefusal(encodeWalletError(error))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A wallet error that must reach the page as code 6, whatever the validator threw. */
|
|
105
|
+
function invalidArgument(e: unknown): Early {
|
|
106
|
+
const wire = encodeWalletError(e)
|
|
107
|
+
return walletRefusal(wire.code === 6 ? wire : encodeWalletError(new WERR_INVALID_PARAMETER('request', 'valid')))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const MAX_SCAN_DEPTH = 64
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* True when the arguments hold a typed array or an ArrayBuffer, or nest deeper than a JSON request
|
|
114
|
+
* could. Byte fields on this boundary are `number[]`. A deep cycle can only come from an
|
|
115
|
+
* in-process caller, and is refused the same way.
|
|
116
|
+
*/
|
|
117
|
+
function hasBinaryOrDeep(v: unknown, depth = 0): boolean {
|
|
118
|
+
if (v === null || typeof v !== 'object') return false
|
|
119
|
+
if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) return true
|
|
120
|
+
if (depth > MAX_SCAN_DEPTH) return true
|
|
121
|
+
if (Array.isArray(v)) {
|
|
122
|
+
for (let i = 0; i < v.length; i++) {
|
|
123
|
+
const item = v[i]
|
|
124
|
+
if (item !== null && typeof item === 'object' && hasBinaryOrDeep(item, depth + 1)) return true
|
|
125
|
+
}
|
|
126
|
+
return false
|
|
127
|
+
}
|
|
128
|
+
for (const value of Object.values(v)) if (hasBinaryOrDeep(value, depth + 1)) return true
|
|
129
|
+
return false
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function closedOutcome(e: CloseEvent): ConnectionError {
|
|
133
|
+
if (e.reason === 'lost') {
|
|
134
|
+
return connectionError('CONNECTION_CLOSED', 'This connection is closed', 'not-sent', {
|
|
135
|
+
epoch: e.epoch,
|
|
136
|
+
cause: 'lost'
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
if (e.reason === 'disconnected') {
|
|
140
|
+
return connectionError('DISCONNECTED', 'This connection was closed', 'not-sent', { epoch: e.epoch })
|
|
141
|
+
}
|
|
142
|
+
return connectionError('PROVIDER_CHANGED', 'This connection was closed', 'not-sent', {
|
|
143
|
+
epoch: e.epoch,
|
|
144
|
+
cause: e.reason
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function readTxid(result: unknown): string | undefined {
|
|
149
|
+
const txid = (result as { txid?: unknown } | null | undefined)?.txid
|
|
150
|
+
return typeof txid === 'string' && /^[0-9a-f]{64}$/i.test(txid) ? txid : undefined
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function defaultNoteChanged(): void {
|
|
154
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
155
|
+
const { TaskBackupPush } = require('../monitor/TaskBackupPush') as typeof import('../monitor/TaskBackupPush')
|
|
156
|
+
TaskBackupPush.noteChanged()
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function createDispatcher(deps: DispatcherDeps): Dispatcher {
|
|
160
|
+
const inFlightByEpoch = new Map<string, number>()
|
|
161
|
+
let inFlightTotal = 0
|
|
162
|
+
let inFlightBytes = 0
|
|
163
|
+
|
|
164
|
+
function admit(epoch: string, size: number): (() => void) | ConnectionError {
|
|
165
|
+
const per = inFlightByEpoch.get(epoch) ?? 0
|
|
166
|
+
if (per >= MAX_IN_FLIGHT_PER_BINDING || inFlightTotal >= MAX_IN_FLIGHT_TOTAL) {
|
|
167
|
+
return connectionError('RESOURCE_LIMIT', 'Too many requests in flight', 'not-sent', { epoch })
|
|
168
|
+
}
|
|
169
|
+
if (inFlightBytes + size > MAX_IN_FLIGHT_BYTES) {
|
|
170
|
+
return connectionError('RESOURCE_LIMIT', 'Too many request bytes in flight', 'not-sent', { epoch })
|
|
171
|
+
}
|
|
172
|
+
inFlightByEpoch.set(epoch, per + 1)
|
|
173
|
+
inFlightTotal += 1
|
|
174
|
+
inFlightBytes += size
|
|
175
|
+
let released = false
|
|
176
|
+
return () => {
|
|
177
|
+
if (released) return
|
|
178
|
+
released = true
|
|
179
|
+
const n = (inFlightByEpoch.get(epoch) ?? 1) - 1
|
|
180
|
+
if (n <= 0) inFlightByEpoch.delete(epoch)
|
|
181
|
+
else inFlightByEpoch.set(epoch, n)
|
|
182
|
+
inFlightTotal -= 1
|
|
183
|
+
inFlightBytes -= size
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function run(transportId: string, req: DispatchRequest): Promise<Outcome> {
|
|
188
|
+
const argLimits = deps.walletArgLimits ?? tierLimits()
|
|
189
|
+
const noteChanged = deps.noteChanged ?? defaultNoteChanged
|
|
190
|
+
|
|
191
|
+
// Without a mounted, loaded host nothing below is safe to touch (the registry throws).
|
|
192
|
+
try {
|
|
193
|
+
assertBridgeHost()
|
|
194
|
+
} catch (e) {
|
|
195
|
+
if (isConnectionError(e)) throw refuse(e)
|
|
196
|
+
throw e
|
|
197
|
+
}
|
|
198
|
+
const transport = getTransport(transportId)
|
|
199
|
+
if (!transport) {
|
|
200
|
+
throw refuse(
|
|
201
|
+
connectionError('CONFIGURATION_ERROR', 'Transport is not registered', 'not-sent', { epoch: req.epoch })
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// 1. Transport bounds, re-checked here. Typed arrays are refused under the same code: the
|
|
206
|
+
// spec lists them with the boundary rules, and a JSON transport can never produce one.
|
|
207
|
+
if (typeof req.sizeBytes !== 'number' || !Number.isFinite(req.sizeBytes) || req.sizeBytes < 0) {
|
|
208
|
+
throw refuse(connectionError('PROTOCOL_ERROR', 'Request size missing', 'not-sent', { epoch: req.epoch }))
|
|
209
|
+
}
|
|
210
|
+
if (req.sizeBytes > MAX_BRIDGE_REQUEST_BYTES) {
|
|
211
|
+
throw refuse(connectionError('RESOURCE_LIMIT', 'Request too large', 'not-sent', { epoch: req.epoch }))
|
|
212
|
+
}
|
|
213
|
+
let binary: boolean
|
|
214
|
+
try {
|
|
215
|
+
binary = hasBinaryOrDeep(req.args)
|
|
216
|
+
} catch (e) {
|
|
217
|
+
// A hostile in-process object (a throwing getter) is an invalid argument, not a crash.
|
|
218
|
+
throw invalidArgument(e)
|
|
219
|
+
}
|
|
220
|
+
if (binary) {
|
|
221
|
+
throw refuse(
|
|
222
|
+
connectionError('RESOURCE_LIMIT', 'Byte fields must be number arrays', 'not-sent', { epoch: req.epoch })
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// 2. Binding.
|
|
227
|
+
const resolved = getBindingRegistry().resolve(transportId, {
|
|
228
|
+
epoch: req.epoch,
|
|
229
|
+
instanceId: req.instanceId,
|
|
230
|
+
continuityKey: req.continuityKey,
|
|
231
|
+
origin: req.origin,
|
|
232
|
+
accountContext: req.accountContext
|
|
233
|
+
})
|
|
234
|
+
if (isConnectionError(resolved)) throw refuse(resolved)
|
|
235
|
+
const binding: Binding = resolved
|
|
236
|
+
|
|
237
|
+
// 3. Method.
|
|
238
|
+
if (!isBridgeMethod(req.method)) {
|
|
239
|
+
throw refuse(connectionError('PROTOCOL_ERROR', 'Unknown method', 'not-sent', { epoch: binding.epoch }))
|
|
240
|
+
}
|
|
241
|
+
const method: WalletMethodName = req.method
|
|
242
|
+
const info = BRIDGE_METHODS[method]
|
|
243
|
+
|
|
244
|
+
// 4. Probes: no gate, no wallet call, no wait. They hold no resource, so the in-flight limits
|
|
245
|
+
// (which exist to bound parked work) do not apply to them.
|
|
246
|
+
if (info.probe) {
|
|
247
|
+
const snap = getBridgeSnapshot()
|
|
248
|
+
if (method === 'isAuthenticated') {
|
|
249
|
+
throw new Early({ ok: true, result: { authenticated: snap.readiness === 'ready' } })
|
|
250
|
+
}
|
|
251
|
+
if (!isValidVersionString(snap.baseVersion)) {
|
|
252
|
+
throw refuse(
|
|
253
|
+
connectionError('CONFIGURATION_ERROR', 'The wallet version string is invalid', 'not-sent', {
|
|
254
|
+
epoch: binding.epoch
|
|
255
|
+
})
|
|
256
|
+
)
|
|
257
|
+
}
|
|
258
|
+
throw new Early({ ok: true, result: { version: snap.baseVersion } })
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const release = admit(binding.epoch, req.sizeBytes)
|
|
262
|
+
if (typeof release !== 'function') throw refuse(release)
|
|
263
|
+
|
|
264
|
+
// Everything from here can park, so it watches this binding's close.
|
|
265
|
+
let closed: CloseEvent | undefined
|
|
266
|
+
const waiters = new Set<() => void>()
|
|
267
|
+
let consentRequested = false
|
|
268
|
+
const unsubscribeClose = onBindingClosed(e => {
|
|
269
|
+
if (e.epoch !== binding.epoch) return
|
|
270
|
+
closed = e
|
|
271
|
+
if (consentRequested) deps.consent.dropRequestsFor(e.epoch)
|
|
272
|
+
for (const w of [...waiters]) w()
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
/** Resolves with `p`, or rejects with the close outcome if the binding closes first. */
|
|
276
|
+
function untilClosed<T>(p: Promise<T>): Promise<T> {
|
|
277
|
+
if (closed) return Promise.reject(refuse(closedOutcome(closed)))
|
|
278
|
+
return new Promise<T>((resolve, reject) => {
|
|
279
|
+
const onClose = () => reject(refuse(closedOutcome(closed as CloseEvent)))
|
|
280
|
+
waiters.add(onClose)
|
|
281
|
+
p.then(
|
|
282
|
+
v => {
|
|
283
|
+
waiters.delete(onClose)
|
|
284
|
+
resolve(v)
|
|
285
|
+
},
|
|
286
|
+
e => {
|
|
287
|
+
waiters.delete(onClose)
|
|
288
|
+
reject(e)
|
|
289
|
+
}
|
|
290
|
+
)
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function notify(reason: AttentionReason) {
|
|
295
|
+
try {
|
|
296
|
+
transport!.requestAttention(reason, binding)
|
|
297
|
+
} catch (e) {
|
|
298
|
+
console.warn('[bridge] requestAttention failed', e)
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Parks until the runtime is `ready`; `none` fails at once. */
|
|
303
|
+
async function ensureReady(): Promise<void> {
|
|
304
|
+
let notified = false
|
|
305
|
+
for (;;) {
|
|
306
|
+
if (closed) throw refuse(closedOutcome(closed))
|
|
307
|
+
const readiness = getBridgeSnapshot().readiness
|
|
308
|
+
if (readiness === 'ready') return
|
|
309
|
+
if (readiness === 'none') {
|
|
310
|
+
throw refuse(
|
|
311
|
+
connectionError('CONFIGURATION_ERROR', 'No wallet is available', 'not-sent', { epoch: binding.epoch })
|
|
312
|
+
)
|
|
313
|
+
}
|
|
314
|
+
if (!notified) {
|
|
315
|
+
notified = true
|
|
316
|
+
notify('wallet-not-ready')
|
|
317
|
+
}
|
|
318
|
+
let off = () => {}
|
|
319
|
+
const changed = new Promise<void>(res => {
|
|
320
|
+
off = onSnapshotChange(() => res())
|
|
321
|
+
})
|
|
322
|
+
try {
|
|
323
|
+
await untilClosed(changed)
|
|
324
|
+
} finally {
|
|
325
|
+
off()
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
let started = false
|
|
331
|
+
try {
|
|
332
|
+
// 5. Arguments.
|
|
333
|
+
let args: unknown = req.args ?? {}
|
|
334
|
+
try {
|
|
335
|
+
args = normalizeBRC100WalletByteFields(args)
|
|
336
|
+
} catch (e) {
|
|
337
|
+
throw invalidArgument(e)
|
|
338
|
+
}
|
|
339
|
+
const refusal = checkWalletArgs(method, args, argLimits)
|
|
340
|
+
if (refusal) throw invalidArgument(new WalletArgTooLarge(refusal.field, refusal.message))
|
|
341
|
+
try {
|
|
342
|
+
validateWalletArgs(method as Parameters<typeof validateWalletArgs>[0], args)
|
|
343
|
+
} catch (e) {
|
|
344
|
+
throw invalidArgument(e)
|
|
345
|
+
}
|
|
346
|
+
if (binding.attestation === 'unattested' && findTokenModuleVariant(args) !== undefined) {
|
|
347
|
+
throw permissionDenied('Token modules are not available to unverified origins')
|
|
348
|
+
}
|
|
349
|
+
let requestSnapshot: unknown
|
|
350
|
+
try {
|
|
351
|
+
requestSnapshot = snapshotWalletResultRequest(method as Parameters<typeof snapshotWalletResultRequest>[0], args)
|
|
352
|
+
} catch (e) {
|
|
353
|
+
throw invalidArgument(e)
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// 6. Wallet state, then consent. The store is authenticated by the admin wallet, which
|
|
357
|
+
// exists only when `ready`.
|
|
358
|
+
await ensureReady()
|
|
359
|
+
if (!binding.consented) {
|
|
360
|
+
const record = await untilClosed(deps.consent.lookup(binding.applicationOrigin, binding.attestation))
|
|
361
|
+
// The connect-time token is checked once, here, and forgotten whatever the result. A
|
|
362
|
+
// missing record and a wrong token look the same to the page: not connected, then the
|
|
363
|
+
// sheet (whose "connected before" line is the spec's only disclosure).
|
|
364
|
+
const presented = getBindingRegistry().takeReconnectToken(binding.epoch)
|
|
365
|
+
if (record !== undefined) {
|
|
366
|
+
if (binding.attestation === 'browser' || deps.consent.checkReconnect(record, presented)) {
|
|
367
|
+
getBindingRegistry().markConsented(binding.epoch, record.originator)
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (!binding.consented) {
|
|
371
|
+
if ((args as { seekPermission?: unknown }).seekPermission === false) {
|
|
372
|
+
throw permissionDenied('Permission denied: this site is not connected')
|
|
373
|
+
}
|
|
374
|
+
let groupPermissions: GroupPermissions | null = null
|
|
375
|
+
if (deps.previewGroup !== undefined) {
|
|
376
|
+
const preview = deps.previewGroup
|
|
377
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
378
|
+
groupPermissions = await untilClosed(
|
|
379
|
+
Promise.race([
|
|
380
|
+
Promise.resolve()
|
|
381
|
+
.then(() => preview(binding))
|
|
382
|
+
.catch(() => null),
|
|
383
|
+
new Promise<null>(res => {
|
|
384
|
+
timer = setTimeout(() => res(null), PREVIEW_GROUP_TIMEOUT_MS)
|
|
385
|
+
})
|
|
386
|
+
]).finally(() => clearTimeout(timer))
|
|
387
|
+
)
|
|
388
|
+
}
|
|
389
|
+
const asked = deps.consent.requestConsent({
|
|
390
|
+
origin: binding.applicationOrigin,
|
|
391
|
+
attestation: binding.attestation,
|
|
392
|
+
transportId,
|
|
393
|
+
bindingEpoch: binding.epoch,
|
|
394
|
+
walletRevision: Number(getBridgeSnapshot().walletRevision),
|
|
395
|
+
connectedBefore: record !== undefined,
|
|
396
|
+
groupPermissions
|
|
397
|
+
})
|
|
398
|
+
if ('refused' in asked) {
|
|
399
|
+
throw refuse(
|
|
400
|
+
connectionError(
|
|
401
|
+
'RESOURCE_LIMIT',
|
|
402
|
+
asked.refused === 'backoff' ? 'This site was just declined' : 'A connection request is already open',
|
|
403
|
+
'not-sent',
|
|
404
|
+
{ epoch: binding.epoch }
|
|
405
|
+
)
|
|
406
|
+
)
|
|
407
|
+
}
|
|
408
|
+
consentRequested = true
|
|
409
|
+
notify('consent')
|
|
410
|
+
const answer = await untilClosed(asked.promise)
|
|
411
|
+
const approved =
|
|
412
|
+
answer === 'approved'
|
|
413
|
+
? await untilClosed(deps.consent.lookup(binding.applicationOrigin, binding.attestation))
|
|
414
|
+
: undefined
|
|
415
|
+
if (approved === undefined) {
|
|
416
|
+
throw refuse(
|
|
417
|
+
connectionError('USER_CANCELLED', 'The connection was declined', 'not-sent', { epoch: binding.epoch })
|
|
418
|
+
)
|
|
419
|
+
}
|
|
420
|
+
getBindingRegistry().markConsented(binding.epoch, approved.originator)
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
if (req.beforeCall) {
|
|
425
|
+
try {
|
|
426
|
+
await untilClosed(req.beforeCall())
|
|
427
|
+
} catch (e) {
|
|
428
|
+
if (e instanceof Early) throw e
|
|
429
|
+
if (isConnectionError(e)) throw refuse({ ...e, epoch: e.epoch ?? binding.epoch })
|
|
430
|
+
throw e
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// 7 and 8. Readiness again, then the synchronous re-check and the call with no await between.
|
|
435
|
+
let call: Promise<unknown>
|
|
436
|
+
for (;;) {
|
|
437
|
+
await ensureReady()
|
|
438
|
+
const snap = getBridgeSnapshot()
|
|
439
|
+
const published = getPublishedManagers()
|
|
440
|
+
const manager = binding.attestation === 'unattested' ? published.unverified : published.attested
|
|
441
|
+
if (snap.readiness !== 'ready') continue
|
|
442
|
+
let current =
|
|
443
|
+
binding.state === 'live' &&
|
|
444
|
+
String(binding.walletRevision) === snap.walletRevision &&
|
|
445
|
+
binding.accountContext === snap.accountContext &&
|
|
446
|
+
manager !== undefined
|
|
447
|
+
if (current) {
|
|
448
|
+
try {
|
|
449
|
+
assertCanonicalOriginator(binding.originator)
|
|
450
|
+
} catch {
|
|
451
|
+
current = false
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (!current || manager === undefined) {
|
|
455
|
+
throw refuse(
|
|
456
|
+
connectionError('PROVIDER_CHANGED', 'The wallet changed since this page connected', 'not-sent', {
|
|
457
|
+
epoch: binding.epoch,
|
|
458
|
+
cause: 'account-changed'
|
|
459
|
+
})
|
|
460
|
+
)
|
|
461
|
+
}
|
|
462
|
+
// 9. Call, on the guarded stack read just now, never cached across builds.
|
|
463
|
+
const wallet = capWalletArgs(manager.wallet as WalletInterface, argLimits)
|
|
464
|
+
started = true
|
|
465
|
+
try {
|
|
466
|
+
call = Promise.resolve(
|
|
467
|
+
(wallet as unknown as Record<string, (a: unknown, o?: string) => unknown>)[method](args, binding.originator)
|
|
468
|
+
)
|
|
469
|
+
} catch (e) {
|
|
470
|
+
call = Promise.reject(e)
|
|
471
|
+
}
|
|
472
|
+
break
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// 10. After the call. A mutating call nudges backup on every outcome, errors included.
|
|
476
|
+
if (info.mutating) {
|
|
477
|
+
const note = () => {
|
|
478
|
+
try {
|
|
479
|
+
noteChanged()
|
|
480
|
+
} catch (e) {
|
|
481
|
+
console.warn('[bridge] noteChanged failed', e)
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
call.then(note, note)
|
|
485
|
+
}
|
|
486
|
+
let result: unknown
|
|
487
|
+
try {
|
|
488
|
+
result = await new Promise<unknown>((resolve, reject) => {
|
|
489
|
+
if (closed) {
|
|
490
|
+
reject(new Early(closedWhileRunning(closed)))
|
|
491
|
+
return
|
|
492
|
+
}
|
|
493
|
+
const onClose = () => reject(new Early(closedWhileRunning(closed as CloseEvent)))
|
|
494
|
+
waiters.add(onClose)
|
|
495
|
+
call.then(
|
|
496
|
+
v => {
|
|
497
|
+
waiters.delete(onClose)
|
|
498
|
+
resolve(v)
|
|
499
|
+
},
|
|
500
|
+
e => {
|
|
501
|
+
waiters.delete(onClose)
|
|
502
|
+
reject(e)
|
|
503
|
+
}
|
|
504
|
+
)
|
|
505
|
+
})
|
|
506
|
+
} catch (e) {
|
|
507
|
+
if (e instanceof Early) throw e
|
|
508
|
+
if (binding.state === 'closed' && closed) throw new Early(closedWhileRunning(closed))
|
|
509
|
+
throw new Early({
|
|
510
|
+
ok: false,
|
|
511
|
+
walletError: encodeWalletError(e),
|
|
512
|
+
delivery: info.mutating ? 'unknown' : 'not-sent'
|
|
513
|
+
})
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
return finishResult(result)
|
|
517
|
+
|
|
518
|
+
function finishResult(raw: unknown): Outcome {
|
|
519
|
+
if (method === 'getVersion') {
|
|
520
|
+
const v = (raw as { version?: unknown } | null)?.version
|
|
521
|
+
if (!isValidVersionString(v)) return invalidResult(raw)
|
|
522
|
+
return { ok: true, result: { version: v } }
|
|
523
|
+
}
|
|
524
|
+
try {
|
|
525
|
+
if (stringifyBRC100(raw).length > MAX_BRIDGE_REQUEST_BYTES) {
|
|
526
|
+
return {
|
|
527
|
+
ok: false,
|
|
528
|
+
connectionError: connectionError('RESOURCE_LIMIT', 'Response too large', 'unknown', {
|
|
529
|
+
epoch: binding.epoch
|
|
530
|
+
})
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
const validated = validateWalletResult(
|
|
534
|
+
method as Parameters<typeof validateWalletResult>[0],
|
|
535
|
+
raw,
|
|
536
|
+
requestSnapshot
|
|
537
|
+
)
|
|
538
|
+
return { ok: true, result: validated }
|
|
539
|
+
} catch {
|
|
540
|
+
return invalidResult(raw)
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function invalidResult(raw: unknown): Outcome {
|
|
545
|
+
if (info.mutating) {
|
|
546
|
+
return {
|
|
547
|
+
ok: false,
|
|
548
|
+
connectionError: connectionError('PROTOCOL_ERROR', 'The wallet returned an invalid result', 'unknown', {
|
|
549
|
+
epoch: binding.epoch,
|
|
550
|
+
cause: 'invalid-result',
|
|
551
|
+
txid: readTxid(raw)
|
|
552
|
+
})
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return {
|
|
556
|
+
ok: false,
|
|
557
|
+
walletError: encodeWalletError(new Error('The wallet returned an invalid result')),
|
|
558
|
+
delivery: 'not-sent'
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
} catch (e) {
|
|
562
|
+
if (e instanceof Early) throw e
|
|
563
|
+
console.warn('[bridge] dispatch failed', e)
|
|
564
|
+
throw refuse(
|
|
565
|
+
connectionError('CONFIGURATION_ERROR', 'The wallet bridge failed', started ? 'unknown' : 'not-sent', {
|
|
566
|
+
epoch: binding.epoch
|
|
567
|
+
})
|
|
568
|
+
)
|
|
569
|
+
} finally {
|
|
570
|
+
unsubscribeClose()
|
|
571
|
+
release()
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function closedWhileRunning(e: CloseEvent): Outcome {
|
|
576
|
+
return {
|
|
577
|
+
ok: false,
|
|
578
|
+
connectionError: connectionError('CONNECTION_CLOSED', 'The connection closed during the call', 'unknown', {
|
|
579
|
+
epoch: e.epoch,
|
|
580
|
+
cause: e.reason
|
|
581
|
+
})
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
return {
|
|
586
|
+
async dispatch({ transport, request }) {
|
|
587
|
+
const transportId = typeof transport === 'string' ? transport : transport.id
|
|
588
|
+
try {
|
|
589
|
+
return await run(transportId, request)
|
|
590
|
+
} catch (e) {
|
|
591
|
+
if (e instanceof Early) return e.outcome
|
|
592
|
+
console.warn('[bridge] dispatch failed', e)
|
|
593
|
+
return {
|
|
594
|
+
ok: false,
|
|
595
|
+
connectionError: connectionError('CONFIGURATION_ERROR', 'The wallet bridge failed', 'not-sent', {
|
|
596
|
+
epoch: request?.epoch
|
|
597
|
+
})
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
let installed: Dispatcher | undefined
|
|
605
|
+
|
|
606
|
+
/** The host's dispatcher, set once the consent store exists. Transports call `dispatch`. */
|
|
607
|
+
export function installDispatcher(d: Dispatcher | undefined): void {
|
|
608
|
+
installed = d
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
export function dispatch(input: { transport: string | { id: string }; request: DispatchRequest }): Promise<Outcome> {
|
|
612
|
+
if (!installed) {
|
|
613
|
+
return Promise.resolve({
|
|
614
|
+
ok: false,
|
|
615
|
+
connectionError: connectionError('CONFIGURATION_ERROR', 'The wallet bridge is not available', 'not-sent', {
|
|
616
|
+
epoch: input.request?.epoch
|
|
617
|
+
})
|
|
618
|
+
})
|
|
619
|
+
}
|
|
620
|
+
return installed.dispatch(input)
|
|
621
|
+
}
|