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
compat.ts · 12.5 KB · 262 lines
1/**
2 * How the browser presents itself to web servers — kept Electron-free so it is unit-tested.
3 *
4 * Two jobs:
5 *
6 * 1. `brandedUserAgent`: a Chromium-compatible User-Agent that says honestly who we are.
7 * Electron's default UA carries an `Electron/x.y.z` token (which many WAFs treat as
8 * "embedded automation, not a browser") and an app token showing ELECTRON's version
9 * rather than ours. We drop both and append our own product token with a link to
10 * dbbasic.com — the same convention Edge ("Edg/…"), Opera ("OPR/…") and Vivaldi use.
11 * We do NOT claim to be Firefox or Chrome: the engine is Chromium, and a UA that
12 * contradicts the client hints, the JS APIs and the TLS fingerprint is worse for
13 * compatibility than an honest Chromium-based UA, besides being untrue.
14 *
15 * 2. `chromiumRequestHeaders`: our transport (src/transport.ts) builds requests with
16 * net.request, which does not add what Chromium's own loader would: client hints
17 * (`sec-ch-ua*`) and correct fetch metadata (`sec-fetch-*`). A server that compares the
18 * HTTP headers with what the page's own JS reports (`navigator.userAgentData`) sees a
19 * contradiction — the classic "this is not a real browser" tell — and may refuse the
20 * page. This restores what a real Chromium navigation sends.
21 */
22
23export interface Product {
24 name: string;
25 version: string;
26 url: string;
27}
28
29/** `Chrome/130.0.6723.191` → 130, or null. */
30export function chromeMajor(ua: string): number | null {
31 const m = /\bChrome\/(\d+)\./.exec(ua);
32 return m ? Number(m[1]) : null;
33}
34
35const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36
37/**
38 * Electron's UA minus its `Electron/x` token and its app-name token, plus
39 * `<name>/<version> (+<url>)` at the end.
40 */
41export function brandedUserAgent(baseUA: string, product: Product): string {
42 const cleaned = baseUA
43 .replace(/\s+Electron\/\S+/g, "")
44 .replace(new RegExp(`\\s+${escapeRe(product.name)}\\/\\S+`, "g"), "")
45 .replace(new RegExp(`\\s*\\(\\+${escapeRe(product.url)}\\)`, "g"), "") // our own earlier link
46 .trim();
47 return `${cleaned} ${product.name}/${product.version} (+${product.url})`;
48}
49
50/** What the engine itself reports in `navigator.userAgentData` — the source of truth for client hints. */
51export interface Hints {
52 brands: Array<{ brand: string; version: string }>;
53 platform: string;
54 mobile: boolean;
55}
56
57const sfv = (s: string) => `"${s.replace(/["\\]/g, "\\$&")}"`;
58
59export function secChUa(h: Hints): string {
60 return h.brands.map((b) => `${sfv(b.brand)};v=${sfv(b.version)}`).join(", ");
61}
62
63/** Chrome only sends client hints / fetch metadata to potentially trustworthy origins. */
64export function isTrustworthy(url: URL): boolean {
65 if (url.protocol === "https:") return true;
66 return url.protocol === "http:" && (url.hostname === "localhost" || /^127(\.\d+){3}$/.test(url.hostname) || url.hostname === "[::1]");
67}
68
69const registrableish = (h: string) => h.split(".").slice(-2).join(".");
70
71function siteRelation(target: URL, initiator: URL | null): "none" | "same-origin" | "same-site" | "cross-site" {
72 if (!initiator) return "none";
73 if (initiator.origin === target.origin) return "same-origin";
74 // Good-enough "same site" (eTLD+1 is approximated by the last two labels; the worst case is
75 // calling a same-site request cross-site on multi-part public suffixes like .co.uk).
76 if (initiator.protocol === target.protocol && registrableish(initiator.hostname) === registrableish(target.hostname)) return "same-site";
77 return "cross-site";
78}
79
80function parseUrl(v: string | null): URL | null {
81 if (!v) return null;
82 try {
83 return new URL(v);
84 } catch {
85 return null;
86 }
87}
88
89/**
90 * The `Referer` header a browser sends, per the page's referrer policy. Chromium gives the
91 * handler the referrer as a Request PROPERTY and expects the network layer to turn it into
92 * a header; through our own transport that never happens, so we do it. Default policy is
93 * `strict-origin-when-cross-origin`, like every current browser.
94 */
95export function refererFor(target: URL, referrer: URL, policy: string): string | null {
96 const sameOrigin = referrer.origin === target.origin;
97 const downgrade = referrer.protocol === "https:" && target.protocol === "http:";
98 const clean = new URL(referrer.href);
99 clean.username = "";
100 clean.password = "";
101 clean.hash = "";
102 const full = clean.href;
103 const origin = `${referrer.origin}/`;
104 switch (policy) {
105 case "no-referrer":
106 return null;
107 case "origin":
108 return origin;
109 case "unsafe-url":
110 return full;
111 case "same-origin":
112 return sameOrigin ? full : null;
113 case "strict-origin":
114 return downgrade ? null : origin;
115 case "origin-when-cross-origin":
116 return sameOrigin ? full : origin;
117 case "no-referrer-when-downgrade":
118 return downgrade ? null : full;
119 default: // "" or strict-origin-when-cross-origin
120 return sameOrigin ? full : downgrade ? null : origin;
121 }
122}
123
124/** What the Request object knows that its headers don't. */
125export interface RequestContext {
126 referrer?: string;
127 referrerPolicy?: string;
128 /**
129 * What kind of request the page made and the origin of the document that made it, as Chromium's loader knew them
130 * (request-kinds.ts). When given, the fetch metadata is Chromium's own, not guessed from Accept.
131 */
132 kind?: { type: string; initiator: string | null } | null;
133}
134
135/** Sec-Fetch-Dest and Sec-Fetch-Mode for a resource type, as Chromium sends them (null: not one we know). */
136export function fetchMetadataFor(type: string, hasOrigin: boolean): { dest: string; mode: string } | null {
137 switch (type) {
138 case "mainFrame": return { dest: "document", mode: "navigate" };
139 case "subFrame": return { dest: "iframe", mode: "navigate" };
140 case "script": return { dest: "script", mode: hasOrigin ? "cors" : "no-cors" };
141 case "stylesheet": return { dest: "style", mode: hasOrigin ? "cors" : "no-cors" };
142 case "image": return { dest: "image", mode: hasOrigin ? "cors" : "no-cors" };
143 case "font": return { dest: "font", mode: "cors" };
144 case "media": return { dest: "video", mode: hasOrigin ? "cors" : "no-cors" };
145 case "object": return { dest: "object", mode: "navigate" };
146 case "xhr": return { dest: "empty", mode: "cors" };
147 case "ping": return { dest: "empty", mode: "no-cors" };
148 case "cspReport": return { dest: "report", mode: "no-cors" };
149 default: return null;
150 }
151}
152
153/**
154 * The headers a real Chromium would send for this request, merged over what the renderer
155 * gave us. Returns a NEW Headers; the input is not modified.
156 *
157 * A top-level/frame navigation is recognised the way servers recognise it: an HTML-first
158 * `Accept` plus `Upgrade-Insecure-Requests: 1`. Everything else is a subresource, where
159 * the destination can only be guessed from `Accept` — scripts and XHR/fetch are
160 * indistinguishable here and are reported as `empty`, which is still far closer than the
161 * unconditional `no-cors`/`empty`/`none` the loader would otherwise send.
162 */
163export function chromiumRequestHeaders(url: URL, input: Headers, hints: Hints | null, ctx: RequestContext = {}, method = "GET"): Headers {
164 const h = new Headers(input);
165 const refUrl = parseUrl(ctx.referrer ?? null);
166 const hasWebReferrer = !!refUrl && (refUrl.protocol === "https:" || refUrl.protocol === "http:");
167 if (hasWebReferrer && !h.has("referer")) {
168 const r = refererFor(url, refUrl, ctx.referrerPolicy ?? "");
169 if (r) h.set("referer", r);
170 }
171 if (!isTrustworthy(url)) return h;
172
173 // client hints (the three low-entropy ones Chrome sends on every request)
174 if (hints) {
175 if (!h.has("sec-ch-ua")) h.set("sec-ch-ua", secChUa(hints));
176 if (!h.has("sec-ch-ua-mobile")) h.set("sec-ch-ua-mobile", hints.mobile ? "?1" : "?0");
177 if (!h.has("sec-ch-ua-platform")) h.set("sec-ch-ua-platform", sfv(hints.platform));
178 }
179
180 // fetch metadata
181 const accept = h.get("accept") ?? "";
182 const known = ctx.kind ? fetchMetadataFor(ctx.kind.type, h.has("origin")) : null;
183 if (known && ctx.kind) {
184 // The page's real request kind and the document that made it: Chromium's own values.
185 const from = parseUrl(ctx.kind.initiator);
186 const site = siteRelation(url, from);
187 h.set("sec-fetch-site", site);
188 // A fetch to another origin: the page's credentials mode isn't known here, so it goes as before (no Origin, the page's
189 // cookies, "no-cors"). Marked "cors" with cookies and no Origin, Chromium refuses it (ERR_INVALID_ARGUMENT).
190 const crossFetch = ctx.kind.type === "xhr" && site !== "same-origin" && !h.has("origin");
191 h.set("sec-fetch-mode", crossFetch ? "no-cors" : known.mode);
192 h.set("sec-fetch-dest", known.dest);
193 if (ctx.kind.type === "mainFrame") h.set("sec-fetch-user", "?1");
194 else h.delete("sec-fetch-user");
195 // Chromium sends Origin on a fetch/XHR other than GET or HEAD, and on every cross-origin one. Only the same-origin case
196 // is added here: a cross-origin request carries the page's cookies (see requestCredentials), and with an Origin the
197 // network stack would then refuse a response that allows any site ("Access-Control-Allow-Origin: *").
198 if (ctx.kind.type === "xhr" && !h.has("origin") && from && site === "same-origin" && method !== "GET" && method !== "HEAD") h.set("origin", from.origin);
199 return h;
200 }
201 const navigation = /\btext\/html\b/.test(accept) && h.get("upgrade-insecure-requests") === "1";
202 const initiator = parseUrl(h.get("origin")) ?? (hasWebReferrer ? refUrl : null) ?? parseUrl(h.get("referer"));
203 const site = siteRelation(url, initiator);
204
205 if (navigation) {
206 h.set("sec-fetch-mode", "navigate");
207 h.set("sec-fetch-dest", "document");
208 h.set("sec-fetch-site", site);
209 h.set("sec-fetch-user", "?1"); // user-activated navigation (typed or clicked)
210 } else {
211 h.delete("sec-fetch-user");
212 h.set("sec-fetch-mode", h.has("origin") ? "cors" : "no-cors");
213 h.set("sec-fetch-dest", /^image\//.test(accept) ? "image" : /^text\/css\b/.test(accept) ? "style" : "empty");
214 h.set("sec-fetch-site", site === "none" ? "same-origin" : site);
215 }
216 return h;
217}
218
219/**
220 * Whether a request should carry cookies.
221 *
222 * The Request a protocol handler gets always says credentials "same-origin": Electron doesn't pass the page's real setting
223 * on (a link, a frame, an image and fetch(…, { credentials: "include" }) all arrive that way). So that word alone can't
224 * decide. Reading it as the truth sent no cookies on any request to another origin, which broke sign-ins: a form posted
225 * to one site and redirected to another failed (ERR_INVALID_ARGUMENT), and x.com's calls to api.x.com went without the
226 * session.
227 *
228 * What a real browser does, as far as the headers tell us (`headers` are chromiumRequestHeaders' output):
229 * - navigations (top level and frames) carry cookies;
230 * - no-cors loads (a plain <img>, <script>) carry them;
231 * - loads with an Origin header (<script crossorigin>, <link crossorigin>, fonts) carry them only to the page's own
232 * origin. That keeps the fix this started as: such a load from a CDN whose answer is "Access-Control-Allow-Origin: *"
233 * is refused when the request carried cookies (YouTube's page stayed on grey boxes). A page's fetch() arrives without
234 * an Origin header, so it is a no-cors load here and carries cookies.
235 * Without fetch-metadata headers (plain http), the same test: a navigation or a load without an Origin header carries
236 * them. "omit" and "include", when a caller other than Electron does pass them, are honoured.
237 */
238export function requestCredentials(input: { url: string; credentials?: string; referrer?: string }, headers: Headers): "include" | "omit" {
239 const mode = input.credentials;
240 if (mode === "omit") return "omit";
241 if (mode !== "same-origin") return "include";
242 const fetchMode = headers.get("sec-fetch-mode");
243 if (fetchMode === "navigate" || fetchMode === "no-cors") return "include";
244 // No fetch metadata (an http:// address): the same test chromiumRequestHeaders uses for a navigation, then the Origin header.
245 if (/\btext\/html\b/.test(headers.get("accept") ?? "") && headers.get("upgrade-insecure-requests") === "1") return "include";
246 if (!headers.has("origin")) return "include";
247 let target: URL;
248 try {
249 target = new URL(input.url);
250 } catch {
251 return "include";
252 }
253 const from = (v: string | null | undefined): string | null => {
254 try {
255 return v && v !== "about:client" ? new URL(v).origin : null;
256 } catch {
257 return null;
258 }
259 };
260 const initiator = from(headers.get("origin")) ?? from(input.referrer) ?? from(headers.get("referer"));
261 return initiator && initiator !== target.origin ? "omit" : "include";
262}