taler-typescript-core

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

commit c803d558f128551f22d57084726ece14343491c1
parent 6c69e44c31b9d1597c9b83e1dfa9880dfbd1943a
Author: Florian Dold <dold@taler.net>
Date:   Thu, 19 Nov 2026 18:30:00 +0100

wallet-core: use the Paivana session timestamp as a minimum access expiry

Diffstat:
Mpackages/taler-util/src/taler-error-codes.ts | 10+++++++++-
Mpackages/taler-util/src/types-taler-wallet.ts | 2+-
Mpackages/taler-wallet-core/src/pay-merchant.ts | 6+++---
Mpackages/taler-wallet-core/src/pay-paivana-common.ts | 18++----------------
Mpackages/taler-wallet-core/src/pay-paivana.ts | 2+-
Mpackages/taler-wallet-core/src/pay-repurchase.test.ts | 127+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mpackages/taler-wallet-core/src/pay-repurchase.ts | 11++---------
Mpackages/taler-wallet-core/src/pay-template.test.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mpackages/taler-wallet-core/src/pay-template.ts | 92+++++++++++++++++++++++++++++++++++++++++--------------------------------------
9 files changed, 199 insertions(+), 175 deletions(-)

diff --git a/packages/taler-util/src/taler-error-codes.ts b/packages/taler-util/src/taler-error-codes.ts @@ -5473,6 +5473,14 @@ export enum TalerErrorCode { /** + * Deprecated. This value is reserved for wallets that treated the timestamp in a Paivana payment link as a session deadline. + * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0). + * (A value of 0 indicates that the error is generated client-side). + */ + WALLET_PAIVANA_SESSION_EXPIRED = 7083, + + + /** * The operation was completed or taken over by another wallet. * Returned with an HTTP status code of #MHD_HTTP_UNINITIALIZED (0). * (A value of 0 indicates that the error is generated client-side). @@ -6529,7 +6537,7 @@ export enum TalerErrorCode { /** - * The specified expiration time for the cookie is longer than what the purchase allows. The request may succeed with a shorter expiration time. Alternatively, the user may need to purchase access again. + * The paid order's pickup deadline has passed or is earlier than the requested minimum access expiry. * Returned with an HTTP status code of #MHD_HTTP_GONE (410). * (A value of 0 indicates that the error is generated client-side). */ diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts @@ -1381,7 +1381,7 @@ export interface PaivanaRedemption { /** Crockford-base32 encoded 16-byte client nonce. */ nonce: string; - /** End of the access period used to derive the Paivana session ID. */ + /** Minimum acceptable access expiry bound into the Paivana session ID. */ expiration: TalerProtocolTimestamp; } diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -171,7 +171,7 @@ import { } from "./exchanges.js"; import { requireValidExchangeRefundConfirmation } from "./exchange-signatures.js"; import { findRepurchase } from "./pay-repurchase.js"; -import { getPaivanaSessionExpiration } from "./pay-paivana-common.js"; +import { getPaivanaMinimumExpiration } from "./pay-paivana-common.js"; import { instantiateTemplateRaw } from "./pay-template.js"; import { runWithMaybeProgressContext } from "./progress.js"; import { @@ -1788,7 +1788,7 @@ async function processDownloadProposal( await findRepurchase(tx, { fulfillmentUrl, sessionId: p.downloadSessionId, - merchantBaseUrl: getPaivanaSessionExpiration(p.downloadSessionId) + merchantBaseUrl: getPaivanaMinimumExpiration(p.downloadSessionId) ? p.merchantBaseUrl : undefined, excludeProposalId: p.proposalId, @@ -2119,7 +2119,7 @@ export async function createOrReusePurchase( const match = await findRepurchase(tx, { fulfillmentUrl: p.download?.fulfillmentUrl, sessionId, - merchantBaseUrl: getPaivanaSessionExpiration(sessionId) + merchantBaseUrl: getPaivanaMinimumExpiration(sessionId) ? p.merchantBaseUrl : undefined, excludeProposalId: p.proposalId, diff --git a/packages/taler-wallet-core/src/pay-paivana-common.ts b/packages/taler-wallet-core/src/pay-paivana-common.ts @@ -49,22 +49,8 @@ export function canonicalizePaivanaUrl(url: string): string { return parsed.href; } -/** Check the externally visible DD 76 session-id shape and expiration. */ -export function isValidPaivanaSessionId( - sessionId: string, - now: TalerProtocolTimestamp = TalerProtocolTimestamp.now(), -): boolean { - const expiration = getPaivanaSessionExpiration(sessionId); - return ( - expiration !== undefined && - now.t_s !== "never" && - expiration.t_s !== "never" && - expiration.t_s >= now.t_s - ); -} - -/** Read the public expiration prefix without changing the session's binding. */ -export function getPaivanaSessionExpiration( +/** Read the minimum acceptable access expiry from the session ID. */ +export function getPaivanaMinimumExpiration( sessionId: string | undefined, ): TalerProtocolTimestamp | undefined { const match = /^([0-9]+)-[A-Za-z0-9_-]{43}$/.exec(sessionId ?? ""); diff --git a/packages/taler-wallet-core/src/pay-paivana.ts b/packages/taler-wallet-core/src/pay-paivana.ts @@ -106,7 +106,7 @@ export function makePaivanaSessionId( return `${expiration.t_s}-${digest}`; } -/** Compute a finite access expiration, with the browser client's 100y cap. */ +/** Choose a finite minimum when the wallet creates its own session. */ export function getPaivanaExpiration( maxPickupDuration: { d_us: number | "forever" } | undefined, now: TalerProtocolTimestamp = TalerProtocolTimestamp.now(), diff --git a/packages/taler-wallet-core/src/pay-repurchase.test.ts b/packages/taler-wallet-core/src/pay-repurchase.test.ts @@ -162,7 +162,7 @@ test("selection skips expired purchases and prefers the longest eligible access" test("Paivana reuse requires coverage of the bound expiration and the advertised merchant", async () => { const tx = selectionTx([[purchase("old"), contract(120)]]); - for (const expiration of [99, 100, 120, 121]) { + for (const expiration of [99, 100, 101, 119, 120, 121]) { const found = await findRepurchase( tx, { @@ -174,7 +174,7 @@ test("Paivana reuse requires coverage of the bound expiration and the advertised ); assert.equal( found?.purchase.proposalId, - expiration === 120 ? "old" : undefined, + expiration <= 120 ? "old" : undefined, ); } assert.equal( @@ -237,61 +237,74 @@ test("wallet-generated Paivana sessions bind the remaining access period", async }); for (const factory of runnerFactories) { - test(`${factory.name}: reopening a cached repurchase after expiry permits a new confirmation`, async () => { - const runner = await factory(); - try { - const original = purchase("original"); - const cached = purchase("cached", PurchaseStatus.DoneRepurchaseDetected); - cached.repurchaseProposalId = original.proposalId; - await runner.runReadWriteTx(async (tx) => { - await tx.upsertPurchase(original); - await tx.upsertPurchase(cached); - await tx.upsertContractTerms({ - h: original.proposalId, - contractTermsRaw: contract(1), - }); - await tx.upsertContractTerms({ - h: cached.proposalId, - contractTermsRaw: contract(), + const now = TalerProtocolTimestamp.now().t_s as number; + for (const [reason, oldDeadline, freshSession] of [ + ["expired access", now - 1, "new-session"], + [ + "ten minutes left with a 25-minute minimum", + now + 600, + session(now + 1500), + ], + ] as const) { + test(`${factory.name}: ${reason} requires confirmation when reopening a repurchase`, async () => { + const runner = await factory(); + try { + const original = purchase("original"); + const cached = purchase( + "cached", + PurchaseStatus.DoneRepurchaseDetected, + ); + cached.repurchaseProposalId = original.proposalId; + await runner.runReadWriteTx(async (tx) => { + await tx.upsertPurchase(original); + await tx.upsertPurchase(cached); + await tx.upsertContractTerms({ + h: original.proposalId, + contractTermsRaw: contract(oldDeadline), + }); + await tx.upsertContractTerms({ + h: cached.proposalId, + contractTermsRaw: contract(), + }); }); - }); - let replays = 0; - const wex = { - ws: { longpollQueue: new LongpollQueue() }, - runWalletDbTx: (f: (tx: WalletDbTransaction) => Promise<unknown>) => - runner.runReadWriteTx(f), - taskScheduler: { - resetTask: async () => { - replays++; + let replays = 0; + const wex = { + ws: { longpollQueue: new LongpollQueue() }, + runWalletDbTx: (f: (tx: WalletDbTransaction) => Promise<unknown>) => + runner.runReadWriteTx(f), + taskScheduler: { + resetTask: async () => { + replays++; + }, }, - }, - } as unknown as WalletExecutionContext; - const result = await createOrReusePurchase( - wex, - merchant, - cached.orderId, - "new-session", - undefined, - undefined, - undefined, - ); - assert.equal(result.proposalId, cached.proposalId); - const updated = await runner.runReadWriteTx((tx) => - tx.getPurchase(cached.proposalId), - ); - assert.equal(updated?.purchaseStatus, PurchaseStatus.DialogProposed); - assert.equal(updated?.repurchaseProposalId, undefined); - assert.equal(replays, 0); - assert.equal( - ( - await runner.runReadWriteTx((tx) => - tx.getPurchase(original.proposalId), - ) - )?.purchaseStatus, - PurchaseStatus.Done, - ); - } finally { - await runner.close(); - } - }); + } as unknown as WalletExecutionContext; + const result = await createOrReusePurchase( + wex, + merchant, + cached.orderId, + freshSession, + undefined, + undefined, + undefined, + ); + assert.equal(result.proposalId, cached.proposalId); + const updated = await runner.runReadWriteTx((tx) => + tx.getPurchase(cached.proposalId), + ); + assert.equal(updated?.purchaseStatus, PurchaseStatus.DialogProposed); + assert.equal(updated?.repurchaseProposalId, undefined); + assert.equal(replays, 0); + assert.equal( + ( + await runner.runReadWriteTx((tx) => + tx.getPurchase(original.proposalId), + ) + )?.purchaseStatus, + PurchaseStatus.Done, + ); + } finally { + await runner.close(); + } + }); + } } diff --git a/packages/taler-wallet-core/src/pay-repurchase.ts b/packages/taler-wallet-core/src/pay-repurchase.ts @@ -21,7 +21,7 @@ import { } from "@gnu-taler/taler-util"; import { PurchaseStatus, WalletPurchase } from "./db/records.js"; import { WalletDbTransaction } from "./db/transaction.js"; -import { getPaivanaSessionExpiration } from "./pay-paivana-common.js"; +import { getPaivanaMinimumExpiration } from "./pay-paivana-common.js"; /** Find a purchase that still grants access, preferring the longest access. */ export async function findRepurchase( @@ -45,14 +45,7 @@ export async function findRepurchase( ) { return undefined; } - const requestedExpiration = getPaivanaSessionExpiration(request.sessionId); - if ( - requestedExpiration?.t_s !== undefined && - requestedExpiration.t_s !== "never" && - requestedExpiration.t_s <= now.t_s - ) { - return undefined; - } + const requestedExpiration = getPaivanaMinimumExpiration(request.sessionId); let best: | { purchase: WalletPurchase; maxPickupTime: TalerProtocolTimestamp } | undefined; diff --git a/packages/taler-wallet-core/src/pay-template.test.ts b/packages/taler-wallet-core/src/pay-template.test.ts @@ -24,6 +24,7 @@ import { ScopeType, TalerMerchantInstanceHttpClient, TalerPayTemplateUri, + TalerProtocolTimestamp, TalerUriAction, TalerUris, TemplateContractDetails, @@ -47,6 +48,7 @@ import { import { WalletDbTransaction } from "./db/transaction.js"; import { ProgressContext } from "./progress.js"; import { WalletExecutionContext } from "./wallet.js"; +import { preparePayForTemplateV2 } from "./pay-merchant.js"; /** Exercise the real balance calculation with isolated database inputs. */ function templateBalanceContext( @@ -147,7 +149,11 @@ for (const template_contract of [ { url: "https://u.example/", amount: "USD:10" }, ], ); - const result = await checkPayForTemplate(wex, templateCheckRequest); + const request = + template_contract.template_type === TemplateType.PAIVANA + ? paivanaRequest(Math.floor(Date.now() / 1000) + 3600) + : templateCheckRequest; + const result = await checkPayForTemplate(wex, request); assert.deepStrictEqual(result.supportedCurrencies, ["EUR", "KUDOS"]); assert.deepStrictEqual(result.availableBalances, [ { @@ -388,49 +394,63 @@ test("Paivana instantiation requires its session and fulfillment URL", async () ); }); -test("Paivana instantiation rejects unredeemable URI bindings", async () => { - const templateInfo: WalletTemplateDetailsResponse = { - template_contract: { - template_type: TemplateType.PAIVANA, - choices: [], - }, - }; - const makeUri = (sessionId: string, fulfillmentUrl: string) => - TalerUris.stringify({ +test("malformed Paivana bindings have a distinct error at inspection and preparation", async (t) => { + const wex = templateBalanceContext(t, { + template_contract: { template_type: TemplateType.PAIVANA, choices: [] }, + }); + const sessionId = `200-${"A".repeat(43)}`; + const fulfillmentUrl = "https://example.com/protected"; + const malformed = (e: unknown) => + e instanceof TalerError && + e.errorDetail.code === TalerErrorCode.WALLET_TALER_URI_MALFORMED; + for (const binding of [ + { sessionId }, + { fulfillmentUrl }, + { sessionId: "1-not-a-dd76-session", fulfillmentUrl }, + { sessionId, fulfillmentUrl: "https://user@example.com/protected" }, + ]) { + const request = { + talerPayTemplateUri: TalerUris.stringify({ + ...paivanaUri("KUDOS:1" as AmountString), + ...binding, + }), + }; + await assert.rejects(checkPayForTemplate(wex, request), malformed); + await assert.rejects(preparePayForTemplateV2(wex, request), malformed); + } +}); + +function paivanaRequest(expiration: number) { + return { + talerPayTemplateUri: TalerUris.stringify({ ...paivanaUri("KUDOS:1" as AmountString), - sessionId, - fulfillmentUrl, - }); - const futureSession = `${Math.floor(Date.now() / 1000) + 3600}-${"A".repeat(43)}`; + sessionId: `${expiration}-${"A".repeat(43)}`, + fulfillmentUrl: "https://example.com/protected", + }), + }; +} - await assert.rejects( - instantiateTemplateRaw( - noHttpContext(), - { - talerPayTemplateUri: makeUri( - futureSession, - "https://user@example.com/protected", - ), - }, - templateInfo, - ), - (e: unknown) => - e instanceof TalerError && - e.errorDetail.code === TalerErrorCode.WALLET_TALER_URI_MALFORMED, - ); - await assert.rejects( - instantiateTemplateRaw( - noHttpContext(), - { - talerPayTemplateUri: makeUri( - "1-not-a-dd76-session", - "https://example.com/protected", - ), - }, - templateInfo, - ), - (e: unknown) => - e instanceof TalerError && - e.errorDetail.code === TalerErrorCode.WALLET_TALER_URI_MALFORMED, +test("a Paivana link can be inspected and instantiated after its minimum access expiry", async (t) => { + const templateInfo: WalletTemplateDetailsResponse = { + template_contract: { template_type: TemplateType.PAIVANA, choices: [] }, + }; + const wex = templateBalanceContext(t, templateInfo); + t.mock.method(TalerProtocolTimestamp, "now", () => ({ t_s: 200 })); + const create = t.mock.method( + TalerMerchantInstanceHttpClient.prototype, + "useTemplateCreateOrder", + async () => ({ type: "ok", body: { order_id: "order" } }), ); + for (const minimum of [199, 200]) { + const request = paivanaRequest(minimum); + const before = create.mock.callCount(); + await checkPayForTemplate(wex, request); + assert.equal(create.mock.callCount(), before); + const order = await instantiateTemplateRaw(wex, request, templateInfo); + assert.equal(order.orderId, "order"); + assert.equal(create.mock.callCount(), before + 1); + const submitted = create.mock.calls[before].arguments[1]; + assert(submitted && "paivana_id" in submitted); + assert.equal(submitted.paivana_id, `${minimum}-${"A".repeat(43)}`); + } }); diff --git a/packages/taler-wallet-core/src/pay-template.ts b/packages/taler-wallet-core/src/pay-template.ts @@ -46,7 +46,7 @@ import { walletMerchantClient, WalletExecutionContext } from "./wallet.js"; import { getBalancesInsideTransaction } from "./balance.js"; import { canonicalizePaivanaUrl, - isValidPaivanaSessionId, + getPaivanaMinimumExpiration, } from "./pay-paivana-common.js"; const logger = new Logger("pay-template.ts"); @@ -187,6 +187,42 @@ export async function checkPayForTemplate( ); } +function paivanaTemplateDetails( + parsed: TalerPayTemplateUri, + talerUri: string, +): UsingTemplateDetailsRequest { + const { sessionId, fulfillmentUrl } = parsed; + const malformed = (hint: string) => + TalerError.fromDetail( + TalerErrorCode.WALLET_TALER_URI_MALFORMED, + { talerUri, expectedAction: TalerUriAction.PayTemplate }, + hint, + ); + if (!sessionId || !fulfillmentUrl) { + throw malformed( + "Paivana payment template URI requires session_id and fulfillment_url", + ); + } + let website: string; + try { + website = canonicalizePaivanaUrl(fulfillmentUrl); + } catch { + throw malformed( + "Paivana payment template URI has an invalid fulfillment_url", + ); + } + if (website !== fulfillmentUrl || !getPaivanaMinimumExpiration(sessionId)) { + throw malformed( + "Paivana template URI has a non-canonical URL or invalid session", + ); + } + return { + template_type: TemplateType.PAIVANA, + paivana_id: sessionId, + website, + }; +} + async function internalCheckPayForTemplate( wex: WalletExecutionContext, req: CheckPayTemplateRequest, @@ -215,6 +251,12 @@ async function internalCheckPayForTemplate( succeedOrThrow(await merchantApi.useTemplateGetInfo(parsedUri.templateId)), ); + if ( + templateDetails.template_contract.template_type === TemplateType.PAIVANA + ) { + paivanaTemplateDetails(parsedUri, req.talerPayTemplateUri); + } + const cfg = await runWithProgressRetries(wex, async () => succeedOrThrow(await merchantApi.getConfig()), ); @@ -304,50 +346,12 @@ export async function instantiateTemplateRaw( }; break; } - case TalerMerchantApi.TemplateType.PAIVANA: { - if (!parsedUri.sessionId || !parsedUri.fulfillmentUrl) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TALER_URI_MALFORMED, - { - talerUri: req.talerPayTemplateUri, - expectedAction: TalerUriAction.PayTemplate, - }, - "Paivana payment template URI requires session_id and fulfillment_url", - ); - } - let website: string; - try { - website = canonicalizePaivanaUrl(parsedUri.fulfillmentUrl); - } catch { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TALER_URI_MALFORMED, - { - talerUri: req.talerPayTemplateUri, - expectedAction: TalerUriAction.PayTemplate, - }, - "Paivana payment template URI has an invalid fulfillment_url", - ); - } - if ( - website !== parsedUri.fulfillmentUrl || - !isValidPaivanaSessionId(parsedUri.sessionId) - ) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TALER_URI_MALFORMED, - { - talerUri: req.talerPayTemplateUri, - expectedAction: TalerUriAction.PayTemplate, - }, - "Paivana template URI has a non-canonical URL or invalid session", - ); - } - templateDetails = { - template_type: TemplateType.PAIVANA, - paivana_id: parsedUri.sessionId, - website, - }; + case TalerMerchantApi.TemplateType.PAIVANA: + templateDetails = paivanaTemplateDetails( + parsedUri, + req.talerPayTemplateUri, + ); break; - } default: assertUnreachable(templateInfo.template_contract); }