commit 42537cfe934c7914036ac3ea66f6112af10eb634
parent 317b13baf6842d187061c18843a6cd29e746b982
Author: Florian Dold <dold@taler.net>
Date: Thu, 26 Nov 2026 04:16:24 +0100
wallet-webui: track template order creation in the action inbox
A merchant can create an order even if its reply never reaches the
wallet. Mark the request as started before sending it, save the
transaction ID on success, and allow another attempt only when the
wallet knows the order was never created.
Diffstat:
7 files changed, 311 insertions(+), 4 deletions(-)
diff --git a/packages/wallet-webui/src/api/contracts.ts b/packages/wallet-webui/src/api/contracts.ts
@@ -1,4 +1,7 @@
-import type { WalletNotification } from "@gnu-taler/taler-util";
+import type {
+ TransactionIdStr,
+ WalletNotification,
+} from "@gnu-taler/taler-util";
import type { WalletCoreApiClient } from "@gnu-taler/taler-wallet-core";
import type { WalletBackupClient } from "./backup.js";
@@ -47,6 +50,7 @@ export type PersistenceCapability = {
export interface ActionEntry {
id: string;
+ templateOrder?: "started" | TransactionIdStr;
uri: string;
createdAt: number;
expiresAt: number;
@@ -68,6 +72,10 @@ export interface ActionInbox {
): Promise<ActionEntry>;
get(id: string): Promise<ActionEntry | undefined>;
list(): Promise<ActionEntry[]>;
+ setTemplateOrder(
+ id: string,
+ order: ActionEntry["templateOrder"],
+ ): Promise<boolean>;
complete(id: string): Promise<void>;
cleanup(now?: number): Promise<void>;
}
diff --git a/packages/wallet-webui/src/api/progress.ts b/packages/wallet-webui/src/api/progress.ts
@@ -248,7 +248,9 @@ export class WalletProgressController {
families: readonly WalletKeyFamily[],
): Promise<Result<WalletCoreResponseType<Op>, WalletCoreErrorType<Op>>> {
const result = await this.callForResult(operation, request);
- await this.invalidate(families);
+ // A cache refresh cannot change the outcome of the wallet operation.
+ // In particular, a failed read must never make order creation retryable.
+ await this.invalidate(families).catch(() => undefined);
return result;
}
diff --git a/packages/wallet-webui/src/platform/action-inbox.ts b/packages/wallet-webui/src/platform/action-inbox.ts
@@ -82,6 +82,24 @@ export async function completeActionBestEffort(
}
}
+/** Only an unclaimed action can begin an order. A started order may record its
+ * known transaction or release the claim after a definitive rejection. */
+export function transitionTemplateOrder(
+ entry: ActionEntry | undefined,
+ order: ActionEntry["templateOrder"],
+): boolean {
+ if (!entry) return false;
+ if (
+ order === "started"
+ ? entry.templateOrder !== undefined
+ : entry.templateOrder !== "started"
+ )
+ return false;
+ if (order === undefined) delete entry.templateOrder;
+ else entry.templateOrder = order;
+ return true;
+}
+
export class StoredActionInbox implements ActionInbox {
/**
* A failed persistence write must not make a completed action actionable
@@ -150,6 +168,19 @@ export class StoredActionInbox implements ActionInbox {
});
}
+ async setTemplateOrder(
+ id: string,
+ order: ActionEntry["templateOrder"],
+ ): Promise<boolean> {
+ return this.mutate((entries) => {
+ const expired = removeExpired(entries, Date.now());
+ const updated =
+ !this.completedIds.has(id) &&
+ transitionTemplateOrder(entries[id], order);
+ return { result: updated, changed: expired || updated };
+ });
+ }
+
async list(): Promise<ActionEntry[]> {
return this.mutate((entries) => {
const changed = removeExpired(entries, Date.now());
diff --git a/packages/wallet-webui/src/routes/action-model.ts b/packages/wallet-webui/src/routes/action-model.ts
@@ -1,4 +1,18 @@
-import { Result, type Result as ResultType } from "@gnu-taler/taler-util";
+import {
+ Result,
+ TalerError,
+ TalerErrorCode,
+ type TalerErrorDetail,
+ type TransactionIdStr,
+ type Result as ResultType,
+} from "@gnu-taler/taler-util";
+import {
+ errorFromException,
+ walletCoreError,
+ type ErrorPresentation,
+} from "../ui/error.js";
+import type { ActionInbox } from "../api/contracts.js";
+import { HostDisconnectedError } from "../api/rpc.js";
import { i18n } from "../i18n/runtime.js";
import { validateActionUri } from "../platform/action-inbox.js";
@@ -47,6 +61,113 @@ export async function runGuardedValueOperation<T>(
return { started: true, value: await operation() };
}
+/** Template order creation is a non-idempotent POST. Only repeat it when the
+ * wallet failed before creating an order or the merchant definitively refused it. */
+function templateOrderWasRejected(detail?: TalerErrorDetail): boolean {
+ if (!detail) return false;
+ if (
+ detail.requestMethod === "GET" ||
+ detail.code === TalerErrorCode.WALLET_TALER_URI_MALFORMED ||
+ detail.code === TalerErrorCode.WALLET_CONTRACT_TERMS_UNSUPPORTED
+ )
+ return true;
+ if (detail.requestMethod !== "POST") return false;
+ const merchantCode = (
+ detail.errorResponse as Partial<TalerErrorDetail> | undefined
+ )?.code;
+ if (detail.httpStatusCode === 404)
+ return (
+ merchantCode === TalerErrorCode.MERCHANT_GENERIC_TEMPLATE_UNKNOWN ||
+ merchantCode === TalerErrorCode.MERCHANT_GENERIC_PRODUCT_UNKNOWN
+ );
+ if (detail.httpStatusCode !== 400 && detail.httpStatusCode !== 409)
+ return false;
+ switch (merchantCode) {
+ case TalerErrorCode.GENERIC_PARAMETER_MALFORMED:
+ case TalerErrorCode.MERCHANT_GENERIC_CURRENCY_MISMATCH:
+ case TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_AMOUNT_CONFLICT_TEMPLATES_CONTRACT_AMOUNT:
+ case TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_SUMMARY_CONFLICT_TEMPLATES_CONTRACT_SUBJECT:
+ case TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_NO_AMOUNT:
+ case TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_NO_SUMMARY:
+ case TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_WRONG_TYPE:
+ case TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_WRONG_PRODUCT:
+ case TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_NO_CURRENCY:
+ return true;
+ default:
+ return false;
+ }
+}
+
+export function uncertainTemplateOrder(
+ detail?: TalerErrorDetail,
+): ErrorPresentation {
+ return {
+ message: i18n.str`The merchant may already have created this order. Check your wallet history or contact the merchant before starting another order.`,
+ detail,
+ };
+}
+
+export async function submitTemplateOrder(
+ inbox: ActionInbox,
+ actionId: string,
+ create: () => Promise<
+ ResultType<{ transactionId: TransactionIdStr }, unknown>
+ >,
+ rejectionMessage = i18n.str`The merchant rejected these payment details.`,
+): Promise<
+ | { transactionId: TransactionIdStr }
+ | { error: ErrorPresentation; retryable: boolean }
+> {
+ // Claim before sending the POST so reload or Back during the request is covered.
+ try {
+ if (!(await inbox.setTemplateOrder(actionId, "started"))) {
+ const existingOrder = (await inbox.get(actionId))?.templateOrder;
+ if (existingOrder && existingOrder !== "started")
+ return { transactionId: existingOrder };
+ return { error: uncertainTemplateOrder(), retryable: false };
+ }
+ } catch (cause) {
+ return {
+ error: errorFromException(cause, i18n.str`Payment preparation failed`),
+ retryable: true,
+ };
+ }
+
+ let failure: ErrorPresentation;
+ let notSent = false;
+ try {
+ const result = await create();
+ if (Result.isOk(result)) {
+ try {
+ await inbox.setTemplateOrder(actionId, result.value.transactionId);
+ } catch {
+ // The submitted claim still blocks another POST. The current caller can open checkout.
+ }
+ return result.value;
+ }
+ failure = walletCoreError(result.detail, rejectionMessage);
+ } catch (cause) {
+ notSent =
+ cause instanceof HostDisconnectedError && cause.outcome === "not-sent";
+ failure = errorFromException(
+ cause,
+ cause instanceof TalerError && cause.errorDetail.requestMethod === "POST"
+ ? rejectionMessage
+ : i18n.str`Payment preparation failed`,
+ );
+ }
+ if (!notSent && !templateOrderWasRejected(failure.detail)) {
+ return { error: uncertainTemplateOrder(failure.detail), retryable: false };
+ }
+ try {
+ const released = await inbox.setTemplateOrder(actionId, undefined);
+ return { error: failure, retryable: released };
+ } catch {
+ // The merchant refused this order, but the inbox cannot safely allow another attempt.
+ return { error: failure, retryable: false };
+ }
+}
+
export function withdrawalTransferResultHint(
status: "success" | "aborted" | undefined,
): string {
diff --git a/packages/wallet-webui/src/testing/demo-wallet.ts b/packages/wallet-webui/src/testing/demo-wallet.ts
@@ -55,7 +55,10 @@ import type {
DemoModeController,
DemoScenarioId,
} from "../routes/context.js";
-import { validateActionUri } from "../platform/action-inbox.js";
+import {
+ transitionTemplateOrder,
+ validateActionUri,
+} from "../platform/action-inbox.js";
import { i18n } from "../i18n/runtime.js";
const exchangeBaseUrl = "https://exchange.demo.invalid/";
@@ -444,6 +447,12 @@ class MemoryActionInbox implements ActionInbox {
async get(id: string) {
return this.entries.get(id);
}
+ async setTemplateOrder(
+ id: string,
+ order: ActionEntry["templateOrder"],
+ ): Promise<boolean> {
+ return transitionTemplateOrder(this.entries.get(id), order);
+ }
async list() {
return [...this.entries.values()];
}
diff --git a/packages/wallet-webui/test/action-inbox.test.ts b/packages/wallet-webui/test/action-inbox.test.ts
@@ -6,6 +6,13 @@ import {
StoredActionInbox,
type ActionEntryStore,
} from "../src/platform/action-inbox.js";
+import { submitTemplateOrder } from "../src/routes/action-model.js";
+import {
+ Result,
+ TalerError,
+ TalerErrorCode,
+ type TransactionIdStr,
+} from "@gnu-taler/taler-util";
import type { ActionEntry, ActionInbox } from "../src/api/contracts.js";
Object.defineProperty(globalThis, "crypto", {
@@ -87,6 +94,115 @@ test("action inbox serializes mutations across inbox instances", async () => {
);
});
+test("only one submit can claim a template, and concurrent inbox additions survive", async () => {
+ const store = new MemoryStore();
+ const first = new StoredActionInbox(store);
+ const second = new StoredActionInbox(store);
+ const template = await first.put(
+ "taler://pay-template/shop.example/template",
+ "paste",
+ );
+ const [a, b, other] = await Promise.all([
+ first.setTemplateOrder(template.id, "started"),
+ second.setTemplateOrder(template.id, "started"),
+ second.put("taler://withdraw/bank.example/another", "link"),
+ ]);
+ assert.equal(Number(a) + Number(b), 1);
+ assert.deepEqual(await second.get(template.id), {
+ ...template,
+ templateOrder: "started",
+ });
+ assert.deepEqual(await first.get(other.id), other);
+ assert.equal(await second.setTemplateOrder(template.id, undefined), true);
+ assert.deepEqual(await first.get(template.id), template);
+});
+test("a failed template claim permits retry without submitting an order", async () => {
+ const store = new MemoryStore();
+ const inbox = new StoredActionInbox(store);
+ const entry = await inbox.put(
+ "taler://pay-template/shop.example/template",
+ "paste",
+ );
+ const write = store.write.bind(store);
+ store.write = async () => {
+ throw Error("storage unavailable");
+ };
+ let posts = 0;
+ const create = async () => {
+ posts++;
+ return Result.of({ transactionId: "txn:payment:test" as TransactionIdStr });
+ };
+ const result = await submitTemplateOrder(inbox, entry.id, create);
+ assert.ok("error" in result && result.retryable);
+ assert.equal(posts, 0);
+ store.write = write;
+ assert.deepEqual(await submitTemplateOrder(inbox, entry.id, create), {
+ transactionId: "txn:payment:test",
+ });
+ assert.equal(posts, 1);
+ assert.equal((await inbox.get(entry.id))?.templateOrder, "txn:payment:test");
+ assert.deepEqual(await submitTemplateOrder(inbox, entry.id, create), {
+ transactionId: "txn:payment:test",
+ });
+ assert.equal(posts, 1);
+});
+test("a rejection remains visible when its inbox claim cannot be released", async () => {
+ const store = new MemoryStore();
+ const inbox = new StoredActionInbox(store);
+ const entry = await inbox.put(
+ "taler://pay-template/shop.example/template",
+ "paste",
+ );
+ let posts = 0;
+ const create = async () => {
+ posts++;
+ store.write = async () => {
+ throw Error("storage unavailable");
+ };
+ throw TalerError.fromUncheckedDetail({
+ code: TalerErrorCode.GENERIC_UNEXPECTED_REQUEST_ERROR,
+ requestMethod: "POST",
+ httpStatusCode: 409,
+ errorResponse: {
+ code: TalerErrorCode.MERCHANT_POST_USING_TEMPLATES_NO_SUMMARY,
+ },
+ });
+ };
+ const result = await submitTemplateOrder(inbox, entry.id, create);
+ assert.ok("error" in result && !result.retryable);
+ assert.equal(
+ result.error.detail?.code,
+ TalerErrorCode.GENERIC_UNEXPECTED_REQUEST_ERROR,
+ );
+ assert.equal((await inbox.get(entry.id))?.templateOrder, "started");
+ await submitTemplateOrder(inbox, entry.id, create);
+ assert.equal(posts, 1);
+});
+
+test("merchant template validation errors leave the order editable", async () => {
+ const inbox = new StoredActionInbox(new MemoryStore());
+ const entry = await inbox.put(
+ "taler://pay-template/shop.example/template",
+ "paste",
+ );
+ for (const [httpStatusCode, code] of [
+ [409, TalerErrorCode.MERCHANT_GENERIC_CURRENCY_MISMATCH],
+ [400, TalerErrorCode.GENERIC_PARAMETER_MALFORMED],
+ [404, TalerErrorCode.MERCHANT_GENERIC_TEMPLATE_UNKNOWN],
+ ] as const) {
+ const outcome = await submitTemplateOrder(inbox, entry.id, async () => {
+ throw TalerError.fromUncheckedDetail({
+ code: TalerErrorCode.GENERIC_UNEXPECTED_REQUEST_ERROR,
+ requestMethod: "POST",
+ httpStatusCode,
+ errorResponse: { code },
+ });
+ });
+ assert.ok("error" in outcome && outcome.retryable);
+ assert.equal((await inbox.get(entry.id))?.templateOrder, undefined);
+ }
+});
+
test("failed cleanup writes keep completed actions hidden for the session", async () => {
const store = new MemoryStore();
const inbox = new StoredActionInbox(store);
diff --git a/packages/wallet-webui/test/progress.test.ts b/packages/wallet-webui/test/progress.test.ts
@@ -156,6 +156,26 @@ test("cancellation uses the core progress key and normalizes the response", asyn
controller.dispose();
});
+test("a failed cache read preserves the submitted order's transaction ID", async () => {
+ const fixture = progressFixture<{ transactionId: string }>();
+ const controller = new WalletProgressController(
+ fixture.connection,
+ async () => {
+ throw Error("wallet unavailable during history refresh");
+ },
+ false,
+ );
+ const pending = controller.callAndInvalidate(
+ WalletApiOperation.PreparePayForTemplateV2,
+ { talerPayTemplateUri: "taler://pay-template/shop.example/template" },
+ ["transactions"],
+ );
+ const result = Result.of({ transactionId: "txn:payment:created" });
+ fixture.request.resolve(result);
+ assert.deepEqual(await pending, result);
+ controller.dispose();
+});
+
test("disposing an active controller cancels the owned request", async () => {
const fixture = progressFixture();
const controller = new WalletProgressController(