commit ff8ae441aed3cabf6d93bddd5895cb14f2b2c1ca parent f0081559d9e7a0c5005bc65db467640fd0a66741 Author: Florian Dold <dold@taler.net> Date: Fri, 25 Sep 2026 00:09:46 +0200 wallet web UI: import and manage fountains from Developer settings Carry onboarding data through the wallet’s hash-based navigation and clear it after import. Hide fountain entry points when disabled and update the active view on wallet notifications. Diffstat:
11 files changed, 630 insertions(+), 50 deletions(-)
diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -238,6 +238,8 @@ import { watchWalletReconnection, } from "../platform/lifecycle.js"; import { i18n } from "../i18n/runtime.js"; +import { navigateWalletHash, walletRouteHref } from "./hash-location.js"; +import { FountainsRoute } from "./FountainsRoute.js"; import { LanguageProvider, useLanguage } from "../i18n/LanguageProvider.js"; import { WalletUpdateBanner } from "../ui/WalletUpdateBanner.js"; import { @@ -266,33 +268,9 @@ export function walletRoutePath(location: string): string { return location.split("?", 1)[0] || "/"; } -function walletRouteHref(path: string): string { - return `#/${path.replace(/^#?\/?/, "")}`; -} - -function navigateWalletRoute( - path: string, - { - replace = false, - state = null, - }: { replace?: boolean; state?: unknown } = {}, -): void { - const oldURL = window.location.href; - const href = walletRouteHref(path); - if (replace) window.history.replaceState(state, "", href); - else window.history.pushState(state, "", href); - // The History API does not fire the event used by useHashLocation. - window.dispatchEvent( - new window.HashChangeEvent("hashchange", { - oldURL, - newURL: window.location.href, - }), - ); -} - function useWalletHashLocation(): ReturnType<typeof useHashLocation> { const [location] = useHashLocation(); - return [walletRoutePath(location), navigateWalletRoute]; + return [walletRoutePath(location), navigateWalletHash]; } export function App(props: AppServices) { @@ -519,6 +497,7 @@ function HostRecoveryNotice() { } function WalletShell() { + const { fountainsEnabled } = useUiPreferences(); const { connection, demo } = useServices(); const attention = useWalletQuery( connection, @@ -546,6 +525,7 @@ function WalletShell() { : /* Translators: The UI has lost its connection to its background wallet engine. */ i18n.str`Disconnected`; return ( <Shell + fountainsEnabled={fountainsEnabled} connectionLabel={label} hasUnreadAttention={unreadCount > 0} demo={ @@ -640,6 +620,7 @@ function WalletShell() { <Route path="/accounts" component={BankAccountsRoute} /> <Route path="/discounts" component={DiscountsRoute} /> <Route path="/passes" component={PassesRoute} /> + <Route path="/fountains" component={FountainsRoute} /> <Route path="/recovery" component={StorageRecoveryRoute} /> <Route> <Redirect to="/" /> @@ -1012,6 +993,11 @@ function BalanceRoute() { onShowTransactions={(scope) => withScope("/transactions", scope)} onShowDiscounts={() => navigate("/discounts")} onShowPasses={() => navigate("/passes")} + onShowFountains={ + uiPreferences.fountainsEnabled + ? () => navigate("/fountains") + : undefined + } onShowDonations={() => navigate("/donations")} onEnterLink={() => navigate("/enter")} onScan={() => navigate("/scan")} @@ -3538,6 +3524,10 @@ function QrScanRoute() { function ActionRoute() { const { connection, platform } = useServices(); + const { fountainsEnabled } = useUiPreferences(); + const fountainEnabledRef = useRef(fountainsEnabled); + fountainEnabledRef.current = fountainsEnabled; + const durability = useDurability(); const [, params] = useRoute("/action/:id"); const [, navigate] = useLocation(); const { controller: progressRequest } = useWalletProgress(connection); @@ -3792,6 +3782,60 @@ function ActionRoute() { setState("complete"); void completeActionBestEffort(platform.actionInbox, entry.id); return; + } else if (parsed.value.type === TalerUriAction.Fountain) { + if (!fountainEnabledRef.current) { + navigate( + `/settings?feature=fountains&returnTo=${encodeURIComponent(`/action/${entry.id}`)}`, + ); + setState("ready"); + return; + } + try { + const allowed = await durability.guardValueOperation(); + if (activeEntry.current !== entry.id) return; + if (!allowed || !fountainEnabledRef.current) { + setState("ready"); + return; + } + const result = await connection.client.callForResult( + WalletApiOperation.ImportFountain, + { talerFountainUri: entry.uri }, + ); + if (Result.isError(result)) { + if (activeEntry.current !== entry.id) return; + setActionError( + walletCoreError( + result.detail, + i18n.str`The fountain could not be imported.`, + ), + ); + setCanRetry(true); + setState("error"); + return; + } + // Import has succeeded even if revalidating a view fails. + void mutate( + (key) => + isWalletKey(key) && key[1] === WalletApiOperation.ListFountains, + ).catch(() => {}); + void completeActionBestEffort(platform.actionInbox, entry.id); + if (activeEntry.current === entry.id) + navigate( + `/fountains?focus=${encodeURIComponent(result.value.fountainId)}`, + ); + } catch (error) { + if (activeEntry.current === entry.id) { + setActionError( + errorFromException( + error, + i18n.str`The fountain could not be imported.`, + ), + ); + setCanRetry(true); + setState("error"); + } + } + return; } else if (parsed.value.type === TalerUriAction.Restore) { setDetail(restoreActionGateReason()); setState("error"); @@ -3854,30 +3898,38 @@ function ActionRoute() { detail={ detail ?? (parsed && Result.isOk(parsed) - ? parsed.value.type === TalerUriAction.AddExchange - ? /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`Add ${parsed.value.exchangeBaseUrl} as a wallet exchange.` - : parsed.value.type === TalerUriAction.DevExperiment - ? entry?.source === "qr" - ? i18n.str`This QR code requests the developer experiment “${parsed.value.devExperimentId}”. Experiments can deliberately alter wallet behavior or data. Only continue if you trust its source.` - : i18n.str`This link requests the developer experiment “${parsed.value.devExperimentId}”. Experiments can deliberately alter wallet behavior or data. Only continue if you trust its source.` - : parsed.value.type === TalerUriAction.WithdrawalTransferResult - ? withdrawalTransferResultHint(parsed.value.status) - : parsed.value.type === TalerUriAction.Restore - ? restoreActionGateReason() - : parsed.value.type === TalerUriAction.AddContact - ? i18n.str`This wallet cannot add contacts from a link.` - : undefined + ? parsed.value.type === TalerUriAction.Fountain + ? fountainsEnabled + ? i18n.str`Import fountain ${parsed.value.fountainId} from ${parsed.value.merchantBaseUrl}? Your wallet will contact this merchant and automatically collect its discounts and passes while the wallet is running.` + : i18n.str`Fountain support is disabled. Enable it in Developer settings to review this import.` + : parsed.value.type === TalerUriAction.AddExchange + ? /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`Add ${parsed.value.exchangeBaseUrl} as a wallet exchange.` + : parsed.value.type === TalerUriAction.DevExperiment + ? entry?.source === "qr" + ? i18n.str`This QR code requests the developer experiment “${parsed.value.devExperimentId}”. Experiments can deliberately alter wallet behavior or data. Only continue if you trust its source.` + : i18n.str`This link requests the developer experiment “${parsed.value.devExperimentId}”. Experiments can deliberately alter wallet behavior or data. Only continue if you trust its source.` + : parsed.value.type === TalerUriAction.WithdrawalTransferResult + ? withdrawalTransferResultHint(parsed.value.status) + : parsed.value.type === TalerUriAction.Restore + ? restoreActionGateReason() + : parsed.value.type === TalerUriAction.AddContact + ? i18n.str`This wallet cannot add contacts from a link.` + : undefined : undefined) } continueLabel={ parsed && Result.isOk(parsed) - ? parsed.value.type === TalerUriAction.WithdrawalTransferResult - ? /* Translators: Withdrawing adds digital cash to this wallet, usually funded by a bank transfer; it does not cash out the wallet to a bank account. */ i18n.str`View withdrawal` - : parsed.value.type === TalerUriAction.DevExperiment - ? version.data?.devMode === true - ? i18n.str`Apply experiment` - : i18n.str`Review developer settings` - : undefined + ? parsed.value.type === TalerUriAction.Fountain + ? fountainsEnabled + ? i18n.str`Import fountain` + : i18n.str`Review developer settings` + : parsed.value.type === TalerUriAction.WithdrawalTransferResult + ? /* Translators: Withdrawing adds digital cash to this wallet, usually funded by a bank transfer; it does not cash out the wallet to a bank account. */ i18n.str`View withdrawal` + : parsed.value.type === TalerUriAction.DevExperiment + ? version.data?.devMode === true + ? i18n.str`Apply experiment` + : i18n.str`Review developer settings` + : undefined : undefined } onContinue={() => void prepare()} @@ -5182,7 +5234,7 @@ function TransactionsRoute() { if (next === "all") params.delete("filter"); else params.set("filter", next); const search = params.toString(); - navigateWalletRoute( + navigateWalletHash( search ? `/transactions?${search}` : "/transactions", { replace: true }, ); @@ -5222,7 +5274,7 @@ function TransactionsRoute() { function returnToTransactionHistory() { if (window.history.state?.fromWalletHistory) window.history.back(); - else navigateWalletRoute("/transactions"); + else navigateWalletHash("/transactions"); } function useTransactionActions(transactionId: TransactionIdStr) { @@ -5961,7 +6013,8 @@ function SettingsRoute() { developerMode={version.data?.devMode === true} developerOpen={ developerReturnTo !== undefined || - hashQueryValue("section") === "refresh" + hashQueryValue("section") === "refresh" || + hashQueryValue("feature") === "fountains" } refreshBlocked={refreshBlock.data?.blocked} onSetRefreshBlocked={async (blocked) => { @@ -5983,6 +6036,12 @@ function SettingsRoute() { setDeveloperBusy(false); } }} + fountainsEnabled={uiPreferences.fountainsEnabled} + onSetFountainsEnabled={(enabled) => { + uiPreferences.setFountainsEnabled(enabled); + if (enabled && hashQueryValue("feature") === "fountains") + navigate(developerReturnTo ?? "/fountains", { replace: true }); + }} developerBusy={developerBusy} developerMessage={developerMessage} developerError={ diff --git a/packages/wallet-webui/src/routes/FountainsRoute.tsx b/packages/wallet-webui/src/routes/FountainsRoute.tsx @@ -0,0 +1,110 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +import { Result, type ListFountainsResponse } from "@gnu-taler/taler-util"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { useHashLocation } from "wouter-preact/use-hash-location"; +import { useLocation } from "wouter-preact"; +import { useServices } from "./context.js"; +import { useWalletQuery } from "../api/wallet.js"; +import { useUiPreferences } from "../stores/preferences.js"; +import { useLanguage } from "../i18n/LanguageProvider.js"; +import { i18n } from "../i18n/runtime.js"; +import { FountainsScreen } from "../screens/FountainsScreen.js"; +import { errorFromException, walletCoreError } from "../ui/error.js"; + +export function FountainsRoute() { + const { connection } = useServices(); + const { fountainsEnabled } = useUiPreferences(); + const { language } = useLanguage(); + const [, navigate] = useLocation(); + const [location] = useHashLocation(); + const query = useWalletQuery( + connection, + WalletApiOperation.ListFountains, + {}, + { enabled: fountainsEnabled }, + ); + const refresh = async (fountainId: string) => { + const fallback = i18n.str`The fountain could not be refreshed.`; + try { + const result = await connection.client.callForResult( + WalletApiOperation.RefreshFountain, + { fountainId }, + ); + if (Result.isError(result)) + return walletCoreError(result.detail, fallback); + return undefined; + } catch (error) { + return errorFromException(error, fallback); + } finally { + void query.mutate().catch(() => {}); + } + }; + const remove = async ( + fountainId: string, + discardPendingWithdrawalId?: string, + ) => { + const fallback = i18n.str`The fountain could not be removed.`; + try { + const result = await connection.client.callForResult( + WalletApiOperation.RemoveFountain, + { fountainId, discardPendingWithdrawalId }, + ); + if (Result.isError(result)) + return walletCoreError(result.detail, fallback); + if (result.value.status === "removed") { + await query.mutate( + (current: ListFountainsResponse | undefined) => + current && { + fountains: current.fountains.filter( + (f) => f.fountainId !== fountainId, + ), + }, + { revalidate: false }, + ); + } + return result.value; + } catch (error) { + return errorFromException(error, fallback); + } finally { + void query.mutate().catch(() => {}); + } + }; + return ( + <FountainsScreen + enabled={fountainsEnabled} + fountains={query.data?.fountains} + loading={fountainsEnabled && query.isLoading} + language={language} + focusId={ + new URLSearchParams(location.split("?")[1]).get("focus") ?? undefined + } + error={ + query.error + ? errorFromException( + query.error, + i18n.str`Fountains could not be loaded.`, + ) + : undefined + } + onSettings={() => navigate("/settings?feature=fountains")} + onImport={() => navigate("/enter")} + onRefresh={refresh} + onRemove={remove} + /> + ); +} diff --git a/packages/wallet-webui/src/routes/hash-location.ts b/packages/wallet-webui/src/routes/hash-location.ts @@ -0,0 +1,39 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +export function walletRouteHref(path: string): string { + return `#/${path.replace(/^#?\/?/, "")}`; +} + +export function navigateWalletHash( + path: string, + { + replace = false, + state = null, + }: { replace?: boolean; state?: unknown } = {}, +): void { + const oldURL = window.location.href; + const href = walletRouteHref(path); + if (replace) window.history.replaceState(state, "", href); + else window.history.pushState(state, "", href); + // The History API does not fire the event used by useHashLocation. + window.dispatchEvent( + new window.HashChangeEvent("hashchange", { + oldURL, + newURL: window.location.href, + }), + ); +} diff --git a/packages/wallet-webui/src/screens/ActionScreen.tsx b/packages/wallet-webui/src/screens/ActionScreen.tsx @@ -29,6 +29,8 @@ function actionSourceLabel(source: string): string { function actionKindLabel(kind: string): string { switch (kind) { + case "fountain": + return i18n.str`Import fountain`; case "withdraw": return i18n.str`Digital cash withdrawal`; case "pay": diff --git a/packages/wallet-webui/src/screens/BalanceScreen.tsx b/packages/wallet-webui/src/screens/BalanceScreen.tsx @@ -737,6 +737,7 @@ export function BalanceScreen(props: { onShowTransactions?: (scope: ScopeInfo) => void; onShowDiscounts?: () => void; onShowPasses?: () => void; + onShowFountains?: () => void; onShowDonations?: () => void; onEnterLink?: () => void; onScan?: () => void; @@ -1124,8 +1125,11 @@ export function BalanceScreen(props: { /> {(props.onShowDiscounts || props.onShowPasses || + props.onShowFountains || props.onShowDonations) && ( - <div class="grid grid-cols-3 gap-4 py-3"> + <div + class={`grid ${props.onShowFountains ? "grid-cols-2 sm:grid-cols-4" : "grid-cols-3"} gap-4 py-3`} + > {props.onShowDiscounts && ( <BenefitAction icon="discount" @@ -1144,6 +1148,13 @@ export function BalanceScreen(props: { onClick={props.onShowPasses} /> )}{" "} + {props.onShowFountains && ( + <BenefitAction + icon="fountain" + label={i18n.str`Fountains`} + onClick={props.onShowFountains} + /> + )} {props.onShowDonations && ( <BenefitAction icon="donation" diff --git a/packages/wallet-webui/src/screens/SettingsScreen.tsx b/packages/wallet-webui/src/screens/SettingsScreen.tsx @@ -181,6 +181,8 @@ export function SettingsScreen(props: { clearingWallet: boolean; clearWalletMessage?: string; clearWalletError?: ErrorPresentation; + fountainsEnabled?: boolean; + onSetFountainsEnabled?: (enabled: boolean) => void; developerMode: boolean; developerOpen?: boolean; refreshBlocked?: boolean; @@ -580,6 +582,19 @@ export function SettingsScreen(props: { </span> </summary> <div class="border-t border-outlineVariant p-5"> + <section class="mb-6 border-b border-outlineVariant pb-6"> + <label class="flex items-center gap-3 font-semibold"> + <input + type="checkbox" + checked={props.fountainsEnabled ?? false} + onChange={(e) => + props.onSetFountainsEnabled?.(e.currentTarget.checked) + } + /> + {i18n.str`Enable fountains`} + </label> + <p class="mt-3 text-sm text-secondary">{i18n.str`Show fountains and allow importing their links. Turning this off hides the feature; fountains already imported continue collecting discounts and passes.`}</p> + </section> <section aria-labelledby="developer-mode-heading"> <h2 id="developer-mode-heading" class="font-semibold"> {/* Translators: wallet-core is the wallet's background subsystem. */} diff --git a/packages/wallet-webui/src/stores/preferences.tsx b/packages/wallet-webui/src/stores/preferences.tsx @@ -43,7 +43,32 @@ export function writeBalanceHistoryEnabled( return enabled; } +export const FOUNTAINS_ENABLED_KEY = "taler-wallet-webui-fountains-enabled"; +export function readFountainsEnabled( + storage: UiPreferenceStorage | undefined = preferenceStorage(), +): boolean { + try { + return storage?.getItem(FOUNTAINS_ENABLED_KEY) === "true"; + } catch { + return false; + } +} +export function writeFountainsEnabled( + enabled: boolean, + storage: UiPreferenceStorage | undefined = preferenceStorage(), +): boolean { + try { + if (enabled) storage?.setItem(FOUNTAINS_ENABLED_KEY, "true"); + else storage?.removeItem(FOUNTAINS_ENABLED_KEY); + } catch { + /* Apply for this document if persistence is blocked. */ + } + return enabled; +} + interface UiPreferences { + fountainsEnabled: boolean; + setFountainsEnabled(enabled: boolean): void; balanceHistoryEnabled: boolean; setBalanceHistoryEnabled(enabled: boolean): void; } @@ -53,6 +78,13 @@ const UiPreferencesContext = createContext<UiPreferences | undefined>( ); export function UiPreferencesProvider(props: { children: ComponentChildren }) { + const [fountainsEnabled, setFountainsEnabledState] = + useState(readFountainsEnabled); + const setFountainsEnabled = useCallback( + (enabled: boolean) => + setFountainsEnabledState(writeFountainsEnabled(enabled)), + [], + ); const [balanceHistoryEnabled, setBalanceHistoryEnabledState] = useState( readBalanceHistoryEnabled, ); @@ -62,6 +94,8 @@ export function UiPreferencesProvider(props: { children: ComponentChildren }) { useEffect(() => { if (typeof window === "undefined") return; const update = (event: StorageEvent) => { + if (event.key === null || event.key === FOUNTAINS_ENABLED_KEY) + setFountainsEnabledState(readFountainsEnabled()); if (event.key === null || event.key === BALANCE_HISTORY_ENABLED_KEY) { setBalanceHistoryEnabledState(readBalanceHistoryEnabled()); } @@ -71,7 +105,12 @@ export function UiPreferencesProvider(props: { children: ComponentChildren }) { }, []); return ( <UiPreferencesContext.Provider - value={{ balanceHistoryEnabled, setBalanceHistoryEnabled }} + value={{ + balanceHistoryEnabled, + setBalanceHistoryEnabled, + fountainsEnabled, + setFountainsEnabled, + }} > {props.children} </UiPreferencesContext.Provider> diff --git a/packages/wallet-webui/src/ui/Shell.tsx b/packages/wallet-webui/src/ui/Shell.tsx @@ -10,6 +10,7 @@ export function Shell(props: { children: ComponentChildren; connectionLabel: string; hasUnreadAttention?: boolean; + fountainsEnabled?: boolean; demo?: { scenarios: readonly DemoScenario[]; notice?: string; @@ -153,6 +154,13 @@ export function Shell(props: { icon="subscriptions" selected={selected("/passes")} >{i18n.str`Passes`}</ActionNav> + {props.fountainsEnabled && ( + <ActionNav + href="/fountains" + icon="fountain" + selected={selected("/fountains")} + >{i18n.str`Fountains`}</ActionNav> + )} <ActionNav href="/donations" icon="donation" diff --git a/packages/wallet-webui/test/fountain-entry.test.tsx b/packages/wallet-webui/test/fountain-entry.test.tsx @@ -0,0 +1,227 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +import assert from "node:assert/strict"; +import test from "node:test"; +import { register } from "node:module"; +import { Window } from "happy-dom"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { createDemoServices } from "../src/testing/demo-wallet.js"; +import { + StoredActionInbox, + SessionStorageActionStore, +} from "../src/platform/action-inbox.js"; +import { Result } from "@gnu-taler/taler-util"; +import { fountainFixture } from "../src/testing/fountain-fixture.js"; +import type { ActionEntry } from "../src/api/contracts.js"; + +// Match the browser bundle's React alias when rendering SWR-backed routes. +register( + `data:text/javascript,${encodeURIComponent(` + export async function resolve(specifier, context, nextResolve) { + if (specifier === "react" || specifier === "use-sync-external-store/shim/index.js") return { url: ${JSON.stringify(import.meta.resolve("preact/compat"))}, shortCircuit: true }; + return nextResolve(specifier, context); + } +`)}`, + import.meta.url, +); + +async function harness( + source: ActionEntry["source"], + enabled = true, + fail = false, +) { + const dom = new Window({ url: "https://wallet.example/" }); + for (const key of [ + "window", + "document", + "navigator", + "location", + "history", + "localStorage", + "sessionStorage", + "HTMLElement", + "Element", + "Node", + "Event", + "MutationObserver", + ] as const) { + Object.defineProperty(globalThis, key, { + configurable: true, + writable: true, + value: key === "window" ? dom : dom[key], + }); + } + for (const key of [ + "addEventListener", + "removeEventListener", + "dispatchEvent", + ] as const) + Object.defineProperty(globalThis, key, { + configurable: true, + writable: true, + value: dom[key].bind(dom), + }); + const { render, cleanup, act } = await import("@testing-library/preact"); + const { SWRConfig } = await import("swr"); + const { App } = await import("../src/routes/App.js"); + const services = createDemoServices(); + services.platform = { + ...services.platform, + actionInbox: new StoredActionInbox(new SessionStorageActionStore()), + }; + if (enabled) + dom.localStorage.setItem("taler-wallet-webui-fountains-enabled", "true"); + const entry = await services.platform.actionInbox.put( + "taler://fountain/merchant.example/instances/museum/merchant-fountain/" + + "0".repeat(52), + source, + ); + dom.location.hash = `#/action/${entry.id}`; + let imports = 0; + let stored = false; + const originalCall = services.connection.client.call; + services.connection.client.call = async (operation, request) => { + if (operation === WalletApiOperation.ListFountains) + return { fountains: stored ? [fountainFixture] : [] } as never; + return originalCall(operation, request); + }; + const original = services.connection.client.callForResult; + services.connection.client.callForResult = async (operation, request) => { + if (operation === WalletApiOperation.ImportFountain) { + imports++; + if (fail && imports === 1) throw Error("unavailable"); + stored = true; + return Result.of(fountainFixture) as never; + } + return original(operation, request); + }; + const view = render( + <SWRConfig value={{ provider: () => new Map(), shouldRetryOnError: false }}> + <App {...services} /> + </SWRConfig>, + ); + const waitFor = async (check: () => void) => { + for (let n = 0; ; n++) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + }); + try { + check(); + return; + } catch (error) { + if (n >= 200) throw error; + } + } + }; + return { + view, + act, + waitFor, + counts: () => imports, + inbox: services.platform.actionInbox, + entry, + dom, + close: async () => { + cleanup(); + services.connection.close(); + await dom.happyDOM.abort(); + }, + }; +} + +for (const source of ["paste", "qr", "protocol", "link"] as const) { + test(`${source} fountain waits for explicit confirmation and clears its credential from the inbox`, async () => { + const h = await harness(source); + try { + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Import fountain" })), + ); + assert.equal(h.counts(), 0); + assert(!h.dom.document.body.textContent!.includes("0".repeat(52))); + assert(!h.dom.location.href.includes("0".repeat(52))); + await h.act(() => + ( + h.view.getByRole("button", { + name: "Import fountain", + }) as HTMLButtonElement + ).click(), + ); + await h.waitFor(() => + assert(h.view.getByRole("heading", { name: "Fountains", exact: true })), + ); + assert.equal(h.counts(), 1); + assert.equal(await h.inbox.get(h.entry.id), undefined); + assert(h.view.getAllByText("Received from this fountain").length); + assert(!h.dom.location.href.includes("0".repeat(52))); + } finally { + await h.close(); + } + }); +} +test("disabled fountain links cannot import and can be canceled", async () => { + const h = await harness("paste", false); + try { + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Review developer settings" })), + ); + assert.equal(h.counts(), 0); + assert.equal( + h.view.queryByRole("button", { name: "Import fountain" }), + null, + ); + await h.act(() => + ( + h.view.getByRole("button", { name: "Cancel" }) as HTMLButtonElement + ).click(), + ); + await h.waitFor(() => assert.equal(h.dom.location.hash, "#/")); + assert.equal(await h.inbox.get(h.entry.id), undefined); + assert.equal(h.counts(), 0); + } finally { + await h.close(); + } +}); +test("failed import remains retryable without consuming the inbox action", async () => { + const h = await harness("paste", true, true); + try { + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Import fountain" })), + ); + await h.act(() => + ( + h.view.getByRole("button", { + name: "Import fountain", + }) as HTMLButtonElement + ).click(), + ); + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Retry" })), + ); + assert(await h.inbox.get(h.entry.id)); + await h.act(() => + ( + h.view.getByRole("button", { name: "Retry" }) as HTMLButtonElement + ).click(), + ); + await h.waitFor(() => + assert(h.view.getByRole("heading", { name: "Fountains", exact: true })), + ); + assert.equal(h.counts(), 2); + } finally { + await h.close(); + } +}); diff --git a/packages/wallet-webui/test/hash-location.test.ts b/packages/wallet-webui/test/hash-location.test.ts @@ -0,0 +1,47 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +import assert from "node:assert/strict"; +import test from "node:test"; +import { Window } from "happy-dom"; +import { navigateWalletHash } from "../src/routes/hash-location.js"; + +test("navigation keeps feature, return and focus parameters in the hash", async () => { + const dom = new Window({ + url: "https://wallet.example/wallet.html?campaign=test#/action/id", + }); + for (const [key, value] of Object.entries({ + window: dom, + history: dom.history, + Event: dom.Event, + dispatchEvent: dom.dispatchEvent.bind(dom), + })) + Object.defineProperty(globalThis, key, { configurable: true, value }); + let updates = 0; + dom.addEventListener("hashchange", () => updates++); + navigateWalletHash("/settings?feature=fountains&returnTo=%2Faction%2Fid"); + assert.equal( + dom.location.hash, + "#/settings?feature=fountains&returnTo=%2Faction%2Fid", + ); + assert.equal(dom.location.search, "?campaign=test"); + navigateWalletHash("/fountains?focus=local-id", { replace: true }); + assert.equal(dom.location.hash, "#/fountains?focus=local-id"); + navigateWalletHash("/"); + assert.equal(dom.location.hash, "#/"); + assert.equal(updates, 3); + await dom.happyDOM.abort(); +}); diff --git a/packages/wallet-webui/test/preferences.test.tsx b/packages/wallet-webui/test/preferences.test.tsx @@ -3,6 +3,9 @@ import test from "node:test"; import { Window } from "happy-dom"; import { BALANCE_HISTORY_ENABLED_KEY, + FOUNTAINS_ENABLED_KEY, + readFountainsEnabled, + writeFountainsEnabled, readBalanceHistoryEnabled, writeBalanceHistoryEnabled, type UiPreferenceStorage, @@ -96,3 +99,23 @@ test("the UI preference provider applies local and cross-tab changes", async () cleanup(); await window.happyDOM.abort(); }); + +test("fountains opt-in persists and fails closed if preference storage is unavailable", () => { + const storage = new MemoryStorage(); + assert.equal(readFountainsEnabled(storage), false); + writeFountainsEnabled(true, storage); + assert.equal(storage.getItem(FOUNTAINS_ENABLED_KEY), "true"); + assert.equal(readFountainsEnabled(storage), true); + writeFountainsEnabled(false, storage); + assert.equal(readFountainsEnabled(storage), false); + assert.equal( + readFountainsEnabled({ + getItem() { + throw Error("blocked"); + }, + setItem() {}, + removeItem() {}, + }), + false, + ); +});