@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.
Files changed (78) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +78 -13
  3. package/core/contacts/contactActivity.ts +48 -28
  4. package/core/contacts/contactsStore.ts +2 -2
  5. package/core/context/WalletContext.tsx +166 -219
  6. package/core/demo/demoAssets.ts +8 -10
  7. package/core/demo/demoLedger.ts +32 -38
  8. package/core/demo/demoMandalaRuntime.ts +67 -49
  9. package/core/demo/index.ts +1 -1
  10. package/core/i18n/translations.tsx +72 -0
  11. package/core/index.ts +55 -37
  12. package/core/localpay/build.ts +110 -569
  13. package/core/localpay/codec.ts +190 -93
  14. package/core/localpay/pending.ts +217 -202
  15. package/core/localpay/session.ts +99 -25
  16. package/core/localpay/types.ts +6 -5
  17. package/core/localpay/verify.ts +118 -173
  18. package/core/mandala/abortGuard.ts +97 -120
  19. package/core/mandala/accessPolicy.ts +133 -0
  20. package/core/mandala/assets.ts +370 -0
  21. package/core/mandala/colorGuard.ts +178 -0
  22. package/core/mandala/colorModule.ts +82 -0
  23. package/core/mandala/createRuntime.ts +483 -2392
  24. package/core/mandala/handle.ts +694 -0
  25. package/core/mandala/kvStore.ts +105 -0
  26. package/core/mandala/nearby.ts +185 -0
  27. package/core/mandala/receipt.ts +121 -0
  28. package/core/mandala/runtime.ts +166 -312
  29. package/core/mandala/settle.ts +540 -0
  30. package/core/mandala/transferJournal.ts +395 -0
  31. package/core/mandala/types.ts +61 -311
  32. package/core/networks.ts +5 -5
  33. package/core/offline/cancelParked.ts +80 -63
  34. package/core/offline/payerHold.ts +52 -118
  35. package/core/parsePeerPayURI.ts +25 -12
  36. package/core/pay/rails/handle.ts +15 -14
  37. package/core/pay/rails/index.ts +5 -3
  38. package/core/pay/rails/nearby.ts +25 -87
  39. package/core/profiles/assertProfileEmpty.ts +19 -10
  40. package/core/services/vault/guard.ts +5 -4
  41. package/core/storage/StorageExpoSQLite.ts +93 -229
  42. package/core/storage/methods/processOfflineActions.ts +86 -136
  43. package/core/storage/schema/createTables.ts +9 -184
  44. package/package.json +6 -5
  45. package/ui/components/pay/AssetPicker.tsx +2 -2
  46. package/ui/components/pay/HandleReceive.tsx +4 -4
  47. package/ui/components/pay/NearbyFlow.tsx +324 -239
  48. package/ui/components/pay/RequestHub.tsx +10 -0
  49. package/ui/components/pay/UniversalSend.tsx +31 -28
  50. package/ui/components/pay/useRecipientInput.ts +2 -2
  51. package/ui/components/ui/PermissionSheet.tsx +94 -160
  52. package/ui/components/ui/colorPrompt.ts +236 -0
  53. package/ui/components/wallet/AmountInput.tsx +9 -6
  54. package/ui/components/wallet/AssetAmount.tsx +6 -6
  55. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  56. package/ui/components/wallet/Balance.tsx +3 -1
  57. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  58. package/ui/components/wallet/tokenEviction.ts +9 -9
  59. package/ui/hooks/useMandala.ts +6 -6
  60. package/ui/hooks/useSpendableBalance.ts +3 -1
  61. package/ui/importDatabases.ts +1 -1
  62. package/ui/screens/PayScreen.tsx +14 -20
  63. package/ui/screens/SettingsScreen.tsx +3 -1
  64. package/ui/screens/WalletCheckScreen.tsx +7 -2
  65. package/ui/screens/WalletHomeScreen.tsx +40 -14
  66. package/ui/screens/tokenRowTitle.ts +28 -15
  67. package/ui/tokenFormat.ts +133 -69
  68. package/ui/tokenStatus.ts +5 -8
  69. package/core/localpay/settlementAck.ts +0 -155
  70. package/core/mandala/basketMigration.ts +0 -166
  71. package/core/mandala/bundle.ts +0 -244
  72. package/core/mandala/drain.ts +0 -754
  73. package/core/mandala/inboxPrehold.ts +0 -193
  74. package/core/mandala/permissionModule.ts +0 -931
  75. package/core/mandala/resendTransfer.ts +0 -178
  76. package/core/mandala/settlementStore.ts +0 -434
  77. package/core/mandala/token.ts +0 -45
  78. package/core/offline/tokenFrames.ts +0 -197
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Guard #4: a settled token payment's action may not be aborted.
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 meet here — the lib no longer clears that
22
- * entry, `reconcileJournals` no longer runs the sweep at all, and this guard
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 { SettlementStore, TokenSettlementRow, TokenSettlementState } from './types'
42
+ import type { TransferJournal } from './transferJournal'
43
+ import type { ColorTransferRow, ColorTransferState } from './types'
34
44
 
