taler-typescript-core

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

commit 90740da83d21a017387ba6772f4cda37659f9264
parent cbfa61f25803f92f3b9ff64a3bc87b693dd70baa
Author: Florian Dold <dold@taler.net>
Date:   Thu, 24 Sep 2026 22:28:25 +0200

wallet CLI: manage fountains and exercise collection against a merchant

Accept an onboarding URI, list by purpose, refresh on demand and make
discarding pending work explicit. Exercise the wallet API against a
merchant through collection, payment and revocation.

Diffstat:
Mpackages/taler-harness/README.md | 41++++++++++++++++++++++++++++++++++++++++-
Apackages/taler-harness/src/integrationtests/test-wallet-fountains.ts | 300+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-harness/src/integrationtests/testrunner.ts | 2++
Mpackages/taler-wallet-cli/src/index.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 443 insertions(+), 1 deletion(-)

diff --git a/packages/taler-harness/README.md b/packages/taler-harness/README.md @@ -53,7 +53,7 @@ Changing the lock key or template cancels pending challenges. Run `taler-harness run-integrationtests riegel` with the built `taler-harness` and `taler-wallet-cli` on PATH for the two-algorithm wallet test. -## Challenge confirmations +## Challenge confirmations and token fountains Generate an offline-device challenge and verify the payment confirmation: @@ -72,6 +72,44 @@ wallet prints `pos_confirmation` after payment. Paste that code into the validator. Exit statuses are 0 (valid), 1 (invalid signature), and 2 (malformed input or EOF). The validator makes no network requests and keeps no replay log. +Wallet fountain commands: + +```sh +taler-wallet-cli fountain import # prompts for the onboarding URI +taler-wallet-cli fountain list +taler-wallet-cli fountain list --purpose access-card +taler-wallet-cli fountain refresh "$LOCAL_FOUNTAIN_ID" +taler-wallet-cli fountain remove "$LOCAL_FOUNTAIN_ID" +``` + +The CLI accepts a fountain URI as an argument to `fountain import` or +`handle-uri`. In wallet-core, `importFountain` saves the credential locally +and schedules collection. It works offline. An `active` fountain is enabled +in this wallet. Its first successful merchant metadata poll sets `lastPoll`. + +`refreshFountain` runs one collection pass. The CLI's import and refresh +commands print the resulting details. A pass can collect up to 64 tokens per +family and issue key. Check `collectionPending` to see whether the first +poll, a saved withdrawal, or more stocking is outstanding. Wallet-core +continues this work in the background while running. Future scheduled polls +alone do not set the flag. + +`listFountains` returns the same details from local storage. For each token +family, `receivedFromFountain` counts this fountain's receipts since tracking +began. `availableInWallet` and `futureInWallet` count unreserved tokens +across the wallet for that merchant and family. + +`removeFountain` takes the wallet-local `fountainId` and returns +`{ status: "removed" }` when the fountain is gone. Tokens already in the wallet +remain usable. If a withdrawal can still be recovered, removal returns +`{ status: "withdrawalPending", pendingWithdrawalId }` and keeps the +credential. The CLI exits with status 6 when this decision is needed. Retry +collection with `fountain refresh`. To explicitly abandon +that withdrawal, pass its ID as `discardPendingWithdrawalId` to the API or +`--discard-pending <withdrawal-id>` to `fountain remove`. Removal works +offline. Listings omit the bearer secret. Whole-database exports include it +and pending withdrawal secrets. + Template preparation accepts `challenge` either in the pay-template URI or as a `preparePayForTemplateV2` request field. Conflicting challenges are rejected. Hosts retrieve confirmations through the existing @@ -81,6 +119,7 @@ Run the merchant-backed tests with a freshly built wallet CLI on `PATH`: ```sh taler-harness run-integrationtests '*challenge-confirmation*' +taler-harness run-integrationtests wallet-fountains taler-harness run-integrationtests otp ``` diff --git a/packages/taler-harness/src/integrationtests/test-wallet-fountains.ts b/packages/taler-harness/src/integrationtests/test-wallet-fountains.ts @@ -0,0 +1,300 @@ +/* + 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import { + AbsoluteTime, + Duration, + FountainPurpose, + HostPortPath, + LibtoolVersion, + OrderInputType, + OrderOutputType, + succeedOrThrow, + TalerMerchantInstanceHttpClient, + TalerProtocolTimestamp, + TalerUriAction, + TalerUris, + TokenFamilyKind, + TransactionMajorState, + TransactionMinorState, +} from "@gnu-taler/taler-util"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { + createSimpleTestkudosEnvironmentV3, + createWalletDaemonWithClient, + withdrawViaBankV4, +} from "../harness/environments.js"; +import { + harnessLongpollQueue, + harnessHttpLib, + GlobalTestState, +} from "../harness/harness.js"; +import { readFileSync } from "node:fs"; + +export async function runWalletFountainsTest(t: GlobalTestState) { + const { + bank, + exchange, + merchant, + walletClient, + merchantAdminAccessToken: token, + } = await createSimpleTestkudosEnvironmentV3(t, undefined, { + additionalExchangeConfig(exchange) { + // Keep the initial denominations withdrawable even just before midnight UTC. + exchange.changeConfig((config) => { + config.setString( + "taler-exchange-secmod-rsa", + "lookahead_sign", + "1 day", + ); + }); + }, + }); + const { version } = await walletClient.call( + WalletApiOperation.GetVersion, + {}, + ); + t.assertTrue(LibtoolVersion.isCompatible(version, "13:0:0")); + const api = new TalerMerchantInstanceHttpClient( + merchant.makeInstanceBaseUrl(), + { httpClient: harnessHttpLib, longpollQueue: harnessLongpollQueue }, + ); + const expiration = AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + Duration.fromSpec({ days: 30 }), + ), + ); + for (const kind of [TokenFamilyKind.Discount, TokenFamilyKind.Subscription]) { + succeedOrThrow( + await api.createTokenFamily(token, { + kind, + slug: kind, + name: kind, + description: kind, + valid_after: TalerProtocolTimestamp.now(), + valid_before: expiration, + duration: { d_us: 86400_000_000 }, + validity_granularity: { d_us: 86400_000_000 }, + }), + ); + } + const merchantVersion = succeedOrThrow(await api.getConfig()).version; + const display = LibtoolVersion.isCompatible(merchantVersion, "46:0:0") + ? { + name: "Campus benefits", + name_i18n: { de: "Campusvorteile" }, + extra_data: { + fountain_purpose: "access-card", + campaign: { semester: "spring" }, + }, + } + : undefined; + const created = succeedOrThrow( + await api.createFountain(token, { + description: "Test promotion", + ...display, + poll_freq: { d_us: 3600_000_000 }, + grants: [], + }), + ); + const uri = TalerUris.stringify({ + type: TalerUriAction.Fountain, + merchantBaseUrl: merchant.makeInstanceBaseUrl() as HostPortPath, + fountainId: created.fountain_id, + fountainSecret: created.fountain_secret, + }); + const f = await walletClient.call(WalletApiOperation.ImportFountain, { + talerFountainUri: uri, + }); + const empty = await walletClient.call(WalletApiOperation.RefreshFountain, { + fountainId: f.fountainId, + }); + t.assertTrue(empty.status === "active" && empty.grants.length === 0); + t.assertDeepEqual(empty.name, display?.name ?? created.fountain_id); + t.assertDeepEqual(empty.nameI18n, display?.name_i18n); + t.assertDeepEqual(empty.extraData, display?.extra_data); + t.assertDeepEqual(empty.purpose, display?.extra_data.fountain_purpose); + const listIds = async (purpose: FountainPurpose) => + ( + await walletClient.call(WalletApiOperation.ListFountains, { purpose }) + ).fountains.map((entry) => entry.fountainId); + t.assertDeepEqual( + await listIds(FountainPurpose.AccessCard), + display ? [f.fountainId] : [], + ); + t.assertDeepEqual(await listIds(FountainPurpose.Promotion), []); + const autumnMetadata = display && { fountain_purpose: "promotion" }; + succeedOrThrow( + await api.updateFountain(token, created.fountain_id, { + ...(display && { name: "Autumn benefits", extra_data: autumnMetadata }), + grants: [TokenFamilyKind.Discount, TokenFamilyKind.Subscription].map( + (kind) => ({ + token_family_slug: kind, + tokens_per_period_limit: 3, + tokens_per_period_stash: 2, + key_window_size: 1, + }), + ), + }), + ); + const updated = await walletClient.call(WalletApiOperation.RefreshFountain, { + fountainId: f.fountainId, + }); + t.assertDeepEqual( + updated.name, + display ? "Autumn benefits" : created.fountain_id, + ); + t.assertDeepEqual(updated.nameI18n, display?.name_i18n); + t.assertDeepEqual(updated.extraData, autumnMetadata); + t.assertDeepEqual(updated.purpose, autumnMetadata?.fountain_purpose); + t.assertDeepEqual(await listIds(FountainPurpose.AccessCard), []); + t.assertDeepEqual( + await listIds(FountainPurpose.Promotion), + display ? [f.fountainId] : [], + ); + const { discounts } = await walletClient.call( + WalletApiOperation.ListDiscounts, + {}, + ); + const { subscriptions } = await walletClient.call( + WalletApiOperation.ListSubscriptions, + {}, + ); + t.assertTrue(discounts.length === 1 && discounts[0].tokensAvailable === 2); + t.assertTrue(subscriptions.length === 1); + // The shared discount grant has one token left. A second wallet initially + // asks for two and must collect the last token after the merchant rejects that batch. + const second = await createWalletDaemonWithClient(t, { + name: "shared-fountain", + }); + const imported = await second.walletClient.call( + WalletApiOperation.ImportFountain, + { talerFountainUri: uri }, + ); + await second.walletClient.call(WalletApiOperation.RefreshFountain, { + fountainId: imported.fountainId, + }); + const sharedDiscounts = await second.walletClient.call( + WalletApiOperation.ListDiscounts, + {}, + ); + t.assertTrue(sharedDiscounts.discounts[0].tokensAvailable === 1); + // Give the first wallet allowance for the replenishment tested below. + succeedOrThrow( + await api.updateFountain(token, created.fountain_id, { + grants: [TokenFamilyKind.Discount, TokenFamilyKind.Subscription].map( + (kind) => ({ + token_family_slug: kind, + tokens_per_period_limit: 4, + tokens_per_period_stash: 2, + key_window_size: 1, + }), + ), + }), + ); + + const withdrawal = await withdrawViaBankV4(t, { + walletClient, + bank, + exchange, + amount: "TESTKUDOS:10", + }); + await withdrawal.withdrawalFinishedCond; + for (const kind of [TokenFamilyKind.Discount, TokenFamilyKind.Subscription]) { + const order = succeedOrThrow( + await api.createOrder(token, { + order: { + version: 1, + summary: `Use fountain ${kind}`, + timestamp: TalerProtocolTimestamp.now(), + pay_deadline: expiration, + choices: [ + { + amount: "TESTKUDOS:1", + inputs: [{ type: OrderInputType.Token, token_family_slug: kind }], + outputs: + kind === TokenFamilyKind.Subscription + ? [{ type: OrderOutputType.Token, token_family_slug: kind }] + : [], + }, + ], + }, + }), + ); + const status = succeedOrThrow( + await api.getOrderDetails(token, order.order_id), + ); + t.assertTrue(status.order_status === "unpaid"); + const pay = await walletClient.call(WalletApiOperation.PreparePayForUriV2, { + talerPayUri: status.taler_pay_uri, + }); + await walletClient.call(WalletApiOperation.TestingWaitTransactionState, { + transactionId: pay.transactionId, + txState: { + major: TransactionMajorState.Dialog, + minor: TransactionMinorState.Proposed, + }, + }); + await walletClient.call(WalletApiOperation.ConfirmPay, { + transactionId: pay.transactionId, + choiceIndex: 0, + }); + await walletClient.call( + WalletApiOperation.TestingWaitTransactionsFinal, + {}, + ); + } + t.assertTrue( + (await walletClient.call(WalletApiOperation.ListDiscounts, {})).discounts[0] + .tokensAvailable === 1, + ); + t.assertTrue( + (await walletClient.call(WalletApiOperation.ListSubscriptions, {})) + .subscriptions.length === 1, + ); + await walletClient.call(WalletApiOperation.RefreshFountain, { + fountainId: f.fountainId, + }); + t.assertTrue( + (await walletClient.call(WalletApiOperation.ListDiscounts, {})).discounts[0] + .tokensAvailable === 2, + ); + succeedOrThrow(await api.deleteFountain(token, created.fountain_id)); + const revoked = await walletClient.call(WalletApiOperation.RefreshFountain, { + fountainId: f.fountainId, + }); + t.assertTrue(revoked.status === "revoked"); + t.assertTrue( + (await walletClient.call(WalletApiOperation.ListDiscounts, {})).discounts[0] + .tokensAvailable === 2, + ); + t.assertTrue(!revoked.collectionPending); + const removal = await walletClient.call(WalletApiOperation.RemoveFountain, { + fountainId: f.fountainId, + }); + t.assertTrue(removal.status === "removed"); + t.assertTrue( + (await walletClient.call(WalletApiOperation.ListFountains, {})).fountains + .length === 0, + ); + t.assertTrue( + !readFileSync(`${t.testDir}/wallet-wallet-stderr.log`, "utf8").includes( + created.fountain_secret, + ), + ); +} +runWalletFountainsTest.suites = ["merchant", "wallet"]; diff --git a/packages/taler-harness/src/integrationtests/testrunner.ts b/packages/taler-harness/src/integrationtests/testrunner.ts @@ -156,6 +156,7 @@ import { runMerchantSettlementTest } from "./test-merchant-settlement.js"; import { runMerchantWireTest } from "./test-merchant-wire.js"; import { runMultiExchangeTest } from "./test-multiexchange.js"; import { runRiegelTest } from "./test-riegel.js"; +import { runWalletFountainsTest } from "./test-wallet-fountains.js"; import { runEcdsaChallengeConfirmationTest, runEddsaChallengeConfirmationTest, @@ -499,6 +500,7 @@ const allTests: TestMainFunction[] = [ runWalletCoinRecoveryV27Test, runWalletCoinRecoveryV27CsAgeTest, runOtpTest, + runWalletFountainsTest, runRiegelTest, runEcdsaChallengeConfirmationTest, runEddsaChallengeConfirmationTest, diff --git a/packages/taler-wallet-cli/src/index.ts b/packages/taler-wallet-cli/src/index.ts @@ -25,6 +25,7 @@ import { CheckPeerPushDebitRequest, ChoiceSelectionDetailType, codecForList, + codecForListFountainsRequest, codecForString, ContractTermsUtil, CoreApiResponse, @@ -2661,6 +2662,20 @@ walletCli throw Error("invalid taler URI"); } switch (parsedTalerUri.type) { + case TalerUriAction.Fountain: { + const imported = await wallet.client.call( + WalletApiOperation.ImportFountain, + { talerFountainUri: uri }, + ); + const details = args.handleUri.noWait + ? imported + : await wallet.client.call(WalletApiOperation.RefreshFountain, { + fountainId: imported.fountainId, + }); + console.log(j2s(details)); + break; + } + case TalerUriAction.PayTemplate: await doPayTemplate(wallet, uri, { alwaysYes: args.handleUri.autoYes, @@ -3493,6 +3508,92 @@ peerCli ); }); +const fountainCli = walletCli.subcommand("fountain", "fountain", { + help: "Import and manage token fountains.", +}); +fountainCli + .subcommand("importFountain", "import", { + help: "Import a fountain and replenish its tokens.", + }) + .maybeArgument("uri", clk.STRING) + .action(async (args) => { + const uri = + args.importFountain.uri ?? (await promptOrFail("Fountain URI: ")); + await withWallet(args, { lazyTaskLoop: true }, async (wallet) => { + const imported = await wallet.client.call( + WalletApiOperation.ImportFountain, + { talerFountainUri: uri }, + ); + console.log( + j2s( + await wallet.client.call(WalletApiOperation.RefreshFountain, { + fountainId: imported.fountainId, + }), + ), + ); + }); + }); +fountainCli + .subcommand("listFountains", "list", { + help: "List fountains without revealing their credentials.", + }) + .maybeOption("purpose", ["--purpose"], clk.STRING, { + help: "Only list fountains with the given purpose (access-card or promotion).", + }) + .action(async (args) => { + const request = codecForListFountainsRequest().decode(args.listFountains); + await withWallet(args, { lazyTaskLoop: true }, async (wallet) => { + console.log( + j2s( + await wallet.client.call(WalletApiOperation.ListFountains, request), + ), + ); + }); + }); +fountainCli + .subcommand("refreshFountain", "refresh", { + help: "Poll and replenish a fountain now.", + }) + .requiredArgument("id", clk.STRING) + .action(async (args) => { + await withWallet(args, { lazyTaskLoop: true }, async (wallet) => { + console.log( + j2s( + await wallet.client.call(WalletApiOperation.RefreshFountain, { + fountainId: args.refreshFountain.id, + }), + ), + ); + }); + }); +fountainCli + .subcommand("removeFountain", "remove", { + help: "Stop a fountain while keeping tokens already collected.", + }) + .maybeOption("discardPending", ["--discard-pending"], clk.STRING, { + help: "Abandon the specific outstanding withdrawal identified by a previous removal attempt.", + }) + .requiredArgument("id", clk.STRING) + .action(async (args) => { + await runCliAction(() => + withWallet(args, { lazyTaskLoop: true }, async (wallet) => { + const id = args.removeFountain.id; + const result = await wallet.client.call( + WalletApiOperation.RemoveFountain, + { + fountainId: id, + discardPendingWithdrawalId: args.removeFountain.discardPending, + }, + ); + if (result.status === "removed") return 0; + console.error( + `The fountain has a pending withdrawal. Retry collection with 'fountain refresh ${id}', or abandon its tokens with 'fountain remove ${id} --discard-pending ${result.pendingWithdrawalId}'.`, + ); + return EXIT_INPUT_REQUIRED; + }), + ); + }); + const advancedCli = walletCli.subcommand("advancedArgs", "advanced", { help: "Subcommands for advanced operations (only use if you know what you're doing!).", });