commit 80d2f5eeaf33ae443cb6d2c584e0df699c2bdb55
parent a462642a7c375e0efa47c59b0ba7e61b63799414
Author: Florian Dold <dold@taler.net>
Date: Tue, 24 Nov 2026 13:55:34 +0100
wallet-core: report why a Taler URI failed to parse
Issue: https://bugs.taler.net/n/11975
Diffstat:
11 files changed, 173 insertions(+), 107 deletions(-)
diff --git a/packages/taler-util/src/errors.ts b/packages/taler-util/src/errors.ts
@@ -98,6 +98,10 @@ export interface DetailsMap {
};
[TalerErrorCode.WALLET_TALER_URI_MALFORMED]: {
talerUri?: string;
+ /** Name of the TalerUriParseError returned by the URI parser. */
+ parseError?: string;
+ /** Zero-based logical component index. A service URL includes its whole prefix. */
+ componentIndex?: number;
/**
* The taler:// action that the request expected, if the URI parsed
* but denotes something else.
diff --git a/packages/taler-util/src/taleruri.test.ts b/packages/taler-util/src/taleruri.test.ts
@@ -16,9 +16,11 @@
import assert from "node:assert";
import { test } from "node:test";
+import { TalerError } from "./errors.js";
// import { AmountString } from "./types-taler-common.js";
import { HostPortPath } from "./payto.js";
import { Result } from "./result.js";
+import { TalerErrorCode } from "./taler-error-codes.js";
import {
canonicalizeMerchantInstanceUrl,
TalerUriAction,
@@ -830,6 +832,47 @@ test("URI parsing rejects malformed financial capabilities and template fields",
}
});
+test("restricted URI parsing preserves the cause even when a different action is malformed", () => {
+ const action = TalerUriAction.PayPush;
+ const valid = TalerUris.parseRestrictedOrThrow(
+ `taler://pay-push/exchange.example/${VALID_PRIVATE_KEY}`,
+ action,
+ );
+ assert.strictEqual(valid.contractPriv, VALID_PRIVATE_KEY);
+
+ for (const [uri, parseError, componentIndex] of [
+ ["https://exchange.example/", "WRONG_PREFIX"],
+ ["taler://pay-push", "INCOMPLETE"],
+ ["taler://unknown/exchange.example", "UNSUPPORTED"],
+ ["taler://pay-push/exchange.example", "COMPONENTS_LENGTH"],
+ [
+ `taler://pay-push/bad host/${VALID_PRIVATE_KEY}`,
+ "INVALID_TARGET_PATH",
+ 0,
+ ],
+ ["taler://pay-pull/exchange.example/short", "INVALID_TARGET_PATH", 1],
+ ["taler://restore/key/%", "INVALID_TARGET_PATH"],
+ ["taler://pay-template/shop.example/id?amount=bad", "INVALID_PARAMETER"],
+ ] as const) {
+ assert.throws(
+ () => TalerUris.parseRestrictedOrThrow(uri, action),
+ (e: unknown) => {
+ assert.ok(e instanceof TalerError);
+ const { when, ...detail } = e.errorDetail;
+ assert.deepStrictEqual(detail, {
+ code: TalerErrorCode.WALLET_TALER_URI_MALFORMED,
+ talerUri: uri,
+ parseError,
+ hint: `malformed Taler URI: ${parseError}`,
+ ...(componentIndex === undefined ? {} : { componentIndex }),
+ });
+ return true;
+ },
+ uri,
+ );
+ }
+});
+
test("canonicalizeMerchantInstanceUrl folds the instance segment", () => {
const canonical = "https://shop.example.com/instances/myshop/";
for (const variant of [
diff --git a/packages/taler-util/src/taleruri.ts b/packages/taler-util/src/taleruri.ts
@@ -25,10 +25,11 @@
*/
import { Amounts } from "./amounts.js";
import { Codec, Context, DecodingError, renderContext } from "./codec.js";
-import { assertUnreachable } from "./errors.js";
+import { assertUnreachable, type DetailsMap, TalerError } from "./errors.js";
import { HostPortPath, Paytos } from "./payto.js";
import { Result, ResultError, ResultOk } from "./result.js";
import { decodeCrockFixed } from "./taler-crypto.js";
+import { TalerErrorCode } from "./taler-error-codes.js";
import {
AmountString,
EddsaPrivateKeyString,
@@ -464,8 +465,8 @@ export namespace TalerUris {
pos: 1;
};
- export type ParseResult =
- | ResultOk<TalerUri>
+ export type ParseResult<T extends TalerUri = TalerUri> =
+ | ResultOk<T>
| ResultError<TalerUriParseError.WRONG_PREFIX>
| ResultError<TalerUriParseError.UNSUPPORTED, { uriType: string }>
| ResultError<TalerUriParseError.INCOMPLETE, { uriType: string }>
@@ -575,15 +576,12 @@ export namespace TalerUris {
}
}
- type ValueOf<T> = T[keyof T];
- type TalerUriTyped<T extends TalerUriAction> = ValueOf<{
- [K in TalerUri as K["type"] extends T ? K["type"] : never]: K;
- }>;
+ type TalerUriTyped<T extends TalerUriAction> = Extract<TalerUri, { type: T }>;
export function parseRestricted<T extends TalerUriAction>(
s: string,
t: T,
- ): Result<TalerUriTyped<T>, TalerUriParseError> {
+ ): ParseResult<TalerUriTyped<T>> {
const p = parse(s);
if (Result.isError(p)) {
return p;
@@ -596,6 +594,37 @@ export namespace TalerUris {
const pt: TalerUriTyped<T> = p.value as TalerUriTyped<T>;
return Result.of(pt);
}
+
+ /** Parse a wallet request URI and report parse failures as wallet errors. */
+ export function parseRestrictedOrThrow<T extends TalerUriAction>(
+ talerUri: string,
+ action: T,
+ ): TalerUriTyped<T> {
+ const res = parseRestricted(talerUri, action);
+ if (res.tag === "ok") {
+ return res.value;
+ }
+ const parseError = TalerUriParseError[res.error];
+ const detail: DetailsMap[TalerErrorCode.WALLET_TALER_URI_MALFORMED] = {
+ talerUri,
+ parseError,
+ };
+ let hint = `malformed Taler URI: ${parseError}`;
+ if (res.error === TalerUriParseError.UNEXPECTED_ACTION) {
+ detail.expectedAction = action;
+ hint = `expected a taler://${action} URI`;
+ } else if (
+ res.error === TalerUriParseError.INVALID_TARGET_PATH &&
+ "pos" in res.detail
+ ) {
+ detail.componentIndex = res.detail.pos;
+ }
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_TALER_URI_MALFORMED,
+ detail,
+ hint,
+ );
+ }
}
function parseWithdraw(
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -6198,14 +6198,10 @@ export async function startRefundQueryForUri(
wex: WalletExecutionContext,
talerUri: string,
): Promise<StartRefundQueryForUriResponse> {
- const parsedUri = Result.orUndefined(TalerUris.parse(talerUri));
- if (parsedUri?.type !== TalerUriAction.Refund) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- { talerUri, expectedAction: TalerUriAction.Refund },
- "expected a taler://refund URI",
- );
- }
+ const parsedUri = TalerUris.parseRestrictedOrThrow(
+ talerUri,
+ TalerUriAction.Refund,
+ );
const purchaseRecord = await wex.runWalletDbTx(async (tx) => {
return tx.getPurchaseByUrlAndOrderId(
parsedUri.merchantBaseUrl,
diff --git a/packages/taler-wallet-core/src/pay-peer-pull-debit.ts b/packages/taler-wallet-core/src/pay-peer-pull-debit.ts
@@ -38,13 +38,11 @@ import {
PreparePeerPullDebitResponse,
PurseConflict,
RefreshReason,
- Result,
ScopeType,
SelectedProspectiveCoin,
TalerError,
TalerErrorCode,
TalerErrorDetail,
- TalerPayPullUri,
TalerPreciseTimestamp,
TalerProtocolTimestamp,
TalerUriAction,
@@ -1372,19 +1370,9 @@ async function internalPreparePeerPullDebit(
);
}
- let uri: TalerPayPullUri | undefined;
- if (req.talerUri) {
- uri = Result.orUndefined(
- TalerUris.parseRestricted(req.talerUri, TalerUriAction.PayPull),
- );
- if (!uri) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- { talerUri: req.talerUri, expectedAction: TalerUriAction.PayPull },
- "expected a taler://pay-pull URI",
- );
- }
- }
+ const uri = req.talerUri
+ ? TalerUris.parseRestrictedOrThrow(req.talerUri, TalerUriAction.PayPull)
+ : undefined;
let parsedTxId: string | undefined;
if (req.transactionId) {
diff --git a/packages/taler-wallet-core/src/pay-peer-push-credit.ts b/packages/taler-wallet-core/src/pay-peer-push-credit.ts
@@ -29,11 +29,9 @@ import {
PeerContractTerms,
PreparePeerPushCreditRequest,
PreparePeerPushCreditResponse,
- Result,
TalerError,
TalerErrorCode,
TalerErrorDetail,
- TalerPayPushUri,
TalerPreciseTimestamp,
TalerUriAction,
TalerUris,
@@ -637,19 +635,9 @@ async function internalPreparePeerPushCredit(
);
}
- let uri: TalerPayPushUri | undefined;
- if (req.talerUri) {
- uri = Result.orUndefined(
- TalerUris.parseRestricted(req.talerUri, TalerUriAction.PayPush),
- );
- if (!uri) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- { talerUri: req.talerUri, expectedAction: TalerUriAction.PayPush },
- "expected a taler://pay-push URI",
- );
- }
- }
+ const uri = req.talerUri
+ ? TalerUris.parseRestrictedOrThrow(req.talerUri, TalerUriAction.PayPush)
+ : undefined;
let parsedTxId: string | undefined;
if (req.transactionId) {
diff --git a/packages/taler-wallet-core/src/pay-template.test.ts b/packages/taler-wallet-core/src/pay-template.test.ts
@@ -388,9 +388,16 @@ test("Paivana instantiation requires its session and fulfillment URL", async ()
},
},
),
- (e: unknown) =>
- e instanceof TalerError &&
- e.errorDetail.code === TalerErrorCode.WALLET_TALER_URI_MALFORMED,
+ (e: unknown) => {
+ assert.ok(e instanceof TalerError);
+ const { when, ...detail } = e.errorDetail;
+ assert.deepStrictEqual(detail, {
+ code: TalerErrorCode.WALLET_TALER_URI_MALFORMED,
+ talerUri: "taler://pay-template/merchant.example/template-id",
+ hint: "Paivana payment template URI requires session_id and fulfillment_url",
+ });
+ return true;
+ },
);
});
diff --git a/packages/taler-wallet-core/src/pay-template.ts b/packages/taler-wallet-core/src/pay-template.ts
@@ -23,7 +23,6 @@ import {
j2s,
Logger,
PreparePayTemplateRequest,
- Result,
succeedOrThrow,
TalerError,
TalerErrorCode,
@@ -195,7 +194,7 @@ function paivanaTemplateDetails(
const malformed = (hint: string) =>
TalerError.fromDetail(
TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- { talerUri, expectedAction: TalerUriAction.PayTemplate },
+ { talerUri },
hint,
);
if (!sessionId || !fulfillmentUrl) {
@@ -227,22 +226,10 @@ async function internalCheckPayForTemplate(
wex: WalletExecutionContext,
req: CheckPayTemplateRequest,
): Promise<CheckPayTemplateReponse> {
- const parsedUri = Result.orUndefined(
- TalerUris.parseRestricted(
- req.talerPayTemplateUri,
- TalerUriAction.PayTemplate,
- ),
+ const parsedUri = TalerUris.parseRestrictedOrThrow(
+ req.talerPayTemplateUri,
+ TalerUriAction.PayTemplate,
);
- if (!parsedUri) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- {
- talerUri: req.talerPayTemplateUri,
- expectedAction: TalerUriAction.PayTemplate,
- },
- "expected a taler://pay-template URI",
- );
- }
const merchantApi = walletMerchantClient(parsedUri.merchantBaseUrl, wex);
@@ -301,24 +288,11 @@ export async function instantiateTemplateRaw(
sessionId: string;
claimToken: string | undefined;
}> {
- const parsedUri = Result.orUndefined(
- TalerUris.parseRestricted(
- req.talerPayTemplateUri,
- TalerUriAction.PayTemplate,
- ),
+ const parsedUri = TalerUris.parseRestrictedOrThrow(
+ req.talerPayTemplateUri,
+ TalerUriAction.PayTemplate,
);
- if (!parsedUri) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- {
- talerUri: req.talerPayTemplateUri,
- expectedAction: TalerUriAction.PayTemplate,
- },
- "expected a taler://pay-template URI",
- );
- }
-
const merchantApi = walletMerchantClient(parsedUri.merchantBaseUrl, wex);
logger.trace(`parsed URI: ${j2s(parsedUri)}`);
diff --git a/packages/taler-wallet-core/src/requests.test.ts b/packages/taler-wallet-core/src/requests.test.ts
@@ -87,6 +87,57 @@ const backendCases = [
["sqlite", makeSqliteRunner],
] as const;
+test("preparePeerPushCredit distinguishes a damaged contract key from a valid pay-pull URI", async (t) => {
+ const wallet = await Wallet.create(
+ await makeSqliteRunner(),
+ () =>
+ ({
+ async fetch() {
+ throw Error("unexpected HTTP request");
+ },
+ }) as HttpRequestLibrary,
+ new SetTimeoutTimerAPI(),
+ new SynchronousCryptoWorkerFactoryPlain(),
+ );
+ t.after(() => wallet.shutdown());
+ await wallet.client.call(WalletApiOperation.SetWalletRunConfig, {
+ config: { lazyTaskLoop: true, testing: { skipDefaults: true } },
+ });
+
+ const key = "H2T1CY6GWMZQ4S3DPF3GSX0EF61GV32BSR9ATJ0JAG0K65Y2CAM0";
+ const badKey = {
+ parseError: "INVALID_TARGET_PATH",
+ componentIndex: 1,
+ hint: "malformed Taler URI: INVALID_TARGET_PATH",
+ };
+ for (const [talerUri, expected] of [
+ ["taler://pay-push/exchange.example/H2T1CY6GWMZQ", badKey],
+ [`taler://pay-push/exchange.example/${key}\n`, badKey],
+ [`taler://pay-push/exchange.example/${key.slice(0, -1)}!`, badKey],
+ [
+ `taler://pay-pull/exchange.example/${key}`,
+ {
+ parseError: "UNEXPECTED_ACTION",
+ expectedAction: "pay-push",
+ hint: "expected a taler://pay-push URI",
+ },
+ ],
+ ] as const) {
+ const response = await wallet.handleCoreApiRequest(
+ WalletApiOperation.PreparePeerPushCredit,
+ "test",
+ { talerUri },
+ );
+ assert.strictEqual(response.type, "error");
+ const { when, ...detail } = response.error;
+ assert.deepStrictEqual(detail, {
+ code: TalerErrorCode.WALLET_TALER_URI_MALFORMED,
+ talerUri,
+ ...expected,
+ });
+ }
+});
+
test("explicit migration failure reports the retained active database", async () => {
const db = await makeUnopenedIdbRunner();
db.migrateToNative = async () => {
diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts
@@ -734,17 +734,10 @@ async function handlePrepareWithdrawExchange(
wex: WalletExecutionContext,
req: PrepareWithdrawExchangeRequest,
): Promise<PrepareWithdrawExchangeResponse> {
- const parsedUri = Result.orUndefined(TalerUris.parse(req.talerUri));
- if (parsedUri?.type !== TalerUriAction.WithdrawExchange) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- {
- talerUri: req.talerUri,
- expectedAction: TalerUriAction.WithdrawExchange,
- },
- "expected a taler://withdraw-exchange URI",
- );
- }
+ const parsedUri = TalerUris.parseRestrictedOrThrow(
+ req.talerUri,
+ TalerUriAction.WithdrawExchange,
+ );
const exchangeBaseUrl = parsedUri.exchangeBaseUrl;
return await runWithMaybeProgressContext(
@@ -1189,15 +1182,10 @@ async function handleAddExchange(
exchangeBaseUrl = req.exchangeBaseUrl;
} else if (req.uri) {
if (req.uri.startsWith("taler")) {
- const p = Result.orUndefined(TalerUris.parse(req.uri));
- if (p?.type !== TalerUriAction.AddExchange) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TALER_URI_MALFORMED,
- { talerUri: req.uri, expectedAction: TalerUriAction.AddExchange },
- "expected a taler://add-exchange/ URI",
- );
- }
- exchangeBaseUrl = p.exchangeBaseUrl;
+ exchangeBaseUrl = TalerUris.parseRestrictedOrThrow(
+ req.uri,
+ TalerUriAction.AddExchange,
+ ).exchangeBaseUrl;
} else if (req.allowCompletion) {
const completeRes = await handleCompleteExchangeBaseUrl(wex, {
url: req.uri,
diff --git a/packages/taler-wallet-core/src/withdraw.ts b/packages/taler-wallet-core/src/withdraw.ts
@@ -5142,12 +5142,10 @@ export async function prepareBankIntegratedWithdrawal(
tx.getWithdrawalGroupByTalerWithdrawUri(req.talerWithdrawUri),
);
- const parsedUri = Result.orUndefined(
- TalerUris.parseRestricted(req.talerWithdrawUri, TalerUriAction.Withdraw),
+ const parsedUri = TalerUris.parseRestrictedOrThrow(
+ req.talerWithdrawUri,
+ TalerUriAction.Withdraw,
);
- if (parsedUri?.type !== TalerUriAction.Withdraw) {
- throw TalerError.fromDetail(TalerErrorCode.WALLET_TALER_URI_MALFORMED, {});
- }
const externalConfirmation = parsedUri.externalConfirmation;