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
handler.ts · 3.8 KB · 107 lines
| 1 | /** |
| 2 | * Bridge between Node's HTTP plumbing and the transport-agnostic X402Engine. |
| 3 | * |
| 4 | * Everything the proxy receives — whether it arrived as plaintext HTTP or was |
| 5 | * decrypted out of a CONNECT tunnel — funnels through `handle()`. That is the whole |
| 6 | * point of the engine-first design: the proxy is dumb pipe, the payment decision |
| 7 | * lives in exactly one place, shared with the browser and the agent runtime. |
| 8 | */ |
| 9 | |
| 10 | import type { IncomingMessage, ServerResponse } from "node:http"; |
| 11 | import { Readable } from "node:stream"; |
| 12 | import type { X402Engine } from "@dbbasic/x402-engine"; |
| 13 | |
| 14 | /** Build the absolute request URL. For CONNECT-tunnelled traffic req.url is a path. */ |
| 15 | function absoluteUrl(req: IncomingMessage, scheme: "http" | "https", connectHost?: string): string { |
| 16 | if (req.url && /^https?:\/\//.test(req.url)) return req.url; // classic forward-proxy form |
| 17 | const host = connectHost ?? req.headers.host; |
| 18 | if (!host) throw new Error("cannot resolve request host"); |
| 19 | return `${scheme}://${host}${req.url ?? "/"}`; |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * The origin of the page the user is actually looking at, used to scope budgets. |
| 24 | * We take it from Referer; a subresource must be billed against its page, never |
| 25 | * against itself, or the pair-scoped rate cap means nothing. Absent Referer (a |
| 26 | * top-level navigation, curl, or an agent) yields "" — its own budget scope. |
| 27 | */ |
| 28 | function topOriginOf(req: IncomingMessage): string { |
| 29 | const ref = req.headers["referer"]; |
| 30 | if (!ref) return ""; |
| 31 | try { |
| 32 | return new URL(ref).origin; |
| 33 | } catch { |
| 34 | return ""; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | function toWebRequest(req: IncomingMessage, url: string): Request { |
| 39 | const headers = new Headers(); |
| 40 | for (const [k, v] of Object.entries(req.headers)) { |
| 41 | if (v === undefined) continue; |
| 42 | // Hop-by-hop and proxy-specific headers must not be forwarded. |
| 43 | if (k === "proxy-connection" || k === "connection" || k === "keep-alive") continue; |
| 44 | headers.set(k, Array.isArray(v) ? v.join(", ") : v); |
| 45 | } |
| 46 | const method = req.method ?? "GET"; |
| 47 | const hasBody = method !== "GET" && method !== "HEAD"; |
| 48 | return new Request(url, { |
| 49 | method, |
| 50 | headers, |
| 51 | body: hasBody ? (Readable.toWeb(req) as ReadableStream) : undefined, |
| 52 | // @ts-expect-error Node requires duplex for streamed request bodies |
| 53 | duplex: hasBody ? "half" : undefined, |
| 54 | redirect: "manual", |
| 55 | }); |
| 56 | } |
| 57 | |
| 58 | async function writeWebResponse(res: ServerResponse, response: Response): Promise<void> { |
| 59 | const headers: Record<string, string | string[]> = {}; |
| 60 | response.headers.forEach((value, key) => { |
| 61 | headers[key] = value; |
| 62 | }); |
| 63 | res.writeHead(response.status, headers); |
| 64 | |
| 65 | if (!response.body) { |
| 66 | res.end(); |
| 67 | return; |
| 68 | } |
| 69 | // Stream, never buffer — large downloads and video must pass through untouched. |
| 70 | const nodeStream = Readable.fromWeb(response.body as import("node:stream/web").ReadableStream); |
| 71 | nodeStream.pipe(res); |
| 72 | await new Promise<void>((resolve, reject) => { |
| 73 | nodeStream.on("end", resolve); |
| 74 | nodeStream.on("error", reject); |
| 75 | res.on("close", resolve); |
| 76 | }); |
| 77 | } |
| 78 | |
| 79 | export interface HandleOptions { |
| 80 | scheme: "http" | "https"; |
| 81 | /** host:port from the CONNECT line, when this came out of a tunnel. */ |
| 82 | connectHost?: string; |
| 83 | onError?: (err: unknown, url: string) => void; |
| 84 | } |
| 85 | |
| 86 | export async function handle( |
| 87 | engine: X402Engine, |
| 88 | req: IncomingMessage, |
| 89 | res: ServerResponse, |
| 90 | opts: HandleOptions, |
| 91 | ): Promise<void> { |
| 92 | let url = ""; |
| 93 | try { |
| 94 | url = absoluteUrl(req, opts.scheme, opts.connectHost); |
| 95 | const webReq = toWebRequest(req, url); |
| 96 | const { response } = await engine.fetch(webReq, topOriginOf(req)); |
| 97 | await writeWebResponse(res, response); |
| 98 | } catch (err) { |
| 99 | opts.onError?.(err, url); |
| 100 | if (!res.headersSent) { |
| 101 | res.writeHead(502, { "content-type": "text/plain" }); |
| 102 | res.end(`x402 proxy error for ${url}: ${String(err)}`); |
| 103 | } else { |
| 104 | res.destroy(); |
| 105 | } |
| 106 | } |
| 107 | } |