@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
|
@@ -26,6 +26,7 @@ import type { BindValue } from '../storage/methods/offlineActions'
|
|
|
26
26
|
import { PENDING_JOURNAL_KEY } from '../identity/handleRegistry/registration'
|
|
27
27
|
import { PENDING_KEY } from '../localpay/pending'
|
|
28
28
|
import { getOutboxEntriesStrict, unsentEntries } from '../peerpay/outbox'
|
|
29
|
+
import { TERMINAL_TRANSFER_STATES } from '../mandala/types'
|
|
29
30
|
|
|
30
31
|
/** Why a profile cannot be removed. One code per thing found, for the UI to explain. */
|
|
31
32
|
export type RemovalBlocker =
|
|
@@ -87,13 +88,14 @@ export interface AssertProfileEmptyDeps {
|
|
|
87
88
|
*/
|
|
88
89
|
creditInbox: () => Promise<{ attention: number; pending: boolean }>
|
|
89
90
|
/**
|
|
90
|
-
* The Mandala runtime's `balances()`, when this wallet has one
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
* this may be left out.
|
|
91
|
+
* The Mandala runtime's `balances()`, when this wallet has one: exact
|
|
92
|
+
* `bigint` units (W10), `units` from the `p color balance` view and
|
|
93
|
+
* `offlineUnits` from the `color_offline` inventory records. Belt and braces
|
|
94
|
+
* only: the SQL checks on outputs and the `color_transfers` journal are what
|
|
95
|
+
* actually cover tokens, which is why this may be left out. Any figure that
|
|
96
|
+
* is not exactly `0n` — including one that is not a bigint at all — blocks.
|
|
95
97
|
*/
|
|
96
|
-
mandalaBalances?: () => Promise<ReadonlyArray<{
|
|
98
|
+
mandalaBalances?: () => Promise<ReadonlyArray<{ units: bigint; offlineUnits: bigint }>>
|
|
97
99
|
}
|
|
98
100
|
|
|
99
101
|
// Terminal lists, not blocking lists — see the header.
|
|
@@ -103,9 +105,14 @@ const OPEN_TRANSACTIONS =
|
|
|
103
105
|
// Equal to queued/posting/parked/import_hold for every status there is.
|
|
104
106
|
const OPEN_OFFLINE_ACTIONS =
|
|
105
107
|
"SELECT 1 AS found FROM offline_actions WHERE userId = ? AND status NOT IN ('sent', 'rejected', 'acknowledged') LIMIT 1"
|
|
106
|
-
// No userId column: this table is
|
|
107
|
-
|
|
108
|
-
|
|
108
|
+
// The `color_transfers` journal (plan 07 W1). No userId column: this table is
|
|
109
|
+
// one database's worth, and a database is one profile's. Terminal states come
|
|
110
|
+
// from the journal's own list, so a state added later blocks until somebody
|
|
111
|
+
// decides it should not. A file without the table (never booted since the
|
|
112
|
+
// 1Color migration) throws here and reads as `check-failed`: fail closed.
|
|
113
|
+
const OPEN_SETTLEMENTS = `SELECT 1 AS found FROM color_transfers WHERE state NOT IN (${TERMINAL_TRANSFER_STATES.map(
|
|
114
|
+
s => `'${s}'`
|
|
115
|
+
).join(', ')}) LIMIT 1`
|
|
109
116
|
// A corrupt localpay queue is copied here and the live key reset (pending.ts `readAll`).
|
|
110
117
|
const QUARANTINED_PENDING =
|
|
111
118
|
"SELECT 1 AS found FROM key_value_store WHERE key LIKE 'localpay\\_pending\\_corrupt\\_%' ESCAPE '\\' LIMIT 1"
|
|
@@ -169,7 +176,9 @@ export async function assertProfileEmpty(
|
|
|
169
176
|
await check('token-balance', async () => {
|
|
170
177
|
if (!deps.mandalaBalances) return false
|
|
171
178
|
const balances = await deps.mandalaBalances()
|
|
172
|
-
|
|
179
|
+
// `units` already includes the offline part, but the two views are
|
|
180
|
+
// separate snapshots (0207:657-660), so each is checked on its own.
|
|
181
|
+
return balances.some(b => !(b.units === 0n && b.offlineUnits === 0n))
|
|
173
182
|
})
|
|
174
183
|
await check('localpay-pending', () => receivedPaymentsWaiting(storage))
|
|
175
184
|
await check('peerpay-outbox', async () => unsentEntries(await getOutboxEntriesStrict(storage)).length > 0)
|
|
@@ -18,9 +18,11 @@
|
|
|
18
18
|
* ledger to persistent storage.
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
|
+
import { isUnattestedOriginator } from '../bridge/unverifiedOriginator'
|
|
22
|
+
|
|
21
23
|
const DAY_MS = 24 * 60 * 60 * 1000
|
|
22
24
|
|
|
23
|
-
export type AutoApproveReason = 'over-threshold' | 'cooldown' | 'daily-cap' | null
|
|
25
|
+
export type AutoApproveReason = 'over-threshold' | 'cooldown' | 'daily-cap' | 'unattested' | null
|
|
24
26
|
|
|
25
27
|
export interface AutoApproveDecision {
|
|
26
28
|
approve: boolean
|
|
@@ -70,6 +72,9 @@ export function createAutoApprovePolicy(deps: AutoApprovePolicyDeps): AutoApprov
|
|
|
70
72
|
|
|
71
73
|
return {
|
|
72
74
|
shouldAutoApprove({ originator, satoshis }) {
|
|
75
|
+
// An unverified origin may be a local app forging a remembered site: spending always asks.
|
|
76
|
+
if (isUnattestedOriginator(originator)) return { approve: false, reason: 'unattested' }
|
|
77
|
+
|
|
73
78
|
const threshold = deps.threshold()
|
|
74
79
|
if (!(threshold > 0) || satoshis > threshold) {
|
|
75
80
|
return { approve: false, reason: 'over-threshold' }
|
|
@@ -89,6 +94,7 @@ export function createAutoApprovePolicy(deps: AutoApprovePolicyDeps): AutoApprov
|
|
|
89
94
|
},
|
|
90
95
|
|
|
91
96
|
record({ originator, satoshis, at }) {
|
|
97
|
+
if (isUnattestedOriginator(originator)) return
|
|
92
98
|
lastApproveAtByOriginator.set(originator, at)
|
|
93
99
|
ledger.push({ originator, satoshis, at })
|
|
94
100
|
pruneLedger(at)
|
|
@@ -50,7 +50,7 @@ export class WalletArgTooLarge extends Error {
|
|
|
50
50
|
* caller that supplies its own limits never touches it at all, and a failure to
|
|
51
51
|
* read the tier falls back to 'mid' rather than leaving the surface uncapped.
|
|
52
52
|
*/
|
|
53
|
-
function tierLimits(): WalletArgLimits {
|
|
53
|
+
export function tierLimits(): WalletArgLimits {
|
|
54
54
|
try {
|
|
55
55
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
56
56
|
const { getDeviceTier } = require('../deviceTier') as typeof import('../deviceTier')
|
|
@@ -67,6 +67,7 @@ const SIZED = new Set<keyof WalletInterface>([
|
|
|
67
67
|
'createAction',
|
|
68
68
|
'signAction',
|
|
69
69
|
'internalizeAction',
|
|
70
|
+
'acquireCertificate',
|
|
70
71
|
'encrypt',
|
|
71
72
|
'decrypt',
|
|
72
73
|
'createHmac',
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import type { SigningPolicyPermissionsManager } from './signingPermissionPolicy'
|
|
2
|
+
|
|
3
|
+
/** A token module's prompt function (BTMS `promptHandler`, Mandala `requestTokenAccess`). */
|
|
4
|
+
export type TokenPromptHandler = (originator: string, message: string) => Promise<boolean>
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Ties a token-module prompt function to the build that created it. Once the
|
|
8
|
+
* build's manager is retired the wrapper resolves `false` without enqueueing,
|
|
9
|
+
* so a module call that was already inside `onRequest` (mid-lookup) when the
|
|
10
|
+
* wallet was replaced ends with its usual denial instead of raising a sheet
|
|
11
|
+
* for a wallet that is gone. The flag is set in the same synchronous step as
|
|
12
|
+
* `manager.retire()`. A check in the module's `onRequest` wrapper would not be
|
|
13
|
+
* enough: a call already inside it has passed that check.
|
|
14
|
+
*/
|
|
15
|
+
export function guardTokenPromptHandlers(handlers: { btms: TokenPromptHandler; mandala: TokenPromptHandler }): {
|
|
16
|
+
btms: TokenPromptHandler
|
|
17
|
+
mandala: TokenPromptHandler
|
|
18
|
+
/** Hand to `manager.onRetire`. */
|
|
19
|
+
retire: () => void
|
|
20
|
+
} {
|
|
21
|
+
let retired = false
|
|
22
|
+
const guarded = (handler: TokenPromptHandler): TokenPromptHandler => {
|
|
23
|
+
return (originator, message) => (retired ? Promise.resolve(false) : handler(originator, message))
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
btms: guarded(handlers.btms),
|
|
27
|
+
mandala: guarded(handlers.mandala),
|
|
28
|
+
retire: () => {
|
|
29
|
+
retired = true
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The places a withdrawal empties. */
|
|
35
|
+
export interface PromptSinks {
|
|
36
|
+
/** Queues whose items are answered through a manager (protocol, basket, certificate, spending, group). */
|
|
37
|
+
managerQueues: Array<{ clear: () => void }>
|
|
38
|
+
/** Queues whose items hold a promise (BTMS, Mandala); each is resolved `false`. */
|
|
39
|
+
tokenQueues: Array<{ clear: (onEach: (item: { resolve: (approved: boolean) => void }) => void) => void }>
|
|
40
|
+
/** Anything else holding a question for the user (pending connection requests). */
|
|
41
|
+
others: Iterable<() => void>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Withdraws every prompt that belonged to wallets that have gone. The old
|
|
46
|
+
* managers are retired FIRST, synchronously, so a call still parked inside one
|
|
47
|
+
* (on a manifest fetch, the grouped lock, a token lookup) cannot raise a prompt
|
|
48
|
+
* after the sweep; then every request they still hold is denied and every queue
|
|
49
|
+
* is emptied, which also closes the modals and gives focus back.
|
|
50
|
+
*/
|
|
51
|
+
export function withdrawPrompts(oldManagers: SigningPolicyPermissionsManager[], sinks: PromptSinks): void {
|
|
52
|
+
for (const manager of oldManagers) manager.retire()
|
|
53
|
+
for (const manager of oldManagers) manager.denyAllActiveRequests()
|
|
54
|
+
for (const queue of sinks.managerQueues) queue.clear()
|
|
55
|
+
for (const queue of sinks.tokenQueues) queue.clear(item => item.resolve(false))
|
|
56
|
+
for (const other of sinks.others) {
|
|
57
|
+
try {
|
|
58
|
+
other()
|
|
59
|
+
} catch (error) {
|
|
60
|
+
console.warn('[permissions] withdrawing a prompt failed', error)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface SpendingPromptArgs {
|
|
66
|
+
requestID?: string
|
|
67
|
+
originator: string
|
|
68
|
+
reason?: string
|
|
69
|
+
renewal?: boolean
|
|
70
|
+
spending?: { satoshis: number; lineItems?: any[] }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface SpendingPromptDeps<Item> {
|
|
74
|
+
/** Re-reads the persisted auto-approve threshold (an AsyncStorage read). */
|
|
75
|
+
loadThreshold: () => Promise<void>
|
|
76
|
+
/** The auto-approve decision for this spend. */
|
|
77
|
+
decide: (originator: string, satoshis: number) => { approve: boolean; reason?: string | null }
|
|
78
|
+
/** Records an auto-approved spend in the ledger. */
|
|
79
|
+
recordAutoApproved: (originator: string, satoshis: number) => void
|
|
80
|
+
enqueue: (item: Item) => void
|
|
81
|
+
/** Only for a request that arrives without the manager it was raised on. */
|
|
82
|
+
currentManager: () => SigningPolicyPermissionsManager | undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The wallet's reaction to a spending-authorization request: auto-grant a small
|
|
87
|
+
* one, otherwise queue it for the sheet. `manager` is the one the request was
|
|
88
|
+
* raised on (the callback is bound per manager). The threshold read is async,
|
|
89
|
+
* so a withdrawal can land inside it; after it, and before the ledger record,
|
|
90
|
+
* the auto-grant or the enqueue, the manager must still hold the request, or
|
|
91
|
+
* the request is gone and nothing more happens. The auto-grant also targets
|
|
92
|
+
* that same manager: a replacement manager restarts its `spend:…:request:N`
|
|
93
|
+
* counter, so the current one must never be asked to grant an old ID.
|
|
94
|
+
*/
|
|
95
|
+
export async function handleSpendingPrompt<Item>(
|
|
96
|
+
args: SpendingPromptArgs,
|
|
97
|
+
manager: SigningPolicyPermissionsManager | undefined,
|
|
98
|
+
deps: SpendingPromptDeps<Item>
|
|
99
|
+
): Promise<void> {
|
|
100
|
+
const { requestID, originator, reason, renewal, spending } = args
|
|
101
|
+
if (!requestID || !spending) return
|
|
102
|
+
|
|
103
|
+
await deps.loadThreshold()
|
|
104
|
+
if (manager && !manager.hasActiveRequest(requestID)) return
|
|
105
|
+
|
|
106
|
+
const decision = deps.decide(originator, spending.satoshis)
|
|
107
|
+
if (decision.approve) {
|
|
108
|
+
deps.recordAutoApproved(originator, spending.satoshis)
|
|
109
|
+
if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
|
|
110
|
+
const target = manager ?? deps.currentManager()
|
|
111
|
+
target?.grantPermission({ requestID, ephemeral: true, amount: spending.satoshis }).catch(() => {})
|
|
112
|
+
return
|
|
113
|
+
}
|
|
114
|
+
if (__DEV__) {
|
|
115
|
+
console.log(
|
|
116
|
+
`[spend-auth] not eligible (${decision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis}`
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
deps.enqueue({
|
|
121
|
+
requestID,
|
|
122
|
+
originator,
|
|
123
|
+
description: reason,
|
|
124
|
+
transactionAmount: 0,
|
|
125
|
+
totalPastSpending: 0,
|
|
126
|
+
amountPreviouslyAuthorized: 0,
|
|
127
|
+
authorizationAmount: spending.satoshis,
|
|
128
|
+
renewal,
|
|
129
|
+
lineItems: spending.lineItems || [],
|
|
130
|
+
manager
|
|
131
|
+
} as Item)
|
|
132
|
+
}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { Hash, Utils } from '@bsv/sdk'
|
|
2
|
-
import { WalletPermissionsManager } from '@bsv/wallet-toolbox-mobile'
|
|
2
|
+
import { WalletPermissionsManager, type GroupedPermissions } from '@bsv/wallet-toolbox-mobile'
|
|
3
|
+
|
|
4
|
+
/** A site's manifest group request (BRC-73), as the Connect sheet shows it and `mintGroupedPermissions` mints it. */
|
|
5
|
+
export type GroupPermissions = GroupedPermissions
|
|
3
6
|
|
|
4
7
|
/**
|
|
5
8
|
* Protocols a connected app may sign under without a protocol prompt, even
|
|
@@ -92,8 +95,88 @@ interface ManagerInternals {
|
|
|
92
95
|
firePermissionRequestEvent(request: ProtocolRequest, key: string): Promise<void>
|
|
93
96
|
underlying: { verifySignature: WalletPermissionsManager['verifySignature'] }
|
|
94
97
|
fetchManifestPermissions(originator: string): Promise<ManifestPermissions>
|
|
98
|
+
callEvent(eventName: string, param: unknown): Promise<void>
|
|
99
|
+
denyActiveRequest(requestID: string): void
|
|
100
|
+
filterAlreadyGrantedPermissions(originator: string, group: GroupPermissions): Promise<GroupPermissions>
|
|
101
|
+
buildOriginatorLookupValues(displayOriginator: string | undefined, originator: string): unknown
|
|
102
|
+
persistPermissionGrant(toCreate: MintItem[], toRenew: MintItem[]): Promise<void>
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** One permission token to create or renew, as `persistPermissionGrant` takes it. */
|
|
106
|
+
interface MintItem {
|
|
107
|
+
request: Record<string, unknown>
|
|
108
|
+
expiry: number
|
|
109
|
+
amount?: number
|
|
110
|
+
oldToken?: unknown
|
|
95
111
|
}
|
|
96
112
|
|
|
113
|
+
const str = (v: unknown): string => (typeof v === 'string' ? v : '')
|
|
114
|
+
const isObject = (v: unknown): v is Record<string, any> => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The manifest group as a well-formed GroupPermissions, or null when it lists nothing. A site writes
|
|
118
|
+
* the manifest, so every entry is checked: one that does not have the shape the manager reads is
|
|
119
|
+
* left out, and what remains is both what the Connect sheet shows and what Connect mints.
|
|
120
|
+
*/
|
|
121
|
+
function sanitizeGroup(raw: unknown): GroupPermissions | null {
|
|
122
|
+
if (!isObject(raw)) return null
|
|
123
|
+
const group: GroupPermissions = {}
|
|
124
|
+
if (typeof raw.description === 'string') group.description = raw.description
|
|
125
|
+
const spending = raw.spendingAuthorization
|
|
126
|
+
if (isObject(spending) && Number.isSafeInteger(spending.amount) && spending.amount > 0) {
|
|
127
|
+
group.spendingAuthorization = { amount: spending.amount, description: str(spending.description) }
|
|
128
|
+
}
|
|
129
|
+
const list = (v: unknown): any[] => (Array.isArray(v) ? v.filter(isObject) : [])
|
|
130
|
+
group.protocolPermissions = list(raw.protocolPermissions)
|
|
131
|
+
.filter(
|
|
132
|
+
p =>
|
|
133
|
+
Array.isArray(p.protocolID) &&
|
|
134
|
+
p.protocolID.length === 2 &&
|
|
135
|
+
[0, 1, 2].includes(p.protocolID[0]) &&
|
|
136
|
+
typeof p.protocolID[1] === 'string' &&
|
|
137
|
+
(p.counterparty === undefined || typeof p.counterparty === 'string')
|
|
138
|
+
)
|
|
139
|
+
.map(p => ({
|
|
140
|
+
protocolID: [p.protocolID[0], p.protocolID[1]] as [0 | 1 | 2, string],
|
|
141
|
+
...(p.counterparty !== undefined ? { counterparty: p.counterparty as string } : {}),
|
|
142
|
+
description: str(p.description)
|
|
143
|
+
}))
|
|
144
|
+
group.basketAccess = list(raw.basketAccess)
|
|
145
|
+
.filter(b => typeof b.basket === 'string' && b.basket.length > 0)
|
|
146
|
+
.map(b => ({ basket: b.basket as string, description: str(b.description) }))
|
|
147
|
+
group.certificateAccess = list(raw.certificateAccess)
|
|
148
|
+
.filter(
|
|
149
|
+
c =>
|
|
150
|
+
typeof c.type === 'string' &&
|
|
151
|
+
typeof c.verifierPublicKey === 'string' &&
|
|
152
|
+
Array.isArray(c.fields) &&
|
|
153
|
+
c.fields.every((f: unknown) => typeof f === 'string')
|
|
154
|
+
)
|
|
155
|
+
.map(c => ({
|
|
156
|
+
type: c.type as string,
|
|
157
|
+
fields: [...c.fields] as string[],
|
|
158
|
+
verifierPublicKey: c.verifierPublicKey as string,
|
|
159
|
+
description: str(c.description)
|
|
160
|
+
}))
|
|
161
|
+
const empty =
|
|
162
|
+
group.spendingAuthorization === undefined &&
|
|
163
|
+
!group.protocolPermissions.length &&
|
|
164
|
+
!group.basketAccess.length &&
|
|
165
|
+
!group.certificateAccess.length
|
|
166
|
+
return empty ? null : group
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The events that put a question to the user (all carry a `requestID`). A
|
|
170
|
+
* retired manager denies these instead of raising them. */
|
|
171
|
+
const PROMPT_EVENTS = new Set([
|
|
172
|
+
'onProtocolPermissionRequested',
|
|
173
|
+
'onBasketAccessRequested',
|
|
174
|
+
'onCertificateAccessRequested',
|
|
175
|
+
'onSpendingAuthorizationRequested',
|
|
176
|
+
'onGroupedPermissionRequested',
|
|
177
|
+
'onCounterpartyPermissionRequested'
|
|
178
|
+
])
|
|
179
|
+
|
|
97
180
|
/** The parts of a site's manifest.json permissions the manager reads. */
|
|
98
181
|
interface ManifestPermissions {
|
|
99
182
|
groupPermissions: { protocolPermissions?: Array<{ protocolID?: unknown }> } | null
|
|
@@ -134,7 +217,10 @@ function withoutAskEveryTime(manifest: ManifestPermissions): ManifestPermissions
|
|
|
134
217
|
* cover is ever read back for them; a site's manifest never puts them in a
|
|
135
218
|
* grouped request; and one origin's createSignature calls under them run
|
|
136
219
|
* one at a time, so a burst of calls cannot ride on one approval;
|
|
137
|
-
* - a non-privileged verifySignature is never prompted
|
|
220
|
+
* - a non-privileged verifySignature is never prompted;
|
|
221
|
+
* - once retired (its wallet was replaced), it raises no prompt: every prompt
|
|
222
|
+
* event is denied on the spot, so a call still parked inside it ends instead
|
|
223
|
+
* of surfacing a sheet for a wallet that is gone.
|
|
138
224
|
* Every other check runs unchanged.
|
|
139
225
|
*/
|
|
140
226
|
export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
|
|
@@ -142,6 +228,8 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
|
|
|
142
228
|
/** Key ID of the ask-every-time createSignature call each (normalized)
|
|
143
229
|
* origin has in flight. The per-origin queue keeps it to one at a time. */
|
|
144
230
|
private readonly keyIDInFlight = new Map<string, string>()
|
|
231
|
+
private retired = false
|
|
232
|
+
private readonly retireHooks: Array<() => void> = []
|
|
145
233
|
|
|
146
234
|
constructor(...args: ConstructorParameters<typeof WalletPermissionsManager>) {
|
|
147
235
|
super(...args)
|
|
@@ -177,6 +265,22 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
|
|
|
177
265
|
}
|
|
178
266
|
return await firePermissionRequestEvent(request, key)
|
|
179
267
|
}
|
|
268
|
+
// Deny, never throw: a throw out of callEvent would leave the entry its
|
|
269
|
+
// caller registered unsettled (its waiter hangs, and a grouped one holds
|
|
270
|
+
// the per-originator lock). Denying settles the waiter and removes it.
|
|
271
|
+
const callEvent = internals.callEvent.bind(this)
|
|
272
|
+
internals.callEvent = async (eventName, param) => {
|
|
273
|
+
const requestID = (param as { requestID?: unknown } | null | undefined)?.requestID
|
|
274
|
+
if (this.retired && PROMPT_EVENTS.has(eventName) && typeof requestID === 'string') {
|
|
275
|
+
try {
|
|
276
|
+
internals.denyActiveRequest.call(this, requestID)
|
|
277
|
+
} catch {
|
|
278
|
+
// Already settled.
|
|
279
|
+
}
|
|
280
|
+
return
|
|
281
|
+
}
|
|
282
|
+
await callEvent(eventName, param)
|
|
283
|
+
}
|
|
180
284
|
const fetchManifestPermissions = internals.fetchManifestPermissions.bind(this)
|
|
181
285
|
internals.fetchManifestPermissions = async originator =>
|
|
182
286
|
withoutAskEveryTime(await fetchManifestPermissions(originator))
|
|
@@ -186,6 +290,130 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
|
|
|
186
290
|
return this as unknown as ManagerInternals
|
|
187
291
|
}
|
|
188
292
|
|
|
293
|
+
/**
|
|
294
|
+
* One-way: from here on this manager raises no prompt. Call it only on a
|
|
295
|
+
* manager that has been replaced, never on the one just published. `onRetire`
|
|
296
|
+
* hooks run in this same synchronous step.
|
|
297
|
+
*/
|
|
298
|
+
retire(): void {
|
|
299
|
+
if (this.retired) return
|
|
300
|
+
this.retired = true
|
|
301
|
+
for (const hook of this.retireHooks.splice(0)) {
|
|
302
|
+
try {
|
|
303
|
+
hook()
|
|
304
|
+
} catch {
|
|
305
|
+
// A hook must not stop the others.
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
isRetired(): boolean {
|
|
311
|
+
return this.retired
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Runs `hook` when this manager is retired (immediately if it already is). */
|
|
315
|
+
onRetire(hook: () => void): void {
|
|
316
|
+
if (this.retired) hook()
|
|
317
|
+
else this.retireHooks.push(hook)
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The group this origin's manifest asks for, as the later group check will read it: the same
|
|
322
|
+
* `fetchManifestPermissions` and its 5-minute cache, with ask-every-time protocols already
|
|
323
|
+
* filtered (and, on the unverified manager, spending and token modules). Null when there is no
|
|
324
|
+
* manifest, it lists nothing, or the fetch fails. Raises no prompt.
|
|
325
|
+
*/
|
|
326
|
+
async peekGroupPermissions(originator: string): Promise<GroupPermissions | null> {
|
|
327
|
+
try {
|
|
328
|
+
const { normalized } = this.internals.prepareOriginator(originator)
|
|
329
|
+
const { groupPermissions } = await this.internals.fetchManifestPermissions(normalized)
|
|
330
|
+
return sanitizeGroup(groupPermissions)
|
|
331
|
+
} catch {
|
|
332
|
+
return null
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Mints a permission token for every item of `group` that does not already hold one, the way
|
|
338
|
+
* `grantGroupedPermission` does for a granted item, but with no active request to answer. An
|
|
339
|
+
* expired token is renewed. Ask-every-time protocols are never minted. Throws if the mint fails;
|
|
340
|
+
* the caller decides what that means.
|
|
341
|
+
*/
|
|
342
|
+
async mintGroupedPermissions(originator: string, group: GroupPermissions): Promise<void> {
|
|
343
|
+
const i = this.internals
|
|
344
|
+
const { normalized } = i.prepareOriginator(originator)
|
|
345
|
+
const wanted: GroupPermissions = {
|
|
346
|
+
...group,
|
|
347
|
+
protocolPermissions: (group.protocolPermissions ?? []).filter(p => !isAskEveryTimeProtocol(p.protocolID))
|
|
348
|
+
}
|
|
349
|
+
const todo = await i.filterAlreadyGrantedPermissions(normalized, wanted)
|
|
350
|
+
const lookup = i.buildOriginatorLookupValues(originator, normalized)
|
|
351
|
+
const toCreate: MintItem[] = []
|
|
352
|
+
const toRenew: MintItem[] = []
|
|
353
|
+
if (todo.spendingAuthorization != null) {
|
|
354
|
+
toCreate.push({
|
|
355
|
+
request: {
|
|
356
|
+
type: 'spending',
|
|
357
|
+
originator: normalized,
|
|
358
|
+
spending: { satoshis: todo.spendingAuthorization.amount },
|
|
359
|
+
reason: todo.spendingAuthorization.description
|
|
360
|
+
},
|
|
361
|
+
expiry: 0,
|
|
362
|
+
amount: todo.spendingAuthorization.amount
|
|
363
|
+
})
|
|
364
|
+
}
|
|
365
|
+
for (const p of todo.protocolPermissions ?? []) {
|
|
366
|
+
const counterparty = (p.protocolID?.[0] ?? 0) === 1 ? '' : p.counterparty || 'self'
|
|
367
|
+
const request = {
|
|
368
|
+
type: 'protocol',
|
|
369
|
+
originator: normalized,
|
|
370
|
+
privileged: false,
|
|
371
|
+
protocolID: p.protocolID,
|
|
372
|
+
counterparty,
|
|
373
|
+
reason: p.description
|
|
374
|
+
}
|
|
375
|
+
const token = await i.findProtocolToken(normalized, false, p.protocolID, counterparty, true, lookup)
|
|
376
|
+
if (token == null) toCreate.push({ request, expiry: 0 })
|
|
377
|
+
else toRenew.push({ oldToken: token, request, expiry: 0 })
|
|
378
|
+
}
|
|
379
|
+
for (const b of todo.basketAccess ?? []) {
|
|
380
|
+
toCreate.push({
|
|
381
|
+
request: { type: 'basket', originator: normalized, basket: b.basket, reason: b.description },
|
|
382
|
+
expiry: 0
|
|
383
|
+
})
|
|
384
|
+
}
|
|
385
|
+
for (const c of todo.certificateAccess ?? []) {
|
|
386
|
+
toCreate.push({
|
|
387
|
+
request: {
|
|
388
|
+
type: 'certificate',
|
|
389
|
+
originator: normalized,
|
|
390
|
+
privileged: false,
|
|
391
|
+
certificate: { verifier: c.verifierPublicKey, certType: c.type, fields: c.fields },
|
|
392
|
+
reason: c.description
|
|
393
|
+
},
|
|
394
|
+
expiry: 0
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
if (toCreate.length === 0 && toRenew.length === 0) return
|
|
398
|
+
await i.persistPermissionGrant(toCreate, toRenew)
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Whether a prompt with this ID is still waiting for an answer. */
|
|
402
|
+
hasActiveRequest(requestID: string): boolean {
|
|
403
|
+
return this.internals.activeRequests.has(requestID)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Denies every request still waiting for an answer. Never throws. */
|
|
407
|
+
denyAllActiveRequests(): void {
|
|
408
|
+
for (const requestID of [...this.internals.activeRequests.keys()]) {
|
|
409
|
+
try {
|
|
410
|
+
this.internals.denyActiveRequest(requestID)
|
|
411
|
+
} catch {
|
|
412
|
+
// Already settled.
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
189
417
|
override async ensureProtocolPermission(args: EnsureProtocolPermissionArgs): Promise<boolean> {
|
|
190
418
|
if (isPromptFreeSigning(args)) {
|
|
191
419
|
// Still refuse a missing or malformed originator, as the full check
|
|
@@ -120,10 +120,11 @@ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
|
|
|
120
120
|
* own vault code ever reaches it. */
|
|
121
121
|
const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'vault descriptor', 'vault meta'])
|
|
122
122
|
|
|
123
|
-
/**
|
|
124
|
-
*
|
|
125
|
-
* (core/mandala/
|
|
126
|
-
*
|
|
123
|
+
/** The 1Color token protocols (`[2, 'p color <assetTag> <prefix> <suffix>']`)
|
|
124
|
+
* are not reserved here: their `'p '` prefix routes every call under them to
|
|
125
|
+
* the BRC-207 color module (`permissionModules.color`, core/mandala/colorModule.ts),
|
|
126
|
+
* which signs only through a signature envelope binding the signature to a
|
|
127
|
+
* transaction the user approved, and refuses a bare digest (A.13).
|
|
127
128
|
*
|
|
128
129
|
* BRC-29 (`[2, '3241645161d8']`) was reserved here too (XR-020) and is not any
|
|
129
130
|
* more: it is the standard BRC-100 payment protocol, and refusing it broke
|
|
@@ -192,6 +193,11 @@ const CONNECTION_AUTHORITY_PROTOCOL_NAMES = new Set(['connection authority'])
|
|
|
192
193
|
* RPC method, authenticating nothing. */
|
|
193
194
|
const PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES = new Set(['pending abort authority'])
|
|
194
195
|
|
|
196
|
+
/** Browser bridge: the `bridge site authority` namespace tags site-consent records and the
|
|
197
|
+
* stored permission policy (core/bridge/permissionPolicy.ts). Reserved for the same reason as
|
|
198
|
+
* `connection authority`: a connected origin must not be able to mint or verify the tag. */
|
|
199
|
+
const BRIDGE_SITE_AUTHORITY_PROTOCOL_NAMES = new Set(['bridge site authority'])
|
|
200
|
+
|
|
195
201
|
function matchesProtocolNamespace(args: unknown, names: Set<string>): boolean {
|
|
196
202
|
if (args === null || typeof args !== 'object' || Array.isArray(args)) return false
|
|
197
203
|
const protocolID = (args as { protocolID?: unknown }).protocolID
|
|
@@ -210,6 +216,10 @@ function requestsConnectionAuthorityProtocol(args: unknown): boolean {
|
|
|
210
216
|
return matchesProtocolNamespace(args, CONNECTION_AUTHORITY_PROTOCOL_NAMES)
|
|
211
217
|
}
|
|
212
218
|
|
|
219
|
+
function requestsBridgeSiteAuthorityProtocol(args: unknown): boolean {
|
|
220
|
+
return matchesProtocolNamespace(args, BRIDGE_SITE_AUTHORITY_PROTOCOL_NAMES)
|
|
221
|
+
}
|
|
222
|
+
|
|
213
223
|
function requestsPendingAbortAuthorityProtocol(args: unknown): boolean {
|
|
214
224
|
return matchesProtocolNamespace(args, PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES)
|
|
215
225
|
}
|
|
@@ -702,6 +712,7 @@ export function guardVaultAccess<T extends WalletInterface>(
|
|
|
702
712
|
requestsVaultProtocol(args) ||
|
|
703
713
|
requestsConnectionAuthorityProtocol(args) ||
|
|
704
714
|
requestsPendingAbortAuthorityProtocol(args) ||
|
|
715
|
+
requestsBridgeSiteAuthorityProtocol(args) ||
|
|
705
716
|
requestsAddressRailKey(args))
|
|
706
717
|
) {
|
|
707
718
|
return deny(String(method), originator)
|
|
@@ -101,7 +101,7 @@ export interface ArgRefusal {
|
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
/** Calls that can carry transaction bytes. Everything else passes untouched. */
|
|
104
|
-
const SIZED_CALLS = new Set(['createAction', 'signAction', 'internalizeAction'])
|
|
104
|
+
const SIZED_CALLS = new Set(['createAction', 'signAction', 'internalizeAction', 'acquireCertificate'])
|
|
105
105
|
|
|
106
106
|
/**
|
|
107
107
|
* XR-026: these carry only small byte-array fields (a hash, a short
|
|
@@ -132,7 +132,10 @@ const refuse = (field: string, actual: number, limit: number, why?: string): Arg
|
|
|
132
132
|
/** Bytes represented by a hex string, or 0 for anything that is not one. */
|
|
133
133
|
const hexBytes = (v: unknown): number => (typeof v === 'string' ? Math.floor(v.length / 2) : 0)
|
|
134
134
|
|
|
135
|
-
|
|
135
|
+
// Typed arrays and ArrayBuffers are byte arrays too. An in-process caller can pass one, and
|
|
136
|
+
// counting it as zero would let a multi-megabyte inputBEEF past the cap.
|
|
137
|
+
const arrayBytes = (v: unknown): number =>
|
|
138
|
+
Array.isArray(v) ? v.length : ArrayBuffer.isView(v) || v instanceof ArrayBuffer ? v.byteLength : 0
|
|
136
139
|
|
|
137
140
|
const asRecord = (v: unknown): Record<string, unknown> | null =>
|
|
138
141
|
v != null && typeof v === 'object' ? (v as Record<string, unknown>) : null
|
|
@@ -176,6 +179,18 @@ export function checkWalletArgs(call: string, args: unknown, limits: WalletArgLi
|
|
|
176
179
|
try {
|
|
177
180
|
let total = 0
|
|
178
181
|
|
|
182
|
+
// ── acquireCertificate ──
|
|
183
|
+
// Carries only strings. Bound the sum of every field value, keyring value and URL by the
|
|
184
|
+
// aggregate, so a page cannot park megabytes in a certificate request.
|
|
185
|
+
if (call === 'acquireCertificate') {
|
|
186
|
+
const sum = (v: unknown): number => {
|
|
187
|
+
if (typeof v === 'string') return v.length
|
|
188
|
+
const r = asRecord(v)
|
|
189
|
+
return r ? Object.values(r).reduce<number>((n, x) => n + (typeof x === 'string' ? x.length : 0), 0) : 0
|
|
190
|
+
}
|
|
191
|
+
total += sum(a.fields) + sum(a.keyringForSubject) + sum(a.certifierUrl) + sum(a.privilegedReason)
|
|
192
|
+
}
|
|
193
|
+
|
|
179
194
|
// ── internalizeAction ──
|
|
180
195
|
if (call === 'internalizeAction') {
|
|
181
196
|
const tx = arrayBytes(a.tx)
|