taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit 1be2fb192e54725b2e2ee581ea9561779b8dc95b
parent 62666d1ce7dd5415ec10d6dbf9ab4b2163e951a3
Author: Florian Dold <dold@taler.net>
Date:   Mon, 23 Nov 2026 19:49:21 +0100

wallet-core: warn when exchange terms, currency or master key change

Diffstat:
Mdoc/wallet-observations.md | 6+++++-
Mpackages/taler-util/src/types-taler-wallet.ts | 3+++
Mpackages/taler-wallet-core/src/db/records.ts | 2++
Mpackages/taler-wallet-core/src/db/shared.ts | 20++++++++++++++++++++
Mpackages/taler-wallet-core/src/exchanges.ts | 7+++++++
Mpackages/taler-wallet-core/src/requests.ts | 13+++++++++++--
Mpackages/taler-wallet-core/src/user-attention.ts | 95++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-wallet-core/src/wallet-api-types.ts | 3+++
Mpackages/taler-wallet-core/src/wallet-notifications.test.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/routes/ManagementRoutes.tsx | 15+++++++++++----
10 files changed, 245 insertions(+), 8 deletions(-)

diff --git a/doc/wallet-observations.md b/doc/wallet-observations.md @@ -179,7 +179,11 @@ Each item has a stable `attentionId` for that occurrence. Call `markUserAttentionRead({ attentionId })` to set its `readAt` timestamp. Show a dismiss action when `dismissible` is true and call `dismissUserAttention({ attentionId })`. An item with `expiresAt` leaves the -inbox at that time. +inbox at that time. Warnings about exchange terms, exchange master keys, +and exchange currencies leave the inbox when their underlying conditions +resolve. When accepting +exchange terms, pass the displayed ETag as `expectedEtag` to +`setExchangeTosAccepted` so the user accepts the version they reviewed. `markAllUserAttentionRead({})` marks every active unread occurrence as read. `clearReadUserAttention({})` dismisses every active occurrence that is both diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts @@ -2857,12 +2857,15 @@ export const codecForGetWithdrawalDetailsForAmountRequest = export interface AcceptExchangeTosRequest { exchangeBaseUrl: string; + /** Accept only the version the user reviewed. */ + expectedEtag?: string; } export const codecForAcceptExchangeTosRequest = (): Codec<AcceptExchangeTosRequest> => buildCodecForObject<AcceptExchangeTosRequest>() .property("exchangeBaseUrl", codecForCanonBaseUrl()) + .property("expectedEtag", codecOptional(codecForString())) .build("AcceptExchangeTosRequest"); export interface ConfirmExchangeKeyChangeRequest { diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts @@ -2218,6 +2218,7 @@ export interface WalletUserAttention { } export enum ConfigRecordKey { + UserAttentionInitialized = "user-attention-initialized", RecoupRecoveryVersion = "recoupRecoveryVersion", WalletBackupState = "walletBackupState", CurrencyDefaultsApplied = "currencyDefaultsApplied", @@ -2305,6 +2306,7 @@ export function expirationRiskScopes( } export type ConfigRecord = + | { key: ConfigRecordKey.UserAttentionInitialized; value: boolean | number } | { key: ConfigRecordKey.WalletBackupState; value: WalletBackupConfState; diff --git a/packages/taler-wallet-core/src/db/shared.ts b/packages/taler-wallet-core/src/db/shared.ts @@ -23,6 +23,7 @@ * reimplemented (and drifting) in each. */ +import { reconcileExchangeAttention } from "../user-attention.js"; import { assertUnreachable, canonicalJson, @@ -335,6 +336,20 @@ async function trackExchangeUpdate( ): Promise<boolean> { const previous = await tx.getExchange(exchange.baseUrl); if ( + previous?.tosAcceptedEtag !== exchange.tosAcceptedEtag || + previous?.tosCurrentEtag !== exchange.tosCurrentEtag || + previous?.supersededKeySet?.masterPublicKey !== + exchange.supersededKeySet?.masterPublicKey || + previous?.supersededKeySet?.currency !== + exchange.supersededKeySet?.currency || + (exchange.supersededKeySet && + (previous?.detailsPointer?.masterPublicKey !== + exchange.detailsPointer?.masterPublicKey || + previous?.detailsPointer?.currency !== + exchange.detailsPointer?.currency)) + ) + await reconcileExchangeAttention(tx, exchange.baseUrl, exchange); + if ( canonicalJson(exchangeCacheInputs(previous)) !== canonicalJson(exchangeCacheInputs(exchange)) ) { @@ -487,6 +502,11 @@ export function watchForCacheInvalidation<T extends WalletDbTransaction>( ).then(() => value.apply(target, args)); } } + if (prop === "deleteExchange") { + return reconcileExchangeAttention(target, args[0] as string).then( + () => write(true), + ); + } return write( typeof prop === "string" && BALANCE_OVERVIEW_WRITES.has(prop), ); diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts @@ -1000,9 +1000,16 @@ function notifyExchangeUpdate( export async function acceptExchangeTermsOfService( wex: WalletExecutionContext, exchangeBaseUrl: string, + expectedEtag?: string, ): Promise<void> { await wex.runWalletDbTx(async (tx) => { const exch = await tx.getExchange(exchangeBaseUrl); + if (expectedEtag !== undefined && exch?.tosCurrentEtag !== expectedEtag) + throw TalerError.fromDetail( + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + { parameter: "expectedEtag" }, + "The exchange terms have changed", + ); if ( exch && exch.tosCurrentEtag && diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -30,6 +30,7 @@ import { observeBalanceRefreshInfo, } from "./refreshBalance.js"; import { + initializeAttention, scheduleAttentionExpirations, getUserAttention, markAllUserAttentionRead, @@ -1092,7 +1093,10 @@ async function handleSetWalletRunConfig( await migrateCoinAvailability(wex); if (!wex.ws.initCalled) { - await wex.runWalletDbTx((tx) => scheduleAttentionExpirations(wex, tx)); + await wex.runWalletDbTx(async (tx) => { + await initializeAttention(tx); + await scheduleAttentionExpirations(wex, tx); + }); await repairLegacyRecoupState(wex); await cleanupFailedClaimsOnStartup(wex); await collectLeftoverClaims(wex); @@ -2055,6 +2059,7 @@ async function importDbDump( const finalize = async (tx: WalletDbTransaction): Promise<void> => { await rematerializeTransactionsAtCurrentVersion(wex, tx); await recomputeCoinAvailabilityAtCurrentVersion(tx); + await initializeAttention(tx); }; try { if (db.importAnyDatabase) { @@ -2802,7 +2807,11 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = { [WalletApiOperation.SetExchangeTosAccepted]: { codec: codecForAcceptExchangeTosRequest(), handler: async (wex, req) => { - await acceptExchangeTermsOfService(wex, req.exchangeBaseUrl); + await acceptExchangeTermsOfService( + wex, + req.exchangeBaseUrl, + req.expectedEtag, + ); return {}; }, }, diff --git a/packages/taler-wallet-core/src/user-attention.ts b/packages/taler-wallet-core/src/user-attention.ts @@ -5,15 +5,22 @@ */ import { AbsoluteTime, + encodeCrock, + getRandomBytes, NotificationType, TalerError, TalerErrorCode, TalerPreciseTimestamp, type TimerHandle, + type UserAttentionDetails, type UserAttentionItem, type UserAttentionSnapshot, } from "@gnu-taler/taler-util"; -import type { WalletUserAttention } from "./db/records.js"; +import { + ConfigRecordKey, + type WalletExchangeEntry, + type WalletUserAttention, +} from "./db/records.js"; import type { WalletDbTransaction } from "./db/transaction.js"; import type { WalletExecutionContext } from "./wallet.js"; @@ -30,6 +37,14 @@ function active(row: WalletUserAttention, now: number) { function changed(tx: WalletDbTransaction) { tx.notify({ type: NotificationType.UserAttentionChanged }); } +function newItem(details: UserAttentionDetails): UserAttentionItem { + return { + ...details, + attentionId: encodeCrock(getRandomBytes(16)), + createdAt: TalerPreciseTimestamp.now(), + dismissible: details.type === "coin-double-spent", + }; +} async function save( tx: WalletDbTransaction, sourceKey: string, @@ -119,6 +134,70 @@ export async function clearReadUserAttention(wex: WalletExecutionContext) { return {}; } +async function setCondition( + tx: WalletDbTransaction, + key: string, + details?: UserAttentionDetails, +) { + const old = await tx.getUserAttention(key); + if (!details) { + if (!old) return; + await tx.deleteUserAttention(key); + } else { + if ( + old && + Object.entries(details).every( + ([k, v]) => old.item[k as keyof UserAttentionItem] === v, + ) + ) + return; + await save(tx, key, newItem(details)); + } + changed(tx); +} + +export async function reconcileExchangeAttention( + tx: WalletDbTransaction, + url: string, + entry?: WalletExchangeEntry, +) { + const accepted = entry?.tosAcceptedEtag; + const current = entry?.tosCurrentEtag; + await setCondition( + tx, + "tos:" + url, + accepted && current && accepted !== current + ? { + type: "exchange-tos-changed", + exchangeBaseUrl: url, + acceptedEtag: accepted, + currentEtag: current, + } + : undefined, + ); + const previous = entry?.supersededKeySet; + const observed = entry?.detailsPointer; + let identityChange: UserAttentionDetails | undefined; + if (previous && observed) { + identityChange = + previous.masterPublicKey !== observed.masterPublicKey + ? { + type: "exchange-master-key-changed", + exchangeBaseUrl: url, + previousMasterPub: previous.masterPublicKey, + currentMasterPub: observed.masterPublicKey, + } + : { + type: "exchange-currency-changed", + exchangeBaseUrl: url, + masterPub: observed.masterPublicKey, + previousCurrency: previous.currency, + currentCurrency: observed.currency, + }; + } + await setCondition(tx, "master:" + url, identityChange); +} + // A deadline also wakes clients that only requested the home-screen count. const expiryTimers = new WeakMap<WalletExecutionContext["ws"], TimerHandle>(); export async function scheduleAttentionExpirations( @@ -160,3 +239,17 @@ export async function scheduleAttentionExpirations( schedule(); }); } + +export async function initializeAttention(tx: WalletDbTransaction) { + // Version 1 (true) only recognized changes of the master public key. + if ( + (await tx.getConfig(ConfigRecordKey.UserAttentionInitialized))?.value !== 2 + ) { + for (const entry of await tx.getExchanges()) + await reconcileExchangeAttention(tx, entry.baseUrl, entry); + await tx.upsertConfig({ + key: ConfigRecordKey.UserAttentionInitialized, + value: 2, + }); + } +} diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts @@ -2082,6 +2082,9 @@ export const walletApiExpectedErrors = { [WalletApiOperation.ObserveUserAttention]: [ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, ], + [WalletApiOperation.SetExchangeTosAccepted]: [ + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + ], [WalletApiOperation.StopObservation]: [ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, ], diff --git a/packages/taler-wallet-core/src/wallet-notifications.test.ts b/packages/taler-wallet-core/src/wallet-notifications.test.ts @@ -58,12 +58,15 @@ import { import { clearReadUserAttention, getUserAttention, + initializeAttention, markAllUserAttentionRead, + updateAttention, } from "./user-attention.js"; import { runnerFactories } from "./db/testing/runners.js"; import { getBalances } from "./balance.js"; import { acceptExchangeTermsOfService, + confirmExchangeKeyChange, doExchangeAutoRefresh, markExchangeUsed, waitReadyExchange, @@ -365,6 +368,92 @@ for (const makeRunner of runnerFactories) { } }); + test(`${makeRunner.name}: exchange attention follows terms and key changes across screens`, async () => { + const f = await fixture(makeRunner); + try { + const url = f.exchange.baseUrl; + const save = () => + f.wex.runWalletDbTx((tx) => tx.upsertExchange(f.exchange)); + f.exchange.tosCurrentEtag = "v1"; + await save(); + assert.equal((await getUserAttention(f.wex)).items.length, 0); + await acceptExchangeTermsOfService(f.wex, url, "v1"); + f.exchange.tosAcceptedEtag = "v1"; + f.exchange.tosCurrentEtag = "v2"; + f.exchange.supersededKeySet = { + masterPublicKey: encodeCrock(new Uint8Array(32).fill(5)), + firstSeen: f.exchange.lastUpdate!, + currency: "TESTKUDOS", + sharesDenominations: false, + }; + await save(); + const current = await getUserAttention(f.wex); + assert.equal(current.unreadCount, 2); + const old = current.items.find((i) => i.type === "exchange-tos-changed")!; + await updateAttention(f.wex, old.attentionId, false); + await save(); + assert.equal((await getUserAttention(f.wex)).unreadCount, 1); + f.exchange.tosCurrentEtag = "v3"; + // The previously observed key is back. + f.exchange.detailsPointer = { + ...f.exchange.detailsPointer!, + masterPublicKey: f.exchange.supersededKeySet.masterPublicKey, + }; + delete f.exchange.supersededKeySet; + await save(); + await updateAttention(f.wex, old.attentionId, false); + assert.equal((await getUserAttention(f.wex)).unreadCount, 1); + await assert.rejects(acceptExchangeTermsOfService(f.wex, url, "v2")); + await acceptExchangeTermsOfService(f.wex, url, "v3"); + assert.deepEqual((await getUserAttention(f.wex)).items, []); + } finally { + await f.close(); + } + }); + + test(`${makeRunner.name}: a pending currency change is backfilled, updated and confirmed`, async () => { + const f = await fixture(makeRunner); + try { + f.exchange.supersededKeySet = { + masterPublicKey: master, + firstSeen: f.exchange.lastUpdate!, + currency: "OLD", + sharesDenominations: false, + }; + // This wallet initialized its inbox before currency-only changes were reported. + await f.db.runReadWriteTx(async (tx) => { + await tx.upsertExchange(f.exchange); + await tx.upsertConfig({ + key: ConfigRecordKey.UserAttentionInitialized, + value: true, + }); + }); + await f.wex.runWalletDbTx(initializeAttention); + const first = (await getUserAttention(f.wex)).items[0]; + assert.equal(first.type, "exchange-currency-changed"); + assert.equal(first.exchangeBaseUrl, exchangeUrl); + assert.equal(first.previousCurrency, "OLD"); + assert.equal(first.currentCurrency, "TESTKUDOS"); + await updateAttention(f.wex, first.attentionId, false); + await f.wex.runWalletDbTx(initializeAttention); + assert.equal((await getUserAttention(f.wex)).unreadCount, 0); + + f.exchange.supersededKeySet.currency = "OTHER"; + await f.wex.runWalletDbTx((tx) => tx.upsertExchange(f.exchange)); + const next = await getUserAttention(f.wex); + assert.equal(next.items.length, 1); + assert.equal(next.unreadCount, 1); + assert.notEqual(next.items[0].attentionId, first.attentionId); + await confirmExchangeKeyChange(f.wex, { + exchangeBaseUrl: exchangeUrl, + currentMasterPub: master, + }); + assert.deepEqual((await getUserAttention(f.wex)).items, []); + } finally { + await f.close(); + } + }); + test(`${makeRunner.name}: exchange retry publishes changed errors and their removal`, async () => { const f = await fixture(makeRunner); try { diff --git a/packages/wallet-webui/src/routes/ManagementRoutes.tsx b/packages/wallet-webui/src/routes/ManagementRoutes.tsx @@ -433,6 +433,7 @@ export function ExchangeTermsRoute() { const { controller: progressRequest } = useWalletProgress(connection); const [dialogLanguage, setDialogLanguage] = useState<string>(); const [, setBrowserLanguageRevision] = useState(0); + const [termsRevision, setTermsRevision] = useState(0); const [terms, setTerms] = useState<GetExchangeTosResult>(); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState<ErrorPresentation>(); @@ -498,21 +499,27 @@ export function ExchangeTermsRoute() { return () => { active = false; }; - }, [exchangeUrl, languagePreference.acceptLanguage, progressRequest]); + }, [ + exchangeUrl, + languagePreference.acceptLanguage, + progressRequest, + termsRevision, + ]); const accept = async () => { setWorking(true); setError(undefined); try { const result = await callMutation( WalletApiOperation.SetExchangeTosAccepted, - { exchangeBaseUrl: exchangeUrl }, + { exchangeBaseUrl: exchangeUrl, expectedEtag: terms?.currentEtag }, ["exchanges"], ); - if (Result.isError(result)) + if (Result.isError(result)) { + setTermsRevision((n) => n + 1); setError( errorHint(result.detail, i18n.str`The terms could not be accepted.`), ); - else navigate(returnTo ?? `/exchange/${exchangeRouteId(exchangeUrl)}`); + } else navigate(returnTo ?? `/exchange/${exchangeRouteId(exchangeUrl)}`); } catch (cause) { setError(errorFromException(cause, i18n.str`Terms acceptance failed`)); } finally {