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
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
16 hours ago
History
server.ts · 4.0 KB · 110 lines
| 1 | /** |
| 2 | * The x402 proxy server. |
| 3 | * |
| 4 | * Two entry points: |
| 5 | * - Plain HTTP: clients send an absolute-URI request line; we route it straight |
| 6 | * through the engine. |
| 7 | * - HTTPS: clients send CONNECT host:443; we answer 200, wrap the raw socket in |
| 8 | * TLS using a per-host leaf cert from our CA, then treat the decrypted stream as |
| 9 | * an ordinary HTTP server connection routed through the same engine. |
| 10 | * |
| 11 | * Either way, one `handle()` per request. The proxy holds no payment logic. |
| 12 | */ |
| 13 | |
| 14 | import { createServer as createHttpServer, type Server as HttpServer, type IncomingMessage, type ServerResponse } from "node:http"; |
| 15 | import { TLSSocket } from "node:tls"; |
| 16 | import type { Duplex } from "node:stream"; |
| 17 | import type { X402Engine } from "@dbbasic/x402-engine"; |
| 18 | import { CertificateAuthority } from "./ca.js"; |
| 19 | import { handle } from "./handler.js"; |
| 20 | |
| 21 | export interface ProxyOptions { |
| 22 | engine: X402Engine; |
| 23 | ca?: CertificateAuthority; |
| 24 | host?: string; |
| 25 | port?: number; |
| 26 | onError?: (err: unknown, url: string) => void; |
| 27 | onConnect?: (host: string) => void; |
| 28 | } |
| 29 | |
| 30 | export class X402Proxy { |
| 31 | private server: HttpServer; |
| 32 | private readonly engine: X402Engine; |
| 33 | private readonly ca: CertificateAuthority; |
| 34 | private readonly onError?: (err: unknown, url: string) => void; |
| 35 | private readonly onConnect?: (host: string) => void; |
| 36 | |
| 37 | constructor(opts: ProxyOptions) { |
| 38 | this.engine = opts.engine; |
| 39 | this.ca = opts.ca ?? CertificateAuthority.loadOrCreate(); |
| 40 | this.onError = opts.onError; |
| 41 | this.onConnect = opts.onConnect; |
| 42 | |
| 43 | this.server = createHttpServer((req, res) => { |
| 44 | handle(this.engine, req, res, { scheme: "http", onError: this.onError }); |
| 45 | }); |
| 46 | this.server.on("connect", (req, socket, head) => this.onConnectTunnel(req, socket, head)); |
| 47 | } |
| 48 | |
| 49 | rootCertPem(): string { |
| 50 | return this.ca.rootCertPem(); |
| 51 | } |
| 52 | |
| 53 | listen(port = 8402, host = "127.0.0.1"): Promise<{ host: string; port: number }> { |
| 54 | return new Promise((resolve) => { |
| 55 | this.server.listen(port, host, () => { |
| 56 | const addr = this.server.address(); |
| 57 | const bound = typeof addr === "object" && addr ? addr.port : port; |
| 58 | resolve({ host, port: bound }); |
| 59 | }); |
| 60 | }); |
| 61 | } |
| 62 | |
| 63 | close(): Promise<void> { |
| 64 | return new Promise((resolve) => this.server.close(() => resolve())); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * A client wants an https tunnel. We terminate it ourselves so the engine can see |
| 69 | * the plaintext and pay any 402s inside. |
| 70 | */ |
| 71 | private onConnectTunnel(req: IncomingMessage, clientSocket: Duplex, head: Buffer): void { |
| 72 | const [host = "", portStr] = (req.url ?? "").split(":"); |
| 73 | const port = Number(portStr) || 443; |
| 74 | this.onConnect?.(host); |
| 75 | |
| 76 | const { cert, key } = this.ca.certFor(host); |
| 77 | clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); |
| 78 | |
| 79 | // Any bytes already read past the CONNECT line are the start of the client's TLS |
| 80 | // ClientHello. Push them back BEFORE the TLS layer attaches, or the handshake |
| 81 | // loses its first bytes and stalls. |
| 82 | if (head && head.length) clientSocket.unshift(head); |
| 83 | |
| 84 | // Wrap the raw client socket in server-side TLS, presenting our per-host leaf. |
| 85 | const tlsSocket = new TLSSocket(clientSocket as import("node:net").Socket, { |
| 86 | isServer: true, |
| 87 | cert, |
| 88 | key, |
| 89 | }); |
| 90 | tlsSocket.on("error", (e) => this.onError?.(e, `CONNECT ${host}:${port}`)); |
| 91 | clientSocket.on("error", () => tlsSocket.destroy()); |
| 92 | |
| 93 | // Feed the decrypted stream into an ephemeral HTTP parser. Each request that |
| 94 | // comes out is routed exactly like a plain-HTTP one, but tagged https and pinned |
| 95 | // to the CONNECT host so the engine reconstructs the right absolute URL. |
| 96 | const connectHost = port === 443 ? host : `${host}:${port}`; |
| 97 | const inner = createHttpServer((ireq, ires) => { |
| 98 | handle(this.engine, ireq, ires, { |
| 99 | scheme: "https", |
| 100 | connectHost, |
| 101 | onError: this.onError, |
| 102 | }); |
| 103 | }); |
| 104 | inner.on("clientError", (e) => this.onError?.(e, `inner clientError ${host}`)); |
| 105 | inner.emit("connection", tlsSocket); |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /** Convenience: the ServerResponse type re-exported for adapters. */ |
| 110 | export type { IncomingMessage, ServerResponse }; |