askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
toolbar: Back and Forward are greyed out when there's nowhere to go
cc08c7a
1 week, 2 days ago
History
transport.ts · 12.3 KB · 256 lines
| 1 | /** |
| 2 | * The browser's network transport: a fetch-shaped function built on Electron's |
| 3 | * `net.request`, whose ONE job beyond fetching is to NOT follow redirects itself. |
| 4 | * |
| 5 | * Why not `net.fetch`: inside `protocol.handle` every response we return is the final |
| 6 | * answer for the renderer's request. If we follow a 3xx internally, the renderer never |
| 7 | * learns it was redirected — the page shows the destination's content under the |
| 8 | * ORIGINAL url and origin. That breaks the address bar, relative links, same-origin |
| 9 | * checks and password-manager origin matching, and it silently dodges the per-request |
| 10 | * payment decision for the redirect target. `net.fetch` can't help: with |
| 11 | * `redirect: "manual"` it throws "Redirect was cancelled" and its Response carries no |
| 12 | * redirect information. |
| 13 | * |
| 14 | * `net.request` can: with `redirect: "manual"` it emits a `redirect` event (status, |
| 15 | * target, headers) and cancels the request unless `followRedirect()` is called. We never |
| 16 | * call it. Instead we return the 3xx as a normal Response (`Location` set to the absolute |
| 17 | * target), the renderer re-requests that URL, and the re-request re-enters our |
| 18 | * `protocol.handle` handler — so every hop gets its own payment decision, and the page's |
| 19 | * URL/origin are always the ones the user is actually looking at. |
| 20 | * |
| 21 | * Cookies: `useSessionCookies` + `credentials: "include"` make the request read and write |
| 22 | * the session's cookie jar exactly like a fetch would — including `Set-Cookie` on the 3xx |
| 23 | * itself, which bot checks such as Anubis depend on. |
| 24 | * |
| 25 | * Recursion: `net.request`, like `net.fetch`, IS routed through our own `protocol.handle` |
| 26 | * handler — without a bypass it would call us back forever. `net.fetch` avoids that with a |
| 27 | * `bypassCustomProtocolHandlers` option; `net.request` has no public equivalent, but |
| 28 | * Electron implements `net.fetch` ON TOP of `ClientRequest` and sets the same flag on the |
| 29 | * request's private `_urlLoaderOptions`. We do exactly what Electron does. That is a |
| 30 | * private field, so `assertBypassAvailable()` fails loudly at startup if a future Electron |
| 31 | * removes it, and the end-to-end transport tests cover it. |
| 32 | */ |
| 33 | |
| 34 | import { EventEmitter } from "node:events"; |
| 35 | import { Readable } from "node:stream"; |
| 36 | import { net, session, type Session } from "electron"; |
| 37 | import { chromiumRequestHeaders, type Hints, requestCredentials } from "./compat.js"; |
| 38 | import type { RawFetch } from "./intercept.js"; |
| 39 | |
| 40 | /** |
| 41 | * The engine's own client-hint values (from `navigator.userAgentData`), reported once by the |
| 42 | * main process after the chrome window loads. Requests wait briefly for it so the very first |
| 43 | * page load already carries hints that match what the page's JS will report; if it never |
| 44 | * arrives we proceed without hints rather than block browsing. |
| 45 | */ |
| 46 | let hintsValue: Hints | null = null; |
| 47 | let resolveHints: (h: Hints | null) => void = () => {}; |
| 48 | const hintsReady = new Promise<Hints | null>((resolve) => { |
| 49 | resolveHints = resolve; |
| 50 | setTimeout(() => resolve(null), 3000).unref?.(); |
| 51 | }); |
| 52 | /** How to find what kind of request the page made (request-kinds.ts, filled by main.ts from webRequest). */ |
| 53 | let kindOf: ((method: string, url: string) => { type: string; initiator: string | null } | null) | null = null; |
| 54 | export function setRequestKindLookup(fn: typeof kindOf): void { |
| 55 | kindOf = fn; |
| 56 | } |
| 57 | |
| 58 | export function setClientHints(h: Hints | null): void { |
| 59 | hintsValue = h; |
| 60 | resolveHints(h); |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Progress of every request through this transport, for the UI ("waiting for…", "receiving 1.2 MB…", |
| 65 | * "redirecting…"). Listen on the "event" channel. We can only report what is observable here — request |
| 66 | * out, response headers in, body bytes, redirect, error; DNS/TCP/TLS happen inside Chromium and are |
| 67 | * invisible, so they are folded into "waiting". |
| 68 | */ |
| 69 | export interface NetEvent { |
| 70 | id: number; |
| 71 | url: string; |
| 72 | type: "start" | "caller" | "headers" | "progress" | "end" | "redirect" | "error"; // "caller": parked, waiting for a caller-supplied network layer |
| 73 | status?: number; |
| 74 | /** Content-Length when the server sent one. */ |
| 75 | total?: number; |
| 76 | /** The response's Content-Type (lowercased, without parameters), e.g. "text/event-stream". */ |
| 77 | contentType?: string; |
| 78 | /** Body bytes received so far (progress/end). */ |
| 79 | bytes?: number; |
| 80 | location?: string; |
| 81 | error?: string; |
| 82 | /** For a failure the CALLER decided (or that waiting on the caller caused): the reason, and who said so. */ |
| 83 | failureKind?: string; |
| 84 | failureSource?: "observed" | "caller"; |
| 85 | } |
| 86 | export const netEvents = new EventEmitter(); |
| 87 | let netSeq = 0; |
| 88 | export const nextNetId = (): number => ++netSeq; |
| 89 | export const emitNet = (e: NetEvent): void => { netEvents.emit("event", e); }; |
| 90 | |
| 91 | /** Headers the network stack owns (or that would leak/duplicate state) — never copy these onto the request. */ |
| 92 | const REQUEST_HEADERS_WE_DONT_SET = new Set([ |
| 93 | "host", |
| 94 | "content-length", |
| 95 | "connection", |
| 96 | "keep-alive", |
| 97 | "transfer-encoding", |
| 98 | "upgrade", |
| 99 | "te", |
| 100 | "trailer", |
| 101 | "expect", |
| 102 | "proxy-connection", |
| 103 | "accept-encoding", // the network stack negotiates (and decodes) this itself |
| 104 | "cookie", // comes from the session's cookie jar via useSessionCookies |
| 105 | ]); |
| 106 | |
| 107 | /** Statuses that must not carry a body in a Response. */ |
| 108 | const NULL_BODY_STATUS = new Set([101, 204, 205, 304]); |
| 109 | |
| 110 | function toHeaders(src: Record<string, string | string[] | undefined>, drop: ReadonlySet<string> = new Set()): Headers { |
| 111 | const out = new Headers(); |
| 112 | for (const [k, v] of Object.entries(src)) { |
| 113 | if (v === undefined || drop.has(k.toLowerCase())) continue; |
| 114 | for (const one of Array.isArray(v) ? v : [v]) { |
| 115 | try { |
| 116 | out.append(k, one); |
| 117 | } catch { |
| 118 | /* a header name/value the Headers class rejects — drop it rather than fail the page */ |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | return out; |
| 123 | } |
| 124 | |
| 125 | /** The private option Electron's own net.fetch sets on a ClientRequest to skip protocol handlers. */ |
| 126 | type WithLoaderOptions = { _urlLoaderOptions?: { bypassCustomProtocolHandlers?: boolean } }; |
| 127 | |
| 128 | function bypassProtocolHandlers(req: unknown): void { |
| 129 | const opts = (req as WithLoaderOptions)._urlLoaderOptions; |
| 130 | if (!opts) { |
| 131 | // Fail loudly: silently continuing would recurse into our own handler and hang every page. |
| 132 | throw new Error("Electron changed ClientRequest internals (_urlLoaderOptions is gone); update transport.ts"); |
| 133 | } |
| 134 | opts.bypassCustomProtocolHandlers = true; |
| 135 | } |
| 136 | |
| 137 | export function netRequestFetch(ses: Session = session.defaultSession): RawFetch { |
| 138 | return async (input: Request): Promise<Response> => { |
| 139 | // Buffer the request body: simplest correct thing for ClientRequest, and bodies here are form posts/API calls. |
| 140 | const body = input.body ? Buffer.from(await input.arrayBuffer()) : null; |
| 141 | // What a real Chromium would send (client hints + fetch metadata) — net.request doesn't add them. |
| 142 | // The page's real request kind and the document that made it, when webRequest saw the request first. |
| 143 | const kind = kindOf ? kindOf(input.method, input.url) : null; |
| 144 | const headers = chromiumRequestHeaders(new URL(input.url), input.headers, hintsValue ?? (await hintsReady), { |
| 145 | referrer: input.referrer, |
| 146 | referrerPolicy: input.referrerPolicy, |
| 147 | kind, |
| 148 | }, input.method.toUpperCase()); |
| 149 | |
| 150 | const id = ++netSeq; |
| 151 | const url = input.url; |
| 152 | emitNet({ id, url, type: "start" }); |
| 153 | return new Promise<Response>((resolve, reject) => { |
| 154 | let settled = false; |
| 155 | const settle = (fn: () => void) => { |
| 156 | if (settled) return; // e.g. the "Redirect was cancelled" error that follows a handed-back 3xx |
| 157 | settled = true; |
| 158 | fn(); |
| 159 | }; |
| 160 | |
| 161 | // Cookies follow the page's own rule: a cross-site request that asked for none (<script crossorigin>, fetch with the default |
| 162 | // credentials) must not carry them, and a response with "Access-Control-Allow-Origin: *" is only acceptable to the network |
| 163 | // stack when the request carried none. Always asking for credentials made every such request fail (ERR_FAILED). |
| 164 | const credentials = requestCredentials(input, headers); |
| 165 | const req = net.request({ |
| 166 | method: input.method, |
| 167 | url: input.url, |
| 168 | session: ses, |
| 169 | redirect: "manual", |
| 170 | credentials, |
| 171 | useSessionCookies: credentials === "include", |
| 172 | // The document that made the request: without it Chromium treats this as the browser's own request and says |
| 173 | // Sec-Fetch-Site: none, whatever we set. Not for a page load (Chromium would then hold back the cookies that only |
| 174 | // go with top-level navigations: a form answered by a redirect to another site would arrive signed out), and not |
| 175 | // for a CORS request to another origin that carries cookies (Chromium would then enforce CORS itself and refuse a |
| 176 | // response that allows any site). |
| 177 | ...(kind?.initiator && kind.type !== "mainFrame" && !(headers.get("sec-fetch-mode") === "cors" && headers.get("sec-fetch-site") !== "same-origin" && credentials === "include") |
| 178 | ? { origin: kind.initiator } |
| 179 | : {}), |
| 180 | }); |
| 181 | |
| 182 | bypassProtocolHandlers(req); |
| 183 | |
| 184 | headers.forEach((value, name) => { |
| 185 | if (REQUEST_HEADERS_WE_DONT_SET.has(name.toLowerCase())) return; |
| 186 | try { |
| 187 | req.setHeader(name, value); |
| 188 | } catch { |
| 189 | /* Chromium refuses a few restricted headers — the request still goes out without them */ |
| 190 | } |
| 191 | }); |
| 192 | |
| 193 | // A redirect: hand it to the renderer. We deliberately do NOT call req.followRedirect(); |
| 194 | // the request is cancelled, and the renderer re-requests `redirectUrl` through us. |
| 195 | req.on("redirect", (status, _method, redirectUrl, headers) => { |
| 196 | // The cookies are already stored by the network stack. The redirect's own body is never shown, so the headers that describe it go |
| 197 | // too: left in, a "text/plain" type with "nosniff" (unpkg sends exactly that on its redirects) made the browser refuse the script |
| 198 | // it was redirected to ("MIME type text/plain is not executable"). |
| 199 | const h = toHeaders(headers, new Set(["set-cookie", "content-type", "x-content-type-options", "content-length", "content-encoding", "content-disposition"])); |
| 200 | h.set("location", redirectUrl); |
| 201 | emitNet({ id, url, type: "redirect", status, location: redirectUrl }); |
| 202 | settle(() => resolve(new Response(null, { status, headers: h }))); |
| 203 | }); |
| 204 | |
| 205 | req.on("response", (incoming) => { |
| 206 | // Electron documents IncomingMessage as a Readable stream; its typings just don't say so. |
| 207 | const res = incoming as typeof incoming & Readable; |
| 208 | const status = res.statusCode; |
| 209 | const headers = toHeaders(res.headers); // passed through untouched, as Electron's own net.fetch does |
| 210 | const total = Number(res.headers["content-length"]); |
| 211 | const ct = String(res.headers["content-type"] ?? "").split(";")[0]!.trim().toLowerCase(); |
| 212 | emitNet({ id, url, type: "headers", status, ...(Number.isFinite(total) ? { total } : {}), ...(ct ? { contentType: ct } : {}) }); |
| 213 | let body: ReadableStream<Uint8Array> | null = null; |
| 214 | if (NULL_BODY_STATUS.has(status) || input.method === "HEAD") { |
| 215 | res.on("data", () => {}); |
| 216 | emitNet({ id, url, type: "end", bytes: 0 }); |
| 217 | } else { |
| 218 | // Count bytes in a pass-through stage (a 'data' listener on `res` would steal chunks from toWeb). |
| 219 | let bytes = 0; |
| 220 | let lastEmit = 0; |
| 221 | body = (Readable.toWeb(res) as ReadableStream<Uint8Array>).pipeThrough( |
| 222 | new TransformStream<Uint8Array, Uint8Array>({ |
| 223 | transform(chunk, controller) { |
| 224 | bytes += chunk.byteLength; |
| 225 | const now = Date.now(); |
| 226 | if (now - lastEmit > 120) { |
| 227 | lastEmit = now; |
| 228 | emitNet({ id, url, type: "progress", bytes }); |
| 229 | } |
| 230 | controller.enqueue(chunk); |
| 231 | }, |
| 232 | flush() { |
| 233 | emitNet({ id, url, type: "end", bytes }); |
| 234 | }, |
| 235 | }), |
| 236 | ); // handles backpressure and cancellation |
| 237 | } |
| 238 | settle(() => resolve(new Response(body, { status, statusText: res.statusMessage, headers }))); |
| 239 | }); |
| 240 | |
| 241 | req.on("error", (e) => { |
| 242 | if (!settled) emitNet({ id, url, type: "error", error: e.message }); |
| 243 | settle(() => reject(e)); |
| 244 | }); |
| 245 | |
| 246 | input.signal.addEventListener("abort", () => { |
| 247 | req.abort(); |
| 248 | if (!settled) emitNet({ id, url, type: "error", error: "aborted" }); |
| 249 | settle(() => reject(new DOMException("The operation was aborted.", "AbortError"))); |
| 250 | }); |
| 251 | |
| 252 | if (body) req.end(body); |
| 253 | else req.end(); |
| 254 | }); |
| 255 | }; |
| 256 | } |