A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.

9 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-browser.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-browser.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-browser.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 toolbar: Back and Forward are greyed out when there's nowhere to go cc08c7a 1 week, 2 days ago History
transport.mjs · 10.5 KB · 126 lines
1// The network layer: redirects reach the page, cookies round-trip, x402 behind a redirect, gzip, headers.
2export default async function (ctx) {
3 const { call: T, check, base, sleep } = ctx;
4 const port = new URL(base).port;
5 const loc = async () => (await T("page.eval", { js: "location.href" })).value;
6 const tab0 = async () => (await T("tabs.list")).find((t) => t.active);
7
8 // redirect chain (301 → 302 → 200): the page and the tab agree on the FINAL url
9 await T("page.goto", { url: base + "/redir/chain" });
10 check((await loc()) === base + "/free" && (await tab0()).url === base + "/free", "redirect chain: location.href AND the tab URL are the final URL", await loc());
11 check(/free/i.test((await T("page.text")).text), "…and the page shows the destination's content");
12
13 // cross-origin redirect: the page's origin must become the DESTINATION's (the security-critical one)
14 await T("page.goto", { url: base + "/redir/cross" });
15 const origin = (await T("page.eval", { js: "location.origin" })).value;
16 check(origin === `http://localhost:${port}`, "cross-origin redirect: the page's origin is the destination's", origin);
17
18 // POST → 302 with Set-Cookie → the cookie round-trips through our transport
19 await T("page.goto", { url: base + "/login" });
20 await T("page.type", { selector: "input[name=username]", text: "demo" });
21 await T("page.type", { selector: "input[name=password]", text: "demo-pass" });
22 await T("page.click", { selector: "button[type=submit]" });
23 await T("page.waitFor", { text: "Welcome, demo", timeoutMs: 8000 });
24 check(new URL(await loc()).pathname === "/account", "POST /login → 302: the address is /account (it used to stay on /login)", await loc());
25 check(/cookie: yes/.test((await T("page.text")).text), "Set-Cookie on the 302 was stored and sent on the next request");
26
27 // A form posted on one site that answers with a redirect to another (an OAuth "Authorize" button): the other site gets the
28 // request WITH its cookies. Before, every request to another origin went without cookies and this one failed outright
29 // (ERR_INVALID_ARGUMENT). Here 127.0.0.1 is the provider and a second server on localhost is the app it sends you back to.
30 const { createServer } = await import("node:http");
31 const seen = [];
32 const app = createServer((req, res) => {
33 seen.push(req.headers.cookie || "");
34 if (req.url === "/set") res.writeHead(200, { "content-type": "text/html", "set-cookie": "app_session=s1; Path=/; SameSite=Lax" }).end("<title>app</title>set");
35 else res.writeHead(200, { "content-type": "text/html" }).end(`<title>back</title><p>back with cookie: ${/app_session=s1/.test(req.headers.cookie || "") ? "yes" : "no"}</p>`);
36 });
37 const provider = createServer((req, res) => {
38 if (req.method === "POST") { req.resume(); req.on("end", () => res.writeHead(302, { location: `${appBase}/callback?code=c1&state=s1` }).end()); return; }
39 res.writeHead(200, { "content-type": "text/html" }).end(`<title>consent</title><form method="post" action="/authorize"><input name="state" value="s1"><button type="submit">Authorize</button></form>`);
40 });
41 await new Promise((r) => app.listen(0, "127.0.0.1", r));
42 await new Promise((r) => provider.listen(0, "127.0.0.1", r));
43 const appBase = `http://localhost:${app.address().port}`;
44 try {
45 await T("page.goto", { url: appBase + "/set" });
46 await T("page.goto", { url: `http://127.0.0.1:${provider.address().port}/consent` });
47 await T("page.click", { selector: "button[type=submit]" });
48 await T("page.waitFor", { text: "back with cookie", timeoutMs: 8000 }).catch(() => {});
49 check(new URL(await loc()).origin === appBase, "a form post answered by a redirect to another site lands there (an OAuth Authorize button)", await loc());
50 check(/back with cookie: yes/.test((await T("page.text")).text), "and that site gets its own cookies on the way back", seen.join(" | "));
51 } finally {
52 app.close();
53 provider.close();
54 }
55
56 // a redirect INTO a 402: paid once, at the destination
57 const e0 = (await T("x402.events", { since: 0 })).next;
58 await T("page.goto", { url: base + "/redir/paid" });
59 const paid = (await T("x402.events", { since: e0 })).events.filter((e) => e.kind === "paid");
60 check(paid.length === 1 && paid[0].resource.endsWith("/room"), "redirect into a 402: exactly one payment, for the destination", paid.map((p) => p.resource + " " + p.amount).join(","));
61 check(new URL(await loc()).pathname === "/room", "…and the address is /room");
62
63 // gzip: decoded exactly once
64 await T("page.goto", { url: base + "/gz" });
65 check(/gzip body decoded ok/.test((await T("page.text")).text), "a gzip Content-Encoding body renders (decoded once, not twice)");
66
67 // back() after redirects
68 await T("page.goto", { url: base + "/free" });
69 await T("page.back");
70 check(new URL(await loc()).pathname !== "/free", "back() works after redirects", await loc());
71
72 // identity: the UA, client hints and fetch metadata a real Chromium navigation sends
73 await T("page.goto", { url: base + "/headers" });
74 const h = JSON.parse((await T("page.text")).text);
75 check(/dbbasic-browser\/\S+ \(\+https:\/\/dbbasic\.com\)$/.test(h["user-agent"]) && !/Electron/.test(h["user-agent"]), "User-Agent: no Electron token, ends with our product token and dbbasic.com", h["user-agent"].slice(-60));
76 check(h["sec-fetch-mode"] === "navigate" && h["sec-fetch-dest"] === "document" && h["sec-fetch-user"] === "?1", "navigation carries navigate / document / ?1");
77 check(!!h["sec-ch-ua"] && !!h["sec-ch-ua-platform"] && h["sec-ch-ua-mobile"] === "?0", "client hints are present");
78 const jsBrands = (await T("page.eval", { js: "navigator.userAgentData.brands.map(b => b.brand).sort().join('|')" })).value;
79 check(jsBrands === [...h["sec-ch-ua"].matchAll(/"([^"]+)";v=/g)].map((m) => m[1]).sort().join("|"), "HTTP client hints match navigator.userAgentData (no contradiction for servers to detect)", jsBrands);
80 check(!h["x-raw-sec-lines"].some((l, i, a) => a.findIndex((m) => m.split(":")[0].toLowerCase() === l.split(":")[0].toLowerCase()) !== i), "no duplicated sec-* header lines");
81 const sub = (await T("page.eval", { js: "fetch('/headers?x=1').then(r => r.json()).then(d => d['referer'])" })).value;
82 check(typeof sub === "string" && sub.startsWith(base + "/headers"), "a same-origin subrequest carries the Referer (it was missing before)", sub);
83
84 // WebSockets bypass our network layer (Chromium opens them itself); a policy can refuse them BEFORE any connection.
85 const upgrades = async () => (await (await fetch(base + "/ws-count")).json()).upgrades;
86 const wsTitle = async () => { await T("page.waitFor", { text: "WebSocket test", timeoutMs: 5000 }); await new Promise((r) => setTimeout(r, 800)); return (await T("tabs.list")).find((t) => t.active).title; };
87 check((await T("net.policy")).blockWebSockets === false, "WebSockets are allowed by default");
88 const before = await upgrades();
89 await T("page.goto", { url: base + "/ws-page" });
90 check((await wsTitle()) === "ws:open" && (await upgrades()) === before + 1, "by default a page's WebSocket opens (the handshake reaches the server)");
91 await T("net.policy", { blockWebSockets: true });
92 const wsEvents0 = (await T("x402.events", { since: 0 })).next;
93 const mid = await upgrades();
94 await T("page.goto", { url: base + "/ws-page" });
95 check((await wsTitle()) === "ws:error", "with the policy on, the page's WebSocket fails");
96 check((await upgrades()) === mid, "…and NO handshake ever reached the server (refused before any connection was opened)");
97 check((await T("x402.events", { since: wsEvents0 })).events.some((e) => e.kind === "websocket-refused"), "…and the refusal is announced as an event (never silent)");
98 check((await T("page.eval", { js: "fetch('/free').then(r => r.status)" })).value === 200, "ordinary requests are unaffected by the policy");
99 await T("net.policy", { blockWebSockets: false });
100 await T("page.goto", { url: base + "/ws-page" });
101 check((await wsTitle()) === "ws:open", "turning the policy off allows WebSockets again");
102 await T("net.policy", { blockWebSockets: "yes" }).then(() => check(false, "a non-boolean policy value was accepted"), (e) => check(e.code === "bad-params", "a non-boolean policy value is rejected"));
103
104 // One goto is ONE request to the site, including when the tab is already on that address (it used to load twice).
105 const hits = async () => (await (await fetch(base + "/hits")).json()).hits;
106 await T("page.goto", { url: base + "/free" });
107 let h0 = await hits();
108 await T("page.goto", { url: base + "/free" });
109 await sleep(500);
110 check((await hits()) - h0 === 1, "going to the address a tab is already on makes ONE request to the server (it used to make two)", `${(await hits()) - h0} request(s)`);
111 h0 = await hits();
112 await T("page.goto", { url: base + "/free?other=1" });
113 await sleep(500);
114 check((await hits()) - h0 === 1, "going to a different address makes one request");
115
116 // Scripts, styles and fonts that a page loads from another site in CORS mode (<script crossorigin>, the way CDNs are used), with and
117 // without an integrity hash, plus a plain one and one through a redirect. These used to fail (ERR_FAILED): the browser always asked for
118 // cookies, and a response that says "any site may read this" is refused when the request carried them.
119 const cdn = await T("page.goto", { url: base + "/cdn-page", settle: { timeoutMs: 10000, frames: false } });
120 const loaded = (await T("page.eval", { js: "JSON.stringify({ redirected: window.redirected, loaded: [...new Set(window.loaded || [])].sort(), bg: getComputedStyle(document.body).backgroundColor, font: window.fontFetch })" })).value;
121 const lj = JSON.parse(loaded);
122 check(cdn.settle.resources.failed === 0 && cdn.settle.resources.requested >= 8, "every cross-origin script, style and fetch on a CDN-style page loads (none fail)", JSON.stringify(cdn.settle.resources.failedExamples ?? []));
123 check(JSON.stringify(lj.loaded) === JSON.stringify(["cors-script", "integrity-script", "plain-script", "redirected-script"]) && lj.redirected === 5, "the CORS-mode scripts, the one with an integrity hash, the plain one, and all five redirected ones (301, 302, 307, 308, with and without crossorigin) run", loaded);
124 check(cdn.settle.console.counts.error === 0, "and the page logs no errors (a redirect that says text/plain with nosniff, as unpkg's does, no longer makes the browser refuse the script it points to)", JSON.stringify(cdn.settle.console.errors.map((e) => e.text.slice(0, 80))));
125 check(lj.bg === "rgb(1, 2, 3)" && lj.font === 17, "the cross-origin stylesheet is applied and a cross-origin fetch succeeds", loaded);
126}