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

0 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 site icons (favicons) in tabs, address bar suggestions and the bookmarks panel 7249579 15 hours, 58 minutes ago History
wire.ts · 1.9 KB · 48 lines
1/** HTTP binding for x402. v2 uses headers; v1 put requirements in the body. */
2
3import type { PaymentPayload, PaymentRequired, SettlementResponse } from "./types.js";
4
5const b64encode = (o: unknown) => Buffer.from(JSON.stringify(o), "utf8").toString("base64");
6const b64decode = <T>(s: string): T => JSON.parse(Buffer.from(s, "base64").toString("utf8")) as T;
7
8export type HeaderGetter = (name: string) => string | null | undefined;
9
10/**
11 * Parse a 402 into PaymentRequired. Prefers v2's PAYMENT-REQUIRED header,
12 * falls back to a v1 JSON body. Returns null if this 402 isn't x402 at all
13 * (plenty of servers return a bare 402 that means nothing).
14 */
15export function parsePaymentRequired(getHeader: HeaderGetter, body?: unknown): PaymentRequired | null {
16 const h = getHeader("payment-required");
17 if (h) {
18 const pr = b64decode<PaymentRequired>(h);
19 if (!Array.isArray(pr.accepts)) throw new Error("PAYMENT-REQUIRED missing accepts[]");
20 return pr;
21 }
22 if (body && typeof body === "object" && "x402Version" in body && "accepts" in body) {
23 return body as PaymentRequired;
24 }
25 return null;
26}
27
28/** Encode the signed payload into the right header for the negotiated version. */
29export function encodePaymentSignature(payload: PaymentPayload): Record<string, string> {
30 const encoded = b64encode(payload);
31 return payload.x402Version >= 2
32 ? { "PAYMENT-SIGNATURE": encoded }
33 : { "X-PAYMENT": encoded, "Access-Control-Expose-Headers": "X-PAYMENT-RESPONSE" };
34}
35
36/** Settlement receipt, if the server sent one. Absence is not an error. */
37export function parseSettlement(getHeader: HeaderGetter): SettlementResponse | null {
38 const h = getHeader("payment-response") ?? getHeader("x-payment-response");
39 if (!h) return null;
40 try {
41 return b64decode<SettlementResponse>(h);
42 } catch {
43 return null;
44 }
45}
46
47export const encodePaymentRequired = b64encode;
48export const encodeSettlement = b64encode;