satsgate-proxy 0.14.1__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ """Self-hosted reverse proxy that sells an existing HTTP API with L402."""
2
+
3
+ __version__ = "0.14.1"
@@ -0,0 +1,48 @@
1
+ """Run the proxy: ``python -m satsgate_proxy --config satsgate-proxy.yaml``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import os
8
+ import sys
9
+
10
+ import uvicorn
11
+
12
+ from satsgate_proxy import __version__
13
+ from satsgate_proxy.app import build_app
14
+ from satsgate_proxy.config import ConfigError, key_fingerprint, load_settings
15
+
16
+
17
+ def main(argv: list[str] | None = None) -> None:
18
+ parser = argparse.ArgumentParser(description="satsgate-proxy")
19
+ parser.add_argument(
20
+ "--config",
21
+ default=os.environ.get("SATSGATE_PROXY_CONFIG", "satsgate-proxy.yaml"),
22
+ help="Path to the YAML config. Defaults to SATSGATE_PROXY_CONFIG or ./satsgate-proxy.yaml.",
23
+ )
24
+ args = parser.parse_args(argv)
25
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
26
+ try:
27
+ settings = load_settings(args.config)
28
+ except ConfigError as exc:
29
+ print(f"satsgate-proxy: {exc}", file=sys.stderr)
30
+ raise SystemExit(2) from exc
31
+ log = logging.getLogger("satsgate_proxy")
32
+ names = ", ".join(name for name, _value in settings.inject_headers)
33
+ log.info(
34
+ "satsgate-proxy %s listen %s:%s core %s key fp %s upstream %s routes %s inject [%s]",
35
+ __version__,
36
+ settings.host,
37
+ settings.port,
38
+ settings.core_base_url,
39
+ key_fingerprint(settings.api_key),
40
+ settings.upstream_base_url,
41
+ len(settings.routes),
42
+ names,
43
+ )
44
+ uvicorn.run(build_app(settings), host=settings.host, port=settings.port, log_level="info")
45
+
46
+
47
+ if __name__ == "__main__":
48
+ main()
satsgate_proxy/app.py ADDED
@@ -0,0 +1,400 @@
1
+ """ASGI app. Unpaid requests get a 402. A credit is taken only after the origin returns 2xx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from collections.abc import AsyncIterator
8
+ from contextlib import asynccontextmanager
9
+
10
+ import httpx
11
+ from starlette.applications import Starlette
12
+ from starlette.requests import Request
13
+ from starlette.responses import JSONResponse, Response
14
+ from starlette.routing import Route
15
+
16
+ from satsgate_proxy import __version__
17
+ from satsgate_proxy.client_ip import buyer_ip_for_core
18
+ from satsgate_proxy.config import Route as PayRoute
19
+ from satsgate_proxy.config import Settings
20
+ from satsgate_proxy.core_client import (
21
+ CoreResult,
22
+ charge_lightning,
23
+ create_challenge,
24
+ settle_x402,
25
+ unlock_with_preimage,
26
+ unlock_without_preimage,
27
+ verify_x402,
28
+ )
29
+ from satsgate_proxy.forward import call_upstream, forward
30
+ from satsgate_proxy.macaroon import macaroon_fields
31
+ from satsgate_proxy.match import match_request
32
+
33
+ log = logging.getLogger("satsgate_proxy")
34
+
35
+ _PAYMENT_SIGNATURE_MAX = 8192
36
+
37
+ _METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
38
+ _POLL_HINT = (
39
+ "Pay the invoice, then retry with Authorization: L402 <macaroon>:<preimage>. "
40
+ "If the wallet does not return a preimage, retry with Authorization: L402 <macaroon> "
41
+ "and this proxy will poll until the invoice settles."
42
+ )
43
+ _PENDING_HINT = (
44
+ "The invoice is not settled yet. Retry the same Authorization header. Do not pay a new invoice."
45
+ )
46
+
47
+
48
+ def _json(status: int, error: str, **extra: object) -> JSONResponse:
49
+ headers = {"Cache-Control": "no-store"}
50
+ retry = extra.get("retry_after_seconds")
51
+ if isinstance(retry, int):
52
+ headers["Retry-After"] = str(retry)
53
+ return JSONResponse({"ok": False, "error": error, **extra}, status_code=status, headers=headers)
54
+
55
+
56
+ async def _read_body(request: Request, limit: int) -> bytes | JSONResponse:
57
+ declared = request.headers.get("content-length")
58
+ if declared is not None:
59
+ try:
60
+ size = int(declared)
61
+ except ValueError:
62
+ return _json(400, "invalid_content_length")
63
+ if size > limit:
64
+ return _json(413, "request_too_large")
65
+ chunks = bytearray()
66
+ async for chunk in request.stream():
67
+ if len(chunks) + len(chunk) > limit:
68
+ return _json(413, "request_too_large")
69
+ chunks.extend(chunk)
70
+ return bytes(chunks)
71
+
72
+
73
+ def _payment_signature(request: Request) -> str | None:
74
+ if "payment-signature" not in request.headers:
75
+ return None
76
+ return request.headers.get("payment-signature", "").strip()
77
+
78
+
79
+ def _l402_authorization(request: Request) -> str | None:
80
+ raw = request.headers.get("authorization")
81
+ if not raw:
82
+ return None
83
+ scheme = raw.split(None, 1)[0].lower()
84
+ if scheme in {"l402", "lsat"}:
85
+ return raw.strip()
86
+ return None
87
+
88
+
89
+ def _split_token(header: str) -> tuple[str, str | None]:
90
+ try:
91
+ _scheme, token = header.split(None, 1)
92
+ except ValueError as exc:
93
+ raise ValueError("malformed Authorization header") from exc
94
+ token = token.strip()
95
+ if ":" in token:
96
+ macaroon, preimage = token.split(":", 1)
97
+ else:
98
+ macaroon, preimage = token, ""
99
+ if not macaroon or any(char.isspace() for char in macaroon):
100
+ raise ValueError("malformed L402 token")
101
+ if preimage == "":
102
+ return macaroon, None
103
+ try:
104
+ raw = bytes.fromhex(preimage)
105
+ except ValueError as exc:
106
+ raise ValueError("preimage is not hex") from exc
107
+ if len(raw) != 32:
108
+ raise ValueError("preimage is not hex")
109
+ return macaroon, preimage.lower()
110
+
111
+
112
+ def _peer(request: Request) -> str:
113
+ client = request.client
114
+ if client is None or not client.host:
115
+ return "unknown"
116
+ return client.host
117
+
118
+
119
+ def _challenge_response(result: CoreResult, reason: str | None, route: PayRoute) -> JSONResponse:
120
+ challenge = result.challenge
121
+ if challenge is None:
122
+ return _json(502, "paywall_unavailable")
123
+ max_uses, access_seconds = route.access.policy()
124
+ body: dict[str, object] = {
125
+ "ok": False,
126
+ "error": "payment_required",
127
+ "amount_sats": challenge.amount_sats,
128
+ "payment_hash": challenge.payment_hash,
129
+ "invoice": challenge.invoice,
130
+ "invoice_expires_at": challenge.invoice_expires_at,
131
+ "macaroon": challenge.macaroon,
132
+ "resource": challenge.resource,
133
+ "max_uses": max_uses,
134
+ "access_seconds": access_seconds,
135
+ "hint": _POLL_HINT,
136
+ }
137
+ if reason:
138
+ body["reason"] = reason
139
+ headers = {"Cache-Control": "no-store"}
140
+ if challenge.www_authenticate:
141
+ headers["WWW-Authenticate"] = challenge.www_authenticate
142
+ if challenge.offers_x402 and challenge.x402 is not None:
143
+ body["x402"] = challenge.x402
144
+ if "testing" in challenge.x402:
145
+ body["testing"] = challenge.x402["testing"]
146
+ if "x402_mode" in challenge.x402:
147
+ body["x402_mode"] = challenge.x402["x402_mode"]
148
+ headers["PAYMENT-REQUIRED"] = challenge.payment_required
149
+ return JSONResponse(body, status_code=402, headers=headers)
150
+
151
+
152
+ def _x402_failure(result: CoreResult) -> JSONResponse:
153
+ code = result.error
154
+ status = result.http_status
155
+ if result.action == "rejected" and status in {400, 402, 409} and code.isidentifier():
156
+ extra: dict[str, object] = {}
157
+ if result.reason:
158
+ extra["reason"] = result.reason
159
+ return _json(status, code, **extra)
160
+ return _json(502, "paywall_unavailable")
161
+
162
+
163
+ def _limited(result: CoreResult) -> JSONResponse:
164
+ retry = result.retry_after if result.retry_after is not None else 1
165
+ return _json(429, result.error or "rate_limited", retry_after_seconds=retry)
166
+
167
+
168
+ def _pending(result: CoreResult) -> JSONResponse:
169
+ retry = result.retry_after if result.retry_after is not None else 1
170
+ body: dict[str, object] = {
171
+ "ok": False,
172
+ "error": "payment_pending",
173
+ "retry_after_seconds": retry,
174
+ "hint": _PENDING_HINT,
175
+ }
176
+ if result.payment_hash:
177
+ body["payment_hash"] = result.payment_hash
178
+ return JSONResponse(body, status_code=402, headers={"Retry-After": str(retry)})
179
+
180
+
181
+ async def _unlock(request: Request, settings: Settings, route: PayRoute, header: str) -> CoreResult:
182
+ client: httpx.AsyncClient = request.app.state.http
183
+ try:
184
+ macaroon, preimage = _split_token(header)
185
+ except ValueError as exc:
186
+ return CoreResult(action="fresh", error=str(exc))
187
+ fields = macaroon_fields(macaroon)
188
+ if fields is not None and fields.get("res") and fields["res"] != route.resource:
189
+ return CoreResult(action="fresh", error="resource mismatch")
190
+ if preimage is None:
191
+ if fields is None or "ph" not in fields:
192
+ return CoreResult(action="fresh", error="invalid macaroon")
193
+ scheme = header.split(None, 1)[0]
194
+ return await unlock_without_preimage(
195
+ client,
196
+ settings,
197
+ route,
198
+ authorization=f"{scheme} {macaroon}",
199
+ payment_hash=fields["ph"],
200
+ )
201
+ return await unlock_with_preimage(client, settings, route, header)
202
+
203
+
204
+ async def _pay_x402(request: Request, settings: Settings, route: PayRoute, payment_signature: str) -> Response:
205
+ """Verify, call the origin, and settle only after a 2xx. The proxy never calls the facilitator."""
206
+ client: httpx.AsyncClient = request.app.state.http
207
+ verified = await verify_x402(
208
+ client,
209
+ settings,
210
+ route,
211
+ payment_signature,
212
+ request_path=request.url.path,
213
+ )
214
+ if verified.action != "serve" or verified.amount_usd_atomic is None or not verified.payment_hash:
215
+ return _x402_failure(verified)
216
+ exchanged = await call_upstream(
217
+ request,
218
+ settings,
219
+ payment_hash=verified.payment_hash,
220
+ resource=route.resource,
221
+ paid_usd_atomic=verified.amount_usd_atomic,
222
+ )
223
+ if exchanged.error or not (200 <= exchanged.status < 300):
224
+ return exchanged.response(use_spent=False if exchanged.error else None)
225
+ settled = await settle_x402(
226
+ client,
227
+ settings,
228
+ route,
229
+ payment_signature,
230
+ request_path=request.url.path,
231
+ )
232
+ if settled.action != "settled" or not settled.payment_response:
233
+ return _x402_failure(settled)
234
+ return exchanged.response(use_spent=None, extra=(("PAYMENT-RESPONSE", settled.payment_response),))
235
+
236
+
237
+ async def _serve_lightning(request: Request, settings: Settings, route: PayRoute, authorization: str) -> Response | str | None:
238
+ """Confirm the Lightning payment, call the origin, and charge only on 2xx."""
239
+ unlocked = await _unlock(request, settings, route, authorization)
240
+ if unlocked.action == "pending":
241
+ return _pending(unlocked)
242
+ if unlocked.action == "limited":
243
+ return _limited(unlocked)
244
+ if unlocked.action == "unavailable":
245
+ return _json(502, "paywall_unavailable")
246
+ if unlocked.action != "forward":
247
+ return unlocked.error or None
248
+
249
+ payment_hash = unlocked.payment_hash
250
+ if not payment_hash:
251
+ fields = None
252
+ try:
253
+ macaroon, _preimage = _split_token(authorization)
254
+ fields = macaroon_fields(macaroon)
255
+ except ValueError:
256
+ fields = None
257
+ if fields is not None:
258
+ payment_hash = fields["ph"]
259
+ if not payment_hash:
260
+ log.warning("settled unlock had no payment hash")
261
+ return _json(502, "paywall_unavailable")
262
+ paid = unlocked.amount_sats if unlocked.amount_sats is not None else route.price_sats
263
+ if isinstance(paid, bool) or not isinstance(paid, int) or paid < 1:
264
+ log.warning("settled unlock had no sats amount")
265
+ return _json(502, "paywall_unavailable")
266
+ exchanged = await call_upstream(
267
+ request,
268
+ settings,
269
+ payment_hash=payment_hash.lower(),
270
+ resource=route.resource,
271
+ paid_sats=paid,
272
+ )
273
+ if exchanged.error:
274
+ return exchanged.response(use_spent=False)
275
+ if not (200 <= exchanged.status < 300):
276
+ return exchanged.response(use_spent=None)
277
+ charged = await charge_lightning(
278
+ request.app.state.http,
279
+ settings,
280
+ route,
281
+ authorization=authorization,
282
+ payment_hash=payment_hash.lower(),
283
+ )
284
+ if charged.action == "charged":
285
+ return exchanged.response(use_spent=None)
286
+ if charged.action == "fresh":
287
+ return charged.error or "token_used_up"
288
+ return _json(502, "paywall_unavailable")
289
+
290
+
291
+ async def handle(request: Request) -> Response:
292
+ settings: Settings = request.app.state.settings
293
+ method = request.method.upper()
294
+ path = request.url.path
295
+ if path == "/healthz" and method in {"GET", "HEAD"}:
296
+ if method == "HEAD":
297
+ return Response(status_code=200, media_type="application/json")
298
+ payload = {"ok": True, "component": "satsgate-proxy", "version": __version__}
299
+ return Response(json.dumps(payload).encode("utf-8"), status_code=200, media_type="application/json")
300
+
301
+ body = await _read_body(request, settings.max_request_bytes)
302
+ if isinstance(body, Response):
303
+ return body
304
+ request.state.body = body
305
+
306
+ if settings.mode == "receipt":
307
+ from satsgate_proxy.receipt_mode import handle_receipt
308
+
309
+ return await handle_receipt(request, settings, method, path)
310
+
311
+ found = match_request(settings.routes, settings.free_patterns, method, path)
312
+ if found.kind == "not_found":
313
+ return _json(404, "not_found")
314
+ if found.kind == "method":
315
+ return JSONResponse(
316
+ {"ok": False, "error": "method_not_allowed"},
317
+ status_code=405,
318
+ headers={"Allow": ", ".join(found.allow)},
319
+ )
320
+
321
+ if found.kind == "free":
322
+ return await forward(
323
+ request,
324
+ settings,
325
+ payment_hash=None,
326
+ resource=None,
327
+ paid_sats=None,
328
+ use_spent=False,
329
+ )
330
+
331
+ route = found.route
332
+ if not isinstance(route, PayRoute):
333
+ return _json(404, "not_found")
334
+
335
+ reason: str | None = None
336
+ authorization = _l402_authorization(request)
337
+ payment_signature = _payment_signature(request)
338
+ if authorization is not None and payment_signature is not None:
339
+ return _json(400, "one_rail_only")
340
+ if payment_signature is not None:
341
+ if (
342
+ not payment_signature
343
+ or len(payment_signature.encode("utf-8")) > _PAYMENT_SIGNATURE_MAX
344
+ or any(char in payment_signature for char in "\r\n")
345
+ ):
346
+ return _json(400, "bad_signature")
347
+ return await _pay_x402(request, settings, route, payment_signature)
348
+ if authorization is not None:
349
+ served = await _serve_lightning(request, settings, route, authorization)
350
+ if isinstance(served, Response):
351
+ return served
352
+ reason = served
353
+
354
+ buyer_ip = buyer_ip_for_core(
355
+ peer=_peer(request),
356
+ forwarded_for=request.headers.get("x-forwarded-for"),
357
+ trusted_proxies=settings.trusted_proxies,
358
+ )
359
+ challenge = await create_challenge(
360
+ request.app.state.http,
361
+ settings,
362
+ route,
363
+ buyer_ip,
364
+ request_path=request.url.path,
365
+ )
366
+ if challenge.action == "limited":
367
+ return _limited(challenge)
368
+ if challenge.action != "challenge":
369
+ return _json(502, "paywall_unavailable")
370
+ return _challenge_response(challenge, reason, route)
371
+
372
+
373
+ def build_app(settings: Settings, *, transport: httpx.AsyncBaseTransport | None = None) -> Starlette:
374
+ @asynccontextmanager
375
+ async def lifespan(app: Starlette) -> AsyncIterator[None]:
376
+ timeout = httpx.Timeout(max(settings.core_timeout, settings.upstream_timeout))
377
+ app.state.http = httpx.AsyncClient(
378
+ transport=transport,
379
+ trust_env=False,
380
+ follow_redirects=False,
381
+ timeout=timeout,
382
+ )
383
+ try:
384
+ yield
385
+ finally:
386
+ await app.state.http.aclose()
387
+
388
+ app = Starlette(
389
+ routes=[
390
+ Route("/", handle, methods=_METHODS),
391
+ Route("/{path:path}", handle, methods=_METHODS),
392
+ ],
393
+ lifespan=lifespan,
394
+ )
395
+ app.state.settings = settings
396
+ if settings.mode == "receipt":
397
+ from satsgate_proxy.receipt_mode import open_store
398
+
399
+ app.state.receipt_store = open_store(settings.receipt_store)
400
+ return app
@@ -0,0 +1,96 @@
1
+ """Buyer address for the proxy.
2
+
3
+ Same forwarding rule as the core: X-Forwarded-For counts only when the TCP
4
+ peer is listed in this proxy's trusted_proxies. The core applies that rule
5
+ again to X-Satsgate-Buyer-Ip, using the proxy's egress address.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ipaddress
11
+
12
+
13
+ def _parse_trusted(raw: str) -> tuple[set[str], list[ipaddress.IPv4Network | ipaddress.IPv6Network]]:
14
+ literals: set[str] = set()
15
+ networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network] = []
16
+ for part in (raw or "").split(","):
17
+ item = part.strip()
18
+ if not item:
19
+ continue
20
+ if item in {"*", "0.0.0.0/0", "::/0"}:
21
+ continue
22
+ try:
23
+ if "/" in item:
24
+ networks.append(ipaddress.ip_network(item, strict=False))
25
+ else:
26
+ literals.add(str(ipaddress.ip_address(item)))
27
+ except ValueError:
28
+ if len(item) <= 64:
29
+ literals.add(item)
30
+ return literals, networks
31
+
32
+
33
+ def _is_trusted(
34
+ peer: str,
35
+ literals: set[str],
36
+ networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network],
37
+ ) -> bool:
38
+ if peer in literals:
39
+ return True
40
+ try:
41
+ addr = ipaddress.ip_address(peer)
42
+ except ValueError:
43
+ return False
44
+ return any(addr in network for network in networks)
45
+
46
+
47
+ def _valid_ip(value: str) -> str | None:
48
+ text = value.strip()
49
+ if not text:
50
+ return None
51
+ if text.startswith("["):
52
+ end = text.find("]")
53
+ if end == -1:
54
+ return None
55
+ text = text[1:end]
56
+ elif text.count(":") == 1 and "." in text:
57
+ host, _, port = text.rpartition(":")
58
+ if port.isdigit():
59
+ text = host
60
+ try:
61
+ return str(ipaddress.ip_address(text.split("%", 1)[0]))
62
+ except ValueError:
63
+ return None
64
+
65
+
66
+ def resolve_client_ip(*, peer: str | None, forwarded_for: str | None, trusted_proxies: str) -> str:
67
+ """Return the address that should own this request's buyer bucket."""
68
+ peer_text = (peer or "").strip() or "unknown"
69
+ if len(peer_text) > 64:
70
+ peer_text = "unknown"
71
+
72
+ literals, networks = _parse_trusted(trusted_proxies)
73
+ if not _is_trusted(peer_text, literals, networks):
74
+ return peer_text
75
+
76
+ parts = [part.strip() for part in (forwarded_for or "").split(",") if part.strip()]
77
+ for hop in reversed(parts):
78
+ ip = _valid_ip(hop)
79
+ if ip is None:
80
+ continue
81
+ if not _is_trusted(ip, literals, networks):
82
+ return ip
83
+ return peer_text
84
+
85
+
86
+ def buyer_ip_for_core(*, peer: str | None, forwarded_for: str | None, trusted_proxies: str) -> str | None:
87
+ """Canonical IP to send as X-Satsgate-Buyer-Ip, or None when it is not an IP.
88
+
89
+ A non-IP peer such as the test client is omitted. The core rejects a
90
+ non-IP value when the caller is trusted, and ignores the header otherwise.
91
+ """
92
+ resolved = resolve_client_ip(peer=peer, forwarded_for=forwarded_for, trusted_proxies=trusted_proxies)
93
+ try:
94
+ return str(ipaddress.ip_address(resolved))
95
+ except ValueError:
96
+ return None