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
engine.test.ts · 8.5 KB · 253 lines
| 1 | import { createServer, type Server } from "node:http"; |
| 2 | import type { AddressInfo } from "node:net"; |
| 3 | import { afterAll, beforeAll, describe, expect, it } from "vitest"; |
| 4 | import { privateKeyToAccount } from "viem/accounts"; |
| 5 | import { verifyTypedData } from "viem"; |
| 6 | |
| 7 | import { X402Engine } from "../src/engine.js"; |
| 8 | import { PolicyEngine, DEFAULT_LIMITS } from "../src/policy.js"; |
| 9 | import { AUTHORIZATION_TYPES, domainFor } from "../src/schemes/exact-evm.js"; |
| 10 | import { lookupAsset } from "../src/assets.js"; |
| 11 | import type { PaymentPayload, PaymentRequired } from "../src/types.js"; |
| 12 | |
| 13 | const NETWORK = "eip155:84532"; // Base Sepolia |
| 14 | const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; |
| 15 | const PAY_TO = "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"; |
| 16 | |
| 17 | const account = privateKeyToAccount( |
| 18 | "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d", |
| 19 | ); |
| 20 | |
| 21 | const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64"); |
| 22 | const unb64 = <T>(s: string): T => JSON.parse(Buffer.from(s, "base64").toString()) as T; |
| 23 | |
| 24 | /** Mock resource server. `challenge` lets each test hand back a hostile 402. */ |
| 25 | interface MockOpts { |
| 26 | challenge?: Partial<PaymentRequired>; |
| 27 | amount?: string; |
| 28 | asset?: string; |
| 29 | maxTimeoutSeconds?: number; |
| 30 | extra?: Record<string, unknown>; |
| 31 | } |
| 32 | |
| 33 | let server: Server; |
| 34 | let base: string; |
| 35 | let opts: MockOpts = {}; |
| 36 | /** Every PAYMENT-SIGNATURE the server received. */ |
| 37 | let received: PaymentPayload[] = []; |
| 38 | |
| 39 | beforeAll(async () => { |
| 40 | server = createServer((req, res) => { |
| 41 | const sig = req.headers["payment-signature"] as string | undefined; |
| 42 | |
| 43 | if (!sig) { |
| 44 | const challenge: PaymentRequired = { |
| 45 | x402Version: 2, |
| 46 | error: "payment required", |
| 47 | resource: { url: `${base}${req.url}`, mimeType: "text/plain" }, |
| 48 | accepts: [ |
| 49 | { |
| 50 | scheme: "exact", |
| 51 | network: NETWORK, |
| 52 | amount: opts.amount ?? "10000", // 0.01 USDC |
| 53 | asset: opts.asset ?? USDC, |
| 54 | payTo: PAY_TO, |
| 55 | maxTimeoutSeconds: opts.maxTimeoutSeconds ?? 60, |
| 56 | extra: opts.extra ?? { assetTransferMethod: "eip3009", name: "USDC", version: "2" }, |
| 57 | }, |
| 58 | ], |
| 59 | ...opts.challenge, |
| 60 | }; |
| 61 | res.writeHead(402, { |
| 62 | "PAYMENT-REQUIRED": b64(challenge), |
| 63 | "content-type": "text/plain", |
| 64 | }); |
| 65 | res.end("payment required"); |
| 66 | return; |
| 67 | } |
| 68 | |
| 69 | received.push(unb64<PaymentPayload>(sig)); |
| 70 | res.writeHead(200, { |
| 71 | "PAYMENT-RESPONSE": b64({ |
| 72 | success: true, |
| 73 | transaction: "0xdeadbeef", |
| 74 | network: NETWORK, |
| 75 | payer: account.address, |
| 76 | }), |
| 77 | "content-type": "text/plain", |
| 78 | }); |
| 79 | res.end("the paid content"); |
| 80 | }); |
| 81 | |
| 82 | await new Promise<void>(r => server.listen(0, "127.0.0.1", r)); |
| 83 | base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; |
| 84 | }); |
| 85 | |
| 86 | afterAll(() => server.close()); |
| 87 | |
| 88 | function freshEngine(limits = DEFAULT_LIMITS) { |
| 89 | received = []; |
| 90 | opts = {}; |
| 91 | return new X402Engine({ |
| 92 | account, |
| 93 | policy: new PolicyEngine(limits), |
| 94 | approve: async () => false, // deny anything needing a prompt unless a test overrides |
| 95 | }); |
| 96 | } |
| 97 | |
| 98 | describe("pay-and-retry", () => { |
| 99 | it("pays a 402 and returns the paid content, with a signature that actually verifies", async () => { |
| 100 | const engine = freshEngine(); |
| 101 | const { response, receipt } = await engine.fetch( |
| 102 | new Request(`${base}/article`), |
| 103 | "https://reader.example", |
| 104 | ); |
| 105 | |
| 106 | expect(response.status).toBe(200); |
| 107 | expect(await response.text()).toBe("the paid content"); |
| 108 | expect(received).toHaveLength(1); |
| 109 | |
| 110 | const payload = received[0]!; |
| 111 | const asset = lookupAsset(NETWORK, USDC)!; |
| 112 | const a = payload.payload.authorization; |
| 113 | |
| 114 | // The signature the server got must verify against the PINNED domain. |
| 115 | const valid = await verifyTypedData({ |
| 116 | address: account.address, |
| 117 | domain: domainFor(asset), |
| 118 | types: AUTHORIZATION_TYPES, |
| 119 | primaryType: "TransferWithAuthorization", |
| 120 | message: { |
| 121 | from: a.from as `0x${string}`, |
| 122 | to: a.to as `0x${string}`, |
| 123 | value: BigInt(a.value), |
| 124 | validAfter: BigInt(a.validAfter), |
| 125 | validBefore: BigInt(a.validBefore), |
| 126 | nonce: a.nonce, |
| 127 | }, |
| 128 | signature: payload.payload.signature, |
| 129 | }); |
| 130 | expect(valid).toBe(true); |
| 131 | |
| 132 | expect(receipt!.status).toBe("delivered"); |
| 133 | expect(receipt!.txHash).toBe("0xdeadbeef"); |
| 134 | expect(receipt!.priceUsdMicro).toBe(10_000n); // $0.01 |
| 135 | expect(engine.spentLabel()).toBe("$0.01"); |
| 136 | }); |
| 137 | |
| 138 | it("records the payment before it is sent, so a signature is never off-ledger", async () => { |
| 139 | const engine = freshEngine(); |
| 140 | await engine.fetch(new Request(`${base}/a`), "https://reader.example"); |
| 141 | expect(engine.ledger.all()).toHaveLength(1); |
| 142 | expect(engine.ledger.totalUsdMicro()).toBe(10_000n); |
| 143 | }); |
| 144 | }); |
| 145 | |
| 146 | describe("hostile resource server", () => { |
| 147 | it("clamps a server that asks for a year-long authorization window", async () => { |
| 148 | const engine = freshEngine(); |
| 149 | opts.maxTimeoutSeconds = 31_536_000; // one year |
| 150 | |
| 151 | await engine.fetch(new Request(`${base}/greedy`), "https://reader.example"); |
| 152 | |
| 153 | const a = received[0]!.payload.authorization; |
| 154 | const lifetime = Number(a.validBefore) - Math.floor(Date.now() / 1000); |
| 155 | // Must be bounded by our clamp (120s), not the server's year. |
| 156 | expect(lifetime).toBeLessThanOrEqual(DEFAULT_LIMITS.maxAuthorizationLifetimeSeconds); |
| 157 | expect(lifetime).toBeGreaterThan(0); |
| 158 | }); |
| 159 | |
| 160 | it("ignores the server's EIP-712 domain and signs over the pinned one", async () => { |
| 161 | const engine = freshEngine(); |
| 162 | // Server lies about the domain, hoping we sign something other than what we think. |
| 163 | opts.extra = { assetTransferMethod: "eip3009", name: "Totally Not USDC", version: "99" }; |
| 164 | |
| 165 | await engine.fetch(new Request(`${base}/liar`), "https://reader.example"); |
| 166 | |
| 167 | const asset = lookupAsset(NETWORK, USDC)!; |
| 168 | const a = received[0]!.payload.authorization; |
| 169 | const valid = await verifyTypedData({ |
| 170 | address: account.address, |
| 171 | domain: domainFor(asset), // the PINNED domain |
| 172 | types: AUTHORIZATION_TYPES, |
| 173 | primaryType: "TransferWithAuthorization", |
| 174 | message: { |
| 175 | from: a.from as `0x${string}`, |
| 176 | to: a.to as `0x${string}`, |
| 177 | value: BigInt(a.value), |
| 178 | validAfter: BigInt(a.validAfter), |
| 179 | validBefore: BigInt(a.validBefore), |
| 180 | nonce: a.nonce, |
| 181 | }, |
| 182 | signature: received[0]!.payload.signature, |
| 183 | }); |
| 184 | expect(valid).toBe(true); |
| 185 | }); |
| 186 | |
| 187 | it("refuses to pay in an asset it cannot price", async () => { |
| 188 | const engine = freshEngine(); |
| 189 | opts.asset = "0x1111111111111111111111111111111111111111"; // scam token |
| 190 | |
| 191 | const { response, receipt, declined } = await engine.fetch( |
| 192 | new Request(`${base}/scam`), |
| 193 | "https://reader.example", |
| 194 | ); |
| 195 | |
| 196 | expect(response.status).toBe(402); // we hand back the original 402 |
| 197 | expect(receipt).toBeUndefined(); |
| 198 | expect(received).toHaveLength(0); // nothing was ever signed |
| 199 | expect(declined).toContain("unknown asset"); |
| 200 | }); |
| 201 | |
| 202 | it("survives a drain attempt: 1000 tiny 402s hit the rate cap", async () => { |
| 203 | const engine = freshEngine({ ...DEFAULT_LIMITS, maxPaymentsPerPairPerWindow: 25 }); |
| 204 | opts.amount = "1"; // 0.000001 USDC — trivially under any amount threshold |
| 205 | |
| 206 | let paid = 0; |
| 207 | let blocked = 0; |
| 208 | for (let i = 0; i < 1000; i++) { |
| 209 | const r = await engine.fetch(new Request(`${base}/drain/${i}`), "https://hostile.example"); |
| 210 | if (r.receipt) paid++; |
| 211 | else blocked++; |
| 212 | } |
| 213 | |
| 214 | // An amount-only budget would have let all 1000 through (1000 * $0.000001 = $0.001). |
| 215 | expect(paid).toBe(25); |
| 216 | expect(blocked).toBe(975); |
| 217 | }); |
| 218 | }); |
| 219 | |
| 220 | describe("policy", () => { |
| 221 | it("prompts above the auto-approve threshold instead of silently paying", async () => { |
| 222 | const prompts: string[] = []; |
| 223 | received = []; |
| 224 | opts = { amount: "1000000" }; // $1.00, well over the $0.05 auto threshold |
| 225 | |
| 226 | const engine = new X402Engine({ |
| 227 | account, |
| 228 | policy: new PolicyEngine(DEFAULT_LIMITS), |
| 229 | approve: async req => { |
| 230 | prompts.push(req.reason); |
| 231 | return true; |
| 232 | }, |
| 233 | }); |
| 234 | |
| 235 | const { receipt } = await engine.fetch(new Request(`${base}/pricey`), "https://reader.example"); |
| 236 | expect(prompts).toHaveLength(1); |
| 237 | expect(prompts[0]).toContain("$1.00"); |
| 238 | expect(receipt!.priceUsdMicro).toBe(1_000_000n); |
| 239 | }); |
| 240 | |
| 241 | it("does not sign when the user declines the prompt", async () => { |
| 242 | const engine = freshEngine(); // approve => false |
| 243 | opts.amount = "1000000"; |
| 244 | |
| 245 | const { receipt, declined } = await engine.fetch( |
| 246 | new Request(`${base}/pricey`), |
| 247 | "https://reader.example", |
| 248 | ); |
| 249 | expect(receipt).toBeUndefined(); |
| 250 | expect(received).toHaveLength(0); |
| 251 | expect(declined).toContain("declined by user"); |
| 252 | }); |
| 253 | }); |