taler-typescript-core

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

commit 81116c28e80fad44b4ca52278d2a3f731c384a08
parent 70c5a639cad5f2ed86c8b557e1cd02eb99410f29
Author: Florian Dold <dold@taler.net>
Date:   Thu, 24 Sep 2026 22:27:21 +0200

wallet: carry DD97 challenges through template payments

Accept the challenge from the URI or the wallet request, reject
conflicting values, and return the merchant confirmation to the caller.
Include verification for both P-256 and Ed25519 devices.

Diffstat:
Apackages/taler-util/src/challenge-confirmation.test.ts | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/taler-util/src/challenge-confirmation.ts | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-util/src/http-client/merchant.ts | 8++++++++
Mpackages/taler-util/src/index.ts | 1+
Mpackages/taler-util/src/taleruri.ts | 15+++++++++++++++
Mpackages/taler-util/src/types-taler-merchant.ts | 20+++++++++++++++++++-
Mpackages/taler-util/src/types-taler-wallet.ts | 3+++
Mpackages/taler-wallet-cli/src/index.ts | 3+++
Mpackages/taler-wallet-core/src/pay-template.test.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/pay-template.ts | 24++++++++++++++++++++++++
10 files changed, 378 insertions(+), 1 deletion(-)

diff --git a/packages/taler-util/src/challenge-confirmation.test.ts b/packages/taler-util/src/challenge-confirmation.test.ts @@ -0,0 +1,136 @@ +/* + 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 assert from "node:assert/strict"; +import { generateKeyPairSync, sign } from "node:crypto"; +import { test } from "node:test"; +import { encodeCrock, decodeCrockFixed } from "./taler-crypto.js"; +import { + generateConfirmationChallenge, + verifyChallengeConfirmation, +} from "./challenge-confirmation.js"; + +import { initNodePrng } from "./prng-node.js"; +initNodePrng(); +const order = + 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n; +for (const algorithm of ["ECDSA_CHALLENGE", "EDDSA_CHALLENGE"] as const) { + test(`${algorithm} verifies independent OpenSSL signatures and rejects altered inputs`, () => { + const pair = + algorithm === "ECDSA_CHALLENGE" + ? generateKeyPairSync("ec", { namedCurve: "prime256v1" }) + : generateKeyPairSync("ed25519"); + const pub = pair.publicKey.export({ format: "jwk" }); + const publicKey = encodeCrock( + algorithm === "ECDSA_CHALLENGE" + ? Buffer.concat([ + Buffer.from([2 + (Buffer.from(pub.y!, "base64url")[31] & 1)]), + Buffer.from(pub.x!, "base64url"), + ]) + : Buffer.from(pub.x!, "base64url"), + ); + const wrongPair = + algorithm === "ECDSA_CHALLENGE" + ? generateKeyPairSync("ec", { namedCurve: "prime256v1" }) + : generateKeyPairSync("ed25519"); + const wrongPub = wrongPair.publicKey.export({ format: "jwk" }); + const wrongKey = encodeCrock( + algorithm === "ECDSA_CHALLENGE" + ? Buffer.concat([ + Buffer.from([2 + (Buffer.from(wrongPub.y!, "base64url")[31] & 1)]), + Buffer.from(wrongPub.x!, "base64url"), + ]) + : Buffer.from(wrongPub.x!, "base64url"), + ); + const challenge = generateConfirmationChallenge(); + const message = Buffer.concat([ + Buffer.from("taler-pos-challenge-v1"), + decodeCrockFixed(challenge, 32), + ]); + const signature = + algorithm === "ECDSA_CHALLENGE" + ? sign("sha256", message, { + key: pair.privateKey, + dsaEncoding: "ieee-p1363", + }) + : sign(null, message, pair.privateKey); + if (algorithm === "ECDSA_CHALLENGE") { + const s = BigInt("0x" + signature.subarray(32).toString("hex")); + if (s > order / 2n) + Buffer.from((order - s).toString(16).padStart(64, "0"), "hex").copy( + signature, + 32, + ); + } + const args = { + algorithm, + publicKey, + challenge, + confirmation: encodeCrock(signature), + }; + assert.equal(verifyChallengeConfirmation(args), true); + assert.equal( + verifyChallengeConfirmation({ ...args, publicKey: wrongKey }), + false, + ); + assert.equal( + verifyChallengeConfirmation({ + ...args, + challenge: generateConfirmationChallenge(), + }), + false, + ); + const changed = Buffer.from(signature); + changed[0] ^= 1; + assert.equal( + verifyChallengeConfirmation({ + ...args, + confirmation: encodeCrock(changed), + }), + false, + ); + assert.throws(() => + verifyChallengeConfirmation({ ...args, confirmation: "invalid" }), + ); + assert.throws(() => + verifyChallengeConfirmation({ + ...args, + challenge: encodeCrock(new Uint8Array(31)), + }), + ); + if (algorithm === "ECDSA_CHALLENGE") { + const s = BigInt("0x" + signature.subarray(32).toString("hex")); + Buffer.from((order - s).toString(16).padStart(64, "0"), "hex").copy( + signature, + 32, + ); + assert.equal( + verifyChallengeConfirmation({ + ...args, + confirmation: encodeCrock(signature), + }), + false, + ); + } + }); +} +test("challenge generation produces independent 32-byte values", () => { + const challenges = new Set( + Array.from({ length: 20 }, generateConfirmationChallenge), + ); + assert.equal(challenges.size, 20); + for (const c of challenges) assert.equal(decodeCrockFixed(c, 32).length, 32); +}); diff --git a/packages/taler-util/src/challenge-confirmation.ts b/packages/taler-util/src/challenge-confirmation.ts @@ -0,0 +1,121 @@ +/* + 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 { p256 } from "@noble/curves/nist.js"; +import { ed25519 } from "@noble/curves/ed25519.js"; +import { + decodeCrockFixed, + encodeCrock, + getRandomBytes, + stringToBytes, +} from "./taler-crypto.js"; + +export type ChallengeConfirmationAlgorithm = + | "ECDSA_CHALLENGE" + | "EDDSA_CHALLENGE"; + +export function parseChallengeConfirmationAlgorithm( + value: string, +): ChallengeConfirmationAlgorithm { + if (value === "ECDSA_CHALLENGE" || value === "3") return "ECDSA_CHALLENGE"; + if (value === "EDDSA_CHALLENGE" || value === "4") return "EDDSA_CHALLENGE"; + throw new Error("Expected ECDSA_CHALLENGE (3) or EDDSA_CHALLENGE (4)"); +} + +export function generateConfirmationChallenge(): string { + return encodeCrock(getRandomBytes(32)); +} + +export function decodeConfirmationPublicKey( + algorithm: ChallengeConfirmationAlgorithm, + key: string, +): Uint8Array { + const bytes = decodeCrockFixed( + key, + algorithm === "ECDSA_CHALLENGE" ? 33 : 32, + ); + if (algorithm === "ECDSA_CHALLENGE") + p256.Point.fromBytes(bytes).assertValidity(); + else { + const point = ed25519.Point.fromBytes(bytes); + point.assertValidity(); + if (point.isSmallOrder() || !point.isTorsionFree()) + throw Error("Invalid Ed25519 public key"); + } + return bytes; +} + +/** DD97 wire message. No GNUnet signature-purpose header or NUL terminator. */ +export function confirmationChallengeMessage(challenge: string): Uint8Array { + const salt = stringToBytes("taler-pos-challenge-v1"); + const bytes = decodeCrockFixed(challenge, 32); + const message = new Uint8Array(salt.length + bytes.length); + message.set(salt); + message.set(bytes, salt.length); + return message; +} + +/** Malformed encodings throw; correctly encoded but invalid signatures return false. */ +export function verifyChallengeConfirmation(args: { + algorithm: ChallengeConfirmationAlgorithm; + publicKey: string; + challenge: string; + confirmation: string; +}): boolean { + const publicKey = decodeConfirmationPublicKey(args.algorithm, args.publicKey); + const message = confirmationChallengeMessage(args.challenge); + const signature = decodeCrockFixed(args.confirmation, 64); + return args.algorithm === "ECDSA_CHALLENGE" + ? p256.verify(signature, message, publicKey, { + prehash: true, + lowS: true, + format: "compact", + }) + : ed25519.verify(signature, message, publicKey, { zip215: false }); +} + +export function generateConfirmationSecret( + algorithm: ChallengeConfirmationAlgorithm, +): string { + const curve = algorithm === "ECDSA_CHALLENGE" ? p256 : ed25519; + return encodeCrock(curve.utils.randomSecretKey()); +} + +export function confirmationPublicKey( + algorithm: ChallengeConfirmationAlgorithm, + secret: string, +): string { + const curve = algorithm === "ECDSA_CHALLENGE" ? p256 : ed25519; + return encodeCrock(curve.getPublicKey(decodeCrockFixed(secret, 32))); +} + +export function signChallengeConfirmation( + algorithm: ChallengeConfirmationAlgorithm, + secret: string, + challenge: string, +): string { + const message = confirmationChallengeMessage(challenge); + const key = decodeCrockFixed(secret, 32); + return encodeCrock( + algorithm === "ECDSA_CHALLENGE" + ? p256.sign(message, key, { + prehash: true, + lowS: true, + format: "compact", + }) + : ed25519.sign(message, key), + ); +} diff --git a/packages/taler-util/src/http-client/merchant.ts b/packages/taler-util/src/http-client/merchant.ts @@ -2630,6 +2630,14 @@ export class TalerMerchantInstanceHttpClient { }); switch (resp.status) { + case HttpStatusCode.Ok: + this.cacheEvictor.notifySuccess( + TalerMerchantInstanceCacheEviction.CREATE_DEVICE, + ); + return opSuccessFromHttp( + resp, + TalerMerchantApi.codecForOtpDeviceCreateResponse(), + ); case HttpStatusCode.NoContent: { this.cacheEvictor.notifySuccess( TalerMerchantInstanceCacheEviction.CREATE_DEVICE, diff --git a/packages/taler-util/src/index.ts b/packages/taler-util/src/index.ts @@ -115,3 +115,4 @@ export * from "./iso-3166.js"; export * from "./result.js"; export * from "./user-attention.js"; +export * from "./challenge-confirmation.js"; diff --git a/packages/taler-util/src/taleruri.ts b/packages/taler-util/src/taleruri.ts @@ -273,6 +273,7 @@ export namespace TalerUris { return result; } case TalerUriAction.PayTemplate: { + if (p.challenge) result.push(["challenge", p.challenge]); if (p.fulfillmentUrl) { result.push(["fulfillment_url", p.fulfillmentUrl]); } @@ -802,10 +803,23 @@ function parsePayTemplate( amount = amountParam; } + const challenge = params["challenge"]; + if (challenge !== undefined) { + try { + decodeCrockFixed(challenge, 32); + } catch { + return Result.errorWithDetail(TalerUriParseError.INVALID_PARAMETER, { + uriType, + name: "challenge", + }); + } + } + return Result.of({ type: TalerUriAction.PayTemplate, merchantBaseUrl: merchant ?? (segments[0] as HostPortPath), templateId, + challenge, fulfillmentUrl: params["fulfillment_url"], sessionId: params["session_id"], amount, @@ -1072,6 +1086,7 @@ export type TemplateParams = { }; export interface TalerPayTemplateUri { + challenge?: string; type: TalerUriAction.PayTemplate; merchantBaseUrl: HostPortPath; templateId: string; diff --git a/packages/taler-util/src/types-taler-merchant.ts b/packages/taler-util/src/types-taler-merchant.ts @@ -3206,12 +3206,14 @@ export interface OtpDeviceAddDetails { // Taler base32-crockford encoding. // Instead it uses the RFC 3548 encoding to // be compatible with the TOTP standard. - otp_key: string; + otp_key?: string; // Algorithm for computing the POS confirmation. // "NONE" or 0: No algorithm (no pos confirmation will be generated) // "TOTP_WITHOUT_PRICE" or 1: Without amounts (typical OTP device) // "TOTP_WITH_PRICE" or 2: With amounts (special-purpose OTP device) + // "ECDSA_CHALLENGE" or 3: P-256 challenge signature (backend generates key) + // "EDDSA_CHALLENGE" or 4: Ed25519 challenge signature (backend generates key) // The "String" variants are supported @since protocol **v7**. otp_algorithm: Integer | string; @@ -3249,7 +3251,18 @@ export interface OtpDeviceEntry { device_description: string; } +export interface OtpDeviceCreateResponse { + otp_device_pub: string; +} + +export const codecForOtpDeviceCreateResponse = + (): Codec<OtpDeviceCreateResponse> => + buildCodecForObject<OtpDeviceCreateResponse>() + .property("otp_device_pub", codecForString()) + .build("OtpDeviceCreateResponse"); + export interface OtpDeviceDetails { + otp_device_pub?: string; // Human-readable description for the device. device_description: string; @@ -3259,6 +3272,8 @@ export interface OtpDeviceDetails { // 0: None // 1: TOTP without price // 2: TOTP with price + // 3: P-256 challenge signature + // 4: Ed25519 challenge signature otp_algorithm: Integer; // Counter for counter-based OTP devices. @@ -3639,6 +3654,8 @@ export type UsingTemplateDetailsRequest = ( UsingTemplateCommonRequest; export interface UsingTemplateCommonRequest { + /** DD97: required for challenge-signature OTP devices. */ + challenge?: string; // Type of the template being instantiated. // Possible values include "fixed-order", // "inventory-cart" and "paivana". @@ -5160,6 +5177,7 @@ export const codecForOtpDeviceDetails = (): Codec<OtpDeviceDetails> => .property("otp_ctr", codecOptional(codecForNumber())) .property("otp_timestamp", codecForNumber()) .property("otp_code", codecOptional(codecForString())) + .property("otp_device_pub", codecOptional(codecForString())) .build("TalerMerchantApi.OtpDeviceDetails"); export const codecForTemplateSummaryResponse = diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts @@ -3085,6 +3085,8 @@ export const codecForCheckPayTemplateRequest = .build("CheckPayTemplateRequest"); export interface PreparePayTemplateRequest { + /** Challenge supplied by the offline verifier (DD97). */ + challenge?: string; talerPayTemplateUri: string; templateParams?: TemplateParams; @@ -3097,6 +3099,7 @@ export const codecForPreparePayTemplateRequest = .property("talerPayTemplateUri", codecForString()) .property("templateParams", codecForAny()) .property("progressToken", codecOptional(codecForString())) + .property("challenge", codecOptional(codecForString())) .build("PreparePayTemplate"); export interface ConfirmPayRequest { diff --git a/packages/taler-wallet-cli/src/index.ts b/packages/taler-wallet-cli/src/index.ts @@ -221,6 +221,7 @@ async function doHandlePayTransaction( } if (paySt.txState.major === TransactionMajorState.Done) { diagnosticLog(`Payment succeeded (already done).`); + if (paySt.posConfirmation) console.log(paySt.posConfirmation); return; } if (paySt.txState.major === TransactionMajorState.Expired) { @@ -280,6 +281,8 @@ async function doHandlePayTransaction( transactionId, }); diagnosticLog(`Finished with status '${tx.txState.major}'.`); + if (tx.type === TransactionType.Payment && tx.posConfirmation) + console.log(tx.posConfirmation); } } diff --git a/packages/taler-wallet-core/src/pay-template.test.ts b/packages/taler-wallet-core/src/pay-template.test.ts @@ -14,6 +14,7 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ +import { encodeCrock } from "@gnu-taler/taler-util"; import { AmountString, Amounts, @@ -461,3 +462,50 @@ test("a Paivana link can be inspected and instantiated after its minimum access assert.equal(submitted.paivana_id, `${minimum}-${"A".repeat(43)}`); } }); + +test("DD97 challenge is forwarded once; conflicting or malformed values never create an order", async () => { + const challenge = encodeCrock(new Uint8Array(32).fill(11)); + const requests: unknown[] = []; + const wex = { + ws: { longpollQueue: new LongpollQueue() }, + http: { + fetch: async (_url: string, options: { body: unknown }) => { + requests.push(options.body); + throw Error("sent"); + }, + }, + } as unknown as WalletExecutionContext; + const templateInfo: WalletTemplateDetailsResponse = { + template_contract: { + template_type: TemplateType.FIXED_ORDER, + amount: "KUDOS:1", + summary: "coffee", + }, + }; + const uri = `taler://pay-template/example.com/coffee?challenge=${challenge}`; + await assert.rejects( + instantiateTemplateRaw(wex, { talerPayTemplateUri: uri }, templateInfo), + /sent/, + ); + assert.deepEqual(requests, [{ template_type: "fixed-order", challenge }]); + await assert.rejects( + instantiateTemplateRaw( + wex, + { talerPayTemplateUri: uri, challenge: encodeCrock(new Uint8Array(32)) }, + templateInfo, + ), + /conflicting/, + ); + await assert.rejects( + instantiateTemplateRaw( + wex, + { + talerPayTemplateUri: "taler://pay-template/example.com/coffee", + challenge: "short", + }, + templateInfo, + ), + /Invalid/, + ); + assert.equal(requests.length, 1); +}); diff --git a/packages/taler-wallet-core/src/pay-template.ts b/packages/taler-wallet-core/src/pay-template.ts @@ -15,6 +15,8 @@ */ import { + decodeCrockFixed, + encodeCrock, Amounts, AmountString, assertUnreachable, @@ -343,6 +345,28 @@ export async function instantiateTemplateRaw( req.templateParams ?? {}, ); + if (req.challenge !== undefined || parsedUri.challenge !== undefined) { + try { + const fromApi = + req.challenge === undefined + ? undefined + : encodeCrock(decodeCrockFixed(req.challenge, 32)); + const fromUri = + parsedUri.challenge === undefined + ? undefined + : encodeCrock(decodeCrockFixed(parsedUri.challenge, 32)); + if (fromApi !== undefined && fromUri !== undefined && fromApi !== fromUri) + throw Error("conflicting challenges"); + templateDetails.challenge = req.challenge ?? parsedUri.challenge; + } catch { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_TALER_URI_MALFORMED, + {}, + "Invalid or conflicting payment confirmation challenge", + ); + } + } + // Instantiating a template is not idempotent. In particular, a transport // failure can happen after the merchant committed the new order. Retrying // here would create an additional order with no way to identify the first