A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.

9 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-browser.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-browser.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-browser.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 toolbar: Back and Forward are greyed out when there's nowhere to go cc08c7a 1 week, 2 days ago History
engine.ts · 5.9 KB · 165 lines
1/**
2 * The pay-and-retry orchestrator.
3 *
4 * Deliberately depends on nothing but `fetch`. The Electron `protocol.handle()` hook
5 * and the local proxy are both thin adapters over this, which means the payment path
6 * a user's browser takes is byte-for-byte the one the agent runtime takes, and both
7 * are testable headlessly with no browser at all.
8 */
9
10import type { LocalAccount } from "viem";
11import { formatUsd } from "./assets.js";
12import { Ledger, type Receipt } from "./ledger.js";
13import { PolicyEngine, type PolicyContext, type Verdict } from "./policy.js";
14import { quoteFrom, signExactEvm } from "./schemes/exact-evm.js";
15import type { Quote } from "./types.js";
16import { encodePaymentSignature, parsePaymentRequired, parseSettlement } from "./wire.js";
17
18export interface PromptRequest {
19 quote: Quote;
20 ctx: PolicyContext;
21 resourceUrl: string;
22 reason: string;
23}
24
25/** Ask the human. Return true to pay once. The browser wires this to the URL-bar prompt. */
26export type Approver = (req: PromptRequest) => Promise<boolean>;
27
28export interface EngineOptions {
29 account: LocalAccount;
30 policy?: PolicyEngine;
31 ledger?: Ledger;
32 approve?: Approver;
33 fetchImpl?: typeof fetch;
34 onEvent?: (e: EngineEvent) => void;
35}
36
37export type EngineEvent =
38 | { type: "quoted"; resourceUrl: string; quotes: Quote[]; rejected: string[] }
39 | { type: "decided"; resourceUrl: string; verdict: Verdict; quote: Quote }
40 | { type: "paid"; receipt: Receipt }
41 | { type: "skipped"; resourceUrl: string; reason: string };
42
43export interface PayResult {
44 response: Response;
45 receipt?: Receipt;
46 /** Set when we saw an x402 challenge but chose not to (or could not) pay it. */
47 declined?: string;
48}
49
50export class X402Engine {
51 readonly policy: PolicyEngine;
52 readonly ledger: Ledger;
53 private readonly account: LocalAccount;
54 private readonly approve: Approver;
55 private readonly fetchImpl: typeof fetch;
56 private readonly onEvent: (e: EngineEvent) => void;
57
58 constructor(opts: EngineOptions) {
59 this.account = opts.account;
60 this.policy = opts.policy ?? new PolicyEngine();
61 this.ledger = opts.ledger ?? new Ledger();
62 this.approve = opts.approve ?? (async () => false);
63 this.fetchImpl = opts.fetchImpl ?? fetch;
64 this.onEvent = opts.onEvent ?? (() => {});
65 }
66
67 /**
68 * Issue a request; if it comes back 402 with an x402 challenge, pay and retry once.
69 * Never retries more than once — a server that 402s the paid request is either
70 * broken or trying to bill twice, and neither deserves a second signature.
71 */
72 async fetch(request: Request, topOrigin = ""): Promise<PayResult> {
73 const first = await this.fetchImpl(request.clone());
74 if (first.status !== 402) return { response: first };
75
76 // A 402 body may be a v1 challenge, so we have to read it — but only if it's JSON,
77 // and we must not consume a body we might need to hand back to the caller.
78 const probe = first.clone();
79 let body: unknown;
80 if (probe.headers.get("content-type")?.includes("json")) {
81 body = await probe.json().catch(() => undefined);
82 }
83
84 const challenge = parsePaymentRequired(n => first.headers.get(n), body);
85 if (!challenge) return { response: first, declined: "402 without an x402 challenge" };
86
87 const resourceUrl = challenge.resource?.url ?? request.url;
88 const destOrigin = new URL(request.url).origin;
89 const ctx: PolicyContext = { topOrigin, destOrigin };
90
91 const { quotes, rejected } = quoteFrom(challenge);
92 this.onEvent({ type: "quoted", resourceUrl, quotes, rejected });
93
94 if (quotes.length === 0) {
95 const why = `no payable option (${rejected.join("; ") || "empty accepts[]"})`;
96 this.onEvent({ type: "skipped", resourceUrl, reason: why });
97 return { response: first, declined: why };
98 }
99
100 // Cheapest wins. The server orders `accepts` in its own interest, not ours.
101 const quote = quotes.reduce((a, b) => (b.priceUsdMicro < a.priceUsdMicro ? b : a));
102
103 const verdict = this.policy.evaluate(quote, ctx);
104 this.onEvent({ type: "decided", resourceUrl, verdict, quote });
105
106 if (verdict.action === "deny") {
107 this.onEvent({ type: "skipped", resourceUrl, reason: verdict.reason });
108 return { response: first, declined: verdict.reason };
109 }
110 if (verdict.action === "prompt") {
111 const ok = await this.approve({ quote, ctx, resourceUrl, reason: verdict.reason });
112 if (!ok) {
113 const why = `declined by user (${verdict.reason})`;
114 this.onEvent({ type: "skipped", resourceUrl, reason: why });
115 return { response: first, declined: why };
116 }
117 }
118
119 const payload = await signExactEvm(this.account, quote, {
120 maxAuthorizationLifetimeSeconds: this.policy.limits.maxAuthorizationLifetimeSeconds,
121 });
122
123 // Record before sending: once the signature leaves us, the money is exposed
124 // regardless of what comes back.
125 const receipt = this.ledger.open({
126 quote,
127 topOrigin,
128 destOrigin,
129 resourceUrl,
130 requestedUrl: request.url,
131 authorization: payload.payload.authorization,
132 signature: payload.payload.signature,
133 });
134 this.policy.record(quote, ctx);
135
136 const retry = new Request(request.clone(), {
137 headers: mergeHeaders(request.headers, encodePaymentSignature(payload)),
138 });
139
140 let paid: Response;
141 try {
142 paid = await this.fetchImpl(retry);
143 } catch (e) {
144 this.ledger.fail(receipt.id, `retry failed: ${String(e)}`);
145 throw e;
146 }
147
148 const settlement = parseSettlement(n => paid.headers.get(n));
149 this.ledger.settle(receipt.id, settlement, paid.ok);
150 this.onEvent({ type: "paid", receipt });
151
152 return { response: paid, receipt };
153 }
154
155 /** What the URL bar shows: total spent in the current window. */
156 spentLabel(): string {
157 return formatUsd(this.policy.spentUsdMicro());
158 }
159}
160
161function mergeHeaders(base: Headers, extra: Record<string, string>): Headers {
162 const h = new Headers(base);
163 for (const [k, v] of Object.entries(extra)) h.set(k, v);
164 return h;
165}