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
proxy.test.ts · 6.8 KB · 190 lines
| 1 | import { createServer as createHttp, type Server, request as httpRequest } from "node:http"; |
| 2 | import { createServer as createHttps } from "node:https"; |
| 3 | import { connect as tlsConnect } from "node:tls"; |
| 4 | import type { AddressInfo } from "node:net"; |
| 5 | import { afterAll, beforeAll, describe, expect, it } from "vitest"; |
| 6 | import { privateKeyToAccount } from "viem/accounts"; |
| 7 | import { PolicyEngine, Ledger, X402Engine } from "@dbbasic/x402-engine"; |
| 8 | import { X402Proxy } from "../src/server.js"; |
| 9 | import { CertificateAuthority } from "../src/ca.js"; |
| 10 | |
| 11 | const NETWORK = "eip155:84532"; |
| 12 | const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; |
| 13 | const PAY_TO = "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"; |
| 14 | const account = privateKeyToAccount( |
| 15 | "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d", |
| 16 | ); |
| 17 | |
| 18 | const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64"); |
| 19 | |
| 20 | /** A mock x402 origin: 402 with a PAYMENT-REQUIRED header, then 200 once paid. */ |
| 21 | function makeOrigin(handler: (req: unknown) => void, https = false, certHost = "localhost") { |
| 22 | const originCa = CertificateAuthority.ephemeral(); |
| 23 | const listener = (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => { |
| 24 | handler(req); |
| 25 | if (!req.headers["payment-signature"]) { |
| 26 | const challenge = { |
| 27 | x402Version: 2, |
| 28 | accepts: [ |
| 29 | { |
| 30 | scheme: "exact", |
| 31 | network: NETWORK, |
| 32 | amount: "10000", |
| 33 | asset: USDC, |
| 34 | payTo: PAY_TO, |
| 35 | maxTimeoutSeconds: 60, |
| 36 | extra: { name: "USDC", version: "2" }, |
| 37 | }, |
| 38 | ], |
| 39 | }; |
| 40 | res.writeHead(402, { "PAYMENT-REQUIRED": b64(challenge), "content-type": "text/plain" }); |
| 41 | res.end("payment required"); |
| 42 | return; |
| 43 | } |
| 44 | res.writeHead(200, { |
| 45 | "PAYMENT-RESPONSE": b64({ success: true, transaction: "0xabc", network: NETWORK }), |
| 46 | "content-type": "text/plain", |
| 47 | }); |
| 48 | res.end("PAID CONTENT"); |
| 49 | }; |
| 50 | if (https) { |
| 51 | const leaf = originCa.certFor(certHost); |
| 52 | return { server: createHttps({ cert: leaf.cert, key: leaf.key }, listener), ca: originCa }; |
| 53 | } |
| 54 | return { server: createHttp(listener), ca: originCa }; |
| 55 | } |
| 56 | |
| 57 | function freshEngine(fetchImpl?: typeof fetch) { |
| 58 | return new X402Engine({ |
| 59 | account, |
| 60 | policy: new PolicyEngine(), |
| 61 | ledger: new Ledger(), |
| 62 | fetchImpl, |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | // ---- HTTP forward-proxy path ---- |
| 67 | describe("proxy: plain HTTP", () => { |
| 68 | let origin: Server; |
| 69 | let originUrl: string; |
| 70 | let proxy: X402Proxy; |
| 71 | let proxyPort: number; |
| 72 | let hits = 0; |
| 73 | |
| 74 | beforeAll(async () => { |
| 75 | const m = makeOrigin(() => hits++); |
| 76 | origin = m.server; |
| 77 | await new Promise<void>((r) => origin.listen(0, "127.0.0.1", r)); |
| 78 | originUrl = `http://127.0.0.1:${(origin.address() as AddressInfo).port}`; |
| 79 | |
| 80 | proxy = new X402Proxy({ engine: freshEngine(), ca: CertificateAuthority.ephemeral() }); |
| 81 | ({ port: proxyPort } = await proxy.listen(0)); |
| 82 | }); |
| 83 | |
| 84 | afterAll(async () => { |
| 85 | await proxy.close(); |
| 86 | origin.close(); |
| 87 | }); |
| 88 | |
| 89 | it("pays a 402 and returns the paid content through the proxy", async () => { |
| 90 | const body = await new Promise<string>((resolve, reject) => { |
| 91 | const req = httpRequest( |
| 92 | { host: "127.0.0.1", port: proxyPort, method: "GET", path: `${originUrl}/article` }, |
| 93 | (res) => { |
| 94 | let data = ""; |
| 95 | res.on("data", (c) => (data += c)); |
| 96 | res.on("end", () => resolve(data)); |
| 97 | }, |
| 98 | ); |
| 99 | req.on("error", reject); |
| 100 | req.end(); |
| 101 | }); |
| 102 | |
| 103 | expect(body).toBe("PAID CONTENT"); |
| 104 | expect(hits).toBe(2); // one 402, one paid retry |
| 105 | }); |
| 106 | }); |
| 107 | |
| 108 | // ---- HTTPS MITM path (the real reason the proxy exists) ---- |
| 109 | describe("proxy: HTTPS via CONNECT + MITM", () => { |
| 110 | let origin: Server; |
| 111 | let originPort: number; |
| 112 | let proxy: X402Proxy; |
| 113 | let proxyPort: number; |
| 114 | let proxyCaPem: string; |
| 115 | |
| 116 | beforeAll(async () => { |
| 117 | const m = makeOrigin(() => {}, true, "127.0.0.1"); |
| 118 | origin = m.server; |
| 119 | await new Promise<void>((r) => origin.listen(0, "127.0.0.1", r)); |
| 120 | originPort = (origin.address() as AddressInfo).port; |
| 121 | |
| 122 | // The proxy's OUTBOUND fetch must trust the mock origin's self-signed cert. |
| 123 | // Scope the relaxation to this test process only. |
| 124 | const prev = process.env.NODE_TLS_REJECT_UNAUTHORIZED; |
| 125 | process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; |
| 126 | afterAll(() => { |
| 127 | if (prev === undefined) delete process.env.NODE_TLS_REJECT_UNAUTHORIZED; |
| 128 | else process.env.NODE_TLS_REJECT_UNAUTHORIZED = prev; |
| 129 | }); |
| 130 | |
| 131 | const proxyCa = CertificateAuthority.ephemeral(); |
| 132 | proxyCaPem = proxyCa.rootCertPem(); |
| 133 | proxy = new X402Proxy({ engine: freshEngine(), ca: proxyCa }); |
| 134 | ({ port: proxyPort } = await proxy.listen(0)); |
| 135 | }); |
| 136 | |
| 137 | afterAll(async () => { |
| 138 | await proxy.close(); |
| 139 | origin.close(); |
| 140 | }); |
| 141 | |
| 142 | it("terminates TLS, pays the 402 inside the tunnel, returns paid content", async () => { |
| 143 | // Use 127.0.0.1 end to end: the origin binds IPv4-only, so resolving "localhost" |
| 144 | // (which prefers ::1) would hang the proxy's outbound fetch. The CA issues IP SANs. |
| 145 | const host = "127.0.0.1"; |
| 146 | const target = `${host}:${originPort}`; |
| 147 | |
| 148 | // 1. CONNECT to the proxy to open a tunnel. |
| 149 | const socket = await new Promise<import("node:stream").Duplex>((resolve, reject) => { |
| 150 | const req = httpRequest({ host: "127.0.0.1", port: proxyPort, method: "CONNECT", path: target }); |
| 151 | req.on("connect", (res, sock) => { |
| 152 | if (res.statusCode !== 200) return reject(new Error(`CONNECT got ${res.statusCode}`)); |
| 153 | resolve(sock); |
| 154 | }); |
| 155 | req.on("error", reject); |
| 156 | req.end(); |
| 157 | }); |
| 158 | |
| 159 | // 2. TLS to the proxy, trusting the proxy's root CA (as an installed CA would). |
| 160 | // SNI can't be an IP literal, so omit servername; chain trust via `ca` is still |
| 161 | // enforced, only the hostname match is skipped (fine for an IP-literal target). |
| 162 | const tls = tlsConnect({ socket, ca: [proxyCaPem], checkServerIdentity: () => undefined }); |
| 163 | await new Promise<void>((resolve, reject) => { |
| 164 | tls.on("secureConnect", () => { |
| 165 | expect(tls.authorized).toBe(true); // proves the MITM leaf chains to our CA |
| 166 | resolve(); |
| 167 | }); |
| 168 | tls.on("error", reject); |
| 169 | setTimeout(() => reject(new Error("TLS handshake timeout")), 3000); |
| 170 | }); |
| 171 | |
| 172 | // 3. Speak plain HTTP inside the encrypted tunnel. |
| 173 | tls.write(`GET /premium HTTP/1.1\r\nHost: ${target}\r\nConnection: close\r\n\r\n`); |
| 174 | const raw = await new Promise<string>((resolve, reject) => { |
| 175 | let data = ""; |
| 176 | const done = () => resolve(data); |
| 177 | tls.on("data", (c) => { |
| 178 | data += c.toString(); |
| 179 | if (data.includes("PAID CONTENT")) done(); // full body arrived |
| 180 | }); |
| 181 | tls.on("end", done); |
| 182 | tls.on("close", done); |
| 183 | tls.on("error", reject); |
| 184 | setTimeout(() => reject(new Error(`response timeout, got ${data.length}B: ${data.slice(0, 120)}`)), 3000); |
| 185 | }); |
| 186 | |
| 187 | expect(raw).toContain("200"); |
| 188 | expect(raw).toContain("PAID CONTENT"); |
| 189 | }); |
| 190 | }); |