35
45
  /**
36
- * States in which the bytes are, or may already be, somewhere this device
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`/`held` are in the list even though nothing has been submitted
40
- * yet: the PAYEE holds the frame, and either party may submit it (offline
41
- * settlement §0.1 — "whoever reconnects first submits"). Releasing the inputs
42
- * under a payee who is about to submit is the same double spend, only with a
43
- * longer fuse. `submitting` is a request in flight whose verdict is unknown,
44
- * and an unknown verdict may be an admission.
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 (FIX F). The payee has NOT been
48
- * handed anything, nothing has been submitted, and cancelling a parked
49
- * payment is a feature (`cancelParkedPayment`) that must keep working.
50
- * · `refused`/`orphaned` — the overlay's final word. The money never moved and
51
- * the inputs SHOULD come back.
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 ABORT_BLOCKED_SETTLEMENT_STATES: readonly TokenSettlementState[] = [
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: TokenSettlementRow | undefined): boolean {
68
+ export function abortIsBlockedBy(row: ColorTransferRow | undefined): boolean {
62
69
  if (!row) return false
63
- return ABORT_BLOCKED_SETTLEMENT_STATES.includes(row.state)
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 settlement rows live, read LATE.
79
+ * Where the journal lives, read LATE.
73
80
  *
74
- * A function rather than a store, because the wrapper is built once around the
75
- * published permissions manager while the Mandala runtime is constructed after
76
- * it — and is replaced wholesale on a network switch or a wallet rebuild.
77
- * Capturing a store here would guard the departed wallet's tables. Returning
78
- * `undefined` (no runtime, no database, not a Mandala chain) means "no token
79
- * payment can be at stake", which is the correct answer, not a failure.
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 SettlementStoreLookup = () =>
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 `settlements` is, and answering ONLY the question of
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
- * `token_settlements` row.
94
+ * `color_transfers` row.
90
95
  *
91
- * XR-034 (SEC1-024 / SEC2-038). `settlements()` answering `undefined` is not
92
- * one fact. WalletContext.tsx wires it to `() => mandalaRef.current?.store`,
93
- * and `mandalaRef.current` reads `undefined` in situations that mean opposite
94
- * things for safety:
95
- * 1. This chain has no Mandala endpoints at all — `createRuntime.ts`'s
96
- * `available` (`endpoints !== undefined && db !== undefined`) is false by
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`/`held`/
102
- * `submitting`/`admitted`/`broadcast` row from a previous build; this
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.tsx
106
- * wires this to `() => mandalaEndpoints !== undefined` — a static fact of the
107
- * chain's own configuration that does not fluctuate with runtime construction,
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 overlay
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 `wrapCreateActionForTokenInputs`: it wraps
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 settlement runtime that has not been built yet, and one
123
- * mid-rebuild are all indistinguishable from "a payment is in flight" — they
124
- * are exactly the moments this device can least tell, which is the opposite of
125
- * evidence that releasing inputs is safe. Refusing the abort in that window
126
- * costs a retry (every caller already treats `{ aborted: false }` as "did not
127
- * release, try again" — see `queueFailedAbort`); wrongly granting it costs a
128
- * double spend. The one shape that still passes through when `settlements()`
129
- * answers `undefined` is `tokenSettlementPossible()` reporting false: a chain
130
- * with no Mandala configuration at all, where a blocking row could never have
131
- * been written and refusing every plain BSV abort forever would be its own
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
- settlements: SettlementStoreLookup,
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 row = await lookupSettlement(store, args?.reference)
170
- if (abortIsBlockedBy(row)) {
171
- console.warn(
172
- `[mandala] refusing to abort ${row!.txid}: its settlement is '${row!.state}', ` +
173
- 'so releasing these inputs would double spend a transaction the overlay may already have'
174
- )
175
- return { aborted: false }
176
- }
177
- if (await hasUnresolvedLegacyBlockedRow(store)) {
178
- console.warn(
179
- '[mandala] refusing to abort: an unresolved legacy settlement row exists with no reference to ' +
180
- 'match against — releasing any inputs while it is unresolved risks double spending a token ' +
181
- 'payment that row already has a claim on'
182
- )
183
- return { aborted: false }
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 settlement state:", e)
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 lookupSettlement(
199
- store: Pick<SettlementStore, 'getSettlementByReference'>,
179
+ async function lookupTransfer(
180
+ journal: Pick<TransferJournal, 'getByReference'>,
200
181
  reference: string | undefined
201
- ): Promise<TokenSettlementRow | undefined> {
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 store.getSettlementByReference(reference)
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
+ }