@bsv/expo-wallet-toolbox 0.22.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +108 -0
- package/README.md +9 -5
- 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/context/WalletConnectionContext.tsx +7 -1
- package/core/context/WalletContext.tsx +258 -133
- package/core/context/sessionTeardown.ts +46 -0
- package/core/hooks/usePermissionQueue.ts +89 -34
- package/core/i18n/translations.tsx +911 -12
- package/core/index.ts +15 -0
- 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 +10 -0
- package/core/services/walletArgLimits.ts +17 -2
- package/core/storage/encryptedDbImage.ts +325 -0
- package/core/toolboxConfig.ts +18 -1
- package/package.json +6 -6
- package/ui/bridgeSheet/ContextRelay.tsx +86 -0
- package/ui/bridgeSheet/relayedContexts.ts +21 -0
- package/ui/components/ui/PermissionSheet.tsx +534 -158
- package/ui/components/ui/Sheet.tsx +59 -7
- package/ui/components/ui/sheetResumeSignal.ts +19 -0
- package/ui/exportDatabases.ts +94 -5
- package/ui/hooks/useExportWalletData.ts +37 -24
- package/ui/importDatabases.ts +123 -28
- package/ui/index.ts +4 -0
- package/ui/screens/WalletConfigScreen.tsx +13 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,113 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.23.0
|
|
6
|
+
|
|
7
|
+
Peer floors raised to the latest `@bsv` releases, the browser wallet bridge
|
|
8
|
+
(BRC-185 core, Android loopback and iOS Safari seams: #57, #58, #59) and
|
|
9
|
+
encrypted wallet database export/import (#60).
|
|
10
|
+
|
|
11
|
+
### Peers
|
|
12
|
+
|
|
13
|
+
- **Raised floors** to the latest published releases: `@bsv/sdk` ^4.0.1,
|
|
14
|
+
`@bsv/wallet-toolbox-mobile` ^2.15.1, `@bsv/btms-permission-module` ^1.2.4,
|
|
15
|
+
`@bsv/message-box-client` ^2.7.0, `@bsv/webrtpay` ^0.2.3. Hosts copy
|
|
16
|
+
`patches/@bsv+wallet-toolbox-mobile+2.15.1.patch` in place of the 2.15.0 patch
|
|
17
|
+
(same changes, ported onto the 2.15.1 signing guard).
|
|
18
|
+
- `@bsv/backup-cache-client` 0.1.0 still peers `@bsv/sdk` ^2.4.1 (and its
|
|
19
|
+
`@bsv/auth` 0.1.3 peers ^2.1.6). Hosts keep an `overrides` entry for
|
|
20
|
+
`@bsv/sdk` until upstream widens these ranges.
|
|
21
|
+
|
|
22
|
+
### Fixed (review of the Android bridge overlay)
|
|
23
|
+
|
|
24
|
+
- `Sheet`: the open-spring completion no longer re-applies the open position once the sheet has been closed, and a
|
|
25
|
+
non-dismissible sheet hides its backdrop from screen readers.
|
|
26
|
+
- `PermissionSheet`: no longer closes a queue's modal flag itself; the queue does it when it empties, so a request
|
|
27
|
+
enqueued just before an answer cannot be left behind a closed flag.
|
|
28
|
+
|
|
29
|
+
### Browser bridge core
|
|
30
|
+
|
|
31
|
+
- **Transport-agnostic BRC-185 bridge engine** (`core/bridge`): origin rule, site consent with
|
|
32
|
+
reconnect tokens and a fresh grant tag per approval, a separate permissions manager for
|
|
33
|
+
unverified origins, bindings, the 28-method dispatcher, a durable inbox contract and host
|
|
34
|
+
wiring through `BrowserBridgeProvider`. No transport ships yet.
|
|
35
|
+
- **Conformance report.** `buildConformanceReport()` returns a versioned JSON listing the 28
|
|
36
|
+
methods, the bridge's refusals and the recorded deviations from BRC-185 / BRC-219; a snapshot
|
|
37
|
+
test keeps it deliberate.
|
|
38
|
+
|
|
39
|
+
### Browser bridge: seams for the Android loopback kit
|
|
40
|
+
|
|
41
|
+
- **`ContextRelay`** (`ui/bridgeSheet`). `ContextRelayPublisher` (first root, inside the providers) copies the
|
|
42
|
+
contexts `PermissionSheet` reads (`RELAYED_CONTEXTS`: theme, wallet, exchange rate, user) into a module store, and
|
|
43
|
+
`ContextRelaySubscriber` re-provides them on a second React root, rendering nothing until every entry is published.
|
|
44
|
+
A theme change reaches the second root without remounting it. Language is the i18n singleton and is not relayed;
|
|
45
|
+
safe-area insets are per native root and the second root mounts its own provider. A scan test fails when the
|
|
46
|
+
sheet's import closure reads a context that is not listed.
|
|
47
|
+
- **`Sheet` re-applies its open position on mount and on a host signal.** `signalSheetResumed()`
|
|
48
|
+
(`ui/components/ui/sheetResumeSignal`) nudges every open `Sheet`, for a host window that resumes without an
|
|
49
|
+
`AppState` change the sheet can see (the Android bridge's second root). The open spring also re-applies once it settles.
|
|
50
|
+
- **`PermissionSheet backdropDismisses={false}`, `Sheet dismissible={false}`.** `PermissionSheet` treats a backdrop tap
|
|
51
|
+
or a swipe down as a rejection; a host window where an outside tap must do nothing (the Android bridge's overlay root)
|
|
52
|
+
passes `false` on its own instance. A swipe then springs back to the open position instead of leaving the sheet off
|
|
53
|
+
screen. The default is unchanged, and the setting is per instance, not process-wide.
|
|
54
|
+
- **A second request queued behind an answered one is shown.** `PermissionSheet` closed the queue's modal flag after
|
|
55
|
+
every grant or deny, even with another request of the same kind still queued, and the queue only opens that flag when
|
|
56
|
+
it goes from empty to non-empty, so the next request (another site's, or the same site's) stayed hidden and its call
|
|
57
|
+
hung. The flag is now closed only when nothing else is queued behind the answered request.
|
|
58
|
+
|
|
59
|
+
- **`BridgeSnapshot.hostAttached`.** True once a host is attached and the runtime has loaded, false at start and
|
|
60
|
+
after detach. Every change goes through `onSnapshotChange`, so a transport hears attach and detach even when
|
|
61
|
+
readiness stays `none` (a cold start with no wallet).
|
|
62
|
+
- **`assertAdvertisesResponder(descriptor, responder)`** (protocol/descriptor): throws `ProofError` unless a
|
|
63
|
+
`http-json` endpoint of the descriptor has the same scheme, host and port as the responder that answered.
|
|
64
|
+
- **Loopback HTTP router** (`core/bridge/loopback/`): the pure BRC-185 4.1 HTTP semantics for a native loopback
|
|
65
|
+
transport. Router (describe, connect, RPC, disconnect, outcome mapping), Host check, endpoint list, CORS, status table
|
|
66
|
+
and the launch proof MACs (hello, describe ack, launch, ack, binding) with their JCS payloads. Platform code supplies
|
|
67
|
+
requests and receives responses; nothing here opens a socket.
|
|
68
|
+
- **Testing helpers** (`core/bridge/testing`): the `PageClient` contract types and the transport-independent
|
|
69
|
+
conformance cases (all 28 methods, error codec, request and response caps) a transport runs against its executor.
|
|
70
|
+
- **Stable test ids on the connection and permission sheet.** `bridge-connect-origin` (the full origin),
|
|
71
|
+
`bridge-approve` and `bridge-deny` for every prompt kind, for UI automation; no visual change.
|
|
72
|
+
- **Android copy.** `bridge_notifications_off`, `bridge_ports_exhausted` and `bridge_not_ready_android` in all
|
|
73
|
+
12 locales.
|
|
74
|
+
|
|
75
|
+
### Browser bridge: seams for a native transport (iOS Safari kit)
|
|
76
|
+
|
|
77
|
+
- **Exports.** The transport API (inbox processor, store contract, origin constants) is exported for
|
|
78
|
+
a native transport to import, the contract suite `__tests__/bridge/inboxContract` runs against any
|
|
79
|
+
store, and the origin and permission-policy constants moved into a pure module so
|
|
80
|
+
an extension bundle can import them without the app's config.
|
|
81
|
+
- **Events gap and retention.** The inbox event log keeps at most 1024 events and 24 hours; a reader
|
|
82
|
+
that asks after a trimmed cursor gets an explicit gap instead of silence. `flushEvents()` writes
|
|
83
|
+
pending events before a transport reads them. The store contract's raw-bytes hook is owned by the
|
|
84
|
+
harness, not the adapter.
|
|
85
|
+
- **`onPromptRaised`** transport hook: fires when a wallet prompt is raised for a binding, so a
|
|
86
|
+
transport can tell a call needed approval.
|
|
87
|
+
- **Merged Connect sheet.** One sheet lists the site's manifest groups (no toggles) and Connect mints
|
|
88
|
+
every listed item at once; the later group check raises no second sheet. "Don't connect" mints and
|
|
89
|
+
records nothing and starts a 30 second backoff (`RESOURCE_LIMIT`, "This site was just declined").
|
|
90
|
+
Unattested origins keep the plain sheet. New copy in all 12 locales (`bridge_*` keys).
|
|
91
|
+
- **`usePermissionSheetBusy()`** (from `PermissionSheet`): true while a permission sheet is open or
|
|
92
|
+
queued, so a done screen never covers one.
|
|
93
|
+
|
|
94
|
+
### Wallet data export
|
|
95
|
+
|
|
96
|
+
- **Encrypted export.** `exportAllWalletDatabases(storage, { encrypt: true, wallet, originator })`
|
|
97
|
+
writes `wallet-…-<ts>.db.enc`: a random file key wrapped by `wallet.encrypt` (counterparty
|
|
98
|
+
`self`, protocol `[2, 'wallet db export']`), body in 1 MiB AES-256-GCM chunks (STREAM nonces,
|
|
99
|
+
so reordered, dropped or truncated chunks fail). The snapshot comes from `VACUUM INTO` and is
|
|
100
|
+
encrypted a chunk at a time in native AES (`globalThis.__bsvNativeCrypto`), never held whole
|
|
101
|
+
in JS memory. Without `encrypt` the plain `.db` export is unchanged.
|
|
102
|
+
- **Encrypted import.** `importWalletDatabase(storage, { wallet, originator })` accepts `.db.enc`
|
|
103
|
+
up to 2 GiB, decrypting chunk by chunk to a temp file that SQLite opens from disk, then the same
|
|
104
|
+
identity/schema checks as before. Another wallet's file or a damaged one is refused as
|
|
105
|
+
untrusted; the picked copy and decrypted temp file are deleted either way.
|
|
106
|
+
- **UI.** Settings and Vault "Export Wallet Data" now export encrypted; dev builds get an extra
|
|
107
|
+
"Export Wallet Data (unencrypted)" row. `useExportWalletData().exportData({ encrypt })`
|
|
108
|
+
defaults to `true`.
|
|
109
|
+
- New core exports: `encryptDbImage`, `decryptDbImage`, `isEncryptedDbImage`, `EncryptedDbError`.
|
|
110
|
+
|
|
3
111
|
## 0.22.0
|
|
4
112
|
|
|
5
113
|
1Color / BRC-207 tokens through `@bsv/color-permission-module`. There is no
|
package/README.md
CHANGED
|
@@ -57,14 +57,14 @@ Expo SDK line.
|
|
|
57
57
|
|
|
58
58
|
| Package | Version |
|
|
59
59
|
| ------------------------------ | ------- |
|
|
60
|
-
| `@bsv/sdk` | ^4.0.
|
|
61
|
-
| `@bsv/wallet-toolbox-mobile` | ^2.15.
|
|
62
|
-
| `@bsv/btms-permission-module` | ^1.2.
|
|
60
|
+
| `@bsv/sdk` | ^4.0.1 |
|
|
61
|
+
| `@bsv/wallet-toolbox-mobile` | ^2.15.1 |
|
|
62
|
+
| `@bsv/btms-permission-module` | ^1.2.4 |
|
|
63
63
|
| `@bsv/color-permission-module` | ^0.2.0 |
|
|
64
64
|
| `@bsv/mandala` | ^0.5.0 |
|
|
65
65
|
| `@bsv/air-gap` | ^0.1.3 |
|
|
66
66
|
| `@bsv/backup-cache-client` | ^0.1.0 |
|
|
67
|
-
| `@bsv/message-box-client` | ^2.
|
|
67
|
+
| `@bsv/message-box-client` | ^2.7.0 |
|
|
68
68
|
| `@bsv/templates` | ^2.2.0 |
|
|
69
69
|
| `@noble/curves` | ^2.3.0 |
|
|
70
70
|
| `qrcode` | ^1.5.4 |
|
|
@@ -76,10 +76,14 @@ React Native app must alias to `@bsv/wallet-toolbox-mobile` (see
|
|
|
76
76
|
[`metro.config.js`](#metroconfigjs) and [Jest configuration](#jest-configuration)).
|
|
77
77
|
The module also declares `@bsv/wallet-toolbox-client` as a peer; satisfy it
|
|
78
78
|
with an npm alias of the mobile toolbox, e.g.
|
|
79
|
-
`"@bsv/wallet-toolbox-client": "npm:@bsv/wallet-toolbox-mobile@^2.15.
|
|
79
|
+
`"@bsv/wallet-toolbox-client": "npm:@bsv/wallet-toolbox-mobile@^2.15.1"`, so no
|
|
80
80
|
second toolbox is installed. That copy is never loaded (the bundler and Jest
|
|
81
81
|
map the name to `-mobile`), so `patch-package` patches only `-mobile`.
|
|
82
82
|
|
|
83
|
+
The files under this repo's `patches/` are in pnpm format: paths are relative
|
|
84
|
+
to the package root. For `patch-package`, prefix each path with
|
|
85
|
+
`node_modules/<package name>/`.
|
|
86
|
+
|
|
83
87
|
### Expo native modules (required — each needs its own autolinking/config)
|
|
84
88
|
|
|
85
89
|
| Package | Version |
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BrowserBridgeProvider publishes the open wallet to the bridge runtime (spec 6.9).
|
|
3
|
+
*
|
|
4
|
+
* Mount it inside `WalletContextProvider` (opt-in; without it every bridge request fails
|
|
5
|
+
* `CONFIGURATION_ERROR`). It follows the `DirectPayProvider` template: once the wallet is built it
|
|
6
|
+
* reads the identity key from that wallet's manager, derives the account context from it and the
|
|
7
|
+
* network, and keeps the result keyed on the manager's object identity so a rebuilt wallet never
|
|
8
|
+
* publishes the last one's context.
|
|
9
|
+
*
|
|
10
|
+
* It reports, in one place: the attested manager, the unverified one when an unattested transport
|
|
11
|
+
* was registered at build time, readiness, network and account context. What the runtime does with
|
|
12
|
+
* a replaced manager (revision bump, binding close, prompt withdrawal) is in `runtime.ts`.
|
|
13
|
+
*
|
|
14
|
+
* Wiring: as soon as the runtime is loaded it builds the `ConsentStore`, installs the dispatcher
|
|
15
|
+
* on it, registers the store's withdrawal with the runtime and hands the store to the
|
|
16
|
+
* PermissionSheet's `connection` kind. The dispatcher is installed whether or not a wallet is
|
|
17
|
+
* built, so a request that arrives while the wallet is still building parks (6.6) instead of
|
|
18
|
+
* failing. The store reaches the admin-scoped wallet (wrapped exactly as `PairScreen` wraps it for
|
|
19
|
+
* `connectionAuthority`) through a lookup that always reads the current one, and the dispatcher
|
|
20
|
+
* only touches the store once readiness is `ready`. A wallet replacement settles pending consent
|
|
21
|
+
* through the binding close (`account-changed`), not by declining it; unmount withdraws the
|
|
22
|
+
* requests and uninstalls all of it.
|
|
23
|
+
*
|
|
24
|
+
* Readiness: `blocked` while the secrets layer is locked, `ready` once a manager and its account
|
|
25
|
+
* context are in hand, `building` while a build runs or the context is still being derived, and
|
|
26
|
+
* `none` otherwise.
|
|
27
|
+
*/
|
|
28
|
+
import React, { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
29
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
30
|
+
import type { WalletInterface } from '@bsv/sdk'
|
|
31
|
+
import { profileScopedKey } from '../profiles/profileStore'
|
|
32
|
+
import { capWalletArgs } from '../services/capWalletArgs'
|
|
33
|
+
import { guardVaultAccess } from '../services/vault/guard'
|
|
34
|
+
import { getUnlockState, subscribeUnlockState } from '../services/secrets'
|
|
35
|
+
import { useWallet, useWalletManagers, useWalletStatus } from '../context/WalletContext'
|
|
36
|
+
import type { SigningPolicyPermissionsManager } from '../services/signingPermissionPolicy'
|
|
37
|
+
import { createConsentStore, type HmacCapableWallet } from './consent'
|
|
38
|
+
import { mintGrantTag, unverifiedOriginator, isUnattestedOriginator } from './unverifiedOriginator'
|
|
39
|
+
import { createDispatcher, installDispatcher } from './dispatcher'
|
|
40
|
+
import { setConsentSheetSource } from './consentSheetSource'
|
|
41
|
+
import { loadStoredPolicy, resolvePermissionPolicy, type PermissionPolicy } from './permissionPolicy'
|
|
42
|
+
import {
|
|
43
|
+
attachBridgeHost,
|
|
44
|
+
computeAccountContext,
|
|
45
|
+
initBridgeRuntime,
|
|
46
|
+
publish,
|
|
47
|
+
registerConsentWithdrawal,
|
|
48
|
+
setActiveConsent,
|
|
49
|
+
getBridgeSnapshot,
|
|
50
|
+
getPublishedManagers,
|
|
51
|
+
setBridgeBaseVersion,
|
|
52
|
+
type BridgeManager,
|
|
53
|
+
type BridgeReadiness
|
|
54
|
+
} from './runtime'
|
|
55
|
+
|
|
56
|
+
const ACCOUNT_CONTEXT_RETRY_MS = 1000
|
|
57
|
+
const ACCOUNT_CONTEXT_RETRY_MAX_MS = 30_000
|
|
58
|
+
|
|
59
|
+
interface ContextFor {
|
|
60
|
+
signing: SigningPolicyPermissionsManager
|
|
61
|
+
network: string
|
|
62
|
+
value: string
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const BrowserBridgeProvider: React.FC<{ children?: React.ReactNode; baseVersion?: string }> = ({
|
|
66
|
+
children,
|
|
67
|
+
baseVersion
|
|
68
|
+
}) => {
|
|
69
|
+
const { managers, adminOriginator } = useWalletManagers()
|
|
70
|
+
const { walletBuilt, walletBuilding, selectedNetwork } = useWalletStatus()
|
|
71
|
+
const { withdrawPrompts, configStatus } = useWallet()
|
|
72
|
+
const unlock = useSyncExternalStore(subscribeUnlockState, getUnlockState, getUnlockState)
|
|
73
|
+
|
|
74
|
+
// The context value changes on every queue change; teardown needs the current function.
|
|
75
|
+
const withdrawRef = useRef(withdrawPrompts)
|
|
76
|
+
withdrawRef.current = withdrawPrompts
|
|
77
|
+
|
|
78
|
+
// Cold start: until the wallet shell has read its stored config (`configStatus` leaves 'initial'
|
|
79
|
+
// for the first time) it is not yet known whether this install has a wallet, so the bridge
|
|
80
|
+
// reports `building`, never `none` (spec 6.15 item 9). A later 'initial' (after logout) is not a
|
|
81
|
+
// cold start: the ref is cleared for good.
|
|
82
|
+
const coldStartRef = useRef(true)
|
|
83
|
+
if (configStatus !== 'initial') coldStartRef.current = false
|
|
84
|
+
const awaitingConfig = coldStartRef.current
|
|
85
|
+
|
|
86
|
+
const [loaded, setLoaded] = useState(false)
|
|
87
|
+
useEffect(() => {
|
|
88
|
+
let current = true
|
|
89
|
+
const detach = attachBridgeHost({ withdrawPrompts: old => withdrawRef.current(old), hasWallet: true })
|
|
90
|
+
initBridgeRuntime().then(
|
|
91
|
+
() => {
|
|
92
|
+
if (current) setLoaded(true)
|
|
93
|
+
},
|
|
94
|
+
e => console.warn('[BrowserBridgeProvider] runtime did not load:', e instanceof Error ? e.message : String(e))
|
|
95
|
+
)
|
|
96
|
+
return () => {
|
|
97
|
+
current = false
|
|
98
|
+
detach()
|
|
99
|
+
}
|
|
100
|
+
}, [])
|
|
101
|
+
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
if (baseVersion !== undefined) setBridgeBaseVersion(baseVersion)
|
|
104
|
+
}, [baseVersion])
|
|
105
|
+
|
|
106
|
+
const signing = managers.signingPermissionsManager
|
|
107
|
+
const wallet = managers.permissionsManager as unknown as (WalletInterface & object) | undefined
|
|
108
|
+
|
|
109
|
+
// The account context of the wallet it was derived from, never of its predecessor. A failed
|
|
110
|
+
// derivation (a locked keychain, a transient secure-store error) is retried with a growing
|
|
111
|
+
// delay; readiness stays `building` meanwhile, so requests park and the dispatcher's own
|
|
112
|
+
// `wallet-not-ready` nudge stays true.
|
|
113
|
+
const [contextFor, setContextFor] = useState<ContextFor | undefined>(undefined)
|
|
114
|
+
const [contextAttempt, setContextAttempt] = useState(0)
|
|
115
|
+
const contextFailures = useRef(0)
|
|
116
|
+
useEffect(() => {
|
|
117
|
+
if (!loaded || !walletBuilt || !signing || !wallet) return
|
|
118
|
+
let current = true
|
|
119
|
+
let retry: ReturnType<typeof setTimeout> | undefined
|
|
120
|
+
wallet
|
|
121
|
+
.getPublicKey({ identityKey: true }, adminOriginator)
|
|
122
|
+
.then(({ publicKey }) => computeAccountContext(publicKey, selectedNetwork))
|
|
123
|
+
.then(value => {
|
|
124
|
+
contextFailures.current = 0
|
|
125
|
+
if (current) setContextFor({ signing, network: selectedNetwork, value })
|
|
126
|
+
})
|
|
127
|
+
.catch(e => {
|
|
128
|
+
console.warn('[BrowserBridgeProvider] No account context:', e instanceof Error ? e.message : String(e))
|
|
129
|
+
if (!current) return
|
|
130
|
+
const delay = Math.min(
|
|
131
|
+
ACCOUNT_CONTEXT_RETRY_MAX_MS,
|
|
132
|
+
ACCOUNT_CONTEXT_RETRY_MS * 2 ** Math.min(contextFailures.current++, 8)
|
|
133
|
+
)
|
|
134
|
+
retry = setTimeout(() => setContextAttempt(n => n + 1), delay)
|
|
135
|
+
})
|
|
136
|
+
return () => {
|
|
137
|
+
current = false
|
|
138
|
+
if (retry !== undefined) clearTimeout(retry)
|
|
139
|
+
}
|
|
140
|
+
}, [loaded, walletBuilt, signing, wallet, adminOriginator, selectedNetwork, contextAttempt, unlock.status])
|
|
141
|
+
|
|
142
|
+
// The admin-scoped wallet the consent store authenticates with. Read through `adminRef`, so the
|
|
143
|
+
// one store (below) always uses the current wallet and never a stale one.
|
|
144
|
+
const adminWallet = useMemo(
|
|
145
|
+
() => (wallet ? capWalletArgs(guardVaultAccess(wallet, adminOriginator)) : undefined),
|
|
146
|
+
[wallet, adminOriginator]
|
|
147
|
+
)
|
|
148
|
+
const adminRef = useRef(adminWallet)
|
|
149
|
+
adminRef.current = adminWallet
|
|
150
|
+
|
|
151
|
+
// The user's stored prompt policy, as the wallet was built with it: what the sheet discloses.
|
|
152
|
+
const storedPolicyRef = useRef<PermissionPolicy | undefined>(undefined)
|
|
153
|
+
useEffect(() => {
|
|
154
|
+
storedPolicyRef.current = undefined
|
|
155
|
+
if (!loaded || !adminWallet) return
|
|
156
|
+
let current = true
|
|
157
|
+
loadStoredPolicy(profileScopedKey(''), adminWallet, adminOriginator).then(
|
|
158
|
+
p => {
|
|
159
|
+
if (current) storedPolicyRef.current = p
|
|
160
|
+
},
|
|
161
|
+
() => undefined
|
|
162
|
+
)
|
|
163
|
+
return () => {
|
|
164
|
+
current = false
|
|
165
|
+
}
|
|
166
|
+
}, [loaded, adminWallet, adminOriginator])
|
|
167
|
+
|
|
168
|
+
// Consent store and dispatcher, installed once the runtime is loaded and kept across wallet
|
|
169
|
+
// replacements. The store's records are tagged by the admin key, so a different wallet never
|
|
170
|
+
// shares one; the profile key is read live, so the store notices a profile switch that has not
|
|
171
|
+
// yet produced a new wallet.
|
|
172
|
+
useEffect(() => {
|
|
173
|
+
if (!loaded) return
|
|
174
|
+
const lookup = (): HmacCapableWallet => {
|
|
175
|
+
const w = adminRef.current
|
|
176
|
+
if (!w) throw new Error('No wallet is available')
|
|
177
|
+
return w
|
|
178
|
+
}
|
|
179
|
+
const lazyAdmin: HmacCapableWallet = {
|
|
180
|
+
createHmac: (args, originator) => lookup().createHmac(args, originator),
|
|
181
|
+
verifyHmac: (args, originator) => lookup().verifyHmac(args, originator)
|
|
182
|
+
}
|
|
183
|
+
const store = createConsentStore({
|
|
184
|
+
storage: AsyncStorage,
|
|
185
|
+
adminWallet: lazyAdmin,
|
|
186
|
+
adminOriginator,
|
|
187
|
+
profileKey: () => profileScopedKey(''),
|
|
188
|
+
now: () => Date.now(),
|
|
189
|
+
randomBytes: n => globalThis.crypto.getRandomValues(new Uint8Array(n)),
|
|
190
|
+
// The manager that will check the group: the unverified one for an unverified originator.
|
|
191
|
+
mint: async (originator, group) => {
|
|
192
|
+
const published = getPublishedManagers()
|
|
193
|
+
const manager = isUnattestedOriginator(originator) ? published.unverified : published.attested
|
|
194
|
+
if (manager === undefined) throw new Error('No permissions manager to mint under')
|
|
195
|
+
await manager.signing.mintGroupedPermissions(originator, group)
|
|
196
|
+
}
|
|
197
|
+
})
|
|
198
|
+
const unregister = registerConsentWithdrawal(() => store.withdrawAll())
|
|
199
|
+
const unregisterActive = setActiveConsent({
|
|
200
|
+
store,
|
|
201
|
+
adminWallet: lazyAdmin,
|
|
202
|
+
adminOriginator,
|
|
203
|
+
profileKey: () => profileScopedKey('')
|
|
204
|
+
})
|
|
205
|
+
const dispatcher = createDispatcher({
|
|
206
|
+
consent: store,
|
|
207
|
+
previewGroup: async binding => {
|
|
208
|
+
const host = /^https?:\/\/([^/:]+)(?::\d+)?$/.exec(binding.applicationOrigin)?.[1]
|
|
209
|
+
if (host === undefined) return null
|
|
210
|
+
const published = getPublishedManagers()
|
|
211
|
+
// An unverified site's real originator carries a grant tag minted at approval; the
|
|
212
|
+
// preview needs only the hostname, which the unverified manager reads the manifest from.
|
|
213
|
+
const preview =
|
|
214
|
+
binding.attestation === 'unattested'
|
|
215
|
+
? { manager: published.unverified, originator: unverifiedOriginator(host, mintGrantTag()) }
|
|
216
|
+
: { manager: published.attested, originator: host }
|
|
217
|
+
return (await preview.manager?.signing.peekGroupPermissions(preview.originator)) ?? null
|
|
218
|
+
}
|
|
219
|
+
})
|
|
220
|
+
installDispatcher(dispatcher)
|
|
221
|
+
setConsentSheetSource({
|
|
222
|
+
store,
|
|
223
|
+
context: () => ({ walletRevision: Number(getBridgeSnapshot().walletRevision), profileKey: profileScopedKey('') }),
|
|
224
|
+
// The policy the unverified manager was built with (WalletContext): the host's statement
|
|
225
|
+
// plus the user's stored policy.
|
|
226
|
+
policy: () => resolvePermissionPolicy(storedPolicyRef.current)
|
|
227
|
+
})
|
|
228
|
+
return () => {
|
|
229
|
+
store.withdrawAll()
|
|
230
|
+
unregister()
|
|
231
|
+
unregisterActive()
|
|
232
|
+
setConsentSheetSource(undefined)
|
|
233
|
+
installDispatcher(undefined)
|
|
234
|
+
}
|
|
235
|
+
}, [loaded, adminOriginator])
|
|
236
|
+
|
|
237
|
+
const unverifiedSigning = managers.unverifiedSigningPermissionsManager
|
|
238
|
+
const unverifiedWallet = managers.unverifiedPermissionsManager as unknown as WalletInterface | undefined
|
|
239
|
+
|
|
240
|
+
useEffect(() => {
|
|
241
|
+
if (!loaded) return
|
|
242
|
+
const haveWallet = walletBuilt && !!signing && !!wallet
|
|
243
|
+
const accountContext =
|
|
244
|
+
haveWallet && contextFor?.signing === signing && contextFor.network === selectedNetwork ? contextFor.value : ''
|
|
245
|
+
const status = unlock.status
|
|
246
|
+
let readiness: BridgeReadiness
|
|
247
|
+
if (status === 'locked' || status === 'unlocking' || status === 'cancelled') readiness = 'blocked'
|
|
248
|
+
else if (haveWallet && accountContext) readiness = 'ready'
|
|
249
|
+
else if (walletBuilding || haveWallet || awaitingConfig) readiness = 'building'
|
|
250
|
+
else readiness = 'none'
|
|
251
|
+
|
|
252
|
+
const attestedManager: BridgeManager | undefined = haveWallet ? { wallet: wallet!, signing: signing! } : undefined
|
|
253
|
+
const unverifiedManager: BridgeManager | undefined =
|
|
254
|
+
haveWallet && unverifiedSigning && unverifiedWallet
|
|
255
|
+
? { wallet: unverifiedWallet, signing: unverifiedSigning }
|
|
256
|
+
: undefined
|
|
257
|
+
publish({ attestedManager, unverifiedManager, readiness, network: selectedNetwork, accountContext })
|
|
258
|
+
}, [
|
|
259
|
+
loaded,
|
|
260
|
+
walletBuilt,
|
|
261
|
+
walletBuilding,
|
|
262
|
+
awaitingConfig,
|
|
263
|
+
signing,
|
|
264
|
+
wallet,
|
|
265
|
+
unverifiedSigning,
|
|
266
|
+
unverifiedWallet,
|
|
267
|
+
selectedNetwork,
|
|
268
|
+
contextFor,
|
|
269
|
+
unlock.status
|
|
270
|
+
])
|
|
271
|
+
|
|
272
|
+
return <>{children}</>
|
|
273
|
+
}
|