@celo/buy-gateway 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # @celo/buy-gateway
2
+
3
+ Declarative x402 paywall gateway for Celo stablecoin payments.
4
+
5
+ Turns a YAML configuration file (`paywall.yml`) into an authenticated HTTP proxy server that intercepts requests, returns `402 Payment Required` challenges, verifies EIP-3009 transfer authorizations (and optional Self.xyz KYC proofs), settles payments on Celo, and proxies requests upstream.
6
+
7
+ ## Features
8
+
9
+ - **Multi-Service Routing:** Route distinct path prefixes to different upstream backends (e.g. Alchemy, Dune, custom AI backends).
10
+ - **Prefix Stripping (`stripPrefix`):** Map `/alchemy/v1/query` to upstream `/v1/query`.
11
+ - **Granular Rate Limiting:** Enforce token-bucket rate limits per client IP (`scope: ip`), per paying wallet (`scope: payer`), or per upstream provider (`scope: service`).
12
+ - **HTTP Method & Body Caps:** Restrict permitted HTTP verbs (`methods: [GET, POST]`) and enforce maximum body payloads (`maxBodyBytes`).
13
+ - **Soft-KYC Gates:** Cross-bind payment signatures to Self.xyz zero-knowledge passport proofs (`scope`, `minimumAge`, `ofac`, `excludedCountries`).
14
+
15
+ ## Configuration Reference
16
+
17
+ ```yaml
18
+ name: my-gateway
19
+ version: 1
20
+ network: celo-sepolia
21
+ payTo: "0x0000000000000000000000000000000000C0FFEE"
22
+
23
+ # Behind a reverse proxy (Cloud Run, an ALB, Cloudflare), set this so IP-scoped
24
+ # limits key on the address the proxy appended to X-Forwarded-For — the LAST
25
+ # entry — rather than on the proxy's own address, which every caller would
26
+ # share. Leave it unset when the gateway is reached directly: with it set, a
27
+ # client-supplied X-Forwarded-For would be believed.
28
+ trustProxy: true
29
+
30
+ # Global rate limit across all incoming requests. Runs before any payment is
31
+ # read, so its only enforceable scope is `ip`.
32
+ rateLimit:
33
+ scope: ip
34
+ requestsPerMinute: 300
35
+ burst: 50
36
+
37
+ # Named Upstream Services
38
+ services:
39
+ alchemy:
40
+ mode: proxy
41
+ upstream: https://eth-sepolia.g.alchemy.com
42
+ timeoutMs: 10000
43
+ injectHeaders:
44
+ Authorization: ALCHEMY_API_KEY
45
+ rateLimit:
46
+ scope: service
47
+ requestsPerMinute: 120
48
+ burst: 20
49
+
50
+ dune:
51
+ mode: proxy
52
+ upstream: https://api.dune.com
53
+ timeoutMs: 30000
54
+ injectHeaders:
55
+ X-DUNE-API-KEY: DUNE_API_KEY
56
+ rateLimit:
57
+ scope: payer
58
+ requestsPerMinute: 30
59
+
60
+ mock-ai:
61
+ mode: respond
62
+ contentType: application/json
63
+ body: '{"status":"ok","output":"Synthetic model output"}'
64
+
65
+ # Endpoints & Allowlist
66
+ endpoints:
67
+ - path: /healthz
68
+ service: mock-ai
69
+ free: true
70
+ restrictions:
71
+ methods: [GET]
72
+
73
+ - path: /alchemy/*
74
+ service: alchemy
75
+ stripPrefix: /alchemy
76
+ price: 0.001 USDC
77
+ restrictions:
78
+ methods: [POST, GET]
79
+ maxBodyBytes: 32768
80
+
81
+ - path: /dune/*
82
+ service: dune
83
+ stripPrefix: /dune
84
+ price: 0.05 USDC
85
+ self:
86
+ scope: buy-dune
87
+ minimumAge: 18
88
+ ofac: true
89
+ ```
90
+
91
+ ### Where each `rateLimit.scope` is enforced
92
+
93
+ A scope is only accepted where the server consults it; anywhere else the config
94
+ is refused at boot rather than silently ignored.
95
+
96
+ | level | `ip` | `payer` | `service` |
97
+ |---|---|---|---|
98
+ | top-level `rateLimit` | ✓ | — | — |
99
+ | `services.<name>.rateLimit` (and `routing.rateLimit`) | ✓ | ✓ (priced endpoints only) | ✓ |
100
+ | endpoint `rateLimit` (priced) | ✓ | ✓ | — |
101
+ | endpoint `rateLimit` (`free: true`) | ✓ | — | — |
102
+
103
+ `ip` limits count every request, including the unpaid 402 probe, so a priced
104
+ endpoint with `burst: 1` can never be bought: the probe spends the token and the
105
+ paid retry is refused. Size `burst` for probe + retry.
106
+
107
+ A service-level `payer` limit is consulted after payment verification, so a
108
+ service with a `free: true` endpoint cannot carry one: it is refused at boot
109
+ rather than silently letting free calls through.
110
+
111
+ `service` limits count only requests that reach the upstream — a free one when
112
+ it is served, a paid one after verification and before settlement (a refusal
113
+ there hands the payer's nonce back, so the same signed payment can be retried).
114
+ The 402 probe does not count: it never reaches the upstream, and a bucket it
115
+ could drain would let anyone throttle every paying customer without paying.
116
+
117
+ ### Two things the protocol does not do
118
+
119
+ **A payment is not bound to the endpoint it was quoted for.** EIP-3009 signs the
120
+ payer, payee, amount and nonce — not the resource. Verification checks the
121
+ same fields. So two endpoints on the same network, token, payee and price are
122
+ interchangeable: a challenge obtained at one can be paid at the other. Price is
123
+ the only thing that separates a cheap service from an expensive one; give them
124
+ different prices if that matters.
125
+
126
+ **Settlement precedes the upstream call.** That is the x402 contract — pay, then
127
+ serve — so an upstream that is down after settlement still costs the payer. The
128
+ gateway returns the transaction and `X-PAYMENT-RESPONSE` on that 502/504 so
129
+ there is something to reconcile with. `buy gate` probes every proxy service's
130
+ upstream with that service's own `injectHeaders` at boot, so a stale key is a
131
+ boot-time refusal naming the header rather than a paid 401.
132
+
package/dist/config.d.ts CHANGED
@@ -13,9 +13,16 @@
13
13
  * mean an endpoint served free, so unknown keys are errors rather than being
14
14
  * dropped.
15
15
  */
16
+ import type { RateLimitConfig } from './rate-limit.js';
16
17
  /** Atomic units per whole token. USDC, USDT and USAT all use 6 decimals on Celo. */
17
18
  export declare const DECIMALS = 6;
18
19
  export type EndpointScheme = 'exact' | 'upto';
20
+ export type EndpointRestrictions = {
21
+ /** Allowed HTTP methods (e.g. ['GET', 'POST']). Uppercased. */
22
+ methods?: string[];
23
+ /** Maximum allowed request body size in bytes. */
24
+ maxBodyBytes?: number;
25
+ };
19
26
  export type EndpointConfig = {
20
27
  /** Path pattern: literal, or literal prefix ending in `/*`. */
21
28
  path: string;
@@ -37,6 +44,17 @@ export type EndpointConfig = {
37
44
  description: string;
38
45
  /** Optional Self.xyz gate for this endpoint. */
39
46
  self?: SelfGateConfig;
47
+ /** Optional named service that handles this endpoint (from `services` map). */
48
+ service?: string;
49
+ /**
50
+ * Optional prefix to strip before proxying upstream.
51
+ * E.g. with path `/alchemy/v1/*` and stripPrefix `/alchemy`, `/alchemy/v1/data` becomes `/v1/data`.
52
+ */
53
+ stripPrefix?: string;
54
+ /** Optional rate limit for this endpoint. */
55
+ rateLimit?: RateLimitConfig;
56
+ /** Optional restrictions on HTTP methods or payload body sizes. */
57
+ restrictions?: EndpointRestrictions;
40
58
  };
41
59
  export type SelfGateConfig = {
42
60
  scope: string;
@@ -53,6 +71,17 @@ export type SelfGateConfig = {
53
71
  endpoint?: string;
54
72
  endpointType?: 'https' | 'staging_https' | 'celo' | 'staging_celo';
55
73
  };
74
+ /**
75
+ * Methods fetch() will forward. It refuses TRACE, TRACK and CONNECT outright,
76
+ * so listing one would challenge, settle, and then fail at the upstream call.
77
+ */
78
+ export declare const FORWARDABLE_METHODS: string[];
79
+ /**
80
+ * What a header VALUE may contain: visible ASCII, space and tab, obs-text.
81
+ * `Headers.set` and `res.writeHead` throw on anything else — a CR/LF above
82
+ * all — and in this gateway that throw would land after settlement.
83
+ */
84
+ export declare function isHeaderValue(value: string): boolean;
56
85
  /**
57
86
  * Headers that frame the connection rather than describe the request.
58
87
  *
@@ -62,23 +91,45 @@ export type SelfGateConfig = {
62
91
  * list — letting config set it would let config decide what gets dropped.
63
92
  */
64
93
  export declare const PROTECTED_HEADERS: ReadonlySet<string>;
65
- export type RoutingConfig = {
94
+ export type ServiceConfig = {
66
95
  mode: 'respond';
67
96
  body: string;
68
97
  contentType: string;
98
+ rateLimit?: RateLimitConfig;
69
99
  } | {
70
100
  mode: 'proxy';
71
101
  upstream: string;
72
102
  /** Header name → env var holding its value. Resolved at boot, not per-request. */
73
103
  injectHeaders: Record<string, string>;
104
+ /**
105
+ * Where the boot-time credential check sends its request. Defaults to a
106
+ * GET of the origin, which proves the credential is accepted anywhere the
107
+ * origin authenticates — but some providers (Google) only look at the key
108
+ * on a real API path, and answer the origin 404 for any key at all.
109
+ */
110
+ probe?: {
111
+ path: string;
112
+ method: string;
113
+ };
114
+ /** Upstream request timeout in milliseconds. Defaults to 30000ms. */
115
+ timeoutMs?: number;
116
+ rateLimit?: RateLimitConfig;
74
117
  };
118
+ export type RoutingConfig = ServiceConfig;
75
119
  export type PaywallConfig = {
76
120
  name: string;
77
121
  version: 1;
78
122
  network: 'celo' | 'celo-sepolia';
79
123
  /** Address that receives payment. */
80
124
  payTo: string;
81
- routing: RoutingConfig;
125
+ /** Whether the gateway is deployed behind a trusted reverse proxy (e.g. Cloud Run, ALB, Cloudflare). */
126
+ trustProxy?: boolean;
127
+ /** Global rate limit applied at the gateway boundary across all unauthenticated requests. */
128
+ rateLimit?: RateLimitConfig;
129
+ /** Legacy single-upstream routing block (version 1 or default service). */
130
+ routing?: RoutingConfig;
131
+ /** Named upstream services for multi-service routing. */
132
+ services?: Record<string, ServiceConfig>;
82
133
  endpoints: EndpointConfig[];
83
134
  /**
84
135
  * Token symbols every priced endpoint is offered in, at that endpoint's
@@ -104,6 +155,15 @@ export declare function parsePrice(raw: string, at: string): {
104
155
  amount: string;
105
156
  currency: string;
106
157
  };
158
+ /**
159
+ * Which scopes a limit may take depends on where it sits, and a scope the
160
+ * server never consults must be refused here rather than accepted: an
161
+ * endpoint `scope: service` used to parse, build a limiter, and enforce
162
+ * nothing, which is the "silently ignored" failure this file exists to rule
163
+ * out — on the one key whose whole job is to cap spend against an upstream.
164
+ */
165
+ export declare function parseRateLimit(raw: unknown, at: string, allowed?: readonly RateLimitConfig['scope'][]): RateLimitConfig;
166
+ export declare function parseService(raw: unknown, at: string): ServiceConfig;
107
167
  /** Parse and validate a paywall config from YAML source. */
108
168
  export declare function parseConfig(source: string): PaywallConfig;
109
169
  /**