paivana

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

commit fc04af4c75f406ef23b48e8054aa5a15762076aa
parent 6bee010952d01e55ae24368af4d31c91b91c4c13
Author: Florian Dold <dold@taler.net>
Date:   Thu, 19 Nov 2026 19:15:03 +0100

paywall: request a minimum access period and retire idle offers locally

Diffstat:
Msrc/frontend/global.d.ts | 3++-
Msrc/frontend/paywall.en.must.j2 | 8++++----
Msrc/frontend/paywall.js | 50+++++++++++++++++++++++++++++---------------------
Msrc/tests/test_paywall_poll.py | 84++++++++++++++++++++++++++++++++++++++++++-------------------------------------
4 files changed, 80 insertions(+), 65 deletions(-)

diff --git a/src/frontend/global.d.ts b/src/frontend/global.d.ts @@ -19,7 +19,7 @@ declare const QR_HEIGHT: number; declare const I18N_PAYMENT_CONFIRMED_LOADING: string; declare const I18N_PAYMENT_CONFIRMED_PROBLEM: string; declare const I18N_PAYMENT_CONFIRMED_RETRYING: string; -declare const I18N_PAYMENT_CONFIRMED_EXPIRED: string; +declare const I18N_REDEMPTION_TIMEOUT: string; declare const I18N_PAYMENT_CONFIRMED_NO_ORDER: string; declare const I18N_OFFER_EXPIRED: string; declare const I18N_PENDING_ORDER: string; @@ -31,6 +31,7 @@ declare const MAX_PICKUP_DELAY: number; declare const TEMPLATE_SUMMARY: string; declare const TEMPLATE_CHOICES: string; declare const POLL_WAIT_MS: number; +declare const REDEMPTION_RETRY_MS: number; declare class QRCode { constructor(el: HTMLElement | null, options: { diff --git a/src/frontend/paywall.en.must.j2 b/src/frontend/paywall.en.must.j2 @@ -12,7 +12,7 @@ const I18N_PAYMENT_CONFIRMED_LOADING = 'Payment confirmed! Loading page...'; 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_REDEMPTION_TIMEOUT = 'Payment confirmed. We couldn’t unlock this page yet. Try again using your existing payment.'; 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.'; @@ -29,6 +29,7 @@ // const TEMPLATE_SUMMARY = '{{ summary }}'; // const TEMPLATE_CHOICES = '{{{ choices }}}'; const POLL_WAIT_MS = 30000; + const REDEMPTION_RETRY_MS = 300000; </script> <script> @< include 'paywall.js' >@ @@ -395,9 +396,7 @@ 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}} + <p id="offer-deadline" hidden>Offer expires <time></time></p> <div class="qr-taler-frame"> <div style="padding: 10px; border-radius: 20px; background-color: white"> <div class="qr-frame" id="qrcode" style="margin: 5px" > @@ -483,6 +482,7 @@ var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this <p id="error-message" role="status"></p> <div class="button-cta"> <a target="_blank" id="taler-link" hidden class="cta">Pay now</a> + <button id="retry-redemption" type="button" hidden class="cta">Retry access</button> <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 @@ -18,8 +18,12 @@ const website = atob(window.location.hash.substring(1)); const encTable = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; -// cap at 100 years, we don't deal well with 'forever' otherwise -const usePickupDelay = Math.min(MAX_PICKUP_DELAY, 60 * 60 * 24 * 365 * 100); +// A new purchase must also be able to cover the requested minimum. +const minAccessSeconds = Math.min(60 * 60, MAX_PICKUP_DELAY); +const openedAt = Math.floor(Date.now() / 1000); +const minExpiration = openedAt + minAccessSeconds; +// Retire the displayed offer after five minutes, or when its minimum passes. +const offerExpiresAt = (openedAt + Math.min(5 * 60, minAccessSeconds)) * 1000; // Strip trailing slash so we can append /templateId cleanly. const merchantBase = MERCHANT_BACKEND.replace(/\/$/, ""); @@ -29,7 +33,6 @@ 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; /** * @param {ArrayBuffer} data @@ -121,22 +124,22 @@ async function sha256b64(data) { } /** - * @param {number} curTime + * @param {number} minExpiration * @param {Uint8Array} nonceBuf * @param {string} website * @returns {Promise<string>} */ -async function makePaivanaId(curTime, nonceBuf, website) { +async function makePaivanaId(minExpiration, nonceBuf, website) { const websiteBuf = new TextEncoder().encode(`${website}\0`); - const curTimeBuf = timestampRoundedToBuffer(curTime); + const minExpirationEnc = timestampRoundedToBuffer(minExpiration); - const length = nonceBuf.length + websiteBuf.length + curTimeBuf.length; + const length = nonceBuf.length + websiteBuf.length + minExpirationEnc.length; const buf = new Uint8Array(length); buf.set(nonceBuf, 0); buf.set(websiteBuf, nonceBuf.length); - buf.set(curTimeBuf, nonceBuf.length + websiteBuf.length); + buf.set(minExpirationEnc, nonceBuf.length + websiteBuf.length); const hash = await sha256b64(buf); - return `${curTime}-${hash}`; + return `${minExpiration}-${hash}`; } /** @@ -211,10 +214,10 @@ async function confirmPayment(order_id, linkEl, errorEl, nonce) { const body = JSON.stringify({ order_id, nonce, - expiration: { t_s: expTime }, + expiration: { t_s: minExpiration }, website, }); - const expiresAt = expTime * 1000; + const expiresAt = Date.now() + REDEMPTION_RETRY_MS; let backoffMs = 1000; /** @type {number | undefined} */ let timeoutAfterStallMs; @@ -237,8 +240,6 @@ async function confirmPayment(order_id, linkEl, errorEl, nonce) { 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; @@ -268,7 +269,15 @@ async function confirmPayment(order_id, linkEl, errorEl, nonce) { } backoffMs = Math.min(backoffMs * 2, 30000); } - errorEl.textContent = I18N_PAYMENT_CONFIRMED_EXPIRED; + errorEl.textContent = I18N_REDEMPTION_TIMEOUT; + const retry = document.getElementById("retry-redemption"); + if (retry) { + retry.hidden = false; + retry.addEventListener("click", () => { + retry.hidden = true; + void confirmPayment(order_id, linkEl, errorEl, nonce); + }, { once: true }); + } } /** @@ -289,7 +298,7 @@ async function main() { crypto.getRandomValues(nonceBuf); const nonce = encodeCrock(nonceBuf.buffer); - const paivanaId = await makePaivanaId(expTime, nonceBuf, website); + const paivanaId = await makePaivanaId(minExpiration, nonceBuf, website); // finally we can compute the talerURI and polling URL const TALER_URI = [ @@ -321,9 +330,9 @@ async function main() { !(renew instanceof HTMLAnchorElement) || !status || !qrDiv ) return; - const expiresAt = expTime * 1000; - const deadline = document.querySelector("#access-deadline time"); - if (deadline instanceof HTMLTimeElement && deadline.parentElement && usePickupDelay > 0) { + const expiresAt = offerExpiresAt; + const deadline = document.querySelector("#offer-deadline time"); + if (deadline instanceof HTMLTimeElement && deadline.parentElement && minAccessSeconds > 0) { const date = new Date(expiresAt); deadline.dateTime = date.toISOString(); deadline.textContent = date.toLocaleString(); @@ -346,10 +355,10 @@ async function main() { hideOffer(talerLink); document.querySelector(".steps")?.remove(); document.getElementById("access-on-payment")?.remove(); - let message = usePickupDelay === 0 ? I18N_ACCESS_UNAVAILABLE : I18N_OFFER_EXPIRED; + let message = minAccessSeconds === 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"); + renew.hidden = minAccessSeconds === 0 || !renew.hasAttribute("href"); return true; }; @@ -391,7 +400,6 @@ async function main() { } 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); } if (checkExpiry()) return; diff --git a/src/tests/test_paywall_poll.py b/src/tests/test_paywall_poll.py @@ -5,7 +5,7 @@ import re import shutil import sys from pathlib import Path -from urllib.parse import urljoin +from urllib.parse import parse_qs, urljoin, urlsplit try: from playwright.sync_api import expect, sync_playwright @@ -76,17 +76,18 @@ 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. +def open_timed_offer(page, url, seconds, poll, retry_ms=None): 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 + body = template.text() + for name, value in [("MAX_PICKUP_DELAY", seconds), ("REDEMPTION_RETRY_MS", retry_ms)]: + if value is not None: + body, count = re.subn(rf"const {name} = [0-9]+;", f"const {name} = {value};", body) + assert count == 1 page.route(document_url, lambda route: route.fulfill( status=402, content_type="text/html", body=body)) page.route("**/sessions/**", poll) @@ -108,11 +109,14 @@ def check_idle_offer(page, url, late_status, wake): route.fulfill(status=202, json={"order_id": "pending"}) # Leave the third poll outstanding until after expiry. - open_timed_offer(page, url, 300, poll) + open_timed_offer(page, url, 7200, poll) + page.route(REDEMPTION, lambda route: grant_access(route, url)) 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") + session_id = parse_qs(urlsplit(uri).query)["session_id"][0] + assert int(session_id.split("-", 1)[0]) == page.evaluate("Date.now() / 1000") + 3600 + deadline = page.locator("#offer-deadline time") expect(deadline).to_be_visible() expect(deadline).to_have_attribute("datetime", "2030-01-01T00:06:00.000Z") for _ in range(2): @@ -134,13 +138,16 @@ def check_idle_offer(page, url, late_status, wake): expect(page.locator("#qrcode")).to_be_hidden() expect(pay).to_be_hidden() expect(renew).to_have_attribute("href", url) + if late_status == 200: + page.route(url, serve_article) 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() + expect(page.locator("body")).to_have_text("Paid article") + assert len(posts) == 1 + assert posts[0].post_data_json["expiration"]["t_s"] == int(session_id.split("-", 1)[0]) else: page.clock.fast_forward(60000) expect(msg).to_contain_text("This offer has expired.") @@ -149,7 +156,7 @@ def check_idle_offer(page, url, late_status, wake): renew.click() expect(pay).to_be_visible() assert pay.get_attribute("href") != uri - assert not posts + assert not posts def check_duration_limits(page, url, seconds): @@ -162,16 +169,17 @@ def check_duration_limits(page, url, seconds): 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)) + session_id = parse_qs(urlsplit(pay.get_attribute("href")).query)["session_id"][0] + start = page.evaluate("Date.now() / 1000") + assert int(session_id.split("-", 1)[0]) == start + min(seconds, 3600) + page.clock.fast_forward(min(seconds, 300) * 1000) 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): +def open_paid_paywall(page, url, *responses, retry_ms=None): """Grant access after the scripted responses, checking every POST.""" polls = [] posts = [] @@ -179,9 +187,6 @@ def open_paid_paywall(page, url, *responses, access_left_ms=None): 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): @@ -198,12 +203,9 @@ def open_paid_paywall(page, url, *responses, access_left_ms=None): assert attempt == len(responses) 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) + open_timed_offer(page, url, None, paid, retry_ms=retry_ms) page.route(url, serve_article) return posts @@ -225,7 +227,7 @@ 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()")) + page.clock.fast_forward(page.evaluate("REDEMPTION_RETRY_MS")) expect(message).to_contain_text(f"HTTP {status}") assert len(posts) == 1 @@ -236,11 +238,13 @@ def check_retry_after_expiry(page, url): 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")) + page.clock.fast_forward(page.evaluate("REDEMPTION_RETRY_MS - 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 + expect(message).to_contain_text("Try again using your existing payment.") + page.get_by_role("button", name="Retry access").click() + expect(page.locator("body")).to_have_text("Paid article") + assert len(posts) == 2 def check_retry_after_dates(page): @@ -283,8 +287,8 @@ 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) +def check_stalled_post(page, url, retry_ms, timeout_ms): + posts = open_paid_paywall(page, url, lambda route: None, retry_ms=retry_ms) message = page.get_by_role("status") expect(message).to_contain_text("Loading") page.clock.fast_forward(timeout_ms - 1) @@ -298,10 +302,10 @@ def check_stalled_post(page, url, access_left_ms, timeout_ms): assert len(posts) == 2 -def check_slow_post(page, url, access_left_ms, latency_ms, times_out_once): +def check_slow_post(page, url, retry_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) + posts = open_paid_paywall(page, url, *responses, retry_ms=retry_ms) if times_out_once: page.clock.fast_forward(30000) expect(page.get_by_role("status")).to_contain_text("Retrying") @@ -319,12 +323,12 @@ 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()")) + page.clock.set_system_time(page.evaluate("new Date(Date.now() + REDEMPTION_RETRY_MS).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) + last_attempt, retry_ms=2500) paywall_url = page.url message = page.get_by_role("status") expect(message).to_contain_text("Retrying") @@ -334,8 +338,10 @@ def check_pending_retry_at_expiry(page, url, 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) + expect(page.get_by_role("button", name="Retry access")).to_be_visible() + expect(page).to_have_url(paywall_url) + else: + expect(page.locator("body")).to_have_text("Paid article") assert len(posts) == 2 @@ -359,7 +365,7 @@ if __name__ == "__main__": 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]: + for seconds in [0, 120, 30 * 86400]: with browser.new_page() as page: check_duration_limits(page, url, seconds) for first_response, delay_ms in [ @@ -381,15 +387,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 [ + for retry_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)]: + check_slow_post(page, url, retry_ms, latency_ms, times_out_once) + for retry_ms, timeout_ms in [(120000, 30000), (5000, 3000)]: with browser.new_page() as page: - check_stalled_post(page, url, access_left_ms, timeout_ms) + check_stalled_post(page, url, retry_ms, timeout_ms) for late_response in (False, True): with browser.new_page() as page: check_pending_retry_at_expiry(page, url, late_response)