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
wire.ts · 1.9 KB · 48 lines
| 1 | /** HTTP binding for x402. v2 uses headers; v1 put requirements in the body. */ |
| 2 | |
| 3 | import type { PaymentPayload, PaymentRequired, SettlementResponse } from "./types.js"; |
| 4 | |
| 5 | const b64encode = (o: unknown) => Buffer.from(JSON.stringify(o), "utf8").toString("base64"); |
| 6 | const b64decode = <T>(s: string): T => JSON.parse(Buffer.from(s, "base64").toString("utf8")) as T; |
| 7 | |
| 8 | export 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 | */ |
| 15 | export 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. */ |
| 29 | export 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. */ |
| 37 | export 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 | |
| 47 | export const encodePaymentRequired = b64encode; |
| 48 | export const encodeSettlement = b64encode; |