taler-typescript-core

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

commit 03005a3b9f4d252359ff5b0b77f3faf6e56e5998
parent 4ea226543158ece0318ae70024b668fdb27c3afd
Author: Florian Dold <dold@taler.net>
Date:   Thu, 26 Nov 2026 00:18:48 +0100

wallet web UI: open payment links directly in checkout

Show payment preparation while the wallet resolves the link so the
balance screen and generic action prompt do not flash before review.

Issue: https://bugs.taler.net/n/10644

Diffstat:
Mpackages/wallet-webui/src/platform/action-inbox.ts | 16+++++++++++++++-
Mpackages/wallet-webui/src/platform/extension-background.ts | 14++++++--------
Mpackages/wallet-webui/src/routes/App.tsx | 395++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Mpackages/wallet-webui/src/screens/PaymentScreen.tsx | 35+++++++++++++++++++++++++++++------
Mpackages/wallet-webui/test/payment-entry.test.tsx | 8++++++--
Mpackages/wallet-webui/test/transaction-observation-routes.test.tsx | 2++
6 files changed, 279 insertions(+), 191 deletions(-)

diff --git a/packages/wallet-webui/src/platform/action-inbox.ts b/packages/wallet-webui/src/platform/action-inbox.ts @@ -1,4 +1,9 @@ -import { Paytos, Result, TalerUris } from "@gnu-taler/taler-util"; +import { + Paytos, + Result, + TalerUriAction, + TalerUris, +} from "@gnu-taler/taler-util"; import type { ActionEntry, ActionInbox, @@ -38,6 +43,15 @@ async function withLocalMutationLock<T>( } } +export function isPaymentUri(uri: string): boolean { + const parsed = TalerUris.parse(uri); + return Result.isOk(parsed) && parsed.value.type === TalerUriAction.Pay; +} + +export function actionRoute(entry: Pick<ActionEntry, "id" | "uri">): string { + return `/${isPaymentUri(entry.uri) ? "checkout" : "action"}/${entry.id}`; +} + export function randomActionId(): string { const bytes = crypto.getRandomValues(new Uint8Array(18)); return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); diff --git a/packages/wallet-webui/src/platform/extension-background.ts b/packages/wallet-webui/src/platform/extension-background.ts @@ -1,6 +1,5 @@ /// <reference types="chrome" /> import { RecoveringWalletHost } from "./host-recovery.js"; -import { Result, TalerUriAction, TalerUris } from "@gnu-taler/taler-util"; import { BROWSER_RPC_VERSION, unavailableCoreResponse, @@ -9,6 +8,8 @@ import { import { ExtensionSessionActionStore, StoredActionInbox, + actionRoute, + isPaymentUri, validateActionUri, } from "./action-inbox.js"; import { @@ -168,11 +169,6 @@ function trustedExtensionSender(sender: chrome.runtime.MessageSender): boolean { } } -function isPaymentUri(uri: string): boolean { - const parsed = TalerUris.parse(uri); - return Result.isOk(parsed) && parsed.value.type === TalerUriAction.Pay; -} - async function queryCurrentPageAction(): Promise< { uri: string; tabId: number } | undefined > { @@ -214,7 +210,9 @@ chrome.runtime.onMessage.addListener( const entry = await inbox.put(action.uri, "metadata", { fulfillmentTarget: "current-tab", }); - const url = chrome.runtime.getURL(`wallet.html#/action/${entry.id}`); + const url = chrome.runtime.getURL( + `wallet.html#${actionRoute(entry)}`, + ); if (isPaymentUri(action.uri)) { await chrome.tabs.update(action.tabId, { url }); } else { @@ -247,7 +245,7 @@ chrome.runtime.onMessage.addListener( }); if (entry.autoOpen) { const url = chrome.runtime.getURL( - `wallet.html#/action/${entry.id}`, + `wallet.html#${actionRoute(entry)}`, ); if ( (message.source === "link" && diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -32,6 +32,7 @@ import type { TransactionIdStr, } from "@gnu-taler/taler-util"; import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import type { ComponentChildren } from "preact"; import { useCallback, useEffect, useMemo, useState } from "preact/hooks"; import { useRef } from "preact/hooks"; import jsQR, * as jsQrTypes from "jsqr"; @@ -77,7 +78,7 @@ import { import { RefundActionRoute } from "./RefundActionRoute.js"; import { RestoreBackupRoute } from "./RestoreBackupRoute.js"; import { StorybookScreen } from "../screens/StorybookScreen.js"; -import { PaymentScreen } from "../screens/PaymentScreen.js"; +import { PaymentLoading, PaymentScreen } from "../screens/PaymentScreen.js"; import { DepositScreen } from "../screens/DepositScreen.js"; import { PeerCreateScreen } from "../screens/PeerCreateScreen.js"; import type { @@ -108,6 +109,8 @@ import { } from "../platform/storage-manager.js"; import { completeActionBestEffort, + actionRoute, + isPaymentUri, InvalidActionUriError, validateActionUri, } from "../platform/action-inbox.js"; @@ -293,7 +296,6 @@ function AppContent(props: AppServices) { <NotificationBridge /> <LifecycleBridge /> <ReconnectionBridge /> - <ProtocolCapture /> <StorageRecoveryBridge /> <WalletUpdateBridge /> <Switch> @@ -405,54 +407,62 @@ function NotificationBridge() { return null; } -function ProtocolCapture() { +function ProtocolCapture({ children }: { children: ComponentChildren }) { const { platform } = useServices(); const [, navigate] = useLocation(); const [error, setError] = useState<"invalid-link" | "save-failed">(); const [working, setWorking] = useState(false); + const [capturingPayment, setCapturingPayment] = useState(() => { + const uri = new URLSearchParams(window.location.search).get("talerUri"); + return !!uri && isPaymentUri(uri); + }); const capture = useCallback(async () => { setWorking(true); try { const entry = await platform.captureProtocolInput(); setError(undefined); - if (entry) navigate(`/action/${entry.id}`, { replace: true }); + if (entry) navigate(actionRoute(entry), { replace: true }); } catch (cause) { setError( cause instanceof InvalidActionUriError ? "invalid-link" : "save-failed", ); } finally { + setCapturingPayment(false); setWorking(false); } }, [navigate, platform]); useEffect(() => { void capture(); }, [capture]); - if (!error) return null; + if (!error) return capturingPayment ? <PaymentLoading /> : <>{children}</>; return ( - <div class="fixed inset-x-4 top-4 z-50 mx-auto max-w-2xl"> - <ErrorCard - error={localError( - error === "invalid-link" - ? i18n.str`This link is invalid or unsupported.` - : i18n.str`The wallet couldn’t open this link.`, - )} - > - <div class="mt-4 flex flex-wrap gap-3"> - {error === "save-failed" && ( - <Button onClick={() => void capture()} disabled={working}> - {working ? i18n.str`Retrying…` : i18n.str`Try again`} - </Button> + <> + {children} + <div class="fixed inset-x-4 top-4 z-50 mx-auto max-w-2xl"> + <ErrorCard + error={localError( + error === "invalid-link" + ? i18n.str`This link is invalid or unsupported.` + : i18n.str`The wallet couldn’t open this link.`, )} - <Button - tone="secondary" - disabled={working} - onClick={() => setError(undefined)} - > - {i18n.str`Dismiss`} - </Button> - </div> - </ErrorCard> - </div> + > + <div class="mt-4 flex flex-wrap gap-3"> + {error === "save-failed" && ( + <Button onClick={() => void capture()} disabled={working}> + {working ? i18n.str`Retrying…` : i18n.str`Try again`} + </Button> + )} + <Button + tone="secondary" + disabled={working} + onClick={() => setError(undefined)} + > + {i18n.str`Dismiss`} + </Button> + </div> + </ErrorCard> + </div> + </> ); } @@ -534,76 +544,85 @@ function WalletShell() { > <HostRecoveryNotice /> <VisibleRequestProgress /> - <Switch> - <Route path="/"> - <HomeAttentionLink unreadCount={unreadCount} /> - <BalanceRoute /> - </Route> - <Route path="/notifications" component={UserAttentionRoute} /> - <Route path="/enter" component={UriInputRoute} /> - <Route path="/action/:id" component={KeyedActionRoute} /> - <Route - path="/pay/:transactionId/:actionId" - component={KeyedPaymentRoute} - /> - <Route - path="/pay-template/:actionId" - component={KeyedPaymentTemplateRoute} - /> - <Route - path="/withdraw-exchange/:actionId" - component={KeyedWithdrawExchangeRoute} - /> - <Route - path="/withdraw-action/:actionId" - component={KeyedIntegratedWithdrawalRoute} - /> - <Route path="/transactions" component={TransactionsRoute} /> - <Route - path="/transaction/:transactionId" - component={KeyedTransactionDetailRoute} - /> - <Route path="/scan" component={QrScanRoute} /> - <Route path="/withdraw"> - <WithdrawalRoute /> - </Route> - <Route path="/deposit-action/:actionId" component={KeyedDepositRoute} /> - <Route path="/deposit" component={DepositRoute} /> - <Route path="/peer/send"> - <PeerCreateRoute key="send" mode="send" /> - </Route> - <Route path="/peer/request"> - <PeerCreateRoute key="request" mode="request" /> - </Route> - <Route - path="/peer/share/:transactionId/:mode" - component={PeerShareRoute} - /> - <Route - path="/peer-receive/:actionId" - component={KeyedPeerReceiveRoute} - /> - <Route path="/settings" component={SettingsRoute} /> - <Route path="/donations" component={DonauSettingsRoute} /> - <Route path="/donation-statements" component={DonauStatementsRoute} /> - <Route path="/shopping" component={ShoppingRoute} /> - <Route path="/exchanges" component={ExchangesRoute} /> - <Route - path="/exchange/:exchangeId/terms" - component={KeyedExchangeTermsRoute} - /> - <Route - path="/exchange/:exchangeId" - component={KeyedExchangeDetailRoute} - /> - <Route path="/accounts" component={BankAccountsRoute} /> - <Route path="/discounts" component={DiscountsRoute} /> - <Route path="/passes" component={PassesRoute} /> - <Route path="/recovery" component={StorageRecoveryRoute} /> - <Route> - <Redirect to="/" /> - </Route> - </Switch> + <ProtocolCapture> + <Switch> + <Route path="/"> + <HomeAttentionLink unreadCount={unreadCount} /> + <BalanceRoute /> + </Route> + <Route path="/notifications" component={UserAttentionRoute} /> + <Route path="/enter" component={UriInputRoute} /> + <Route + path="/checkout/:actionId/:transactionId?" + component={CheckoutRoute} + /> + <Route path="/action/:id" component={KeyedActionRoute} /> + <Route + path="/pay/:transactionId/:actionId" + component={KeyedPaymentRoute} + /> + <Route + path="/pay-template/:actionId" + component={KeyedPaymentTemplateRoute} + /> + <Route + path="/withdraw-exchange/:actionId" + component={KeyedWithdrawExchangeRoute} + /> + <Route + path="/withdraw-action/:actionId" + component={KeyedIntegratedWithdrawalRoute} + /> + <Route path="/transactions" component={TransactionsRoute} /> + <Route + path="/transaction/:transactionId" + component={KeyedTransactionDetailRoute} + /> + <Route path="/scan" component={QrScanRoute} /> + <Route path="/withdraw"> + <WithdrawalRoute /> + </Route> + <Route + path="/deposit-action/:actionId" + component={KeyedDepositRoute} + /> + <Route path="/deposit" component={DepositRoute} /> + <Route path="/peer/send"> + <PeerCreateRoute key="send" mode="send" /> + </Route> + <Route path="/peer/request"> + <PeerCreateRoute key="request" mode="request" /> + </Route> + <Route + path="/peer/share/:transactionId/:mode" + component={PeerShareRoute} + /> + <Route + path="/peer-receive/:actionId" + component={KeyedPeerReceiveRoute} + /> + <Route path="/settings" component={SettingsRoute} /> + <Route path="/donations" component={DonauSettingsRoute} /> + <Route path="/donation-statements" component={DonauStatementsRoute} /> + <Route path="/shopping" component={ShoppingRoute} /> + <Route path="/exchanges" component={ExchangesRoute} /> + <Route + path="/exchange/:exchangeId/terms" + component={KeyedExchangeTermsRoute} + /> + <Route + path="/exchange/:exchangeId" + component={KeyedExchangeDetailRoute} + /> + <Route path="/accounts" component={BankAccountsRoute} /> + <Route path="/discounts" component={DiscountsRoute} /> + <Route path="/passes" component={PassesRoute} /> + <Route path="/recovery" component={StorageRecoveryRoute} /> + <Route> + <Redirect to="/" /> + </Route> + </Switch> + </ProtocolCapture> </Shell> ); } @@ -624,10 +643,30 @@ function KeyedActionRoute() { return <ActionRoute key={params?.id ?? ""} />; } +function CheckoutRoute() { + const [, params] = useRoute("/checkout/:actionId/:transactionId?"); + const actionId = params?.actionId ?? ""; + return params?.transactionId ? ( + <PaymentRoute + key={actionId} + actionId={actionId} + transactionId={params.transactionId as TransactionIdStr} + /> + ) : ( + <PrepareCheckout key={actionId} actionId={actionId} /> + ); +} + function KeyedPaymentRoute() { const [, params] = useRoute("/pay/:transactionId/:actionId"); const routeKey = `${params?.transactionId ?? ""}:${params?.actionId ?? ""}`; - return <PaymentRoute key={routeKey} />; + return ( + <PaymentRoute + key={routeKey} + actionId={params?.actionId ?? ""} + transactionId={params?.transactionId as TransactionIdStr} + /> + ); } function KeyedPaymentTemplateRoute() { @@ -688,7 +727,7 @@ function UriInputRoute() { setError(undefined); try { const entry = await platform.actionInbox.put(input, "paste"); - navigate(`/action/${entry.id}`); + navigate(actionRoute(entry)); } catch { setError(i18n.str`The wallet link could not be opened.`); setWorking(false); @@ -1858,7 +1897,9 @@ function PeerCreateRoute(props: { mode: "send" | "request" }) { scope, insufficient: recovery?.message ?? - insufficientBalanceMessage(result.value.insufficientBalanceDetails), + insufficientBalanceMessage( + result.value.insufficientBalanceDetails, + ), ...(recovery ? { recovery } : {}), }); } else { @@ -3107,7 +3148,7 @@ function QrScanRoute() { if (finished) return; finished = true; for (const track of stream?.getTracks() ?? []) track.stop(); - navigate(`/action/${entry.id}`, { replace: true }); + navigate(actionRoute(entry), { replace: true }); } catch { if (!finished) setScanHint(i18n.str`The wallet link could not be opened.`); @@ -3188,53 +3229,6 @@ function ActionRoute() { const [detail, setDetail] = useState<string>(); const [actionError, setActionError] = useState<ErrorPresentation>(); const [canRetry, setCanRetry] = useState(false); - const paymentRequest = useRef({ active: false, preparing: false }); - const preparePayment = useCallback( - async (action: NonNullable<typeof entry>) => { - const request = paymentRequest.current; - if (!request.active || request.preparing) return; - request.preparing = true; - setState("working"); - setActionError(undefined); - setCanRetry(false); - try { - const result = await progressRequest.callAndInvalidate( - WalletApiOperation.PreparePayForUriV2, - { talerPayUri: action.uri }, - ["transactions"], - ); - if (!request.active) return; - if (Result.isError(result)) { - setActionError( - walletCoreError( - result.detail, - /* Translators: wallet-core is the background wallet engine; keep the component name unchanged. */ i18n.str`Wallet-core could not prepare this payment.`, - ), - ); - setCanRetry(true); - setState("error"); - return; - } - navigate(`/pay/${result.value.transactionId}/${action.id}`); - } catch (error) { - if (!request.active) return; - if (isProgressRequestCancelled(error)) { - request.active = false; - void completeActionBestEffort(platform.actionInbox, action.id); - navigate("/"); - } else { - setActionError( - errorFromException(error, i18n.str`Action preparation failed`), - ); - setCanRetry(true); - setState("error"); - } - } finally { - request.preparing = false; - } - }, - [navigate, platform, progressRequest], - ); const parsed = useMemo( () => (entry ? TalerUris.parse(entry.uri) : undefined), [entry], @@ -3256,8 +3250,6 @@ function ActionRoute() { ); useEffect(() => { let active = true; - const request = { active: true, preparing: false }; - paymentRequest.current = request; setEntry(undefined); setState("loading"); setDetail(undefined); @@ -3275,7 +3267,7 @@ function ActionRoute() { Result.isOk(uri) && uri.value.type === TalerUriAction.Pay ) { - void preparePayment(value); + navigate(actionRoute(value), { replace: true }); } else { setState(value ? "ready" : "missing"); } @@ -3287,16 +3279,13 @@ function ActionRoute() { }); return () => { active = false; - request.active = false; }; - }, [params?.id, platform, preparePayment]); + }, [params?.id, platform, navigate]); const discard = () => { - paymentRequest.current.active = false; void completeActionBestEffort(platform.actionInbox, params?.id); navigate("/"); }; const back = () => { - paymentRequest.current.active = false; navigate("/"); }; const prepare = async () => { @@ -3314,7 +3303,7 @@ function ActionRoute() { setState("error"); return; } else if (parsed.value.type === TalerUriAction.Pay) { - await preparePayment(entry); + navigate(actionRoute(entry), { replace: true }); return; } else if (parsed.value.type === TalerUriAction.PayTemplate) { const checked = await progressRequest.callForResult( @@ -4156,13 +4145,79 @@ function PaymentTemplateRoute() { ); } -function PaymentRoute() { +function PrepareCheckout({ actionId }: { actionId: string }) { + const { connection, platform } = useServices(); + const [, navigate] = useLocation(); + const { controller } = useWalletProgress(connection); + const [error, setError] = useState<ErrorPresentation>(); + const [attempt, setAttempt] = useState(0); + const backToWallet = useCallback(() => { + void completeActionBestEffort(platform.actionInbox, actionId); + navigate("/"); + }, [actionId, platform, navigate]); + useEffect(() => { + let active = true; + setError(undefined); + void (async () => { + try { + const action = await platform.actionInbox.get(actionId); + if (!active) return; + if (!action || !isPaymentUri(action.uri)) { + setError( + localError(i18n.str`This action expired or was already completed.`), + ); + return; + } + const result = await controller.callAndInvalidate( + WalletApiOperation.PreparePayForUriV2, + { talerPayUri: action.uri }, + ["transactions"], + ); + if (!active) return; + if (Result.isError(result)) { + setError( + walletCoreError( + result.detail, + i18n.str`Wallet-core could not prepare this payment.`, + ), + ); + return; + } + navigate(`/checkout/${actionId}/${result.value.transactionId}`, { + replace: true, + }); + } catch (cause) { + if (!active) return; + if (isProgressRequestCancelled(cause)) backToWallet(); + else + setError( + errorFromException(cause, i18n.str`Action preparation failed`), + ); + } + })(); + return () => { + active = false; + }; + }, [actionId, attempt, platform, navigate, controller, backToWallet]); + return ( + <PaymentLoading + onBack={backToWallet} + error={error} + onRetry={() => setAttempt(attempt + 1)} + /> + ); +} + +function PaymentRoute({ + transactionId, + actionId, +}: { + transactionId: TransactionIdStr; + actionId: string; +}) { const { connection, platform } = useServices(); const callMutation = useWalletMutation(connection); - const [, params] = useRoute("/pay/:transactionId/:actionId"); const [, navigate] = useLocation(); - const transactionId = (params?.transactionId ?? "") as TransactionIdStr; - const actionId = params?.actionId ?? ""; const { fulfillmentTarget, browserCheckout, @@ -4321,18 +4376,7 @@ function PaymentRoute() { fulfillmentTarget === undefined || !payment ) - return ( - <PaymentScreen - onRetryObservation={view.canRetry ? view.retry : undefined} - state="loading" - onSelectChoice={() => {}} - onConfirm={() => {}} - onWithdraw={() => navigate("/withdraw")} - onBack={completeAndReturn} - onCancel={completeAndReturn} - onOpenFulfillment={() => {}} - /> - ); + return <PaymentLoading onBack={completeAndReturn} />; const transaction = payment; const terms = contract.terms; if (!transaction.info) { @@ -5078,7 +5122,10 @@ function SettingsRoute() { } catch (error) { setMessage(undefined); setSettingsError( - errorFromException(error, i18n.str`Could not download the current wallet.`), + errorFromException( + error, + i18n.str`Could not download the current wallet.`, + ), ); } finally { setBusy(false); diff --git a/packages/wallet-webui/src/screens/PaymentScreen.tsx b/packages/wallet-webui/src/screens/PaymentScreen.tsx @@ -435,6 +435,33 @@ export function PaymentHandoff(props: { ); } +export function PaymentLoading(props: { + error?: ErrorPresentation; + onRetry?: () => void; + onBack?: () => void; +}) { + return ( + <div class="mx-auto max-w-2xl space-y-5"> + <h1 class="text-2xl font-medium">{i18n.str`Payment`}</h1> + {props.error ? ( + <ErrorCard error={props.error}> + <Button onClick={props.onRetry}>{i18n.str`Retry`}</Button> + </ErrorCard> + ) : ( + <Card> + <p role="status">{i18n.str`Loading payment details…`}</p> + </Card> + )} + {props.onBack && ( + <Button + tone="secondary" + onClick={props.onBack} + >{i18n.str`Back to wallet`}</Button> + )} + </div> + ); +} + export function PaymentScreen(props: { state: PaymentScreenState; merchantName?: string; @@ -478,6 +505,8 @@ export function PaymentScreen(props: { onCopyPosConfirmation?: (code: string) => void; }) { const [confirmUnclaim, setConfirmUnclaim] = useState(false); + if (props.state === "loading") + return <PaymentLoading onBack={props.onBack} />; // Translators: Payment subtitle; the placeholder is the merchant's display // name. “to” expresses that the payment is being made to this merchant. const merchantSubtitle = i18n.str`to ${props.merchantName ?? ""}`; @@ -508,12 +537,6 @@ export function PaymentScreen(props: { </div> </div> - {props.state === "loading" && ( - <Card> - <p role="status">{i18n.str`Loading payment details…`}</p> - </Card> - )} - {props.state === "error" && ( <ErrorCard title={i18n.str`Payment could not continue`} diff --git a/packages/wallet-webui/test/payment-entry.test.tsx b/packages/wallet-webui/test/payment-entry.test.tsx @@ -264,12 +264,16 @@ test("automatic payment preparation requires explicit retry after failure", asyn } }); -test("cancelled payment preparation cannot navigate back to review", async () => { +test("leaving payment preparation cannot navigate back to review", async () => { const h = await harness("protocol", "delayed"); try { await h.waitFor(() => assert.equal(h.counts().prepares, 1)); + assert.ok(h.view.getByText("Loading payment details…")); + assert.equal(h.view.queryByText("Wallet action"), null); await h.act(() => - h.view.getByRole("button", { name: "Cancel", exact: true }).click(), + h.view + .getByRole("button", { name: "Back to wallet", exact: true }) + .click(), ); h.release(); await h.waitFor(() => diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx @@ -582,6 +582,8 @@ test("a failed claim observation shows retry despite retained claim progress", a try { await h.waitFor(() => assert.equal(h.registrations.length, 1)); assert.ok(h.view.getByText("Loading payment details…")); + assert.ok(h.view.getByRole("button", { name: "Back to wallet" })); + assert.equal(h.view.queryByRole("button", { name: "Cancel" }), null); await h.act(async () => h.failObservation()); await h.waitFor(() => assert.ok(h.view.getByRole("button", { name: "Retry updates" })),