commit d59094c70e3c3e257ddbc4ba4dd09c5b4615bd2b
parent 74645b08aa5710b2a7f402ed9649d53cb2abf763
Author: Florian Dold <dold@taler.net>
Date: Thu, 19 Nov 2026 18:16:51 +0100
paywall: replace expired payment links and QR codes with a new offer action
Diffstat:
7 files changed, 224 insertions(+), 64 deletions(-)
diff --git a/src/backend/paivana-httpd_templates.c b/src/backend/paivana-httpd_templates.c
@@ -772,6 +772,9 @@ load_paywall (struct MHD_Connection *conn,
GNUNET_JSON_pack_object_incref (
"default_choice",
json_array_get (t->choices, 0))),
+ GNUNET_JSON_pack_bool (
+ "has_pickup_deadline",
+ ! GNUNET_TIME_relative_is_forever (t->max_pickup_delay)),
GNUNET_JSON_pack_uint64 (
"max_pickup_delay",
/* Note: 'forever' will result in a very large number
diff --git a/src/frontend/global.d.ts b/src/frontend/global.d.ts
@@ -21,6 +21,9 @@ declare const I18N_PAYMENT_CONFIRMED_PROBLEM: string;
declare const I18N_PAYMENT_CONFIRMED_RETRYING: string;
declare const I18N_PAYMENT_CONFIRMED_EXPIRED: string;
declare const I18N_PAYMENT_CONFIRMED_NO_ORDER: string;
+declare const I18N_OFFER_EXPIRED: string;
+declare const I18N_PENDING_ORDER: string;
+declare const I18N_ACCESS_UNAVAILABLE: string;
declare const I18N_PAYMENT_STATUS_ERROR: string;
declare const MERCHANT_BACKEND: string;
declare const MERCHANT_TEMPLATE_ID: string;
diff --git a/src/frontend/paywall.en.must.j2 b/src/frontend/paywall.en.must.j2
@@ -14,6 +14,9 @@
const I18N_PAYMENT_CONFIRMED_RETRYING = 'Payment confirmed. Retrying access…';
const I18N_PAYMENT_CONFIRMED_EXPIRED = 'Payment confirmed. The access period has ended.';
const I18N_PAYMENT_CONFIRMED_NO_ORDER = 'Unexpected 200 OK response without an order_id. Trying again.';
+ const I18N_OFFER_EXPIRED = 'This offer has expired.';
+ const I18N_PENDING_ORDER = 'Check your wallet before starting another payment.';
+ const I18N_ACCESS_UNAVAILABLE = 'Access is unavailable with this offer.';
const I18N_PAYMENT_STATUS_ERROR = 'Could not check payment status. Retrying...';
// The _js values arrive as complete JavaScript string literals,
// quotes included, so they are interpolated unescaped: mustache's
@@ -392,6 +395,9 @@ var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this
{{/summary}}
<p class="merchant-host">{{ merchant_backend }}</p>
+ {{#has_pickup_deadline}}
+ <p id="access-deadline" hidden>Access ends <time></time></p>
+ {{/has_pickup_deadline}}
<div class="qr-taler-frame">
<div style="padding: 10px; border-radius: 20px; background-color: white">
<div class="qr-frame" id="qrcode" style="margin: 5px" >
@@ -467,7 +473,7 @@ var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this
</div>
<p class="footer-note">
- Access is granted automatically once the transaction confirms.<br />
+ <span id="access-on-payment">Access is granted automatically once the transaction confirms.<br /></span>
Need help? <a href="https://www.taler.net/en/">Contact support</a>
</p>
</div>
@@ -476,7 +482,8 @@ var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this
<div class="footer">
<p id="error-message" role="status"></p>
<div class="button-cta">
- <a target="_blank" id="taler-link" href="" class="cta">Pay now</a>
+ <a target="_blank" id="taler-link" hidden class="cta">Pay now</a>
+ <a id="renew-offer" hidden class="cta">Get a new offer</a>
</div>
</div>
diff --git a/src/frontend/paywall.js b/src/frontend/paywall.js
@@ -28,6 +28,7 @@ const merchantProto = merchantUrl.protocol;
const suffix = merchantProto === "http:" ? "+http" : "";
const merchantHost = merchantUrl.host;
const merchantPath = merchantUrl.pathname;
+const maxTimerMs = 0x7fffffff; // Largest delay supported by browser timers.
const expTime = Math.floor(Date.now() / 1000) + usePickupDelay;
/**
@@ -189,6 +190,14 @@ async function redemptionError(res) {
return detail ? `${message} ${JSON.stringify(detail)}` : message;
}
+/** @param {HTMLElement} linkEl */
+function hideOffer(linkEl) {
+ linkEl.removeAttribute("href");
+ linkEl.hidden = true;
+ document.querySelector(".qr-taler-frame")?.remove();
+ document.querySelector(".qr-legend")?.remove();
+}
+
/**
* @param {string} order_id
* @param {HTMLElement} linkEl
@@ -197,10 +206,7 @@ async function redemptionError(res) {
* @returns {Promise<void>}
*/
async function confirmPayment(order_id, linkEl, errorEl, nonce) {
- linkEl.removeAttribute("href");
- linkEl.hidden = true;
- document.querySelector(".qr-taler-frame")?.remove();
- document.querySelector(".qr-legend")?.remove();
+ hideOffer(linkEl);
errorEl.textContent = I18N_PAYMENT_CONFIRMED_LOADING;
const body = JSON.stringify({
order_id,
@@ -209,7 +215,6 @@ async function confirmPayment(order_id, linkEl, errorEl, nonce) {
website,
});
const expiresAt = expTime * 1000;
- const maxTimerMs = 0x7fffffff; // Largest delay supported by browser timers.
let backoffMs = 1000;
/** @type {number | undefined} */
let timeoutAfterStallMs;
@@ -307,18 +312,63 @@ async function main() {
POLL_WAIT_MS,
].join("");
- // grab all the html element we need
- const talerLink = document.getElementById("taler-link");
- const errorMessageLabel = document.getElementById("error-message");
+ const talerLink = document.querySelector("#taler-link");
+ const renew = document.querySelector("#renew-offer");
+ const status = document.getElementById("error-message");
const qrDiv = document.getElementById("qrcode");
+ if (
+ !(talerLink instanceof HTMLAnchorElement) ||
+ !(renew instanceof HTMLAnchorElement) || !status || !qrDiv
+ ) return;
- if (talerLink) {
- // show the taler URI as a link
- // because we want the user to be able to use the webex
- // @ts-ignore
- talerLink.href = TALER_URI;
+ const expiresAt = expTime * 1000;
+ const deadline = document.querySelector("#access-deadline time");
+ if (deadline instanceof HTMLTimeElement && deadline.parentElement && usePickupDelay > 0) {
+ const date = new Date(expiresAt);
+ deadline.dateTime = date.toISOString();
+ deadline.textContent = date.toLocaleString();
+ deadline.parentElement.hidden = false;
}
+ // The protected URL comes from the fragment. Only link back to this proxy.
+ const target = new URL(website, location.href);
+ if (target.origin === location.origin && ["https:", "http:"].includes(target.protocol)) {
+ renew.href = target.href;
+ }
+ let expired = false;
+ let pendingOrder = false;
+ /** @type {number | undefined} */
+ let timer;
+
+ const checkExpiry = () => {
+ if (!expired && Date.now() < expiresAt) return false;
+ expired = true;
+ hideOffer(talerLink);
+ document.querySelector(".steps")?.remove();
+ document.getElementById("access-on-payment")?.remove();
+ let message = usePickupDelay === 0 ? I18N_ACCESS_UNAVAILABLE : I18N_OFFER_EXPIRED;
+ if (pendingOrder) message += " " + I18N_PENDING_ORDER;
+ if (status.textContent !== message) status.textContent = message;
+ renew.hidden = usePickupDelay === 0 || !renew.hasAttribute("href");
+ return true;
+ };
+
+ function watchExpiry() {
+ clearTimeout(timer);
+ if (checkExpiry()) return false;
+ timer = setTimeout(watchExpiry, Math.min(expiresAt - Date.now(), maxTimerMs));
+ return true;
+ }
+
+ if (!watchExpiry()) return;
+ window.addEventListener("pageshow", watchExpiry);
+ document.addEventListener("visibilitychange", watchExpiry);
+ talerLink.addEventListener("click", (event) => {
+ if (checkExpiry()) event.preventDefault();
+ });
+ talerLink.href = TALER_URI;
+ talerLink.hidden = false;
+
// show the qr code
new QRCode(qrDiv, {
text: TALER_URI,
@@ -327,56 +377,50 @@ async function main() {
correctLevel: QRCode.CorrectLevel.M,
});
- // From here we just poll. Whe the request from polling
- // returns that the order has been paid we show to the
- // proxy that we hold the nonce and it should return
- // us a valid cookie.
- while (true) {
- const start = performance.now();
- try {
- const res = await fetch(PAIVANA_POLL_URL, { cache: "no-store" });
- // 404 is normal until the wallet creates an order. 202 means it is unpaid.
- if (![200, 202, 404].includes(res.status)) {
- throw new Error(`Unexpected session status response: HTTP ${res.status}`);
- }
- if (errorMessageLabel) {
- errorMessageLabel.textContent = "";
- }
- if (res.status === 200) {
- let info = null;
- try {
- info = await res.json();
- } catch (_) {}
- console.log("[paivana] Got reponse from backend", res, info);
- if (info && info.order_id) {
- if (talerLink && errorMessageLabel) {
- await confirmPayment(
- info.order_id,
- talerLink,
- errorMessageLabel,
- nonce,
- );
- }
- } else {
- if (talerLink) {
- talerLink.textContent = I18N_PAYMENT_CONFIRMED_NO_ORDER;
+ // An outstanding poll can still report a payment after the controls expire.
+ try {
+ while (!checkExpiry()) {
+ const start = performance.now();
+ try {
+ const res = await fetch(PAIVANA_POLL_URL, { cache: "no-store" });
+ if (res.status === 202) pendingOrder = true;
+ if (res.status === 200) {
+ let info;
+ try {
+ info = await res.json();
+ } catch (_) {}
+ if (info?.order_id) {
+ renew.hidden = true;
+ // Hand the deadline over to the paid redemption loop.
+ return confirmPayment(info.order_id, talerLink, status, nonce);
}
- const remMs = Math.round(POLL_WAIT_MS - (performance.now() - start));
- if (remMs > 0) await waitMs(remMs);
- location.href = website;
+ if (checkExpiry()) return;
+ talerLink.textContent = I18N_PAYMENT_CONFIRMED_NO_ORDER;
+ await waitMs(Math.max(0, POLL_WAIT_MS - (performance.now() - start)));
+ if (!checkExpiry()) location.href = website;
+ return;
+ }
+ if (checkExpiry()) return;
+ if (res.status !== 202 && res.status !== 404) {
+ throw new Error(`Unexpected session status response: HTTP ${res.status}`);
+ }
+ status.textContent = "";
+ } catch (e) {
+ if (checkExpiry()) return;
+ console.warn("[paivana] poll error:", e);
+ if (status.textContent !== I18N_PAYMENT_STATUS_ERROR) {
+ status.textContent = I18N_PAYMENT_STATUS_ERROR;
}
- return;
- }
- } catch (e) {
- console.warn("[paivana] poll error:", e);
- if (
- errorMessageLabel &&
- errorMessageLabel.textContent !== I18N_PAYMENT_STATUS_ERROR
- ) {
- errorMessageLabel.textContent = I18N_PAYMENT_STATUS_ERROR;
}
+ const remaining = Math.min(
+ expiresAt - Date.now(),
+ POLL_WAIT_MS - (performance.now() - start),
+ );
+ if (remaining > 0) await waitMs(remaining);
}
- const remMs = Math.round(POLL_WAIT_MS - (performance.now() - start));
- if (remMs > 0) await waitMs(remMs);
+ } finally {
+ clearTimeout(timer);
+ window.removeEventListener("pageshow", watchExpiry);
+ document.removeEventListener("visibilitychange", watchExpiry);
}
}
diff --git a/src/meson.build b/src/meson.build
@@ -1,4 +1,4 @@
# This file is in the public domain
subdir('backend')
-subdir('tests')
subdir('frontend')
+subdir('tests')
diff --git a/src/tests/meson.build b/src/tests/meson.build
@@ -222,7 +222,7 @@ test(
'paywall',
files('test_paywall.sh'),
env: test_env,
- depends: test_deps,
+ depends: test_deps + [paywall_must],
timeout: 900,
)
diff --git a/src/tests/test_paywall_poll.py b/src/tests/test_paywall_poll.py
@@ -1,9 +1,11 @@
#!/usr/bin/env python3
"""Exercise payment polling and cookie redemption in the served paywall."""
+import re
import shutil
import sys
from pathlib import Path
+from urllib.parse import urljoin
try:
from playwright.sync_api import expect, sync_playwright
@@ -74,6 +76,101 @@ def check_polling(page, url):
expect(page.locator("body")).to_have_text("Paid article")
+def open_timed_offer(page, url, seconds, poll):
+ # Use the served template and change only its configured pickup duration.
+ redirect = page.request.get(url, max_redirects=0)
+ assert redirect.status == 302
+ offer = urljoin(url, redirect.headers["location"])
+ document_url = offer.split("#")[0]
+ template = page.request.get(document_url)
+ assert template.status == 402
+ body, count = re.subn(r"const MAX_PICKUP_DELAY = [0-9]+;",
+ f"const MAX_PICKUP_DELAY = {seconds};", template.text())
+ assert count == 1
+ page.route(document_url, lambda route: route.fulfill(
+ status=402, content_type="text/html", body=body))
+ page.route("**/sessions/**", poll)
+ page.clock.install(time="2030-01-01T00:00:00Z")
+ page.clock.pause_at("2030-01-01T00:01:00Z")
+ page.goto(offer)
+
+
+def check_idle_offer(page, url, late_status, wake):
+ polls = []
+ posts = []
+ page.on("request", lambda req: posts.append(req) if req.method == "POST" else None)
+
+ def poll(route):
+ polls.append(route)
+ if len(polls) == 1:
+ route.fulfill(status=404, json={})
+ elif len(polls) == 2:
+ route.fulfill(status=202, json={"order_id": "pending"})
+ # Leave the third poll outstanding until after expiry.
+
+ open_timed_offer(page, url, 300, poll)
+ pay = page.get_by_role("link", name="Pay now")
+ expect(pay).to_be_visible()
+ uri = pay.get_attribute("href")
+ deadline = page.locator("#access-deadline time")
+ expect(deadline).to_be_visible()
+ expect(deadline).to_have_attribute("datetime", "2030-01-01T00:06:00.000Z")
+ for _ in range(2):
+ with page.expect_request("**/sessions/**"):
+ page.clock.fast_forward(30000)
+ expect(pay).to_have_attribute("href", uri)
+ expect(page.locator("#qrcode")).to_have_attribute("title", uri)
+ if wake == "timer":
+ page.clock.fast_forward(240000)
+ else:
+ page.clock.set_system_time("2030-01-01T00:06:00Z")
+ if wake == "click":
+ assert pay.evaluate("el => !el.dispatchEvent(new MouseEvent('click', {cancelable:true}))")
+ else:
+ page.evaluate("document.dispatchEvent(new Event('visibilitychange'))")
+ msg = page.get_by_role("status")
+ renew = page.get_by_role("link", name="Get a new offer")
+ expect(msg).to_contain_text("Check your wallet")
+ expect(page.locator("#qrcode")).to_be_hidden()
+ expect(pay).to_be_hidden()
+ expect(renew).to_have_attribute("href", url)
+ if late_status:
+ polls[2].fulfill(status=late_status, json={"order_id": "pending"})
+ else:
+ polls[2].abort()
+ if late_status == 200:
+ expect(msg).to_contain_text("Payment confirmed. The access period has ended.")
+ expect(renew).to_be_hidden()
+ else:
+ page.clock.fast_forward(60000)
+ expect(msg).to_contain_text("This offer has expired.")
+ assert len(polls) == 3
+ with page.expect_request(url):
+ renew.click()
+ expect(pay).to_be_visible()
+ assert pay.get_attribute("href") != uri
+ assert not posts
+
+
+def check_duration_limits(page, url, seconds):
+ polls = []
+ open_timed_offer(page, url, seconds, lambda route: polls.append(route))
+ if seconds == 0:
+ expect(page.get_by_role("status")).to_contain_text("Access is unavailable")
+ expect(page.locator("#renew-offer")).to_be_hidden()
+ assert not polls
+ else:
+ pay = page.get_by_role("link", name="Pay now")
+ expect(pay).to_be_visible()
+ page.clock.fast_forward(2**31 - 1)
+ expect(pay).to_be_visible()
+ page.clock.fast_forward(seconds * 1000 - (2**31 - 1))
+ expect(page.get_by_role("status")).to_have_text("This offer has expired.")
+ assert len(polls) == 1
+ expect(page.locator("#taler-link")).to_be_hidden()
+ expect(page.locator("#qrcode")).to_be_hidden()
+
+
def open_paid_paywall(page, url, *responses, access_left_ms=None):
"""Grant access after the scripted responses, checking every POST."""
polls = []
@@ -259,6 +356,12 @@ if __name__ == "__main__":
check_polling(page, sys.argv[1])
page.close()
url = sys.argv[1]
+ for late_status, wake in [(404, "timer"), (202, "resume"), (200, "timer"), (0, "click")]:
+ with browser.new_page() as page:
+ check_idle_offer(page, url, late_status, wake)
+ for seconds in [0, 30 * 86400]:
+ with browser.new_page() as page:
+ check_duration_limits(page, url, seconds)
for first_response, delay_ms in [
(lambda r: r.abort("connectionreset"), 1000),
(lambda r: r.fulfill(status=500, json={"code": 9804}), 1000),