@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,770 @@
1
+ /**
2
+ * The loopback router (spec 6.5): BRC-185 section 4.1 HTTP semantics over the ports in `routerTypes.ts`.
3
+ * Pure TypeScript: Kotlin parses and writes HTTP, this decides what every request means.
4
+ *
5
+ * This file holds the entry point, the gate (path allowlist, Host, Origin, CORS, preflight), describe, connect,
6
+ * RPC and disconnect.
7
+ *
8
+ * Nothing here logs. `k`, epochs, proofs, acks, binding secrets, tokens and bodies are never written anywhere.
9
+ */
10
+ import type { Outcome } from '../dispatcher'
11
+ import { b64uDecode, b64uEncode } from '../protocol/base64url'
12
+ import { connectionError, isConnectionError, type ConnectionError } from '../protocol/connectionError'
13
+ import {
14
+ assertAdvertisesResponder,
15
+ signConnect,
16
+ signDescribe,
17
+ validateDescriptor,
18
+ type Descriptor
19
+ } from '../protocol/descriptor'
20
+ import { parseStrictJson } from '../protocol/json'
21
+ import { MAX_BRIDGE_REQUEST_BYTES } from '../protocol/limits'
22
+ import { isBridgeMethod } from '../protocol/methods'
23
+ import type { ContinuityHandle } from '../protocol/continuity'
24
+ import { canonicalizeBridgeOrigin } from '../protocol/origin'
25
+ import { BASE_HEADERS, corsHeaders, preflightHeaders, type CorsKind } from './cors'
26
+ import { loopbackEndpoints } from './endpoints'
27
+ import { isAllowedHost } from './hostCheck'
28
+ import { bindingSecret, connectAck, describeAck, launchProof, timingSafeEqualB64u } from './launchProof'
29
+ import type { RawRequest, RoutePlan, RouteResponse, RouterEnv, LoopbackRouter } from './routerTypes'
30
+ import { STATUS, statusForConnectionError } from './status'
31
+
32
+ const encoder = new TextEncoder()
33
+
34
+ /** A describe request carries no body of interest; anything over this is refused rather than buffered on. */
35
+ const MAX_DESCRIBE_BODY_BYTES = 16384
36
+ const EPOCH_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
37
+ const METHOD_SEGMENT_RE = /^[A-Za-z0-9]{1,64}$/
38
+ const DISCOVERY_PATH = '/.well-known/brc-wallet'
39
+ const CONNECT_PATH = '/.well-known/brc-wallet/connect'
40
+ const CONNECT_PREFIX = '/.well-known/brc-wallet/connect/'
41
+ const RPC_PREFIX = '/brc185/v1/rpc/'
42
+
43
+ export type RouteKind = 'describe' | 'connect' | 'disconnect' | 'rpc'
44
+
45
+ interface Matched {
46
+ kind: RouteKind
47
+ /** The epoch (disconnect) or method name (rpc) segment, literal. */
48
+ segment?: string
49
+ /** Raw query string without `?`, only ever non-empty for describe. */
50
+ query: string
51
+ allow: string
52
+ }
53
+
54
+ /** What a route handler gets once a request has passed the gate. */
55
+ export interface GateContext {
56
+ env: RouterEnv
57
+ req: RawRequest
58
+ route: Matched
59
+ /** The canonical request origin (passed step 2). */
60
+ origin: string
61
+ /** The request's own `Host` value (already checked against the bound set). */
62
+ host: string
63
+ header(name: string): string | undefined
64
+ }
65
+
66
+ export type RouteHandler = (ctx: GateContext) => Promise<RoutePlan>
67
+
68
+ function utf8Length(s: string): number {
69
+ return encoder.encode(s).length
70
+ }
71
+
72
+ function respond(status: number, headers: [string, string][], body: string): RoutePlan {
73
+ return { kind: 'respond', status, headers, body }
74
+ }
75
+
76
+ /** Base headers on every response, errors included (spec 6.6.1). */
77
+ function base(extra: [string, string][] = []): [string, string][] {
78
+ return [...BASE_HEADERS.map(h => [h[0], h[1]] as [string, string]), ...extra]
79
+ }
80
+
81
+ function emptyResponse(status: number, extra: [string, string][] = []): RoutePlan {
82
+ return respond(status, base(extra), '')
83
+ }
84
+
85
+ function jsonHeaders(extra: [string, string][]): [string, string][] {
86
+ return base([['Content-Type', 'application/json'], ...extra])
87
+ }
88
+
89
+ export function errorResponse(
90
+ e: ConnectionError,
91
+ opts: { situation?: keyof typeof STATUS; cors?: [string, string][]; headers?: [string, string][] } = {}
92
+ ): RoutePlan {
93
+ const status = statusForConnectionError(e, opts.situation)
94
+ return respond(status, jsonHeaders([...(opts.cors ?? []), ...(opts.headers ?? [])]), JSON.stringify(e))
95
+ }
96
+
97
+ export function plan(r: RouteResponse): RoutePlan {
98
+ return { kind: 'respond', ...r }
99
+ }
100
+
101
+ function protocolError(message: string, cors: [string, string][] = []): RoutePlan {
102
+ return errorResponse(connectionError('PROTOCOL_ERROR', message, 'not-sent'), { cors })
103
+ }
104
+
105
+ function internalError(cors: [string, string][] = []): RoutePlan {
106
+ return errorResponse(connectionError('CONFIGURATION_ERROR', 'Internal error', 'not-sent'), {
107
+ situation: 'internal',
108
+ cors
109
+ })
110
+ }
111
+
112
+ /**
113
+ * Step 1. The target is matched literally: no decoding, no normalisation. Anything with a percent escape, a
114
+ * fragment, a dot segment, an absolute form or a non-canonical epoch is simply not on the list.
115
+ */
116
+ function matchTarget(target: string): Matched | undefined {
117
+ if (typeof target !== 'string' || !target.startsWith('/') || target.startsWith('//')) return undefined
118
+ if (target.includes('%') || target.includes('#') || target.includes('\\')) return undefined
119
+ // eslint-disable-next-line no-control-regex
120
+ if (/[\u0000- \u007f-￿]/.test(target)) return undefined
121
+ const q = target.indexOf('?')
122
+ const path = q === -1 ? target : target.slice(0, q)
123
+ const query = q === -1 ? '' : target.slice(q + 1)
124
+ if (path.split('/').some(s => s === '.' || s === '..')) return undefined
125
+ if (path === DISCOVERY_PATH) return { kind: 'describe', query, allow: 'GET, OPTIONS' }
126
+ if (query !== '' || q !== -1) return undefined
127
+ if (path === CONNECT_PATH) return { kind: 'connect', query, allow: 'POST, OPTIONS' }
128
+ if (path.startsWith(CONNECT_PREFIX)) {
129
+ const epoch = path.slice(CONNECT_PREFIX.length)
130
+ return EPOCH_RE.test(epoch) ? { kind: 'disconnect', segment: epoch, query, allow: 'DELETE, OPTIONS' } : undefined
131
+ }
132
+ if (path.startsWith(RPC_PREFIX)) {
133
+ const name = path.slice(RPC_PREFIX.length)
134
+ return METHOD_SEGMENT_RE.test(name) ? { kind: 'rpc', segment: name, query, allow: 'POST, OPTIONS' } : undefined
135
+ }
136
+ return undefined
137
+ }
138
+
139
+ function verbFor(kind: RouteKind): string {
140
+ return kind === 'describe' ? 'GET' : kind === 'disconnect' ? 'DELETE' : 'POST'
141
+ }
142
+
143
+ /** Header lookup over the lowercased pairs: the value when the name appears exactly once, else `undefined`. */
144
+ function only(headers: [string, string][], name: string): string | undefined {
145
+ let found: string | undefined
146
+ let n = 0
147
+ for (const [k, v] of headers) {
148
+ if (k === name) {
149
+ n++
150
+ found = v
151
+ }
152
+ }
153
+ return n === 1 ? found : undefined
154
+ }
155
+
156
+ function count(headers: [string, string][], name: string): number {
157
+ let n = 0
158
+ for (const [k] of headers) if (k === name) n++
159
+ return n
160
+ }
161
+
162
+ /** Parse `a=b&c=d` where every name may appear at most once and only `allowed` names are legal. */
163
+ function parseQuery(query: string, allowed: string[]): Map<string, string> | undefined {
164
+ const out = new Map<string, string>()
165
+ if (query === '') return out
166
+ for (const part of query.split('&')) {
167
+ const eq = part.indexOf('=')
168
+ if (eq <= 0) return undefined
169
+ const name = part.slice(0, eq)
170
+ if (!allowed.includes(name) || out.has(name)) return undefined
171
+ out.set(name, part.slice(eq + 1))
172
+ }
173
+ return out
174
+ }
175
+
176
+ function canonicalB64u32(s: string | undefined): string | undefined {
177
+ if (s === undefined || s === '') return undefined
178
+ try {
179
+ return b64uDecode(s).length === 32 ? s : undefined
180
+ } catch {
181
+ return undefined
182
+ }
183
+ }
184
+
185
+ /** Public CORS (discovery, connect, preflight): any origin that passed the gate. */
186
+ export function publicCors(origin: string): [string, string][] {
187
+ return corsHeaders({ origin, kind: 'public' as CorsKind })
188
+ }
189
+
190
+ /**
191
+ * The descriptor this wallet advertises to one origin. Refuses to produce one the page would refuse, or one that
192
+ * does not name the endpoint that answered. `raw` is what gets signed: the page's check runs over exactly what was sent.
193
+ */
194
+ function buildDescriptor(env: RouterEnv, identity: ContinuityHandle, host: string): { raw: Descriptor } | undefined {
195
+ const raw: Record<string, unknown> = {
196
+ version: 1,
197
+ instanceId: identity.instanceId,
198
+ name: env.descriptorBase.name,
199
+ instanceLabel: env.descriptorBase.instanceLabel,
200
+ vendor: env.descriptorBase.vendor,
201
+ continuityKey: identity.continuityKey,
202
+ endpoints: loopbackEndpoints(env.bound())
203
+ }
204
+ if (env.descriptorBase.icon !== undefined) raw.icon = env.descriptorBase.icon
205
+ try {
206
+ const descriptor = validateDescriptor(raw)
207
+ assertAdvertisesResponder(descriptor, { type: 'http-json', address: `http://${host}` })
208
+ } catch {
209
+ return undefined
210
+ }
211
+ return { raw: raw as unknown as Descriptor }
212
+ }
213
+
214
+ async function describe(ctx: GateContext): Promise<RoutePlan> {
215
+ const { env, req, origin, host } = ctx
216
+ const cors = publicCors(origin)
217
+ if (utf8Length(req.body) > MAX_DESCRIBE_BODY_BYTES) {
218
+ return errorResponse(connectionError('RESOURCE_LIMIT', 'Request body is too large', 'not-sent'), {
219
+ situation: 'bodyTooLarge',
220
+ cors
221
+ })
222
+ }
223
+ const q = parseQuery(ctx.route.query, ['challenge', 'hello'])
224
+ if (!q) return protocolError('Unknown or repeated query parameter', cors)
225
+ const challenge = canonicalB64u32(q.get('challenge'))
226
+ if (challenge === undefined) return protocolError('challenge must be 32 bytes of canonical base64url', cors)
227
+ let hello: string | undefined
228
+ if (q.has('hello')) {
229
+ hello = canonicalB64u32(q.get('hello'))
230
+ if (hello === undefined) return protocolError('hello must be 32 bytes of canonical base64url', cors)
231
+ }
232
+
233
+ const identity = await env.identity(origin)
234
+ const built = buildDescriptor(env, identity, host)
235
+ if (!built) return internalError(cors)
236
+ const { raw } = built
237
+ // Sign the raw object: the page's signature check runs over exactly what was sent.
238
+ const signed = await signDescribe(identity, { origin, challenge, descriptor: raw })
239
+
240
+ const headers = jsonHeaders(cors)
241
+ if (hello !== undefined) {
242
+ const record = env.launches.matchHello({ hello, origin, challenge, host })
243
+ if (record) {
244
+ const ack = describeAck(record.k, {
245
+ wallet: { instanceId: identity.instanceId, continuityKey: identity.continuityKey },
246
+ origin,
247
+ challenge,
248
+ host,
249
+ nonce: record.n
250
+ })
251
+ headers.push(['BRC-185-Android-Ack', ack])
252
+ }
253
+ }
254
+ return respond(STATUS.ok, headers, JSON.stringify(signed))
255
+ }
256
+
257
+ const CONNECT_MAX_BODY_BYTES = 4096
258
+ const CONNECT_MEMBERS = ['epoch', 'challenge', 'instanceId', 'continuityKey', 'android']
259
+ const ANDROID_MEMBERS = ['launchProof', 'reconnectToken']
260
+ const LAUNCH_PROOF_MESSAGE = 'launch proof required'
261
+
262
+ interface ConnectBody {
263
+ epoch: string
264
+ challenge: string
265
+ instanceId: string
266
+ continuityKey: string
267
+ launchProof: string
268
+ reconnectToken?: string
269
+ }
270
+
271
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
272
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
273
+ }
274
+
275
+ /** Exactly the five members, no nulls, no extras; `android` holds `launchProof` and optionally `reconnectToken`. */
276
+ function parseConnectBody(text: string): ConnectBody | undefined {
277
+ let v: unknown
278
+ try {
279
+ v = parseStrictJson(text)
280
+ } catch {
281
+ return undefined
282
+ }
283
+ if (!isPlainObject(v)) return undefined
284
+ const keys = Object.keys(v)
285
+ if (keys.length !== CONNECT_MEMBERS.length || !CONNECT_MEMBERS.every(k => keys.includes(k))) return undefined
286
+ const { epoch, challenge, instanceId, continuityKey, android } = v
287
+ if (typeof epoch !== 'string' || !EPOCH_RE.test(epoch)) return undefined
288
+ if (canonicalB64u32(typeof challenge === 'string' ? challenge : undefined) === undefined) return undefined
289
+ if (typeof instanceId !== 'string' || typeof continuityKey !== 'string') return undefined
290
+ if (!isPlainObject(android)) return undefined
291
+ const akeys = Object.keys(android)
292
+ if (!akeys.every(k => ANDROID_MEMBERS.includes(k)) || !akeys.includes('launchProof')) return undefined
293
+ const { launchProof: proof, reconnectToken } = android
294
+ if (typeof proof !== 'string') return undefined
295
+ if (akeys.includes('reconnectToken') && typeof reconnectToken !== 'string') return undefined
296
+ const out: ConnectBody = {
297
+ epoch,
298
+ challenge: challenge as string,
299
+ instanceId,
300
+ continuityKey,
301
+ launchProof: proof
302
+ }
303
+ if (typeof reconnectToken === 'string') out.reconnectToken = reconnectToken
304
+ return out
305
+ }
306
+
307
+ /** A `respond` plan as a plain response (the connect continuation settles with responses, not plans). */
308
+ function asResponse(p: RoutePlan): RouteResponse {
309
+ if (p.kind !== 'respond') throw new Error('expected an immediate response')
310
+ return { status: p.status, headers: p.headers, body: p.body }
311
+ }
312
+
313
+ /**
314
+ * Connect (spec 6.5 steps 5 to 8, 6.7, 7.5). Everything that can refuse runs before `connectExplicit`, which is
315
+ * the last step of validation; the gate re-check, the snapshot read, `connectExplicit`, `ledger.open`,
316
+ * `unsettledGate.claim` and `session.onConnect` then run in one synchronous turn (Review Focus 6).
317
+ */
318
+ async function connect(ctx: GateContext): Promise<RoutePlan> {
319
+ const { env, req, origin, host } = ctx
320
+ const cors = publicCors(origin)
321
+ const retry: [string, string][] = [['Retry-After', '5']]
322
+
323
+ // 415 before anything is touched; exactly one Content-Type, exactly `application/json`.
324
+ if (ctx.header('content-type') !== 'application/json') {
325
+ return errorResponse(connectionError('PROTOCOL_ERROR', 'Content-Type must be application/json', 'not-sent'), {
326
+ situation: 'unsupportedMediaType',
327
+ cors
328
+ })
329
+ }
330
+ if (utf8Length(req.body) > CONNECT_MAX_BODY_BYTES) {
331
+ return errorResponse(connectionError('RESOURCE_LIMIT', 'Request body is too large', 'not-sent'), {
332
+ situation: 'bodyTooLarge',
333
+ cors
334
+ })
335
+ }
336
+ const body = parseConnectBody(req.body)
337
+ if (!body) return protocolError('Connect body is malformed', cors)
338
+
339
+ // Identity for this origin must be the one the page pinned.
340
+ const identity = await env.identity(origin)
341
+ if (body.instanceId !== identity.instanceId || body.continuityKey !== identity.continuityKey) {
342
+ return errorResponse(
343
+ connectionError('PROVIDER_CHANGED', 'Wallet identity changed', 'not-sent', { epoch: body.epoch }),
344
+ { cors }
345
+ )
346
+ }
347
+ const built = buildDescriptor(env, identity, host)
348
+ if (!built) return internalError(cors)
349
+
350
+ // Unsettled-binding gate, before the launch proof is burnt so a second tab can retry on the same launch.
351
+ if (!env.unsettledGate.check(origin)) {
352
+ return errorResponse(connectionError('RESOURCE_LIMIT', 'Another connection is awaiting approval', 'not-sent'), {
353
+ cors,
354
+ headers: retry
355
+ })
356
+ }
357
+
358
+ // Launch proof: looked up and burnt at arrival, whatever the outcome. One fixed message for every cause.
359
+ const record = env.launches.take(body.epoch)
360
+ const message = record && {
361
+ wallet: { instanceId: identity.instanceId, continuityKey: identity.continuityKey },
362
+ epoch: body.epoch,
363
+ origin,
364
+ challenge: body.challenge,
365
+ host,
366
+ nonce: record.n
367
+ }
368
+ if (!record || !message || !timingSafeEqualB64u(body.launchProof, launchProof(record.k, message))) {
369
+ return errorResponse(connectionError('CONFIGURATION_ERROR', LAUNCH_PROOF_MESSAGE, 'not-sent'), {
370
+ situation: 'launchProof',
371
+ cors
372
+ })
373
+ }
374
+ const k = record.k
375
+
376
+ const finish = async (): Promise<RouteResponse> => {
377
+ // The page left while this connect waited: no binding for a request nobody is waiting on.
378
+ if (env.ledger.isGone(req.id)) {
379
+ env.ledger.clearGone(req.id)
380
+ return asResponse(
381
+ errorResponse(connectionError('CONNECTION_CLOSED', 'Client closed the connection', 'not-sent'), { cors })
382
+ )
383
+ }
384
+ // Synchronous from here to `onConnect`: nothing between the gate check and the claim may yield.
385
+ if (!env.unsettledGate.check(origin)) {
386
+ return asResponse(
387
+ errorResponse(connectionError('RESOURCE_LIMIT', 'Another connection is awaiting approval', 'not-sent'), {
388
+ cors,
389
+ headers: retry
390
+ })
391
+ )
392
+ }
393
+ const snap = env.snapshot()
394
+ try {
395
+ env.connectExplicit({
396
+ epoch: body.epoch,
397
+ transportId: env.transportId,
398
+ applicationOrigin: origin,
399
+ attestation: 'unattested',
400
+ instanceId: identity.instanceId,
401
+ continuityKey: identity.continuityKey,
402
+ accountContext: snap.accountContext,
403
+ walletRevision: snap.walletRevision,
404
+ launchProofVerified: true,
405
+ ...(body.reconnectToken !== undefined ? { reconnectToken: body.reconnectToken } : {})
406
+ })
407
+ } catch (e) {
408
+ if (isConnectionError(e)) return asResponse(errorResponse(e, { cors }))
409
+ return asResponse(internalError(cors))
410
+ }
411
+ const secret = bindingSecret(k, message)
412
+ env.ledger.open(body.epoch, origin, b64uDecode(secret))
413
+ env.unsettledGate.claim(origin, body.epoch)
414
+ env.session.onConnect(body.epoch)
415
+
416
+ try {
417
+ const signed = await signConnect(identity, {
418
+ origin,
419
+ epoch: body.epoch,
420
+ challenge: body.challenge,
421
+ descriptor: built.raw
422
+ })
423
+ const headers = jsonHeaders(cors)
424
+ headers.push(['BRC-185-Android-Ack', connectAck(k, message)])
425
+ return { status: STATUS.ok, headers, body: JSON.stringify(signed) }
426
+ } catch {
427
+ // Signing failed after the binding exists: take it back so the page can start over.
428
+ try {
429
+ env.registry.close(body.epoch, 'disconnected')
430
+ } catch {
431
+ /* the registry already dropped it */
432
+ }
433
+ env.ledger.close(body.epoch)
434
+ env.unsettledGate.release(body.epoch)
435
+ env.session.onBindingClosed(body.epoch)
436
+ return asResponse(internalError(cors))
437
+ }
438
+ }
439
+
440
+ const guarded = async (): Promise<RouteResponse> => {
441
+ try {
442
+ return await finish()
443
+ } catch {
444
+ return asResponse(internalError(cors))
445
+ }
446
+ }
447
+
448
+ const readiness = env.session.readiness()
449
+ if (readiness === 'none-fail') {
450
+ return errorResponse(connectionError('CONFIGURATION_ERROR', 'Wallet is not available', 'not-sent'), {
451
+ situation: 'notBuilt',
452
+ cors
453
+ })
454
+ }
455
+ if (readiness === 'go') return plan(await guarded())
456
+
457
+ // The wallet is not ready: hold the socket and wait to be released (or refused).
458
+ const settled = env.session
459
+ .parkConnect(req.id, origin, body.epoch)
460
+ .then(async (result): Promise<RouteResponse> => {
461
+ if (result === 'resume') return guarded()
462
+ if (result === 'full') {
463
+ return asResponse(
464
+ errorResponse(connectionError('RESOURCE_LIMIT', 'Too many connections are waiting', 'not-sent'), { cors })
465
+ )
466
+ }
467
+ return asResponse(
468
+ errorResponse(connectionError('CONFIGURATION_ERROR', 'Wallet is not available', 'not-sent'), {
469
+ situation: 'notBuilt',
470
+ cors
471
+ })
472
+ )
473
+ })
474
+ .catch(() => asResponse(internalError(cors)))
475
+ return { kind: 'hold', id: req.id, settled }
476
+ }
477
+
478
+ /**
479
+ * The refusal for every way a binding can fail to authorise (spec 6.5 steps 7 and 8): a missing, repeated or wrong
480
+ * header, an unknown or retired epoch, a wrong binding secret, another origin, an identity that does not match. One
481
+ * body for all of them, so a caller who does not hold the secret learns nothing about which epochs exist. No CORS:
482
+ * a page that cannot prove the binding is not owed a readable answer. The epoch is echoed only when it is well formed.
483
+ */
484
+ function unknownBinding(epochHeader: string | undefined): RoutePlan {
485
+ const epoch = epochHeader !== undefined && EPOCH_RE.test(epochHeader) ? epochHeader : undefined
486
+ return errorResponse(connectionError('PROVIDER_CHANGED', 'Unknown connection', 'not-sent', epoch ? { epoch } : {}))
487
+ }
488
+
489
+ interface Authorised {
490
+ epoch: string
491
+ instanceId: string
492
+ continuityKey: string
493
+ /** CORS for the binding's origin: exposes the reconnect token. Only ever built after authorisation. */
494
+ cors: [string, string][]
495
+ }
496
+
497
+ const ZERO_SECRET_B64U = b64uEncode(new Uint8Array(32))
498
+
499
+ /**
500
+ * The four binding headers, the secret in constant time, the origin of the live binding, and the registry's own
501
+ * `resolve`, in that order, all before anything of the body is read. Shared by RPC and DELETE.
502
+ */
503
+ function authorise(ctx: GateContext): { auth: Authorised } | { refuse: RoutePlan } {
504
+ const { env, origin } = ctx
505
+ const epoch = ctx.header('brc-185-epoch')
506
+ const instanceId = ctx.header('brc-185-instance')
507
+ const continuityKey = ctx.header('brc-185-key')
508
+ const presented = ctx.header('brc-185-android-binding')
509
+ const refuse = (): { refuse: RoutePlan } => ({ refuse: unknownBinding(epoch) })
510
+ if (epoch === undefined || instanceId === undefined || continuityKey === undefined || presented === undefined) {
511
+ return refuse()
512
+ }
513
+ const stored = env.ledger.secret(epoch)
514
+ // Compare against a fixed-size dummy when there is no binding, so the work does not depend on the epoch existing.
515
+ const same = timingSafeEqualB64u(presented, stored ? b64uEncode(stored) : ZERO_SECRET_B64U)
516
+ if (!stored || !same) return refuse()
517
+ if (env.ledger.origin(epoch) !== origin) return refuse()
518
+ const resolved = env.registry.resolve(env.transportId, { epoch, instanceId, continuityKey, origin })
519
+ if (isConnectionError(resolved)) return refuse()
520
+ return { auth: { epoch, instanceId, continuityKey, cors: corsHeaders({ origin, kind: 'binding' }) } }
521
+ }
522
+
523
+ function responseSize(text: string): number {
524
+ return utf8Length(text)
525
+ }
526
+
527
+ /** Maps a dispatcher `Outcome` to the HTTP response of spec 6.5 (Outcome mapping) and 6.6.2. */
528
+ function mapOutcome(outcome: Outcome, epoch: string, cors: [string, string][]): RouteResponse {
529
+ if (outcome.ok) {
530
+ let text: string | undefined
531
+ try {
532
+ text = JSON.stringify(outcome.result)
533
+ } catch {
534
+ text = undefined
535
+ }
536
+ if (typeof text !== 'string' || responseSize(text) > MAX_BRIDGE_REQUEST_BYTES) {
537
+ return asResponse(
538
+ errorResponse(connectionError('RESOURCE_LIMIT', 'Response too large', 'unknown', { epoch }), {
539
+ situation: 'oversizeResponse',
540
+ cors
541
+ })
542
+ )
543
+ }
544
+ return { status: STATUS.ok, headers: jsonHeaders(cors), body: text }
545
+ }
546
+ if ('walletError' in outcome) {
547
+ return { status: STATUS.walletError, headers: jsonHeaders(cors), body: JSON.stringify(outcome.walletError) }
548
+ }
549
+ const e = outcome.connectionError
550
+ // The dispatcher reports an oversize result as RESOURCE_LIMIT with delivery 'unknown'; that is the 502 row.
551
+ if (e.code === 'RESOURCE_LIMIT' && e.delivery === 'unknown') {
552
+ return asResponse(errorResponse(e, { situation: 'oversizeResponse', cors }))
553
+ }
554
+ // The dispatcher settles a request parked on a binding that was then closed with DISCONNECTED; the status table
555
+ // has no row for a server-emitted DISCONNECTED, and the connection is closed, so it is the 410 row.
556
+ if (e.code === 'DISCONNECTED') return asResponse(errorResponse(e, { situation: 'connectionClosed', cors }))
557
+ return asResponse(errorResponse(e, { cors }))
558
+ }
559
+
560
+ /** RPC (spec 6.5 step 7). The response is held until the dispatcher's `Outcome` arrives (G5, BRC-219: no deadline). */
561
+ async function rpc(ctx: GateContext): Promise<RoutePlan> {
562
+ const { env, req, origin } = ctx
563
+ const authorised = authorise(ctx)
564
+ if ('refuse' in authorised) return authorised.refuse
565
+ const { epoch, instanceId, continuityKey, cors } = authorised.auth
566
+ const method = ctx.route.segment as string
567
+
568
+ // The token goes on the next response written for this epoch. `take` does not consume it: the controller calls
569
+ // `confirmWritten` once the response head has reached the socket (spec 7.6), so a failed write keeps it.
570
+ const withToken = (r: RouteResponse): RouteResponse => {
571
+ const token = env.tokenOutbox.take(epoch)
572
+ return token === undefined ? r : { ...r, headers: [...r.headers, ['BRC-185-Reconnect-Token', token]] }
573
+ }
574
+ const now = (p: RoutePlan): RoutePlan => (p.kind === 'respond' ? plan(withToken(asResponse(p))) : p)
575
+
576
+ if (ctx.header('content-type') !== 'application/json') {
577
+ return now(
578
+ errorResponse(connectionError('PROTOCOL_ERROR', 'Content-Type must be application/json', 'not-sent', { epoch }), {
579
+ situation: 'unsupportedMediaType',
580
+ cors
581
+ })
582
+ )
583
+ }
584
+ const sizeBytes = utf8Length(req.body)
585
+ if (sizeBytes > MAX_BRIDGE_REQUEST_BYTES) {
586
+ return now(
587
+ errorResponse(connectionError('RESOURCE_LIMIT', 'Request body is too large', 'not-sent', { epoch }), {
588
+ situation: 'bodyTooLarge',
589
+ cors
590
+ })
591
+ )
592
+ }
593
+ let args: unknown
594
+ try {
595
+ args = parseStrictJson(req.body)
596
+ } catch {
597
+ return now(
598
+ errorResponse(connectionError('PROTOCOL_ERROR', 'Request body is not valid JSON', 'not-sent', { epoch }), {
599
+ cors
600
+ })
601
+ )
602
+ }
603
+ if (!isBridgeMethod(method)) {
604
+ return now(
605
+ errorResponse(connectionError('PROTOCOL_ERROR', 'Unknown method', 'not-sent', { epoch }), {
606
+ situation: 'notFound',
607
+ cors
608
+ })
609
+ )
610
+ }
611
+
612
+ const settled = (async (): Promise<RouteResponse> => {
613
+ let counted = false
614
+ let started = false
615
+ try {
616
+ env.ledger.touch(epoch)
617
+ env.ledger.inFlight(epoch, 1)
618
+ counted = true
619
+ const pending = env.dispatch({
620
+ transport: env.transportId,
621
+ request: {
622
+ epoch,
623
+ instanceId,
624
+ continuityKey,
625
+ origin,
626
+ method,
627
+ args,
628
+ sizeBytes,
629
+ // A page that left before the wallet was called never reaches it (spec 6.5, hold-open and client-gone).
630
+ beforeCall: async () => {
631
+ if (env.ledger.isGone(req.id)) {
632
+ throw connectionError('CONNECTION_CLOSED', 'Client closed the connection', 'not-sent', { epoch })
633
+ }
634
+ }
635
+ }
636
+ })
637
+ started = true
638
+ const outcome = await pending
639
+ env.ledger.touch(epoch)
640
+ return withToken(mapOutcome(outcome, epoch, cors))
641
+ } catch {
642
+ // Never the thrown message: it may carry a path or a stack.
643
+ return withToken(
644
+ asResponse(
645
+ errorResponse(
646
+ connectionError('CONFIGURATION_ERROR', 'Internal error', started ? 'unknown' : 'not-sent', { epoch }),
647
+ {
648
+ situation: 'internal',
649
+ cors
650
+ }
651
+ )
652
+ )
653
+ )
654
+ } finally {
655
+ if (counted) {
656
+ try {
657
+ env.ledger.inFlight(epoch, -1)
658
+ env.ledger.clearGone(req.id)
659
+ } catch {
660
+ /* bookkeeping must never turn into an unanswered request */
661
+ }
662
+ }
663
+ }
664
+ })().catch(() => asResponse(internalError(cors)))
665
+ return { kind: 'hold', id: req.id, settled }
666
+ }
667
+
668
+ /** Disconnect (spec 6.5 step 8): the same authorisation, then the binding closes `disconnected`. */
669
+ async function disconnect(ctx: GateContext): Promise<RoutePlan> {
670
+ const { env } = ctx
671
+ const authorised = authorise(ctx)
672
+ if ('refuse' in authorised) return authorised.refuse
673
+ const { epoch, cors } = authorised.auth
674
+ if (ctx.route.segment !== epoch) {
675
+ return errorResponse(connectionError('PROVIDER_CHANGED', 'Unknown connection', 'not-sent', { epoch }), { cors })
676
+ }
677
+ try {
678
+ env.registry.close(epoch, 'disconnected')
679
+ } catch {
680
+ /* already closed: the answer is the same */
681
+ }
682
+ // Same teardown as the failed-connect rollback. Each port call is idempotent, so a registry close listener that
683
+ // does the same work is harmless.
684
+ env.ledger.close(epoch)
685
+ env.unsettledGate.release(epoch)
686
+ env.tokenOutbox.drop(epoch)
687
+ env.session.onBindingClosed(epoch)
688
+ return respond(STATUS.noContent, base(cors), '')
689
+ }
690
+
691
+ export const defaultRoutes: Record<RouteKind, RouteHandler> = {
692
+ describe,
693
+ connect,
694
+ disconnect,
695
+ rpc
696
+ }
697
+
698
+ export function createLoopbackRouter(
699
+ env: RouterEnv,
700
+ routes: Partial<Record<RouteKind, RouteHandler>> = {}
701
+ ): LoopbackRouter {
702
+ const handlers = { ...defaultRoutes, ...routes }
703
+
704
+ async function route(req: RawRequest): Promise<RoutePlan> {
705
+ // Host: Kotlin checked it; the router checks it again against the same bound set. Exactly one, exact match.
706
+ if (count(req.headers, 'host') !== 1 || !isAllowedHost(only(req.headers, 'host'), env.bound())) {
707
+ return emptyResponse(STATUS.forbidden)
708
+ }
709
+ const host = only(req.headers, 'host') as string
710
+
711
+ // Step 1: path allowlist, then verb. No CORS on either.
712
+ const matched = matchTarget(req.target)
713
+ if (!matched) return emptyResponse(STATUS.notFound)
714
+ const verb = verbFor(matched.kind)
715
+ if (req.method !== verb && req.method !== 'OPTIONS') {
716
+ return emptyResponse(STATUS.methodNotAllowed, [['Allow', matched.allow]])
717
+ }
718
+
719
+ // Step 2: Origin present exactly once and canonical. Refusals say nothing, with no CORS.
720
+ if (count(req.headers, 'origin') !== 1) return emptyResponse(STATUS.forbidden)
721
+ let origin: string
722
+ try {
723
+ const value = only(req.headers, 'origin') as string
724
+ origin = canonicalizeBridgeOrigin({
725
+ origin: value,
726
+ attestation: 'unattested',
727
+ allowLocalhostHttp: env.allowLocalhostHttp()
728
+ }).applicationOrigin
729
+ } catch {
730
+ return emptyResponse(STATUS.forbidden)
731
+ }
732
+ // The origin is never taken from a header the page can set freely. No CORS: no page is meant to send these.
733
+ if (count(req.headers, 'originator') > 0 || count(req.headers, 'brc-185-context') > 0) {
734
+ return protocolError('Originator and BRC-185-Context headers are not accepted')
735
+ }
736
+
737
+ // Step 4: preflight. Noninteractive, touches no state; CORS for any origin that passed step 2.
738
+ if (req.method === 'OPTIONS') {
739
+ return respond(
740
+ STATUS.noContent,
741
+ preflightHeaders({
742
+ origin,
743
+ requestHeaders: only(req.headers, 'access-control-request-headers'),
744
+ privateNetwork: only(req.headers, 'access-control-request-private-network') === 'true'
745
+ }),
746
+ ''
747
+ )
748
+ }
749
+
750
+ return handlers[matched.kind]({
751
+ env,
752
+ req,
753
+ route: matched,
754
+ origin,
755
+ host,
756
+ header: name => only(req.headers, name.toLowerCase())
757
+ })
758
+ }
759
+
760
+ return {
761
+ async handle(req) {
762
+ try {
763
+ return await route(req)
764
+ } catch {
765
+ // Nothing here has started a dispatch yet, so the wallet never saw the call.
766
+ return internalError()
767
+ }
768
+ }
769
+ }
770
+ }