commit b47fe1d7b813803420d57a531714d7536b74e7bd
parent 5e5bb88b508ffe4f9068d2d2b9988099e021c15c
Author: Florian Dold <dold@taler.net>
Date: Thu, 19 Nov 2026 16:51:03 +0100
paywall: retry access cookie requests after temporary failures
Diffstat:
5 files changed, 255 insertions(+), 32 deletions(-)
diff --git a/src/frontend/global.d.ts b/src/frontend/global.d.ts
@@ -18,7 +18,8 @@ declare const QR_WIDTH: number;
declare const QR_HEIGHT: number;
declare const I18N_PAYMENT_CONFIRMED_LOADING: string;
declare const I18N_PAYMENT_CONFIRMED_PROBLEM: string;
-declare const I18N_PAYMENT_CONFIRMED_ERROR: 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_PAYMENT_STATUS_ERROR: string;
declare const MERCHANT_BACKEND: string;
diff --git a/src/frontend/paywall.en.must.j2 b/src/frontend/paywall.en.must.j2
@@ -10,8 +10,9 @@
const QR_WIDTH = 300;
const QR_HEIGHT = 300;
const I18N_PAYMENT_CONFIRMED_LOADING = 'Payment confirmed! Loading page...';
- const I18N_PAYMENT_CONFIRMED_PROBLEM = 'Payment confirmed, but something went wrong when we tried to obtain the access token. This is a bug, please contact the operator if the issue persists.';
- const I18N_PAYMENT_CONFIRMED_ERROR = 'Could not reach the server!';
+ const I18N_PAYMENT_CONFIRMED_PROBLEM = 'Payment confirmed, but access could not be granted. Please contact the operator.';
+ 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_PAYMENT_STATUS_ERROR = 'Could not check payment status. Retrying...';
// The _js values arrive as complete JavaScript string literals,
diff --git a/src/frontend/paywall.js b/src/frontend/paywall.js
@@ -139,6 +139,57 @@ async function makePaivanaId(curTime, nonceBuf, website) {
}
/**
+ * @param {string | null} value Retry-After header from the redemption response
+ * @returns {number} delay in milliseconds, or zero to use the local backoff
+ */
+function retryAfterMs(value) {
+ if (!value) return 0;
+ if (/^\d+$/.test(value)) return Number(value) * 1000;
+
+ // Normalize the two obsolete HTTP-date forms to the one toUTCString emits.
+ const rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(\w{3})-(\d\d) (\d\d:\d\d:\d\d GMT)$/.exec(value);
+ const asctime = /^(\w{3}) (\w{3}) ([ \d]\d) (\d\d:\d\d:\d\d) (\d{4})$/.exec(value);
+ if (rfc850) {
+ const [, weekday, day, month, shortYear, time] = rfc850;
+ // A two-digit year can be at most 50 years in the future (RFC 9110).
+ const limit = new Date();
+ limit.setUTCFullYear(limit.getUTCFullYear() + 50);
+ let year = limit.getUTCFullYear();
+ year -= (year - Number(shortYear)) % 100;
+ if (Date.parse(`${day} ${month} ${year} ${time}`) > limit.getTime()) year -= 100;
+ value = `${weekday.slice(0, 3)}, ${day} ${month} ${year} ${time}`;
+ } else if (asctime) {
+ const [, weekday, month, day, time, year] = asctime;
+ value = `${weekday}, ${day.replace(" ", "0")} ${month} ${year} ${time} GMT`;
+ }
+ // Date.parse alone accepts malformed headers such as decimal numbers.
+ const date = new Date(value);
+ if (!Number.isFinite(date.getTime()) || date.toUTCString() !== value) return 0;
+ return Math.max(0, date.getTime() - Date.now());
+}
+
+/**
+ * @param {Response} res failed redemption response
+ * @returns {Promise<string | null>} message to show, or null to retry
+ */
+async function redemptionError(res) {
+ if ([408, 429, 502, 503, 504].includes(res.status)) return null;
+ let detail;
+ try {
+ detail = await res.json();
+ } catch (e) {
+ // A 500 may carry a retryable code. Try again if the body was cut off.
+ // For a definitive status, the body only supplies diagnostic detail.
+ if (res.status === 500 && !(e instanceof SyntaxError)) throw e;
+ }
+ // Paivana could not allocate the merchant order lookup for this request.
+ const PAIVANA_GET_ORDER_FAILED = 9804;
+ if (res.status === 500 && detail?.code === PAIVANA_GET_ORDER_FAILED) return null;
+ const message = `${I18N_PAYMENT_CONFIRMED_PROBLEM} (HTTP ${res.status})`;
+ return detail ? `${message} ${JSON.stringify(detail)}` : message;
+}
+
+/**
* @param {string} order_id
* @param {HTMLElement} linkEl
* @param {HTMLElement} errorEl
@@ -146,32 +197,53 @@ async function makePaivanaId(curTime, nonceBuf, website) {
* @returns {Promise<void>}
*/
async function confirmPayment(order_id, linkEl, errorEl, nonce) {
- linkEl.textContent = I18N_PAYMENT_CONFIRMED_LOADING;
- // @ts-ignore
- linkEl.href = "#";
- try {
- const res = await fetch(`${window.location.origin}/.well-known/paivana`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- redirect: "manual",
- body: JSON.stringify({
- order_id,
- nonce,
- expiration: { t_s: expTime },
- website,
- }),
- });
- if (res.status >= 400) {
- linkEl.textContent = I18N_PAYMENT_CONFIRMED_PROBLEM;
- errorEl.textContent = JSON.stringify(await res.json());
- return;
+ linkEl.removeAttribute("href");
+ linkEl.hidden = true;
+ document.querySelector(".qr-taler-frame")?.remove();
+ document.querySelector(".qr-legend")?.remove();
+ errorEl.textContent = I18N_PAYMENT_CONFIRMED_LOADING;
+ const body = JSON.stringify({
+ order_id,
+ nonce,
+ expiration: { t_s: expTime },
+ website,
+ });
+ const expiresAt = expTime * 1000;
+ let backoffMs = 1000;
+ while (Date.now() < expiresAt) {
+ let delayMs = backoffMs;
+ try {
+ const res = await fetch("/.well-known/paivana", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ redirect: "manual",
+ body,
+ });
+ // A successful manual redirect is opaque and has status zero.
+ if (res.status < 400) {
+ location.href = res.redirected ? res.url : website;
+ return;
+ }
+ const message = await redemptionError(res);
+ if (message) {
+ errorEl.textContent = message;
+ return;
+ }
+ delayMs = Math.max(delayMs, retryAfterMs(res.headers.get("Retry-After")));
+ } catch (e) {
+ console.warn("[paivana] Error trying to confirm payment:", e);
}
- const dest = res.redirected ? res.url : website;
- location.href = dest;
- } catch (e) {
- console.warn("[paivana] Error trying to confirm payment:", e);
- errorEl.textContent = I18N_PAYMENT_CONFIRMED_ERROR;
+ if (errorEl.textContent !== I18N_PAYMENT_CONFIRMED_RETRYING) {
+ errorEl.textContent = I18N_PAYMENT_CONFIRMED_RETRYING;
+ }
+ const wakeAt = Math.min(expiresAt, Date.now() + delayMs);
+ // Browser timers accept at most a signed 32-bit delay.
+ while (Date.now() < wakeAt) {
+ await waitMs(Math.min(wakeAt - Date.now(), 0x7fffffff));
+ }
+ backoffMs = Math.min(backoffMs * 2, 30000);
}
+ errorEl.textContent = I18N_PAYMENT_CONFIRMED_EXPIRED;
}
/**
diff --git a/src/tests/test_paywall.sh b/src/tests/test_paywall.sh
@@ -426,9 +426,9 @@ else
fi
if python3 "$SRCDIR/test_paywall_poll.py" "${BASE_URL}hello"; then
- ok "the browser keeps payment and support available while retrying"
+ ok "the browser recovers from temporary polling and redemption failures"
elif [ "$?" -ne 77 ]; then
- fail "paywall polling in the browser"
+ fail "paywall polling and redemption in the browser"
fi
# --------------------------------------------------------------------
diff --git a/src/tests/test_paywall_poll.py b/src/tests/test_paywall_poll.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Exercise the served paywall with a local Chromium and simulated polls."""
+"""Exercise payment polling and cookie redemption in the served paywall."""
import shutil
import sys
@@ -12,6 +12,25 @@ except ModuleNotFoundError:
sys.exit(77)
+ACCESS_COOKIE = "Paivana-Cookie=test-access"
+REDEMPTION = "**/.well-known/paivana"
+
+
+def grant_access(route, url):
+ route.fulfill(status=303, headers={
+ "Location": url,
+ "Set-Cookie": ACCESS_COOKIE + "; Path=/; HttpOnly; SameSite=Lax",
+ })
+
+
+def serve_article(route):
+ cookies = (route.request.header_value("cookie") or "").split("; ")
+ if ACCESS_COOKIE in cookies:
+ route.fulfill(body="Paid article")
+ else:
+ route.fulfill(status=402, body="Payment required")
+
+
def check_polling(page, url):
status_code = None
@@ -29,6 +48,8 @@ def check_polling(page, url):
pay = page.get_by_role("link", name="Pay now")
expect(retry).to_contain_text("Retrying")
uri = page.locator("#qrcode").get_attribute("title")
+ expect(page.locator("#qrcode")).to_be_visible()
+ expect(page.locator(".qr-legend")).to_be_visible()
assert uri.startswith(("taler://pay-template/", "taler+http://pay-template/"))
expect(pay).to_have_attribute("href", uri)
@@ -47,12 +68,119 @@ def check_polling(page, url):
expect(pay).to_have_attribute("href", uri)
status_code = 200
- page.route("**/.well-known/paivana", lambda route: route.fulfill(status=204))
- page.route(url, lambda route: route.fulfill(body="Paid article"))
+ page.route(REDEMPTION, lambda route: grant_access(route, url))
+ page.route(url, serve_article)
page.clock.fast_forward(interval)
expect(page.locator("body")).to_have_text("Paid article")
+def open_paid_paywall(page, url, first_response):
+ """Hold the clock still and grant access on the second identical POST."""
+ polls = []
+ posts = []
+
+ def paid(route):
+ polls.append(route.request.url)
+ assert len(polls) == 1
+ route.fulfill(json={"order_id": "paid-order"})
+
+ def redeem(route):
+ proof = route.request.post_data_json
+ assert route.request.method == "POST"
+ assert proof["order_id"] == "paid-order" and proof["website"] == url
+ assert proof["nonce"] and proof["expiration"]["t_s"] > 0
+ posts.append(route.request.post_data)
+ if len(posts) == 1:
+ first_response(route)
+ else:
+ assert len(posts) == 2 and posts[1] == posts[0]
+ grant_access(route, url)
+
+ page.clock.install(time="2030-01-01T00:00:00Z")
+ page.clock.pause_at("2030-01-01T00:01:00Z")
+ page.route("**/sessions/**", paid)
+ page.route(REDEMPTION, redeem)
+ with page.expect_request(REDEMPTION):
+ page.goto(url)
+ page.route(url, serve_article)
+ return posts
+
+
+def check_recovery(page, url, first_response, delay_ms):
+ posts = open_paid_paywall(page, url, first_response)
+ expect(page.get_by_role("status")).to_contain_text("Retrying")
+ expect(page.locator("#taler-link")).to_be_hidden()
+ expect(page.locator("#qrcode")).to_be_hidden()
+ expect(page.locator(".qr-legend")).to_be_hidden()
+ page.clock.fast_forward(delay_ms - 1)
+ assert len(posts) == 1
+ page.clock.fast_forward(1)
+ expect(page.locator("body")).to_have_text("Paid article")
+ assert len(posts) == 2
+
+
+def check_terminal_error(page, url, status, **response):
+ posts = open_paid_paywall(page, url, lambda r: r.fulfill(status=status, **response))
+ message = page.get_by_role("status")
+ expect(message).to_contain_text(f"HTTP {status}")
+ page.clock.fast_forward(page.evaluate("expTime * 1000 - Date.now()"))
+ expect(message).to_contain_text(f"HTTP {status}")
+ assert len(posts) == 1
+
+
+def check_retry_after_expiry(page, url):
+ posts = open_paid_paywall(page, url, lambda r: r.fulfill(
+ status=503, headers={"Retry-After": "99999999999"}))
+ message = page.get_by_role("status")
+ expect(message).to_contain_text("Retrying")
+ check_retry_after_dates(page)
+ page.clock.fast_forward(page.evaluate("expTime * 1000 - Date.now() - 1"))
+ expect(message).to_contain_text("Retrying")
+ page.clock.fast_forward(1)
+ expect(message).to_contain_text("access period has ended")
+ assert len(posts) == 1
+
+
+def check_retry_after_dates(page):
+ # The clock is frozen at 2030-01-01 00:01:00 UTC on the paid page.
+ fifty_years_ms = page.evaluate("Date.UTC(2080, 0, 1, 0, 1) - Date.now()")
+ for header, expected_ms in [
+ ("5", 5000),
+ ("Tue, 01 Jan 2030 00:01:07 GMT", 7000),
+ ("Tuesday, 01-Jan-30 00:01:07 GMT", 7000),
+ ("Tue Jan 1 00:01:07 2030", 7000),
+ ("Monday, 01-Jan-80 00:01:00 GMT", fifty_years_ms),
+ ("Monday, 01-Jan-80 00:01:01 GMT", 0),
+ ("Tue, 01 Jan 2030 00:00:59 GMT", 0),
+ ("Fri, 31 Feb 2030 00:01:07 GMT", 0),
+ ("1.5", 0),
+ (None, 0),
+ ]:
+ assert page.evaluate("value => retryAfterMs(value)", header) == expected_ms, header
+
+
+def check_retry_backoff(page, url):
+ open_paid_paywall(page, url, lambda r: r.abort("connectionreset"))
+ expect(page.get_by_role("status")).to_contain_text("Retrying")
+
+ # After the real connection reset, reject the intermediate retries in the
+ # page. Each rejection settles before we advance the frozen clock again.
+ delays = [1000, 2000, 4000, 8000, 16000, 30000, 30000]
+ page.evaluate("""lastAttempt => {
+ const fetch = window.fetch;
+ window.retryCount = 0;
+ window.fetch = (...args) => {
+ if (++window.retryCount === lastAttempt) return fetch(...args);
+ return Promise.reject(new TypeError("Network error"));
+ };
+ }""", len(delays))
+ for attempt, delay in enumerate(delays):
+ page.clock.fast_forward(delay - 1)
+ assert page.evaluate("retryCount") == attempt
+ page.clock.fast_forward(1)
+ expect(page.locator("body")).to_have_text("Paid article")
+
+
if __name__ == "__main__":
with sync_playwright() as playwright:
chromium = (
@@ -68,3 +196,24 @@ if __name__ == "__main__":
devtools = page.context.new_cdp_session(page)
devtools.send("Page.setFontSizes", {"fontSizes": {"standard": 32}})
check_polling(page, sys.argv[1])
+ page.close()
+ url = sys.argv[1]
+ for first_response, delay_ms in [
+ (lambda r: r.abort("connectionreset"), 1000),
+ (lambda r: r.fulfill(status=500, json={"code": 9804}), 1000),
+ (lambda r: r.fulfill(status=503, headers={"Retry-After": "5"}), 5000),
+ (lambda r: r.fulfill(status=429, headers={
+ "Retry-After": "Tue, 01 Jan 2030 00:01:07 GMT"}), 7000),
+ (lambda r: r.fulfill(status=502, headers={"Retry-After": "1.5"}), 1000),
+ (lambda r: r.fulfill(status=504), 1000),
+ (lambda r: r.fulfill(status=408), 1000),
+ ]:
+ with browser.new_page() as page:
+ check_recovery(page, url, first_response, delay_ms)
+ for status, response in [(409, {"body": "Conflict"}), (500, {"json": {"code": 9801}})]:
+ with browser.new_page() as page:
+ check_terminal_error(page, url, status, **response)
+ with browser.new_page() as page:
+ check_retry_after_expiry(page, url)
+ with browser.new_page() as page:
+ check_retry_backoff(page, url)