paivana

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

paywall.js (15857B)


      1 /*
      2  This file is part of GNU Taler
      3  (C) 2026 Taler Systems S.A.
      4 
      5  GNU Taler is free software; you can redistribute it and/or modify it under the
      6  terms of the GNU Affero General Public License as published by the Free Software
      7  Foundation; either version 3, or (at your option) any later version.
      8 
      9  GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
     10  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13  You should have received a copy of the GNU Affero General Public License along with
     14  GNU Anastasis; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15  */
     16 
     17 // @ts-check
     18 
     19 const website = atob(window.location.hash.substring(1));
     20 const encTable = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
     21 // A new purchase must also be able to cover the requested minimum.
     22 const minAccessSeconds = Math.min(60 * 60, MAX_PICKUP_DELAY);
     23 const openedAt = Math.floor(Date.now() / 1000);
     24 const minExpiration = openedAt + minAccessSeconds;
     25 // Retire the displayed offer after five minutes, or when its minimum passes.
     26 const offerExpiresAt = (openedAt + Math.min(5 * 60, minAccessSeconds)) * 1000;
     27 
     28 // Strip trailing slash so we can append /templateId cleanly.
     29 const merchantBase = MERCHANT_BACKEND.replace(/\/$/, "");
     30 const merchantUrl = new URL(merchantBase);
     31 const merchantProto = merchantUrl.protocol;
     32 const suffix = merchantProto === "http:" ? "+http" : "";
     33 const merchantHost = merchantUrl.host;
     34 const merchantPath = merchantUrl.pathname;
     35 const maxTimerMs = 0x7fffffff; // Largest delay supported by browser timers.
     36 
     37 /**
     38  * @param {ArrayBuffer} data
     39  * @returns {string}
     40  */
     41 function encodeCrock(data) {
     42   const dataBytes = new Uint8Array(data);
     43   let sb = "";
     44   const size = data.byteLength;
     45   let bitBuf = 0;
     46   let numBits = 0;
     47   let pos = 0;
     48   while (pos < size || numBits > 0) {
     49     if (pos < size && numBits < 5) {
     50       const d = dataBytes[pos++];
     51       bitBuf = (bitBuf << 8) | d;
     52       numBits += 8;
     53     }
     54     if (numBits < 5) {
     55       bitBuf = bitBuf << (5 - numBits);
     56       numBits = 5;
     57     }
     58     const v = (bitBuf >>> (numBits - 5)) & 31;
     59     sb += encTable[v];
     60     numBits -= 5;
     61   }
     62   return sb;
     63 }
     64 
     65 /**
     66  * @param {number} sec
     67  * @returns {Uint8Array}
     68  */
     69 function timestampRoundedToBuffer(sec) {
     70   const b = new ArrayBuffer(8);
     71   const v = new DataView(b);
     72   const numVal = BigInt(sec) * 1000n * 1000n;
     73   // The buffer we sign over represents the timestamp in microseconds.
     74   v.setBigUint64(0, numVal);
     75   return new Uint8Array(b);
     76 }
     77 
     78 /**
     79  * @param {number} ms
     80  * @returns {Promise<void>}
     81  */
     82 function waitMs(ms) {
     83   return new Promise((resolve) => setTimeout(resolve, ms));
     84 }
     85 
     86 /**
     87  * Encode @a bytes in the RFC 4648 section 5 URL-safe alphabet, with
     88  * the padding stripped -- the same form the daemon produces with
     89  * GNUNET_STRINGS_base64url_encode(), and the mirror of the decode at
     90  * the top of this file.
     91  *
     92  * Deliberately built out of btoa() rather than the much tidier
     93  * `bytes.toBase64({alphabet: "base64url"})'.  That method is a 2024-25
     94  * addition (Firefox 133, Safari 18.2, Chrome 140), so on anything
     95  * older it is simply not a function -- and this runs on the payment
     96  * path, where the exception would leave a paywall that cannot be paid
     97  * with no indication why.  That is the same failure the decode above
     98  * exists to prevent, and it is not worth reintroducing at the other
     99  * end for the sake of one line.
    100  *
    101  * @param {Uint8Array} bytes
    102  * @returns {string}
    103  */
    104 function base64url(bytes) {
    105   let s = "";
    106 
    107   /* Not String.fromCharCode(...bytes): spreading a large array
    108      overflows the argument limit.  The digests here are 32 bytes, but
    109      the loop costs nothing and does not have to be re-examined if a
    110      caller ever passes something bigger. */
    111   for (const b of bytes) {
    112     s += String.fromCharCode(b);
    113   }
    114   return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
    115 }
    116 
    117 /**
    118  * @param {BufferSource} data
    119  * @returns {Promise<string>}
    120  */
    121 async function sha256b64(data) {
    122   const buf = await crypto.subtle.digest("SHA-256", data);
    123   return base64url(new Uint8Array(buf));
    124 }
    125 
    126 /**
    127  * @param {number} minExpiration
    128  * @param {Uint8Array} nonceBuf
    129  * @param {string} website
    130  * @returns {Promise<string>}
    131  */
    132 async function makePaivanaId(minExpiration, nonceBuf, website) {
    133   const websiteBuf = new TextEncoder().encode(`${website}\0`);
    134   const minExpirationEnc = timestampRoundedToBuffer(minExpiration);
    135 
    136   const length = nonceBuf.length + websiteBuf.length + minExpirationEnc.length;
    137   const buf = new Uint8Array(length);
    138   buf.set(nonceBuf, 0);
    139   buf.set(websiteBuf, nonceBuf.length);
    140   buf.set(minExpirationEnc, nonceBuf.length + websiteBuf.length);
    141   const hash = await sha256b64(buf);
    142   return `${minExpiration}-${hash}`;
    143 }
    144 
    145 /**
    146  * @param {string | null} value Retry-After header from the redemption response
    147  * @returns {number} delay in milliseconds, or zero to use the local backoff
    148  */
    149 function retryAfterMs(value) {
    150   if (!value) return 0;
    151   if (/^\d+$/.test(value)) return Number(value) * 1000;
    152 
    153   // Normalize the two obsolete HTTP-date forms to the one toUTCString emits.
    154   const rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(\w{3})-(\d\d) (\d\d:\d\d:\d\d GMT)$/.exec(value);
    155   const asctime = /^(\w{3}) (\w{3}) ([ \d]\d) (\d\d:\d\d:\d\d) (\d{4})$/.exec(value);
    156   if (rfc850) {
    157     const [, weekday, day, month, shortYear, time] = rfc850;
    158     // A two-digit year can be at most 50 years in the future (RFC 9110).
    159     const limit = new Date();
    160     limit.setUTCFullYear(limit.getUTCFullYear() + 50);
    161     let year = limit.getUTCFullYear();
    162     year -= (year - Number(shortYear)) % 100;
    163     if (Date.parse(`${day} ${month} ${year} ${time}`) > limit.getTime()) year -= 100;
    164     value = `${weekday.slice(0, 3)}, ${day} ${month} ${year} ${time}`;
    165   } else if (asctime) {
    166     const [, weekday, month, day, time, year] = asctime;
    167     value = `${weekday}, ${day.replace(" ", "0")} ${month} ${year} ${time} GMT`;
    168   }
    169   // Date.parse alone accepts malformed headers such as decimal numbers.
    170   const date = new Date(value);
    171   if (!Number.isFinite(date.getTime()) || date.toUTCString() !== value) return 0;
    172   return Math.max(0, date.getTime() - Date.now());
    173 }
    174 
    175 /**
    176  * @param {Response} res failed redemption response
    177  * @returns {Promise<string | null>} message to show, or null to retry
    178  */
    179 async function redemptionError(res) {
    180   if ([408, 429, 502, 503, 504].includes(res.status)) return null;
    181   let detail;
    182   try {
    183     detail = await res.json();
    184   } catch (e) {
    185     // A 500 may carry a retryable code. Try again if the body was cut off.
    186     // For a definitive status, the body only supplies diagnostic detail.
    187     if (res.status === 500 && !(e instanceof SyntaxError)) throw e;
    188   }
    189   // Paivana could not allocate the merchant order lookup for this request.
    190   const PAIVANA_GET_ORDER_FAILED = 9804;
    191   if (res.status === 500 && detail?.code === PAIVANA_GET_ORDER_FAILED) return null;
    192   const message = `${I18N_PAYMENT_CONFIRMED_PROBLEM} (HTTP ${res.status})`;
    193   return detail ? `${message} ${JSON.stringify(detail)}` : message;
    194 }
    195 
    196 /** @param {HTMLElement} linkEl */
    197 function hideOffer(linkEl) {
    198   linkEl.removeAttribute("href");
    199   linkEl.hidden = true;
    200   document.querySelector(".qr-taler-frame")?.remove();
    201   document.querySelector(".qr-legend")?.remove();
    202 }
    203 
    204 /**
    205  * @param {string} order_id
    206  * @param {HTMLElement} linkEl
    207  * @param {HTMLElement} errorEl
    208  * @param {string} nonce
    209  * @returns {Promise<void>}
    210  */
    211 async function confirmPayment(order_id, linkEl, errorEl, nonce) {
    212   hideOffer(linkEl);
    213   errorEl.textContent = I18N_PAYMENT_CONFIRMED_LOADING;
    214   const body = JSON.stringify({
    215     order_id,
    216     nonce,
    217     expiration: { t_s: minExpiration },
    218     website,
    219   });
    220   const expiresAt = Date.now() + REDEMPTION_RETRY_MS;
    221   let backoffMs = 1000;
    222   /** @type {number | undefined} */
    223   let timeoutAfterStallMs;
    224   while (Date.now() < expiresAt) {
    225     let delayMs = backoffMs;
    226     const remainingMs = expiresAt - Date.now();
    227     // Start with 30 seconds. Near expiry, leave one second for a retry
    228     // after backoff if the current attempt can also get at least a second.
    229     const beforeRetryMs = remainingMs - backoffMs - 1000;
    230     const initialMs = Math.min(30000, beforeRetryMs >= 1000 ? beforeRetryMs : remainingMs);
    231     const timeoutMs = Math.min(remainingMs, timeoutAfterStallMs ?? initialMs);
    232     const controller = new AbortController();
    233     const timer = setTimeout(() => controller.abort(), timeoutMs);
    234     try {
    235       const res = await fetch("/.well-known/paivana", {
    236         method: "POST",
    237         headers: { "Content-Type": "application/json" },
    238         redirect: "manual",
    239         body,
    240         signal: controller.signal,
    241       });
    242       const message = res.status >= 400 ? await redemptionError(res) : null;
    243       // A successful manual redirect is opaque and has status zero.
    244       if (res.status < 400) {
    245         location.href = res.redirected ? res.url : website;
    246         return;
    247       }
    248       if (message) {
    249         errorEl.textContent = message;
    250         return;
    251       }
    252       delayMs = Math.max(delayMs, retryAfterMs(res.headers.get("Retry-After")));
    253     } catch (e) {
    254       if (Date.now() >= expiresAt) break;
    255       // A timeout may mean the connection is slow. Give the next POST longer.
    256       if (controller.signal.aborted) {
    257         timeoutAfterStallMs = Math.min(timeoutMs * 2, maxTimerMs);
    258       }
    259       console.warn("[paivana] Error trying to confirm payment:", e);
    260     } finally {
    261       clearTimeout(timer);
    262     }
    263     if (errorEl.textContent !== I18N_PAYMENT_CONFIRMED_RETRYING) {
    264       errorEl.textContent = I18N_PAYMENT_CONFIRMED_RETRYING;
    265     }
    266     const wakeAt = Math.min(expiresAt, Date.now() + delayMs);
    267     while (Date.now() < wakeAt) {
    268       await waitMs(Math.min(wakeAt - Date.now(), maxTimerMs));
    269     }
    270     backoffMs = Math.min(backoffMs * 2, 30000);
    271   }
    272   errorEl.textContent = I18N_REDEMPTION_TIMEOUT;
    273   const retry = document.getElementById("retry-redemption");
    274   if (retry) {
    275     retry.hidden = false;
    276     retry.addEventListener("click", () => {
    277       retry.hidden = true;
    278       void confirmPayment(order_id, linkEl, errorEl, nonce);
    279     }, { once: true });
    280   }
    281 }
    282 
    283 /**
    284  * @param {string} text
    285  * @returns {Element}
    286  */
    287 function qrSvg(text) {
    288   // Byte mode in UTF-8, which wallets read; the library's default keeps
    289   // only the low byte of each UTF-16 code unit.
    290   qrcode.stringToBytes = qrcode.stringToBytesFuncs["UTF-8"];
    291   const qr = qrcode(0, "M");
    292   qr.addData(text, "Byte");
    293   qr.make();
    294   // The frame supplies the white margin around the code.
    295   const svg = new DOMParser().parseFromString(
    296     qr.createSvgTag({ cellSize: 1, margin: 0, scalable: true }),
    297     "image/svg+xml",
    298   ).documentElement;
    299   svg.setAttribute("width", String(QR_WIDTH));
    300   svg.setAttribute("height", String(QR_HEIGHT));
    301   svg.setAttribute("shape-rendering", "crispEdges");
    302   return svg;
    303 }
    304 
    305 /**
    306  * @param {HTMLElement} el
    307  * @returns {void}
    308  */
    309 function toggleDescription(el) {
    310   for (const a of el.getElementsByClassName("arrow")) {
    311     a.classList.toggle("upside-down");
    312   }
    313   for (const a of el.getElementsByClassName("price-list")) {
    314     a.classList.toggle("hidden");
    315   }
    316 }
    317 
    318 async function main() {
    319   const nonceBuf = new Uint8Array(16);
    320   crypto.getRandomValues(nonceBuf);
    321   const nonce = encodeCrock(nonceBuf.buffer);
    322 
    323   const paivanaId = await makePaivanaId(minExpiration, nonceBuf, website);
    324 
    325   // finally we can compute the talerURI and polling URL
    326   const TALER_URI = [
    327     `taler${suffix}://pay-template/`,
    328     merchantHost,
    329     merchantPath,
    330     `/`,
    331     MERCHANT_TEMPLATE_ID,
    332     `?session_id=${encodeURIComponent(paivanaId)}`,
    333     `&fulfillment_url=${encodeURIComponent(website)}`,
    334   ].join("");
    335 
    336   const PAIVANA_POLL_URL = [
    337     merchantBase,
    338     "/sessions/",
    339     encodeURIComponent(paivanaId),
    340     "?fulfillment_url=",
    341     encodeURIComponent(website),
    342     "&timeout_ms=",
    343     POLL_WAIT_MS,
    344   ].join("");
    345 
    346   const talerLink = document.querySelector("#taler-link");
    347   const renew = document.querySelector("#renew-offer");
    348   const status = document.getElementById("error-message");
    349   const qrDiv = document.getElementById("qrcode");
    350   if (
    351     !(talerLink instanceof HTMLAnchorElement) ||
    352     !(renew instanceof HTMLAnchorElement) || !status || !qrDiv
    353   ) return;
    354 
    355   const expiresAt = offerExpiresAt;
    356   const deadline = document.querySelector("#offer-deadline time");
    357   if (deadline instanceof HTMLTimeElement && deadline.parentElement && minAccessSeconds > 0) {
    358     const date = new Date(expiresAt);
    359     deadline.dateTime = date.toISOString();
    360     deadline.textContent = date.toLocaleString();
    361     deadline.parentElement.hidden = false;
    362   }
    363 
    364   // The protected URL comes from the fragment. Only link back to this proxy.
    365   const target = new URL(website, location.href);
    366   if (target.origin === location.origin && ["https:", "http:"].includes(target.protocol)) {
    367     renew.href = target.href;
    368   }
    369   let expired = false;
    370   let pendingOrder = false;
    371   /** @type {number | undefined} */
    372   let timer;
    373 
    374   const checkExpiry = () => {
    375     if (!expired && Date.now() < expiresAt) return false;
    376     expired = true;
    377     hideOffer(talerLink);
    378     document.querySelector(".steps")?.remove();
    379     document.getElementById("access-on-payment")?.remove();
    380     let message = minAccessSeconds === 0 ? I18N_ACCESS_UNAVAILABLE : I18N_OFFER_EXPIRED;
    381     if (pendingOrder) message += " " + I18N_PENDING_ORDER;
    382     if (status.textContent !== message) status.textContent = message;
    383     renew.hidden = minAccessSeconds === 0 || !renew.hasAttribute("href");
    384     return true;
    385   };
    386 
    387   function watchExpiry() {
    388     clearTimeout(timer);
    389     if (checkExpiry()) return false;
    390     timer = setTimeout(watchExpiry, Math.min(expiresAt - Date.now(), maxTimerMs));
    391     return true;
    392   }
    393 
    394   if (!watchExpiry()) return;
    395   window.addEventListener("pageshow", watchExpiry);
    396   document.addEventListener("visibilitychange", watchExpiry);
    397   talerLink.addEventListener("click", (event) => {
    398     if (checkExpiry()) event.preventDefault();
    399   });
    400   talerLink.href = TALER_URI;
    401   talerLink.hidden = false;
    402 
    403   qrDiv.replaceChildren(qrSvg(TALER_URI));
    404   qrDiv.title = TALER_URI;
    405 
    406   // An outstanding poll can still report a payment after the controls expire.
    407   try {
    408     while (!checkExpiry()) {
    409       const start = performance.now();
    410       try {
    411         const res = await fetch(PAIVANA_POLL_URL, { cache: "no-store" });
    412         if (res.status === 202) pendingOrder = true;
    413         if (res.status === 200) {
    414           let info;
    415           try {
    416             info = await res.json();
    417           } catch (_) {}
    418           if (info?.order_id) {
    419             renew.hidden = true;
    420             return confirmPayment(info.order_id, talerLink, status, nonce);
    421           }
    422           if (checkExpiry()) return;
    423           talerLink.textContent = I18N_PAYMENT_CONFIRMED_NO_ORDER;
    424           await waitMs(Math.max(0, POLL_WAIT_MS - (performance.now() - start)));
    425           if (!checkExpiry()) location.href = website;
    426           return;
    427         }
    428         if (checkExpiry()) return;
    429         if (res.status !== 202 && res.status !== 404) {
    430           throw new Error(`Unexpected session status response: HTTP ${res.status}`);
    431         }
    432         status.textContent = "";
    433       } catch (e) {
    434         if (checkExpiry()) return;
    435         console.warn("[paivana] poll error:", e);
    436         if (status.textContent !== I18N_PAYMENT_STATUS_ERROR) {
    437           status.textContent = I18N_PAYMENT_STATUS_ERROR;
    438         }
    439       }
    440       const remaining = Math.min(
    441         expiresAt - Date.now(),
    442         POLL_WAIT_MS - (performance.now() - start),
    443       );
    444       if (remaining > 0) await waitMs(remaining);
    445     }
    446   } finally {
    447     clearTimeout(timer);
    448     window.removeEventListener("pageshow", watchExpiry);
    449     document.removeEventListener("visibilitychange", watchExpiry);
    450   }
    451 }