Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(paywall): read payment terms only from a live same-origin 402, never from the URL

nirholasbc6e1b3e5f03
diff --git a/api/_lib/x402/paywall-handler.js b/api/_lib/x402/paywall-handler.js
index 984d965af..54327e976 100644
--- a/api/_lib/x402/paywall-handler.js
+++ b/api/_lib/x402/paywall-handler.js
@@ -17,8 +17,10 @@
// return;
// }
//
-// The paywall page decodes the requirements from the `?req=` query param and
-// renders a branded payment UI with wallet options.
+// The paywall page re-fetches the live 402 challenge from the same-origin
+// `?return=` path and renders a branded payment UI from THAT response. It never
+// trusts terms carried in the URL: a crafted `?req=` would otherwise show a
+// three.ws-branded page that pays the link author's own address.
/**
* Determine whether the current request should receive the HTML paywall
@@ -45,18 +47,16 @@ export function shouldServePaywall(req) {
/**
* Build the redirect URL for the paywall page.
*
- * Encodes the x402 PaymentRequirements array as base64url in the `?req=`
- * query param so the paywall page can render service name, price, network
- * options, etc. without an additional round-trip.
+ * Only the gated path travels in the URL. The page reads the payment terms
+ * from a fresh same-origin 402 for that path, so `requirements` is not encoded.
*
- * @param {Array<object>} requirements accepts[] from the 402 challenge
+ * @param {Array<object>} _requirements accepts[] from the 402 challenge (unused)
* @param {import('http').IncomingMessage} req
- * @returns {string} Absolute-path URL, e.g. /paywall.html?req=…&return=%2Fapi%2F…
+ * @returns {string} Absolute-path URL, e.g. /paywall.html?return=%2Fapi%2F...
*/
-export function buildPaywallRedirect(requirements, req) {
- const encoded = Buffer.from(JSON.stringify(requirements)).toString('base64url');
+export function buildPaywallRedirect(_requirements, req) {
const returnUrl = encodeURIComponent(req.url || '/');
- return `/paywall.html?req=${encoded}&return=${returnUrl}`;
+ return `/paywall.html?return=${returnUrl}`;
}
/**
diff --git a/public/paywall.js b/public/paywall.js
index 39ec7f85d..5f216ef8e 100644
--- a/public/paywall.js
+++ b/public/paywall.js
@@ -8,30 +8,57 @@
}
/**
- * Decode the base64url-encoded PaymentRequirements from ?req=
- * Handles both base64url (from Buffer.toString('base64url')) and
- * standard base64 (from btoa).
+ * The gated resource this paywall is for, as a same-origin path, or null.
+ * Only a path on this origin is accepted: the payment terms are re-read from
+ * it, so a cross-origin or protocol-relative value would let a link pick
+ * whose 402 the page trusts.
*
- * @returns {Array|null}
+ * @returns {string|null}
*/
- function decodeRequirements() {
- var params = getParams();
- var raw = params.get('req');
- if (!raw) return null;
+ function resourcePath() {
+ var ret = getReturnUrl();
+ if (typeof ret !== 'string' || ret.charAt(0) !== '/' || ret.charAt(1) === '/') return null;
+ if (ret.indexOf('\\') !== -1 || /[\u0000-\u001f]/.test(ret)) return null;
try {
- // Normalise base64url → base64
- var b64 = raw.replace(/-/g, '+').replace(/_/g, '/');
- // Pad to multiple of 4
- while (b64.length % 4 !== 0) b64 += '=';
- var json = decodeURIComponent(escape(atob(b64)));
- var parsed = JSON.parse(json);
- // Accept either a single object (one requirement) or an array
- return Array.isArray(parsed) ? parsed : [parsed];
+ var u = new URL(ret, location.origin);
+ return u.origin === location.origin ? u.pathname + u.search : null;
} catch (e) {
return null;
}
}
+ /**
+ * Fetch the live 402 challenge for the gated resource and return its
+ * `accepts` list. The terms (payTo, amount, asset, network) come ONLY from
+ * this same-origin response. The `?req=` query parameter is never read: a
+ * crafted link could otherwise dress a payment to the link author's own
+ * address in this origin's branding.
+ *
+ * @returns {Promise<Array|null>}
+ */
+ function loadRequirements() {
+ var path = resourcePath();
+ if (!path) return Promise.resolve(null);
+ return fetch(path, { headers: { Accept: 'application/json' }, credentials: 'same-origin' })
+ .then(function (res) {
+ if (res.status !== 402) return null;
+ return res.json().catch(function () { return null; }).then(function (body) {
+ var accepts = body && Array.isArray(body.accepts) ? body.accepts : null;
+ if (!accepts) {
+ try {
+ var hdr = res.headers.get('PAYMENT-REQUIRED');
+ var decoded = hdr ? JSON.parse(atob(hdr)) : null;
+ accepts = decoded && Array.isArray(decoded.accepts) ? decoded.accepts : null;
+ } catch (e) {
+ accepts = null;
+ }
+ }
+ return accepts && accepts.length ? accepts : null;
+ });
+ })
+ .catch(function () { return null; });
+ }
+
// safeNavUrl: inline copy of src/safe-next.js (tests/safe-next.test.js drift-guards it).
function safeNavUrl(raw, fallback = '/') {
if (typeof raw !== 'string' || raw.length === 0) return fallback;
@@ -123,7 +150,7 @@ function safeNavUrl(raw, fallback = '/') {
setEl('service-name', 'Payment Required');
setEl('service-desc', 'This endpoint requires a micropayment.');
setEl('price-amount', '—');
- setEl('raw-json', '(no payment requirements found in URL)');
+ setEl('raw-json', '(no live payment challenge was returned for this resource)');
return;
}
@@ -280,7 +307,14 @@ function safeNavUrl(raw, fallback = '/') {
return;
}
- var resourceUrl = api.resolveResourceUrl(accept, getReturnUrl());
+ // Retry exactly the same-origin resource whose 402 supplied these terms,
+ // never a URL named inside the requirement.
+ var path = resourcePath();
+ if (!path) {
+ setWalletError(statusEl, 'This payment link does not name a three.ws resource.');
+ return;
+ }
+ var resourceUrl = new URL(path, location.origin).href;
paymentInFlight = true;
setButtonsDisabled(true);
@@ -379,8 +413,12 @@ function safeNavUrl(raw, fallback = '/') {
// ── Wire events ────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function () {
- var requirements = decodeRequirements();
- render(requirements);
+ var requirements = null;
+ render(null);
+ loadRequirements().then(function (reqs) {
+ requirements = reqs;
+ render(reqs);
+ });
// Tab clicks
var tabRow = document.getElementById('tab-row');
diff --git a/tests/paywall-terms-source.test.js b/tests/paywall-terms-source.test.js
new file mode 100644
index 000000000..de6d33682
--- /dev/null
+++ b/tests/paywall-terms-source.test.js
@@ -0,0 +1,73 @@
+// @vitest-environment jsdom
+//
+// The full-page paywall takes its payment terms only from a live same-origin 402.
+//
+// It used to decode payTo, amount and resource from the `?req=` query string, so
+// anyone could mail out a three.ws-branded /paywall.html link whose "Pay" button
+// paid the link author's own wallet. The page now re-fetches the challenge from
+// the same-origin `?return=` path and never reads `req`.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SRC = readFileSync(path.join(ROOT, 'public/paywall.js'), 'utf8');
+
+const ATTACKER = 'AttackerWa11et1111111111111111111111111111111';
+const PLATFORM = 'P1atformPayTo1111111111111111111111111111111';
+
+function forgedReq() {
+ const accepts = [{ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', payTo: ATTACKER, amount: '1000000000', asset: 'USDC' }];
+ return Buffer.from(JSON.stringify(accepts)).toString('base64url');
+}
+
+function mountPage(search) {
+ document.body.innerHTML = '<span id="service-name"></span><span id="price-amount"></span><pre id="raw-json"></pre><a id="close-btn"></a><div id="pay-card"></div>';
+ window.history.replaceState({}, '', `/paywall.html${search}`);
+}
+
+async function boot() {
+ // eslint-disable-next-line no-new-func
+ new Function(SRC)();
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await new Promise((r) => setTimeout(r, 0));
+ await new Promise((r) => setTimeout(r, 0));
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('paywall payment terms', () => {
+ it('never reads the ?req= query parameter', () => {
+ expect(SRC).not.toMatch(/get\('req'\)/);
+ });
+
+ it('renders the terms from the same-origin 402, not the forged ?req=', async () => {
+ const fetchMock = vi.fn(async () => new Response(
+ JSON.stringify({ x402Version: 2, accepts: [{ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', payTo: PLATFORM, amount: '10000', asset: 'USDC' }] }),
+ { status: 402, headers: { 'content-type': 'application/json' } },
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ mountPage(`?req=${forgedReq()}&return=%2Fapi%2Fx402%2Fecho`);
+ await boot();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0][0]).toBe('/api/x402/echo');
+ const raw = document.getElementById('raw-json').textContent;
+ expect(raw).toContain(PLATFORM);
+ expect(raw).not.toContain(ATTACKER);
+ });
+
+ it('refuses a cross-origin or protocol-relative return target without fetching it', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ for (const ret of ['https%3A%2F%2Fevil.example%2Fpay', '%2F%2Fevil.example%2Fpay', '%2F%5Cevil.example']) {
+ mountPage(`?req=${forgedReq()}&return=${ret}`);
+ await boot();
+ expect(document.getElementById('raw-json').textContent).not.toContain(ATTACKER);
+ }
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});