taler-typescript-core

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

commit e7b20cdb86f77cdc782177b5d60c514c20c11005
parent 507ea73ebef11c2b901abcb738fb2e501b4f6a64
Author: Florian Dold <dold@taler.net>
Date:   Thu, 26 Nov 2026 04:23:57 +0100

wallet-webui: recheck the deposit link and quote before sending

An expired link could fall back to a saved recipient, and a fresh
deposit could reuse an old draft. Match the draft to its recovery link
and recheck the recipient and quote before sending. Keep the transaction
ID so the wallet can look up the deposit after a lost reply.

Diffstat:
Mpackages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-peer-deposit.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/routes/App.tsx | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mpackages/wallet-webui/test/payment-entry.test.tsx | 240+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 543 insertions(+), 27 deletions(-)

diff --git a/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-peer-deposit.ts b/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-peer-deposit.ts @@ -271,6 +271,70 @@ export async function runWalletWebUiPwaPeerDepositTest(t: GlobalTestState) { .waitFor(); }); + await stage.step( + "review payment instructions and revisit a cancelled bank link", + async (page) => { + await waitForSpendablePeerFunds(page, senderUrl); + const link = + getTestHarnessPaytoForLabel("other-recipient") + + "&amount=TESTKUDOS%3A3.25&message=Invoice%2042"; + await page.goto(`${senderUrl}#/enter`); + await page.getByLabel("Wallet link").fill(link); + await page + .getByRole("button", { name: "Open link", exact: true }) + .click(); + await page + .getByRole("button", { name: "Continue", exact: true }) + .click(); + const input = page.getByLabel("Amount", { exact: true }); + await input.waitFor(); + if ((await input.inputValue()) !== "3.25") + throw Error("deposit link amount was lost"); + await page.getByText("Invoice 42", { exact: true }).waitFor(); + await page.getByRole("button", { name: "Review deposit" }).click(); + const confirm = page.getByRole("button", { name: "Confirm deposit" }); + await confirm.waitFor(); + if (await confirm.isEnabled()) + throw Error("unacknowledged reference was accepted"); + await page.getByRole("checkbox").check(); + if (!(await confirm.isEnabled())) + throw Error("acknowledged cash-out was unavailable"); + await page + .getByRole("button", { name: "Change", exact: true }) + .click(); + await input.fill("2"); + await page.getByRole("button", { name: "Review deposit" }).click(); + await confirm.waitFor(); + if (await confirm.isEnabled()) + throw Error("editing retained the prior acknowledgment"); + await page + .getByRole("button", { name: "Change", exact: true }) + .click(); + await page + .getByRole("button", { name: "Cancel", exact: true }) + .click(); + await page + .getByRole("heading", { name: "Balances", exact: true }) + .waitFor(); + await page.goBack(); + await page + .getByText("This bank-account action expired or is invalid.", { + exact: true, + }) + .waitFor(); + await page + .getByRole("button", { name: "Start a new deposit" }) + .waitFor(); + if ( + (await input.count()) || + (await confirm.count()) || + (await page.getByRole("button", { name: "Review deposit" }).count()) + ) { + throw Error("cancelled deposit link exposed a transfer form"); + } + }, + ); + await stage.step("create deposit from saved account", async (page) => { await waitForSpendablePeerFunds(page, senderUrl); await page.goto(`${senderUrl}#/deposit?currency=TESTKUDOS`); diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -10,6 +10,7 @@ import { } from "../api/observations.js"; import { Amounts, + depositQuotesMatch, ExchangeTosStatus, Paytos, Result, @@ -51,6 +52,7 @@ import { type HistoryFilter, } from "../api/transaction-history.js"; import { isWalletKey } from "../api/canonical.js"; +import { HostDisconnectedError } from "../api/rpc.js"; import type { AppServices } from "./context.js"; import { ServicesContext, useServices } from "./context.js"; import { operationsForNotification } from "../api/notifications.js"; @@ -1339,12 +1341,15 @@ function loadDepositGateDraft(returnTo: string): DepositGateDraft | undefined { returnTo?: unknown; draft?: Partial<DepositGateDraft>; }; + if (value.returnTo !== returnTo) return undefined; if ( typeof value.savedAt !== "number" || - value.returnTo !== returnTo || Date.now() - value.savedAt > 30 * 60 * 1000 || + value.savedAt > Date.now() || typeof value.draft?.amount !== "string" || - typeof value.draft.paytoUri !== "string" + !Amounts.parse(value.draft.amount) || + typeof value.draft.paytoUri !== "string" || + !Paytos.parsePaytoUri(value.draft.paytoUri)?.targetType ) { sessionStorage.removeItem(depositGateDraftKey); return undefined; @@ -1366,9 +1371,10 @@ function saveDepositGateDraft(returnTo: string, draft: DepositGateDraft): void { } } -function clearDepositGateDraft(): void { +function clearDepositGateDraft(returnTo: string): void { try { - sessionStorage.removeItem(depositGateDraftKey); + if (loadDepositGateDraft(returnTo)) + sessionStorage.removeItem(depositGateDraftKey); } catch { // Nothing else to clear. } @@ -1425,8 +1431,24 @@ function DepositRoute() { eligibleBalances[0]; const currency = initialBalance?.scopeInfo.currency ?? requestedCurrency; const actionId = actionParams?.actionId ?? hashQueryValue("actionId"); - const returnTo = actionId ? `/deposit-action/${actionId}` : "/deposit"; - const [gateDraft] = useState(() => loadDepositGateDraft(returnTo)); + const returnTo = window.location.hash.slice(1); + const returningFromRecovery = hashRouteParameters(returnTo).has("recovery"); + const [gateDraft] = useState(() => + returningFromRecovery ? loadDepositGateDraft(returnTo) : undefined, + ); + const [submittedId, setSubmittedId] = useState<TransactionIdStr | undefined>( + () => { + const submission = window.history.state?.depositSubmission; + return submission?.route === returnTo && + typeof submission.id === "string" && + /^txn:deposit:[a-zA-Z0-9-]+$/.test(submission.id) + ? submission.id + : undefined; + }, + ); + const [actionFailure, setActionFailure] = useState<ErrorPresentation>(); + const [actionRetryable, setActionRetryable] = useState(false); + const [actionAttempt, setActionAttempt] = useState(0); const [actionLoading, setActionLoading] = useState(actionId.length > 0); const [prepared, setPrepared] = useState<{ amount: AmountString; @@ -1438,14 +1460,25 @@ function DepositRoute() { const [error, setError] = useState<ErrorPresentation>(); const [recovery, setRecovery] = useState<ExchangeKeyRecovery>(); const [recoveryDraft, setRecoveryDraft] = useState<DepositGateDraft>(); + const confirming = useRef(false); + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); useEffect(() => { if (!actionId) return; let active = true; + setActionLoading(true); + setActionFailure(undefined); + setActionRetryable(false); void platform.actionInbox.get(actionId).then( (entry) => { if (!active) return; if (!entry || Result.isError(Paytos.fromString(entry.uri))) { - setError( + setActionFailure( localError( i18n.str`This bank-account action expired or is invalid.`, ), @@ -1457,7 +1490,8 @@ function DepositRoute() { }, (cause) => { if (!active) return; - setError( + setActionRetryable(true); + setActionFailure( errorFromException( cause, i18n.str`The bank-account action could not be loaded.`, @@ -1469,7 +1503,27 @@ function DepositRoute() { return () => { active = false; }; - }, [actionId, platform]); + }, [actionId, actionAttempt, platform]); + const linkIsCurrent = async () => { + if (!actionId) return true; + try { + const entry = await platform.actionInbox.get(actionId); + if (initialPaytoUri && entry?.uri === initialPaytoUri) return true; + setActionFailure( + localError(i18n.str`This bank-account action expired or is invalid.`), + ); + } catch (cause) { + setActionRetryable(true); + setActionFailure( + errorFromException( + cause, + i18n.str`The bank-account action could not be loaded.`, + ), + ); + } + setPrepared(undefined); + return false; + }; const review = async (values: { currency: string; amount: string; @@ -1480,6 +1534,7 @@ function DepositRoute() { setError(undefined); setRecovery(undefined); try { + if (!(await linkIsCurrent())) return; const amount = amountFromForm(values); const paytoUri = validatedPaytoUri(values.paytoUri); const result = await progressRequest.callForResult( @@ -1529,22 +1584,95 @@ function DepositRoute() { } }; const confirm = async () => { - if (!prepared) return; - if (!(await durability.guardValueOperation())) return; + if (!prepared || confirming.current) return; + confirming.current = true; setWorking(true); setError(undefined); setRecovery(undefined); + let sentId: TransactionIdStr | undefined; + const clearSubmission = () => { + if (sentId && window.history.state?.depositSubmission?.id === sentId) { + const state = { ...window.history.state }; + delete state.depositSubmission; + window.history.replaceState(state, ""); + } + sentId = undefined; + }; try { - const result = await progressRequest.callAndInvalidate( - WalletApiOperation.CreateDepositGroup, + if (!(await durability.guardValueOperation()) || !mounted.current) return; + const request = { + amount: prepared.amount, + depositPaytoUri: prepared.paytoUri, + ...(prepared.scope ? { restrictScope: prepared.scope } : {}), + }; + const changedQuote = (response: CheckDepositResponse) => { + setPrepared({ ...prepared, response }); + setError( + localError( + i18n.str`The deposit quote changed. Review the new details before confirming.`, + ), + ); + }; + if (link) { + const checked = await progressRequest.callForResult( + WalletApiOperation.CheckDeposit, + request, + ); + if (Result.isError(checked)) { + setPrepared(undefined); + setError( + walletErrorHint( + checked.detail, + i18n.str`The wallet could not prepare this deposit.`, + ), + ); + return; + } + if (!depositQuotesMatch(prepared.response, checked.value)) { + changedQuote(checked.value); + return; + } + } + if (!(await linkIsCurrent()) || !mounted.current) return; + // Reopening a link uses the same deposit ID. Reloading a submitted form + // must lead to that transaction even if the wallet's reply was lost. + const transactionId = + `txn:deposit:${actionId || crypto.randomUUID()}` as TransactionIdStr; + window.history.replaceState( { - amount: prepared.amount, - depositPaytoUri: prepared.paytoUri, - ...(prepared.scope ? { restrictScope: prepared.scope } : {}), + ...window.history.state, + depositSubmission: { route: returnTo, id: transactionId }, }, + "", + ); + sentId = transactionId; + const result = await progressRequest.callAndInvalidate( + WalletApiOperation.CreateDepositGroup, + { ...request, expectedQuote: prepared.response, transactionId }, ["balances", "transactions"], ); if (Result.isError(result)) { + clearSubmission(); + if ( + result.error === TalerErrorCode.WALLET_CORE_API_BAD_REQUEST && + (result.detail as { parameter?: string })?.parameter === + "expectedQuote" + ) { + setPrepared(undefined); + const checked = await progressRequest.callForResult( + WalletApiOperation.CheckDeposit, + request, + ); + if (Result.isOk(checked)) changedQuote(checked.value); + else + setError( + walletErrorHint( + checked.detail, + i18n.str`The wallet could not prepare this deposit.`, + ), + ); + return; + } const nextRecovery = exchangeKeyRecoveryFromError(result.detail) ?? exchangeKeyRecoveryFromInsufficientBalance( @@ -1566,11 +1694,33 @@ function DepositRoute() { ), ); } else { - clearDepositGateDraft(); - navigate(`/transaction/${result.value.transactionId}`); + if (gateDraft) clearDepositGateDraft(returnTo); void completeActionBestEffort(platform.actionInbox, actionId); + if (mounted.current) + navigate(`/transaction/${result.value.transactionId}`, { + replace: true, + }); } } catch (cause) { + if ( + sentId && + !( + cause instanceof HostDisconnectedError && cause.outcome === "not-sent" + ) + ) { + try { + await connection.client.call(WalletApiOperation.GetTransactionById, { + transactionId: sentId, + }); + void completeActionBestEffort(platform.actionInbox, actionId); + if (mounted.current) + navigate(`/transaction/${sentId}`, { replace: true }); + } catch { + if (mounted.current) setSubmittedId(sentId); + } + return; + } + clearSubmission(); if (!isProgressRequestCancelled(cause)) setError( errorFromException( @@ -1579,9 +1729,69 @@ function DepositRoute() { ), ); } finally { - setWorking(false); + confirming.current = false; + if (mounted.current) setWorking(false); } }; + if (submittedId) + return ( + <div class="mx-auto max-w-2xl space-y-4"> + <h1 class="text-2xl font-medium">{i18n.str`Deposit to a bank account`}</h1> + <p role="status">{i18n.str`The wallet could not verify whether this deposit was created. Check the transaction before starting another deposit.`}</p> + <Button + onClick={() => navigate(`/transaction/${submittedId}`)} + >{i18n.str`View transaction`}</Button> + <Button + tone="secondary" + onClick={() => navigate("/")} + >{i18n.str`Back to balances`}</Button> + </div> + ); + const recoveryAccount = + gateDraft && !actionId + ? accounts.data?.accounts.find( + (account) => account.paytoUri === gateDraft.paytoUri, + ) + : undefined; + const invalidRecovery = + returningFromRecovery && + (!gateDraft || + (actionId + ? initialPaytoUri !== gateDraft.paytoUri + : Boolean(accounts.data && !recoveryAccount))); + if ( + invalidRecovery || + (actionId && (actionLoading || actionFailure || !initialPaytoUri)) + ) { + if (actionLoading) return <p role="status">{i18n.str`Loading action…`}</p>; + return ( + <div class="mx-auto max-w-2xl space-y-4"> + <h1 class="text-2xl font-medium">{i18n.str`Deposit to a bank account`}</h1> + <ErrorCard + error={ + actionFailure ?? + localError( + i18n.str`This bank-account action expired or is invalid.`, + ) + } + /> + <div class="flex flex-wrap gap-3"> + {actionRetryable && ( + <Button + onClick={() => setActionAttempt((value) => value + 1)} + >{i18n.str`Retry`}</Button> + )} + <Button + onClick={() => navigate("/enter")} + >{i18n.str`Enter a wallet link`}</Button> + <Button + tone="secondary" + onClick={() => navigate("/deposit", { replace: true })} + >{i18n.str`Start a new deposit`}</Button> + </div> + </div> + ); + } const response = prepared?.response; const loading = accounts.isLoading || balances.isLoading || actionLoading; const initialScopeId = gateDraft?.scope @@ -1609,16 +1819,15 @@ function DepositRoute() { available: balance.available, scope: balance.scopeInfo, }))} - initialPaytoUri={gateDraft?.paytoUri ?? initialPaytoUri} + initialPaytoUri={initialPaytoUri} + initialAccountId={recoveryAccount?.bankAccountId} initialAmount={ suggested ? Amounts.stringifyValue(Amounts.parseOrThrow(suggested)) : undefined } initialDestination={ - gateDraft?.paytoUri || initialPaytoUri - ? depositDestinationView(gateDraft?.paytoUri ?? initialPaytoUri!) - : undefined + initialPaytoUri ? depositDestinationView(initialPaytoUri) : undefined } accounts={accounts.data?.accounts.map((account) => ({ id: account.bankAccountId, @@ -1647,8 +1856,12 @@ function DepositRoute() { onErrorAction={ recovery ? () => { - if (recoveryDraft) saveDepositGateDraft(returnTo, recoveryDraft); - navigate(exchangeRecoveryRoute(recovery, returnTo)); + if (!recoveryDraft) return; + const query = hashRouteParameters(returnTo); + query.set("recovery", crypto.randomUUID()); + const resumeRoute = `${walletRoutePath(returnTo)}?${query}`; + saveDepositGateDraft(resumeRoute, recoveryDraft); + navigate(exchangeRecoveryRoute(recovery, resumeRoute)); } : undefined } @@ -1694,12 +1907,11 @@ function DepositRoute() { onReview={(values) => void review(values)} onConfirm={() => void confirm()} onBack={() => { - clearDepositGateDraft(); setPrepared(undefined); setError(undefined); }} onCancel={() => { - clearDepositGateDraft(); + if (gateDraft) clearDepositGateDraft(returnTo); void completeActionBestEffort(platform.actionInbox, actionId); navigate("/"); }} diff --git a/packages/wallet-webui/test/payment-entry.test.tsx b/packages/wallet-webui/test/payment-entry.test.tsx @@ -19,6 +19,7 @@ import test from "node:test"; import { register } from "node:module"; import { Window } from "happy-dom"; import { + type CheckDepositResponse, TalerError, TalerErrorCode, Result, @@ -260,6 +261,245 @@ test("entering a payto link opens a deposit to the pasted account", async () => } }); +test("a saved deposit draft resumes only from its own exchange recovery link", async () => { + const h = await harness("paste"); + try { + const original = h.services.connection.client.callForResult; + h.services.connection.client.callForResult = async (operation, request) => { + if (operation === WalletApiOperation.CheckDeposit) { + const code = TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE; + return Result.errorWithDetail(code, { + code, + insufficientBalanceDetails: { + exchanges: { + "https://exchange.demo.invalid/": { + reasons: [{ type: "superseded-exchange-master-pub" }], + }, + }, + }, + }) as never; + } + return original(operation, request); + }; + h.dom.location.hash = "#/deposit?currency=CHF"; + await h.waitFor(() => assert(h.view.getByLabelText("Amount"))); + const amount = h.view.getByLabelText<HTMLInputElement>("Amount"); + await h.act(() => { + amount.value = "2.55"; + amount.dispatchEvent(new Event("input", { bubbles: true })); + }); + await h.act(() => + h.view.getByRole("button", { name: "Review deposit" }).click(), + ); + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Manage legacy balance" })), + ); + await h.act(() => + h.view.getByRole("button", { name: "Manage legacy balance" }).click(), + ); + const resume = new URLSearchParams(h.dom.location.hash.split("?")[1]).get( + "returnTo", + ); + assert(resume?.startsWith("/deposit?")); + h.dom.location.hash = `#${resume}`; + await h.waitFor(() => + assert.equal( + h.view.getByLabelText<HTMLInputElement>("Amount").value, + "2.55", + ), + ); + assert.equal( + h.view.getByLabelText<HTMLSelectElement>("Bank account").value, + "demo-account-1", + ); + h.dom.location.hash = "#/deposit?currency=CHF"; + await h.waitFor(() => + assert.equal(h.view.getByLabelText<HTMLInputElement>("Amount").value, ""), + ); + h.dom.location.hash = "#/deposit?recovery=unknown"; + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Start a new deposit" })), + ); + assert.equal( + h.view.queryByRole("button", { name: "Review deposit" }), + null, + ); + } finally { + await h.close(); + } +}); + +for (const outcome of ["confirmed", "expired", "left"] as const) { + test(`linked deposit confirmation checks the action after a delayed quote (${outcome})`, async () => { + const h = await harness("paste"); + let release!: () => void; + const gate = new Promise<void>((resolve) => { + release = resolve; + }); + try { + let quotes = 0; + let creates = 0; + const original = h.services.connection.client.callForResult; + h.services.connection.client.callForResult = async ( + operation, + request, + ) => { + if (operation === WalletApiOperation.CheckDeposit && ++quotes >= 2) + await gate; + if (operation === WalletApiOperation.CreateDepositGroup) creates++; + return original(operation, request); + }; + await h.pasteLink("payto://x-taler-bank/bank.example/alice?amount=CHF:3"); + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Continue" })), + ); + await h.act(() => + h.view.getByRole("button", { name: "Continue" }).click(), + ); + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Review deposit" })), + ); + await h.act(() => + h.view.getByRole("button", { name: "Review deposit" }).click(), + ); + await h.waitFor(() => assert(h.view.getByRole("checkbox"))); + await h.act(() => h.view.getByRole("checkbox").click()); + const confirm = h.view.getByRole("button", { name: "Confirm deposit" }); + await h.act(() => { + confirm.click(); + confirm.click(); + }); + await h.waitFor(() => assert.equal(quotes, 2)); + assert( + h.view.getByRole("button", { name: "Change" }).hasAttribute("disabled"), + ); + if (outcome === "expired") { + await makePwaPlatform().actionInbox.complete( + h.dom.location.hash.split("/").pop()!, + ); + } + if (outcome === "left") { + h.dom.location.hash = "#/enter"; + await h.waitFor(() => assert(h.view.getByLabelText("Wallet link"))); + } + await h.act(async () => { + release(); + await gate; + }); + if (outcome === "confirmed") { + await h.waitFor(() => + assert.match(h.dom.location.hash, /^#\/transaction\//), + ); + assert.equal(creates, 1); + } else if (outcome === "expired") { + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Start a new deposit" })), + ); + assert.equal(creates, 0); + } else { + assert.equal(h.dom.location.hash, "#/enter"); + assert.equal(creates, 0); + } + } finally { + release(); + await h.close(); + } + }); +} + +for (const outcome of [ + "changed", + "lost after creation", + "disconnected", +] as const) { + test(`a saved-account deposit handles a confirmation that is ${outcome}`, async () => { + const h = await harness("paste"); + try { + let quotes = 0; + let creates = 0; + const original = h.services.connection.client.callForResult; + h.services.connection.client.callForResult = async ( + operation, + request, + ) => { + if (operation === WalletApiOperation.CheckDeposit) { + const result = await original(operation, request); + if (++quotes === 1 && outcome === "changed" && Result.isOk(result)) { + return Result.of({ + ...(result.value as CheckDepositResponse), + totalDepositCost: "CHF:4.00", + }) as never; + } + return result; + } + if (operation === WalletApiOperation.CreateDepositGroup) { + creates++; + if (outcome === "disconnected") throw Error("lost wallet connection"); + const result = await original(operation, request); + if (outcome === "lost after creation") throw Error("lost reply"); + return result; + } + return original(operation, request); + }; + h.dom.location.hash = "#/deposit"; + await h.waitFor(() => assert(h.view.getByLabelText("Amount"))); + const field = h.view.getByLabelText<HTMLInputElement>("Amount"); + await h.act(() => { + field.value = "3"; + field.dispatchEvent(new Event("input", { bubbles: true })); + }); + await h.act(() => + h.view.getByRole("button", { name: "Review deposit" }).click(), + ); + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Confirm deposit" })), + ); + await h.act(() => + h.view.getByRole("button", { name: "Confirm deposit" }).click(), + ); + if (outcome === "changed") { + await h.waitFor(() => + assert(h.view.getByText(/The deposit quote changed/)), + ); + assert(h.view.getByText("CHF:3.20")); + const balances = await h.services.connection.client.call( + WalletApiOperation.GetBalances, + {}, + ); + assert.equal(balances.balances[0].available, "CHF:42.50"); + await h.act(() => + h.view.getByRole("button", { name: "Confirm deposit" }).click(), + ); + } + if (outcome === "disconnected") { + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "View transaction" })), + ); + await h.remount(); + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "View transaction" })), + ); + assert.equal( + h.view.queryByRole("button", { name: "Confirm deposit" }), + null, + ); + } else { + await h.waitFor(() => + assert.match(h.dom.location.hash, /^#\/transaction\//), + ); + const balances = await h.services.connection.client.call( + WalletApiOperation.GetBalances, + {}, + ); + assert.equal(balances.balances[0].available, "CHF:39.30"); + } + assert.equal(creates, outcome === "changed" ? 2 : 1); + } finally { + await h.close(); + } + }); +} + test("automatic payment preparation requires explicit retry after failure", async () => { const h = await harness("protocol", "failure"); try {