kaptra-pay 0.1.0__tar.gz
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.
- kaptra_pay-0.1.0/PKG-INFO +6 -0
- kaptra_pay-0.1.0/kaptra_pay/__init__.py +224 -0
- kaptra_pay-0.1.0/kaptra_pay.egg-info/PKG-INFO +6 -0
- kaptra_pay-0.1.0/kaptra_pay.egg-info/SOURCES.txt +7 -0
- kaptra_pay-0.1.0/kaptra_pay.egg-info/dependency_links.txt +1 -0
- kaptra_pay-0.1.0/kaptra_pay.egg-info/top_level.txt +1 -0
- kaptra_pay-0.1.0/pyproject.toml +11 -0
- kaptra_pay-0.1.0/setup.cfg +4 -0
- kaptra_pay-0.1.0/tests/test_kaptra_pay.py +92 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Accept payments from AI agents on Kaptra over HTTP 402 (x402 v2).
|
|
2
|
+
|
|
3
|
+
from fastapi import FastAPI
|
|
4
|
+
from kaptra_pay import KaptraPaywall, Price
|
|
5
|
+
|
|
6
|
+
app = FastAPI()
|
|
7
|
+
app.add_middleware(
|
|
8
|
+
KaptraPaywall,
|
|
9
|
+
pay_to="kptr1...", # your address
|
|
10
|
+
facilitator="https://pay.kaptra.network",
|
|
11
|
+
routes={"/answer": Price.kptr("0.05")}, # path -> price; other paths are free
|
|
12
|
+
webhook=("https://you.example/hook", "whsec_..."),
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
An unpaid request gets 402 with the price. An agent pays and repeats the
|
|
16
|
+
request with a PAYMENT-SIGNATURE header; the payment is settled on chain
|
|
17
|
+
through the facilitator before your handler runs, and the response carries
|
|
18
|
+
PAYMENT-RESPONSE. The handler finds the receipt in request.scope["kaptra_payment"].
|
|
19
|
+
No third-party dependencies.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import base64
|
|
25
|
+
import hashlib
|
|
26
|
+
import hmac
|
|
27
|
+
import json
|
|
28
|
+
import re
|
|
29
|
+
import secrets
|
|
30
|
+
import time
|
|
31
|
+
import urllib.request
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from typing import Awaitable, Callable, Dict, Optional, Tuple, Union
|
|
34
|
+
|
|
35
|
+
__all__ = ["Price", "KaptraPaywall", "Facilitator", "sign_webhook", "verify_webhook"]
|
|
36
|
+
|
|
37
|
+
X402_VERSION = 2
|
|
38
|
+
SCHEME = "exact"
|
|
39
|
+
H_REQUIRED, H_SIGNATURE, H_RESPONSE = "PAYMENT-REQUIRED", "PAYMENT-SIGNATURE", "PAYMENT-RESPONSE"
|
|
40
|
+
_INVOICE_RE = re.compile(r"^[\x21-\x7e]{1,128}$")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Price:
|
|
45
|
+
amount: str # smallest unit of asset
|
|
46
|
+
asset: str # bank denom: "ukptr" or an ibc/... USDC denom
|
|
47
|
+
|
|
48
|
+
@staticmethod
|
|
49
|
+
def kptr(value: Union[str, int, float]) -> "Price":
|
|
50
|
+
s = str(value).strip()
|
|
51
|
+
if not re.fullmatch(r"\d+(\.\d{1,6})?", s):
|
|
52
|
+
raise ValueError(f"bad KPTR price {s!r}")
|
|
53
|
+
i, _, f = s.partition(".")
|
|
54
|
+
return Price(str(int(i) * 1_000_000 + int(f.ljust(6, "0") or 0)), "ukptr")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _b64(o) -> str:
|
|
58
|
+
return base64.b64encode(json.dumps(o, separators=(",", ":")).encode()).decode()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _unb64(s: Optional[str]):
|
|
62
|
+
if not s:
|
|
63
|
+
return None
|
|
64
|
+
try:
|
|
65
|
+
return json.loads(base64.b64decode(s))
|
|
66
|
+
except Exception:
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Facilitator:
|
|
71
|
+
"""HTTP client of an x402 facilitator (POST /verify, POST /settle, GET /supported)."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, url: str, timeout: float = 40.0):
|
|
74
|
+
self.url = url.rstrip("/")
|
|
75
|
+
self.timeout = timeout
|
|
76
|
+
|
|
77
|
+
def _call(self, path: str, body=None) -> dict:
|
|
78
|
+
data = None if body is None else json.dumps(body).encode()
|
|
79
|
+
req = urllib.request.Request(self.url + path, data=data, headers={"content-type": "application/json"})
|
|
80
|
+
try:
|
|
81
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
82
|
+
return json.loads(r.read())
|
|
83
|
+
except urllib.error.HTTPError as e: # 400 carries a JSON answer too
|
|
84
|
+
return json.loads(e.read() or b"{}")
|
|
85
|
+
|
|
86
|
+
async def supported(self) -> dict:
|
|
87
|
+
return await asyncio.to_thread(self._call, "/supported")
|
|
88
|
+
|
|
89
|
+
async def settle(self, payload: dict, requirements: dict) -> dict:
|
|
90
|
+
body = {"x402Version": X402_VERSION, "paymentPayload": payload, "paymentRequirements": requirements}
|
|
91
|
+
return await asyncio.to_thread(self._call, "/settle", body)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def sign_webhook(secret: str, body: str, t: Optional[int] = None) -> str:
|
|
95
|
+
t = int(time.time()) if t is None else t
|
|
96
|
+
mac = hmac.new(secret.encode(), f"{t}.{body}".encode(), hashlib.sha256).hexdigest()
|
|
97
|
+
return f"t={t},v1={mac}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def verify_webhook(secret: str, header: Optional[str], body: Union[str, bytes], tolerance: int = 300, now: Optional[int] = None) -> bool:
|
|
101
|
+
"""Checks the Kaptra-Signature header of an invoice.paid webhook."""
|
|
102
|
+
m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
|
|
103
|
+
if not m:
|
|
104
|
+
return False
|
|
105
|
+
t = int(m.group(1))
|
|
106
|
+
if abs((int(time.time()) if now is None else now) - t) > tolerance:
|
|
107
|
+
return False
|
|
108
|
+
if isinstance(body, bytes):
|
|
109
|
+
body = body.decode()
|
|
110
|
+
want = hmac.new(secret.encode(), f"{t}.{body}".encode(), hashlib.sha256).hexdigest()
|
|
111
|
+
return hmac.compare_digest(want, m.group(2))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _post_webhook(url: str, secret: str, event: dict) -> None:
|
|
115
|
+
body = json.dumps(event)
|
|
116
|
+
for i in range(3):
|
|
117
|
+
try:
|
|
118
|
+
req = urllib.request.Request(url, data=body.encode(), headers={"content-type": "application/json", "kaptra-signature": sign_webhook(secret, body)})
|
|
119
|
+
with urllib.request.urlopen(req, timeout=10):
|
|
120
|
+
return
|
|
121
|
+
except Exception:
|
|
122
|
+
time.sleep(2 ** i)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
Scope = dict
|
|
126
|
+
ASGIApp = Callable[[Scope, Callable, Callable], Awaitable[None]]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class KaptraPaywall:
|
|
130
|
+
"""ASGI middleware: charges for the paths listed in routes."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
app: ASGIApp,
|
|
135
|
+
pay_to: str,
|
|
136
|
+
facilitator: Union[str, Facilitator],
|
|
137
|
+
routes: Dict[str, Price],
|
|
138
|
+
network: Optional[str] = None,
|
|
139
|
+
description: Optional[str] = None,
|
|
140
|
+
service_name: Optional[str] = None,
|
|
141
|
+
max_timeout_seconds: int = 120,
|
|
142
|
+
webhook: Optional[Tuple[str, str]] = None,
|
|
143
|
+
on_paid: Optional[Callable[[dict], Awaitable[None]]] = None,
|
|
144
|
+
public_url: Optional[str] = None,
|
|
145
|
+
):
|
|
146
|
+
self.app = app
|
|
147
|
+
self.pay_to = pay_to
|
|
148
|
+
self.fac = Facilitator(facilitator) if isinstance(facilitator, str) else facilitator
|
|
149
|
+
self.routes = routes
|
|
150
|
+
self.network = network
|
|
151
|
+
self.description = description
|
|
152
|
+
self.service_name = service_name
|
|
153
|
+
self.timeout = max_timeout_seconds
|
|
154
|
+
self.webhook = webhook
|
|
155
|
+
self.on_paid = on_paid
|
|
156
|
+
self.public_url = public_url
|
|
157
|
+
|
|
158
|
+
async def _network(self) -> str:
|
|
159
|
+
if not self.network:
|
|
160
|
+
sup = await self.fac.supported()
|
|
161
|
+
kinds = [k for k in sup.get("kinds", []) if k.get("scheme") == SCHEME and str(k.get("network", "")).startswith("cosmos:")]
|
|
162
|
+
if not kinds:
|
|
163
|
+
raise RuntimeError("facilitator does not support Kaptra")
|
|
164
|
+
self.network = kinds[0]["network"]
|
|
165
|
+
return self.network
|
|
166
|
+
|
|
167
|
+
async def __call__(self, scope: Scope, receive, send):
|
|
168
|
+
if scope["type"] != "http" or scope["path"] not in self.routes:
|
|
169
|
+
return await self.app(scope, receive, send)
|
|
170
|
+
price = self.routes[scope["path"]]
|
|
171
|
+
headers = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
|
|
172
|
+
base_url = self.public_url or f"{scope.get('scheme', 'http')}://{headers.get('host', 'localhost')}"
|
|
173
|
+
qs = scope.get("query_string", b"").decode()
|
|
174
|
+
url = base_url.rstrip("/") + scope["path"] + (f"?{qs}" if qs else "")
|
|
175
|
+
base = {"scheme": SCHEME, "network": await self._network(), "amount": price.amount, "asset": price.asset,
|
|
176
|
+
"payTo": self.pay_to, "maxTimeoutSeconds": self.timeout}
|
|
177
|
+
resource = {k: v for k, v in {"url": url, "description": self.description, "serviceName": self.service_name}.items() if v}
|
|
178
|
+
|
|
179
|
+
async def ask(error: Optional[str] = None):
|
|
180
|
+
pr = {"x402Version": X402_VERSION, "resource": resource,
|
|
181
|
+
"accepts": [dict(base, extra={"invoiceId": "inv_" + secrets.token_urlsafe(16), "validUntil": int(time.time()) + self.timeout})]}
|
|
182
|
+
if error:
|
|
183
|
+
pr["error"] = error
|
|
184
|
+
body = json.dumps(pr).encode()
|
|
185
|
+
await send({"type": "http.response.start", "status": 402, "headers": [
|
|
186
|
+
(b"content-type", b"application/json"), (H_REQUIRED.encode(), _b64(pr).encode()),
|
|
187
|
+
(b"access-control-expose-headers", f"{H_REQUIRED}, {H_RESPONSE}".encode())]})
|
|
188
|
+
await send({"type": "http.response.body", "body": body})
|
|
189
|
+
|
|
190
|
+
raw = headers.get(H_SIGNATURE.lower()) or headers.get("x-payment")
|
|
191
|
+
payload = _unb64(raw)
|
|
192
|
+
if not isinstance(payload, dict):
|
|
193
|
+
return await ask("malformed PAYMENT-SIGNATURE header" if raw else None)
|
|
194
|
+
acc = payload.get("accepted") or {}
|
|
195
|
+
extra = acc.get("extra") or {}
|
|
196
|
+
inv, until = extra.get("invoiceId"), extra.get("validUntil")
|
|
197
|
+
if not isinstance(inv, str) or not _INVOICE_RE.match(inv) or not isinstance(until, int):
|
|
198
|
+
return await ask("missing invoice id")
|
|
199
|
+
if any(acc.get(k) != base[k] for k in ("scheme", "network", "amount", "asset", "payTo")):
|
|
200
|
+
return await ask("the payment does not match the current price")
|
|
201
|
+
requirements = dict(base, extra={"invoiceId": inv, "validUntil": until})
|
|
202
|
+
s = await self.fac.settle(payload, requirements)
|
|
203
|
+
if not s.get("success"):
|
|
204
|
+
msg = s.get("errorReason", "settle failed") + (f": {s['errorMessage']}" if s.get("errorMessage") else "")
|
|
205
|
+
return await ask(msg)
|
|
206
|
+
|
|
207
|
+
paid = {"invoiceId": inv, "payer": s.get("payer", ""), "amount": price.amount, "asset": price.asset,
|
|
208
|
+
"transaction": s.get("transaction", ""), "network": s.get("network", ""), "resource": url}
|
|
209
|
+
scope["kaptra_payment"] = paid
|
|
210
|
+
if self.webhook:
|
|
211
|
+
event = {"type": "invoice.paid", "created": int(time.time()), "data": paid}
|
|
212
|
+
asyncio.get_running_loop().run_in_executor(None, _post_webhook, self.webhook[0], self.webhook[1], event)
|
|
213
|
+
if self.on_paid:
|
|
214
|
+
await self.on_paid(paid)
|
|
215
|
+
response_header = _b64(s).encode()
|
|
216
|
+
|
|
217
|
+
async def send_with_receipt(message):
|
|
218
|
+
if message["type"] == "http.response.start":
|
|
219
|
+
message = dict(message, headers=list(message.get("headers", [])) + [
|
|
220
|
+
(H_RESPONSE.encode(), response_header),
|
|
221
|
+
(b"access-control-expose-headers", f"{H_REQUIRED}, {H_RESPONSE}".encode())])
|
|
222
|
+
await send(message)
|
|
223
|
+
|
|
224
|
+
await self.app(scope, receive, send_with_receipt)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
kaptra_pay
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "kaptra-pay"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Accept x402 payments from AI agents on Kaptra: ASGI paywall middleware (FastAPI, Starlette) and webhook checks"
|
|
5
|
+
requires-python = ">=3.9"
|
|
6
|
+
license = { text = "Apache-2.0" }
|
|
7
|
+
dependencies = []
|
|
8
|
+
|
|
9
|
+
[build-system]
|
|
10
|
+
requires = ["setuptools>=61"]
|
|
11
|
+
build-backend = "setuptools.build_meta"
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Unit tests with a fake facilitator: python3 -m unittest discover -s tests"""
|
|
2
|
+
import asyncio
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
import unittest
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
10
|
+
from kaptra_pay import KaptraPaywall, Price, sign_webhook, verify_webhook # noqa: E402
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FakeFacilitator:
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self.settled = []
|
|
16
|
+
|
|
17
|
+
async def supported(self):
|
|
18
|
+
return {"kinds": [{"x402Version": 2, "scheme": "exact", "network": "cosmos:test-1"}]}
|
|
19
|
+
|
|
20
|
+
async def settle(self, payload, req):
|
|
21
|
+
if req["extra"]["invoiceId"] in [r["extra"]["invoiceId"] for r in self.settled]:
|
|
22
|
+
return {"success": False, "errorReason": "invalid_transaction_state", "transaction": "", "network": req["network"]}
|
|
23
|
+
self.settled.append(req)
|
|
24
|
+
return {"success": True, "payer": "kptr1payer", "transaction": "ABC", "network": req["network"]}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def app(scope, receive, send):
|
|
28
|
+
body = json.dumps({"answer": 42, "paid": scope.get("kaptra_payment", {}).get("payer")}).encode()
|
|
29
|
+
await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"application/json")]})
|
|
30
|
+
await send({"type": "http.response.body", "body": body})
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def call(mw, path, headers=()):
|
|
34
|
+
out = {}
|
|
35
|
+
|
|
36
|
+
async def receive():
|
|
37
|
+
return {"type": "http.request", "body": b""}
|
|
38
|
+
|
|
39
|
+
async def send(m):
|
|
40
|
+
if m["type"] == "http.response.start":
|
|
41
|
+
out["status"], out["headers"] = m["status"], {k.decode(): v.decode() for k, v in m["headers"]}
|
|
42
|
+
else:
|
|
43
|
+
out["body"] = json.loads(m["body"])
|
|
44
|
+
|
|
45
|
+
scope = {"type": "http", "path": path, "headers": [(k.lower().encode(), v.encode()) for k, v in headers], "query_string": b""}
|
|
46
|
+
asyncio.run(mw(scope, receive, send))
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class PaywallTest(unittest.TestCase):
|
|
51
|
+
def setUp(self):
|
|
52
|
+
self.fac = FakeFacilitator()
|
|
53
|
+
self.mw = KaptraPaywall(app, pay_to="kptr1shop", facilitator=self.fac, routes={"/answer": Price.kptr("0.5")})
|
|
54
|
+
|
|
55
|
+
def test_free_path(self):
|
|
56
|
+
self.assertEqual(call(self.mw, "/free")["status"], 200)
|
|
57
|
+
|
|
58
|
+
def test_flow(self):
|
|
59
|
+
r = call(self.mw, "/answer")
|
|
60
|
+
self.assertEqual(r["status"], 402)
|
|
61
|
+
req = r["body"]["accepts"][0]
|
|
62
|
+
self.assertEqual((req["amount"], req["asset"], req["network"]), ("500000", "ukptr", "cosmos:test-1"))
|
|
63
|
+
self.assertEqual(json.loads(base64.b64decode(r["headers"]["PAYMENT-REQUIRED"])), r["body"])
|
|
64
|
+
|
|
65
|
+
payload = {"x402Version": 2, "accepted": req, "payload": {"transaction": "dHg="}}
|
|
66
|
+
h = [("PAYMENT-SIGNATURE", base64.b64encode(json.dumps(payload).encode()).decode())]
|
|
67
|
+
ok = call(self.mw, "/answer", h)
|
|
68
|
+
self.assertEqual(ok["status"], 200)
|
|
69
|
+
self.assertEqual(ok["body"]["paid"], "kptr1payer")
|
|
70
|
+
self.assertIn("PAYMENT-RESPONSE", ok["headers"])
|
|
71
|
+
self.assertEqual(call(self.mw, "/answer", h)["status"], 402, "replay")
|
|
72
|
+
|
|
73
|
+
cheap = dict(req, amount="1")
|
|
74
|
+
h2 = [("PAYMENT-SIGNATURE", base64.b64encode(json.dumps(dict(payload, accepted=cheap)).encode()).decode())]
|
|
75
|
+
self.assertIn("does not match", call(self.mw, "/answer", h2)["body"]["error"])
|
|
76
|
+
|
|
77
|
+
def test_price(self):
|
|
78
|
+
self.assertEqual(Price.kptr("2"), Price("2000000", "ukptr"))
|
|
79
|
+
self.assertEqual(Price.kptr("0.000001"), Price("1", "ukptr"))
|
|
80
|
+
with self.assertRaises(ValueError):
|
|
81
|
+
Price.kptr("1.2345678")
|
|
82
|
+
|
|
83
|
+
def test_webhook(self):
|
|
84
|
+
body = '{"type":"invoice.paid"}'
|
|
85
|
+
h = sign_webhook("s", body, t=1000)
|
|
86
|
+
self.assertTrue(verify_webhook("s", h, body, now=1100))
|
|
87
|
+
self.assertFalse(verify_webhook("x", h, body, now=1100))
|
|
88
|
+
self.assertFalse(verify_webhook("s", h, body, now=5000))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
unittest.main()
|