paivana

HTTP paywall reverse proxy
Log | Files | Refs | Submodules | README | LICENSE

commit 74645b08aa5710b2a7f402ed9649d53cb2abf763
parent b47fe1d7b813803420d57a531714d7536b74e7bd
Author: Florian Dold <dold@taler.net>
Date:   Thu, 19 Nov 2026 16:58:10 +0100

paywall: retry stalled cookie requests before paid access expires

Give the first redemption up to thirty seconds and allow more time if
it times out. Near expiry, leave room for a quick retry when possible.
Check the access deadline again before following a late response.

Diffstat:
Msrc/frontend/paywall.js | 26+++++++++++++++++++++++---
Msrc/tests/test_paywall_poll.py | 83++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
2 files changed, 101 insertions(+), 8 deletions(-)

diff --git a/src/frontend/paywall.js b/src/frontend/paywall.js @@ -209,37 +209,57 @@ 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; while (Date.now() < expiresAt) { let delayMs = backoffMs; + const remainingMs = expiresAt - Date.now(); + // Start with 30 seconds. Near expiry, leave one second for a retry + // after backoff if the current attempt can also get at least a second. + const beforeRetryMs = remainingMs - backoffMs - 1000; + const initialMs = Math.min(30000, beforeRetryMs >= 1000 ? beforeRetryMs : remainingMs); + const timeoutMs = Math.min(remainingMs, timeoutAfterStallMs ?? initialMs); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch("/.well-known/paivana", { method: "POST", headers: { "Content-Type": "application/json" }, redirect: "manual", body, + signal: controller.signal, }); + const message = res.status >= 400 ? await redemptionError(res) : null; + // A response can arrive after expiry before the timer has run. + if (Date.now() >= expiresAt) break; // 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) { + if (Date.now() >= expiresAt) break; + // A timeout may mean the connection is slow. Give the next POST longer. + if (controller.signal.aborted) { + timeoutAfterStallMs = Math.min(timeoutMs * 2, maxTimerMs); + } console.warn("[paivana] Error trying to confirm payment:", e); + } finally { + clearTimeout(timer); } 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)); + await waitMs(Math.min(wakeAt - Date.now(), maxTimerMs)); } backoffMs = Math.min(backoffMs * 2, 30000); } diff --git a/src/tests/test_paywall_poll.py b/src/tests/test_paywall_poll.py @@ -74,14 +74,17 @@ def check_polling(page, url): 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.""" +def open_paid_paywall(page, url, *responses, access_left_ms=None): + """Grant access after the scripted responses, checking every POST.""" polls = [] posts = [] def paid(route): polls.append(route.request.url) assert len(polls) == 1 + if access_left_ms is not None: + # Simulate a payment confirmed shortly before access ends. + page.clock.fast_forward(page.evaluate("expTime * 1000 - Date.now()") - access_left_ms) route.fulfill(json={"order_id": "paid-order"}) def redeem(route): @@ -89,11 +92,13 @@ def open_paid_paywall(page, url, first_response): assert route.request.method == "POST" assert proof["order_id"] == "paid-order" and proof["website"] == url assert proof["nonce"] and proof["expiration"]["t_s"] > 0 + attempt = len(posts) posts.append(route.request.post_data) - if len(posts) == 1: - first_response(route) + assert posts[attempt] == posts[0] + if attempt < len(responses): + responses[attempt](route) else: - assert len(posts) == 2 and posts[1] == posts[0] + assert attempt == len(responses) grant_access(route, url) page.clock.install(time="2030-01-01T00:00:00Z") @@ -181,6 +186,62 @@ def check_retry_backoff(page, url): expect(page.locator("body")).to_have_text("Paid article") +def check_stalled_post(page, url, access_left_ms, timeout_ms): + posts = open_paid_paywall(page, url, lambda route: None, access_left_ms=access_left_ms) + message = page.get_by_role("status") + expect(message).to_contain_text("Loading") + page.clock.fast_forward(timeout_ms - 1) + expect(message).to_contain_text("Loading") + with page.expect_event("requestfailed", predicate=lambda r: r.url.endswith("/.well-known/paivana")): + page.clock.fast_forward(1) + expect(message).to_contain_text("Retrying") + assert len(posts) == 1 + page.clock.fast_forward(1000) + expect(page.locator("body")).to_have_text("Paid article") + assert len(posts) == 2 + + +def check_slow_post(page, url, access_left_ms, latency_ms, times_out_once): + pending = [] + responses = [pending.append] * (2 if times_out_once else 1) + posts = open_paid_paywall(page, url, *responses, access_left_ms=access_left_ms) + if times_out_once: + page.clock.fast_forward(30000) + expect(page.get_by_role("status")).to_contain_text("Retrying") + with page.expect_request(REDEMPTION): + page.clock.fast_forward(1000) + + # The browser has sent the POST. Let time pass before delivering the 303. + page.clock.fast_forward(latency_ms) + grant_access(pending[-1], url) + expect(page.locator("body")).to_have_text("Paid article") + assert len(posts) == len(responses) + + +def check_pending_retry_at_expiry(page, url, late_response): + def last_attempt(route): + if late_response: + # Deliver the response after expiry without running the abort timer. + page.clock.set_system_time(page.evaluate("new Date(expTime * 1000 + 1).toISOString()")) + grant_access(route, url) + # Otherwise leave the request pending until its timer fires. + + posts = open_paid_paywall(page, url, lambda r: r.fulfill(status=503), + last_attempt, access_left_ms=2500) + paywall_url = page.url + message = page.get_by_role("status") + expect(message).to_contain_text("Retrying") + with page.expect_request(REDEMPTION): + page.clock.fast_forward(1000) + if not late_response: + page.clock.fast_forward(1499) + expect(message).to_contain_text("Retrying") + page.clock.fast_forward(1) + expect(message).to_contain_text("access period has ended") + expect(page).to_have_url(paywall_url) + assert len(posts) == 2 + + if __name__ == "__main__": with sync_playwright() as playwright: chromium = ( @@ -217,3 +278,15 @@ if __name__ == "__main__": check_retry_after_expiry(page, url) with browser.new_page() as page: check_retry_backoff(page, url) + for access_left_ms, latency_ms, times_out_once in [ + (25000, 20000, False), + (85000, 45000, True), + ]: + with browser.new_page() as page: + check_slow_post(page, url, access_left_ms, latency_ms, times_out_once) + for access_left_ms, timeout_ms in [(120000, 30000), (5000, 3000)]: + with browser.new_page() as page: + check_stalled_post(page, url, access_left_ms, timeout_ms) + for late_response in (False, True): + with browser.new_page() as page: + check_pending_retry_at_expiry(page, url, late_response)