@bsv/expo-wallet-toolbox 0.21.0 → 0.22.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 +114 -0
- package/README.md +78 -13
- package/core/contacts/contactActivity.ts +48 -28
- package/core/contacts/contactsStore.ts +2 -2
- package/core/context/WalletContext.tsx +166 -219
- 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/i18n/translations.tsx +72 -0
- package/core/index.ts +55 -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/vault/guard.ts +5 -4
- package/core/storage/StorageExpoSQLite.ts +93 -229
- package/core/storage/methods/processOfflineActions.ts +86 -136
- package/core/storage/schema/createTables.ts +9 -184
- package/package.json +6 -5
- 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 +94 -160
- package/ui/components/ui/colorPrompt.ts +236 -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/hooks/useMandala.ts +6 -6
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/importDatabases.ts +1 -1
- package/ui/screens/PayScreen.tsx +14 -20
- package/ui/screens/SettingsScreen.tsx +3 -1
- package/ui/screens/WalletCheckScreen.tsx +7 -2
- 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
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Guard #4: a settled token payment
|
|
2
|
+
* Guard #4: the action behind a handed-over or settled token payment may not
|
|
3
|
+
* be aborted.
|
|
3
4
|
*
|
|
4
5
|
* THE 2026-09-15 INCIDENT, in one paragraph. A token transfer is built and
|
|
5
6
|
* signed `noSend`, handed to the payee, and only then submitted to the issuer's
|
|
@@ -18,11 +19,19 @@
|
|
|
18
19
|
* the action for an abandoned `noSend` because our
|
|
19
20
|
* `StorageExpoSQLite.attemptToPostReqsToNetwork` HOLDS token requests rather
|
|
20
21
|
* than posting them, so the lib's journal entry had been cleared as "broadcast"
|
|
21
|
-
* when nothing had been. Three fixes
|
|
22
|
-
* entry, `reconcileJournals` no longer
|
|
22
|
+
* when nothing had been. Three fixes met here — the lib no longer cleared that
|
|
23
|
+
* entry, `reconcileJournals` no longer ran the sweep at all, and this guard
|
|
23
24
|
* makes the abort itself unreachable from any caller, including one we have
|
|
24
25
|
* not thought of.
|
|
25
26
|
*
|
|
27
|
+
* 1Color (plan 07, W1): the decision is now keyed on the wallet's one durable
|
|
28
|
+
* host record, the `color_transfers` journal, looked up by the `createAction`
|
|
29
|
+
* reference that built the tx. The four σI settlement tables are gone (Task 6
|
|
30
|
+
* dropped them with no legacy rows left behind), so the old coarse "any
|
|
31
|
+
* reference-less legacy row in a blocked state" check (XR-033) has nothing to
|
|
32
|
+
* read and is removed. The guard never reads the color module's internal
|
|
33
|
+
* `color.v1.*` keys (IC §2.1: that layout is T2-internal).
|
|
34
|
+
*
|
|
26
35
|
* **The guard is a refusal, not a repair.** It answers `{ aborted: false }`,
|
|
27
36
|
* which is exactly what `abortAction` already returns for an action it will not
|
|
28
37
|
* abort, and every existing caller in this wallet already treats that as a
|
|
@@ -30,37 +39,35 @@
|
|
|
30
39
|
* `finalizeDelivery`'s `queueFailedAbort`). It never throws: a throw from a
|
|
31
40
|
* cleanup path is how a caller ends up abandoning something it was tidying.
|
|
32
41
|
*/
|
|
33
|
-
import type {
|
|
42
|
+
import type { TransferJournal } from './transferJournal'
|
|
43
|
+
import type { ColorTransferRow, ColorTransferState } from './types'
|
|
34
44
|
|
|
35
45
|
/**
|
|
36
|
-
*
|
|
37
|
-
* cannot recall them from.
|
|
46
|
+
* Journal states in which the bytes are, or may already be, somewhere this
|
|
47
|
+
* device cannot recall them from.
|
|
38
48
|
*
|
|
39
|
-
* `handed_over
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
49
|
+
* `handed_over` is in the list whatever `delivered` says (W4). On the handle
|
|
50
|
+
* rail the row moves to `handed_over` BEFORE `deliverHandover` runs, because a
|
|
51
|
+
* lost MessageBox response may still have delivered; on the nearby rail the
|
|
52
|
+
* payee holds the frame. Either way the payee may submit it, and releasing the
|
|
53
|
+
* inputs under a payee who is about to submit is the incident's double spend,
|
|
54
|
+
* only with a longer fuse. `settled` is the overlay's admission, which
|
|
55
|
+
* broadcasts — the incident's own state.
|
|
45
56
|
*
|
|
46
57
|
* Everything else is safe to abort, and deliberately so:
|
|
47
|
-
* · `built`/`parked` — the payer's own states
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* · `refused`/`
|
|
51
|
-
*
|
|
58
|
+
* · `built`/`parked` — the payer's own states. The payee has NOT been handed
|
|
59
|
+
* anything, nothing has been submitted, and cancelling a parked payment is a
|
|
60
|
+
* feature (`cancelParkedPayment`) that must keep working.
|
|
61
|
+
* · `refused`/`cancelled` — a final word that the money never moved. The
|
|
62
|
+
* inputs SHOULD come back.
|
|
63
|
+
* · `held` is a received-role state; a received row carries no `reference`,
|
|
64
|
+
* so no abort can ever name it.
|
|
52
65
|
*/
|
|
53
|
-
export const
|
|
54
|
-
'held',
|
|
55
|
-
'handed_over',
|
|
56
|
-
'submitting',
|
|
57
|
-
'admitted',
|
|
58
|
-
'broadcast'
|
|
59
|
-
]
|
|
66
|
+
export const ABORT_BLOCKED_TRANSFER_STATES: readonly ColorTransferState[] = ['handed_over', 'settled']
|
|
60
67
|
|
|
61
|
-
export function abortIsBlockedBy(row:
|
|
68
|
+
export function abortIsBlockedBy(row: ColorTransferRow | undefined): boolean {
|
|
62
69
|
if (!row) return false
|
|
63
|
-
return
|
|
70
|
+
return ABORT_BLOCKED_TRANSFER_STATES.includes(row.state)
|
|
64
71
|
}
|
|
65
72
|
|
|
66
73
|
/** The shape this wrapper needs of a manager. Structural, so a test can pass a plain object. */
|
|
@@ -69,121 +76,95 @@ export interface AbortableManager {
|
|
|
69
76
|
}
|
|
70
77
|
|
|
71
78
|
/**
|
|
72
|
-
* Where the
|
|
79
|
+
* Where the journal lives, read LATE.
|
|
73
80
|
*
|
|
74
|
-
* A function rather than a
|
|
75
|
-
* published permissions manager while the
|
|
76
|
-
* it — and is replaced wholesale on a network switch or a wallet
|
|
77
|
-
* Capturing a
|
|
78
|
-
* `undefined`
|
|
79
|
-
*
|
|
81
|
+
* A function rather than a journal, because the wrapper is built once around
|
|
82
|
+
* the published permissions manager while the token runtime is constructed
|
|
83
|
+
* after it — and is replaced wholesale on a network switch or a wallet
|
|
84
|
+
* rebuild. Capturing a journal here would guard the departed wallet's table.
|
|
85
|
+
* Returning `undefined` is NOT "no payment at stake" on its own; see
|
|
86
|
+
* `TokenSettlementPossible`.
|
|
80
87
|
*/
|
|
81
|
-
export type
|
|
82
|
-
| Pick<SettlementStore, 'getSettlementByReference' | 'hasUnresolvedLegacyBlockedRows'>
|
|
83
|
-
| undefined
|
|
88
|
+
export type TransferJournalLookup = () => Pick<TransferJournal, 'getByReference'> | undefined
|
|
84
89
|
|
|
85
90
|
/**
|
|
86
91
|
* Whether a token payment could exist on THIS wallet build at all — read LATE,
|
|
87
|
-
* for the same reason
|
|
92
|
+
* for the same reason the journal is, and answering ONLY the question of
|
|
88
93
|
* whether the current chain's configuration could ever have written a
|
|
89
|
-
* `
|
|
94
|
+
* `color_transfers` row.
|
|
90
95
|
*
|
|
91
|
-
* XR-034 (SEC1-024 / SEC2-038). `
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
* construction, so no token action has ever existed here, or ever can.
|
|
98
|
-
* 2. `createMandalaRuntime` THREW while endpoints exist (WalletContext.tsx's
|
|
99
|
-
* catch around the construction), or a network switch/rebuild has
|
|
96
|
+
* XR-034 (SEC1-024 / SEC2-038). `journal()` answering `undefined` is not one
|
|
97
|
+
* fact. It reads `undefined` in situations that mean opposite things for
|
|
98
|
+
* safety:
|
|
99
|
+
* 1. This chain has no Mandala endpoints at all, so no token action has ever
|
|
100
|
+
* existed here, or ever can.
|
|
101
|
+
* 2. The runtime THREW while endpoints exist, or a network switch/rebuild has
|
|
100
102
|
* cleared the ref ahead of the new build's runtime replacing it. Either
|
|
101
|
-
* way the chain's own storage may still carry a `handed_over`/`
|
|
102
|
-
*
|
|
103
|
-
* call simply cannot see it right now.
|
|
103
|
+
* way the chain's own storage may still carry a `handed_over`/`settled`
|
|
104
|
+
* row; this call simply cannot see it right now.
|
|
104
105
|
*
|
|
105
|
-
* Only case 1 licenses treating `undefined` as "no row, safe". WalletContext
|
|
106
|
-
* wires this to
|
|
107
|
-
*
|
|
108
|
-
* build failures, or rebuild timing the way `mandalaRef.current` does.
|
|
106
|
+
* Only case 1 licenses treating `undefined` as "no row, safe". WalletContext
|
|
107
|
+
* wires this to a static fact of the chain's own configuration that does not
|
|
108
|
+
* fluctuate with runtime construction, build failures, or rebuild timing.
|
|
109
109
|
*/
|
|
110
110
|
export type TokenSettlementPossible = () => boolean
|
|
111
111
|
|
|
112
112
|
/**
|
|
113
|
-
* Wrap `abortAction` so an action that built a token transaction the
|
|
114
|
-
* may already have cannot release its inputs.
|
|
113
|
+
* Wrap `abortAction` so an action that built a token transaction the payee or
|
|
114
|
+
* the overlay may already have cannot release its inputs.
|
|
115
115
|
*
|
|
116
|
-
* Same pattern and same placement as
|
|
116
|
+
* Same pattern and same placement as the createAction input wrapper: it wraps
|
|
117
117
|
* the RAW permissions manager and `guardVaultAccess` is applied to the RESULT,
|
|
118
118
|
* so the published object is still the one the guard's own re-wrap dedup
|
|
119
119
|
* recognises. Every other method and property passes through untouched.
|
|
120
120
|
*
|
|
121
121
|
* **XR-034: fails CLOSED on anything but a definitive "no".** A database that
|
|
122
|
-
* will not answer, a
|
|
123
|
-
*
|
|
124
|
-
* are exactly the moments this device can least tell, which is
|
|
125
|
-
* evidence that releasing inputs is safe. Refusing the abort in
|
|
126
|
-
* costs a retry (every caller already treats `{ aborted: false }`
|
|
127
|
-
* release, try again" — see `queueFailedAbort`); wrongly granting
|
|
128
|
-
* double spend. The one shape that still passes through when
|
|
129
|
-
* answers `undefined` is `tokenSettlementPossible()` reporting
|
|
130
|
-
* with no Mandala configuration at all, where a blocking row
|
|
131
|
-
* been written and refusing every plain BSV abort forever
|
|
132
|
-
* outage.
|
|
133
|
-
*
|
|
134
|
-
* **XR-033, a second and coarser check.** A row that predates the `reference`
|
|
135
|
-
* column (or whose backfill at migration time could not resolve one — see
|
|
136
|
-
* `createTables.ts`'s `ensureTokenSettlementColumns`) reads back with
|
|
137
|
-
* `reference === undefined` forever, which the lookup above can never match
|
|
138
|
-
* against ANY reference — so a legacy row stuck in a blocked state is
|
|
139
|
-
* invisible to it no matter which action is being aborted. `hasUnresolvedLegacyBlockedRows`
|
|
140
|
-
* asks the coarser question instead: does ANY such row exist at all. It only
|
|
141
|
-
* ever narrows an abort from allowed to refused, never the reverse, and (like
|
|
142
|
-
* the lookup above) now fails CLOSED on its own read fault, for the same
|
|
143
|
-
* reason.
|
|
122
|
+
* will not answer, a runtime that has not been built yet, one mid-rebuild, and
|
|
123
|
+
* a lookup that itself throws are all indistinguishable from "a payment is in
|
|
124
|
+
* flight" — they are exactly the moments this device can least tell, which is
|
|
125
|
+
* the opposite of evidence that releasing inputs is safe. Refusing the abort in
|
|
126
|
+
* that window costs a retry (every caller already treats `{ aborted: false }`
|
|
127
|
+
* as "did not release, try again" — see `queueFailedAbort`); wrongly granting
|
|
128
|
+
* it costs a double spend. The one shape that still passes through when
|
|
129
|
+
* `journal()` answers `undefined` is `tokenSettlementPossible()` reporting
|
|
130
|
+
* false: a chain with no Mandala configuration at all, where a blocking row
|
|
131
|
+
* could never have been written and refusing every plain BSV abort forever
|
|
132
|
+
* would be its own outage.
|
|
144
133
|
*/
|
|
145
134
|
export function wrapAbortActionForSettlements<T extends AbortableManager>(
|
|
146
135
|
manager: T,
|
|
147
|
-
|
|
136
|
+
journal: TransferJournalLookup,
|
|
148
137
|
tokenSettlementPossible: TokenSettlementPossible
|
|
149
138
|
): T {
|
|
150
139
|
return new Proxy(manager, {
|
|
151
140
|
get(target, prop, receiver) {
|
|
152
141
|
if (prop === 'abortAction') {
|
|
153
142
|
return async (args: { reference: string }, originator?: string) => {
|
|
154
|
-
const store = settlements()
|
|
155
|
-
if (!store) {
|
|
156
|
-
if (tokenSettlementPossible()) {
|
|
157
|
-
console.warn(
|
|
158
|
-
'[mandala] refusing to abort: token settlement state is unavailable right now ' +
|
|
159
|
-
'(the runtime is not built, is rebuilding, or its store could not be reached) and this ' +
|
|
160
|
-
'chain can carry token payments — releasing inputs could double spend one the overlay already has'
|
|
161
|
-
)
|
|
162
|
-
return { aborted: false }
|
|
163
|
-
}
|
|
164
|
-
// No Mandala endpoints on this chain: a blocking row could never
|
|
165
|
-
// have been written, so this is a plain BSV abort like any other.
|
|
166
|
-
return await target.abortAction(args, originator)
|
|
167
|
-
}
|
|
168
143
|
try {
|
|
169
|
-
const
|
|
170
|
-
if (
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
'
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
)
|
|
183
|
-
|
|
144
|
+
const current = journal()
|
|
145
|
+
if (!current) {
|
|
146
|
+
if (tokenSettlementPossible()) {
|
|
147
|
+
console.warn(
|
|
148
|
+
'[mandala] refusing to abort: the token transfer journal is unavailable right now ' +
|
|
149
|
+
'(the runtime is not built, is rebuilding, or its database could not be reached) and this ' +
|
|
150
|
+
'chain can carry token payments — releasing inputs could double spend one the payee or overlay already has'
|
|
151
|
+
)
|
|
152
|
+
return { aborted: false }
|
|
153
|
+
}
|
|
154
|
+
// No Mandala endpoints on this chain: a blocking row could never
|
|
155
|
+
// have been written, so this is a plain BSV abort like any other.
|
|
156
|
+
} else {
|
|
157
|
+
const row = await lookupTransfer(current, args?.reference)
|
|
158
|
+
if (abortIsBlockedBy(row)) {
|
|
159
|
+
console.warn(
|
|
160
|
+
`[mandala] refusing to abort ${row!.txid}: its token transfer is '${row!.state}', ` +
|
|
161
|
+
'so releasing these inputs would double spend a transaction the payee or overlay may already have'
|
|
162
|
+
)
|
|
163
|
+
return { aborted: false }
|
|
164
|
+
}
|
|
184
165
|
}
|
|
185
166
|
} catch (e) {
|
|
186
|
-
console.warn("[mandala] refusing to abort: could not read this action's
|
|
167
|
+
console.warn("[mandala] refusing to abort: could not read this action's token transfer state:", e)
|
|
187
168
|
return { aborted: false }
|
|
188
169
|
}
|
|
189
170
|
return await target.abortAction(args, originator)
|
|
@@ -195,16 +176,12 @@ export function wrapAbortActionForSettlements<T extends AbortableManager>(
|
|
|
195
176
|
}) as T
|
|
196
177
|
}
|
|
197
178
|
|
|
198
|
-
async function
|
|
199
|
-
|
|
179
|
+
async function lookupTransfer(
|
|
180
|
+
journal: Pick<TransferJournal, 'getByReference'>,
|
|
200
181
|
reference: string | undefined
|
|
201
|
-
): Promise<
|
|
182
|
+
): Promise<ColorTransferRow | undefined> {
|
|
183
|
+
// No reference names no journal row: the underlying abortAction refuses it
|
|
184
|
+
// on its own, and no token action is ever built without one.
|
|
202
185
|
if (!reference) return undefined
|
|
203
|
-
return await
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
async function hasUnresolvedLegacyBlockedRow(
|
|
207
|
-
store: Pick<SettlementStore, 'hasUnresolvedLegacyBlockedRows'>
|
|
208
|
-
): Promise<boolean> {
|
|
209
|
-
return await store.hasUnresolvedLegacyBlockedRows()
|
|
186
|
+
return await journal.getByReference(reference)
|
|
210
187
|
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { ColorTokenAccessHandler } from '@bsv/color-permission-module'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Every consent message type the color module 0.2.0 sends. B7 removed
|
|
5
|
+
* `color_receive_offline` (the module transports and validates no history),
|
|
6
|
+
* so a message naming it is an unknown type and fails closed.
|
|
7
|
+
*/
|
|
8
|
+
export type ColorPromptType = 'color_send' | 'color_signature' | 'color_access' | 'color_relinquish'
|
|
9
|
+
|
|
10
|
+
export const COLOR_PROMPT_TYPES: readonly ColorPromptType[] = [
|
|
11
|
+
'color_send',
|
|
12
|
+
'color_signature',
|
|
13
|
+
'color_access',
|
|
14
|
+
'color_relinquish'
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
export interface ColorAccessPolicyOptions {
|
|
18
|
+
/** The wallet's own originator. Its screens are the consent surface (W2). */
|
|
19
|
+
adminOriginator: string
|
|
20
|
+
/** Shows the request to the user and resolves true only on an explicit approval. */
|
|
21
|
+
prompt: (originator: string, message: string) => Promise<boolean>
|
|
22
|
+
now?: () => number
|
|
23
|
+
/** How long a `color_access` approval covers further reads by the same originator. */
|
|
24
|
+
readGrantMs?: number /* default 1_800_000 */
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const DEFAULT_READ_GRANT_MS = 1_800_000
|
|
28
|
+
|
|
29
|
+
/** The message's `type` when it is a JSON object naming a known consent type, else undefined. */
|
|
30
|
+
export function colorPromptType(message: string): { type: ColorPromptType; seekPermission: boolean } | undefined {
|
|
31
|
+
let parsed: unknown
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(message)
|
|
34
|
+
} catch {
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
|
|
38
|
+
const { type, seekPermission } = parsed as { type?: unknown; seekPermission?: unknown }
|
|
39
|
+
if (typeof type !== 'string' || !(COLOR_PROMPT_TYPES as readonly string[]).includes(type)) return undefined
|
|
40
|
+
// The module always sends a boolean; anything but an explicit false may prompt (`!== false`, IC §2.5).
|
|
41
|
+
return { type: type as ColorPromptType, seekPermission: seekPermission !== false }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The host's `requestTokenAccess` for the color module.
|
|
46
|
+
*
|
|
47
|
+
* - An unreadable message or an unknown type is refused for everyone, without a prompt.
|
|
48
|
+
* - `adminOriginator` is approved for every known type without a prompt (W2).
|
|
49
|
+
* - Only `color_access` (a read) can be answered from a grant: an approval leaves a
|
|
50
|
+
* `readGrantMs` grant for that originator alone. Spend, signature, relinquish and
|
|
51
|
+
* offline-credit requests prompt every time, and their approvals grant nothing (C10).
|
|
52
|
+
* - `seekPermission: false` with no live grant refuses without a prompt.
|
|
53
|
+
* - Anything but a literal `true` from the prompt, including a rejection, is a refusal.
|
|
54
|
+
*
|
|
55
|
+
* Concurrent reads by one originator (two tabs, a list racing a balance) share one
|
|
56
|
+
* prompt, so the user answers once; the grant then covers the rest.
|
|
57
|
+
*/
|
|
58
|
+
export function createColorAccessPolicy(
|
|
59
|
+
o: ColorAccessPolicyOptions
|
|
60
|
+
): ColorTokenAccessHandler & { clearGrants(): void } {
|
|
61
|
+
if (typeof o?.adminOriginator !== 'string' || o.adminOriginator.length === 0) {
|
|
62
|
+
throw new TypeError('createColorAccessPolicy: adminOriginator is required')
|
|
63
|
+
}
|
|
64
|
+
if (typeof o.prompt !== 'function') throw new TypeError('createColorAccessPolicy: prompt is required')
|
|
65
|
+
const readGrantMs = o.readGrantMs ?? DEFAULT_READ_GRANT_MS
|
|
66
|
+
if (typeof readGrantMs !== 'number' || !Number.isFinite(readGrantMs) || readGrantMs < 0) {
|
|
67
|
+
throw new TypeError('createColorAccessPolicy: readGrantMs must be a finite number >= 0')
|
|
68
|
+
}
|
|
69
|
+
const { adminOriginator, prompt } = o
|
|
70
|
+
const now = o.now ?? Date.now
|
|
71
|
+
|
|
72
|
+
/** originator → time the read grant was given. */
|
|
73
|
+
const readGrants = new Map<string, number>()
|
|
74
|
+
/** originator → the read prompt in flight, shared by concurrent reads. */
|
|
75
|
+
const readPrompts = new Map<string, Promise<boolean>>()
|
|
76
|
+
/** Bumped by clearGrants, so a prompt answered after a clear grants nothing. */
|
|
77
|
+
let generation = 0
|
|
78
|
+
|
|
79
|
+
const hasReadGrant = (originator: string): boolean => {
|
|
80
|
+
const grantedAt = readGrants.get(originator)
|
|
81
|
+
if (grantedAt === undefined) return false
|
|
82
|
+
const elapsed = now() - grantedAt
|
|
83
|
+
// A clock that went backwards proves nothing about the grant's age: fail closed.
|
|
84
|
+
if (elapsed >= 0 && elapsed < readGrantMs) return true
|
|
85
|
+
readGrants.delete(originator)
|
|
86
|
+
return false
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const ask = async (originator: string, message: string): Promise<boolean> => {
|
|
90
|
+
try {
|
|
91
|
+
return (await prompt(originator, message)) === true
|
|
92
|
+
} catch {
|
|
93
|
+
return false
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const askRead = (originator: string, message: string): Promise<boolean> => {
|
|
98
|
+
const inFlight = readPrompts.get(originator)
|
|
99
|
+
if (inFlight !== undefined) return inFlight
|
|
100
|
+
const asked = generation
|
|
101
|
+
const answer = ask(originator, message).then(approved => {
|
|
102
|
+
if (approved && asked === generation) readGrants.set(originator, now())
|
|
103
|
+
return approved
|
|
104
|
+
})
|
|
105
|
+
readPrompts.set(originator, answer)
|
|
106
|
+
const release = (): void => {
|
|
107
|
+
if (readPrompts.get(originator) === answer) readPrompts.delete(originator)
|
|
108
|
+
}
|
|
109
|
+
answer.then(release, release)
|
|
110
|
+
return answer
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const policy = async (app: string, message: string): Promise<boolean> => {
|
|
114
|
+
if (typeof app !== 'string' || typeof message !== 'string') return false
|
|
115
|
+
const request = colorPromptType(message)
|
|
116
|
+
if (request === undefined) return false
|
|
117
|
+
if (app === adminOriginator) return true
|
|
118
|
+
if (request.type === 'color_access') {
|
|
119
|
+
if (hasReadGrant(app)) return true
|
|
120
|
+
if (!request.seekPermission) return false
|
|
121
|
+
return await askRead(app, message)
|
|
122
|
+
}
|
|
123
|
+
if (!request.seekPermission) return false
|
|
124
|
+
return await ask(app, message)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return Object.assign(policy, {
|
|
128
|
+
clearGrants(): void {
|
|
129
|
+
generation += 1
|
|
130
|
+
readGrants.clear()
|
|
131
|
+
}
|
|
132
|
+
})
|
|
133
|
+
}
|