plug402 0.1.0__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.
plug402/httpx.py ADDED
@@ -0,0 +1,136 @@
1
+ """httpx add-on: ``X402Auth``, an ``httpx.Auth`` that pays ``402`` responses.
2
+
3
+ Works with both ``httpx.Client`` and ``httpx.AsyncClient``, new or existing::
4
+
5
+ import httpx
6
+ from plug402.httpx import X402Auth
7
+
8
+ auth = X402Auth(account, policy="policy.json")
9
+ with httpx.Client(auth=auth) as client:
10
+ r = client.get("https://api.example.com/paid")
11
+
12
+ Why an ``httpx.Auth`` and not the official ``x402AsyncTransport``: an auth flow
13
+ is the httpx extension point for "send, look at the response, send again", it
14
+ plugs into an existing client (``auth=``, or per request) without replacing its
15
+ transport, and it runs on sync and async clients alike. The official package
16
+ ships only an async transport. The wire format and the signing still come from
17
+ the official package (``x402HTTPClientSync`` header helpers, ``x402Client`` /
18
+ ``x402ClientSync`` and the official exact schemes).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from collections.abc import AsyncGenerator, Generator, Mapping
24
+ from typing import Any
25
+
26
+ import httpx
27
+ from x402.http.constants import PAYMENT_REQUIRED_HEADER
28
+
29
+ from ._engine import Engine, Payment, has_payment_header
30
+ from .errors import PaymentFailed
31
+ from .ledger import Ledger, origin_of
32
+ from .policy import Approve, Policy
33
+
34
+ __all__ = ["X402Auth"]
35
+
36
+
37
+ class X402Auth(httpx.Auth):
38
+ """Pay ``402 Payment Required`` responses under a plug402 spend policy.
39
+
40
+ On a ``402`` the policy decides every offered entry; nothing is signed
41
+ unless one is allowed (or approved). The request is retried once with the
42
+ payment. A second ``402`` raises :class:`~plug402.PaymentFailed`; it is
43
+ never paid twice.
44
+
45
+ Args:
46
+ signers: An eth-account ``LocalAccount``, a solders ``Keypair``, an
47
+ official ``EthAccountSigner`` / ``KeypairSigner``, or a list with
48
+ at most one EVM and one Solana signer.
49
+ policy: A :class:`~plug402.Policy`, a policy dict, or a path to a JSON file.
50
+ ledger: Receipt store; a :class:`~plug402.MemoryLedger` by default.
51
+ approve: Called with an :class:`~plug402.ApprovalRequest` when the
52
+ policy says ``ask``; return ``True`` to pay. It may be ``async``
53
+ when used with ``httpx.AsyncClient``.
54
+ svm_rpc_url: Solana RPC endpoint for the official SVM scheme.
55
+
56
+ Raises (from the request call):
57
+ PaymentDenied: nothing could be paid; nothing was signed.
58
+ PaymentFailed: the paid retry came back ``402``.
59
+ PaymentError: the 402 was malformed or the payment could not be created.
60
+ """
61
+
62
+ requires_request_body = True # the paid retry resends the body
63
+
64
+ def __init__(
65
+ self,
66
+ signers: Any,
67
+ policy: Policy | Mapping[str, Any] | str,
68
+ ledger: Ledger | None = None,
69
+ approve: Approve | None = None,
70
+ *,
71
+ svm_rpc_url: str | None = None,
72
+ ) -> None:
73
+ self.engine = Engine(signers, policy, ledger, approve, svm_rpc_url=svm_rpc_url)
74
+
75
+ @property
76
+ def ledger(self) -> Ledger:
77
+ """The ledger receipts are written to."""
78
+ return self.engine.ledger
79
+
80
+ @property
81
+ def policy(self) -> Policy:
82
+ """The spend policy in force."""
83
+ return self.engine.policy
84
+
85
+ @staticmethod
86
+ def _wants_payment(request: httpx.Request, response: httpx.Response) -> bool:
87
+ return response.status_code == 402 and not has_payment_header(request.headers.get)
88
+
89
+ @staticmethod
90
+ def _failed(payment: Payment, response: httpx.Response) -> PaymentFailed:
91
+ return PaymentFailed(
92
+ "the paid request was answered with 402 again; it is not paid twice",
93
+ status_code=response.status_code,
94
+ receipt_id=payment.receipt.id,
95
+ response=response,
96
+ )
97
+
98
+ def sync_auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
99
+ request.read()
100
+ response = yield request
101
+ if not self._wants_payment(request, response):
102
+ return
103
+ body = None if response.headers.get(PAYMENT_REQUIRED_HEADER) else response.read()
104
+ payment = self.engine.pay_sync(origin_of(request.url), response.headers.get, body)
105
+ if payment is None: # a 402 without x402 payment requirements: hand it back
106
+ return
107
+ request.headers.update(payment.headers)
108
+ try:
109
+ paid = yield request
110
+ except GeneratorExit: # transport error (or cancellation) before any response
111
+ payment.fail()
112
+ raise
113
+ payment.complete(paid.status_code, paid.headers.get)
114
+ if paid.status_code == 402:
115
+ paid.read()
116
+ raise self._failed(payment, paid)
117
+
118
+ async def async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]:
119
+ await request.aread()
120
+ response = yield request
121
+ if not self._wants_payment(request, response):
122
+ return
123
+ body = None if response.headers.get(PAYMENT_REQUIRED_HEADER) else await response.aread()
124
+ payment = await self.engine.pay_async(origin_of(request.url), response.headers.get, body)
125
+ if payment is None:
126
+ return
127
+ request.headers.update(payment.headers)
128
+ try:
129
+ paid = yield request
130
+ except GeneratorExit:
131
+ payment.fail()
132
+ raise
133
+ payment.complete(paid.status_code, paid.headers.get)
134
+ if paid.status_code == 402:
135
+ await paid.aread()
136
+ raise self._failed(payment, paid)
plug402/ledger.py ADDED
@@ -0,0 +1,294 @@
1
+ """Receipts and ledgers (spec sections 3.3 and 4). Pure Python, no third-party dependencies.
2
+
3
+ A ledger stores one :class:`Receipt` per payment and answers the two state
4
+ questions the policy needs: how much was spent today (UTC) on a network +
5
+ asset, and how many payments were made in the last 60 seconds. Receipts never
6
+ hold full URLs, queries, headers, bodies, signatures, payloads or keys.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ import json
13
+ import os
14
+ import secrets
15
+ import threading
16
+ from collections.abc import Iterator
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass
19
+ from datetime import datetime, timedelta, timezone
20
+ from typing import Any, Literal, Protocol, runtime_checkable
21
+ from urllib.parse import urlsplit
22
+
23
+ from .policy import State, parse_amount, same_address
24
+
25
+ __all__ = [
26
+ "JsonlLedger",
27
+ "Ledger",
28
+ "MemoryLedger",
29
+ "Receipt",
30
+ "format_ts",
31
+ "new_receipt_id",
32
+ "origin_of",
33
+ "parse_ts",
34
+ ]
35
+
36
+ Status = Literal["pending", "settled", "failed"]
37
+
38
+ _DEFAULT_PORTS = {"http": 80, "https": 443}
39
+
40
+
41
+ def origin_of(url: object) -> str:
42
+ """Scheme, host and port of ``url`` and nothing else.
43
+
44
+ No user info, path, query or fragment. Default ports are omitted, as in a
45
+ browser origin (``https://api.example.com``). Accepts a string or any
46
+ object whose ``str()`` is the URL (``httpx.URL``).
47
+ """
48
+ parts = urlsplit(str(url))
49
+ scheme = parts.scheme.lower()
50
+ host = (parts.hostname or "").lower()
51
+ if not scheme or not host:
52
+ raise ValueError("cannot take the origin of a URL without a scheme and host")
53
+ if ":" in host: # IPv6 literal
54
+ host = f"[{host}]"
55
+ try:
56
+ port = parts.port
57
+ except ValueError:
58
+ port = None
59
+ if port is not None and port != _DEFAULT_PORTS.get(scheme):
60
+ return f"{scheme}://{host}:{port}"
61
+ return f"{scheme}://{host}"
62
+
63
+
64
+ def format_ts(dt: datetime) -> str:
65
+ """UTC timestamp with milliseconds, e.g. ``2026-11-30T12:00:00.000Z``."""
66
+ dt = dt.astimezone(timezone.utc)
67
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
68
+
69
+
70
+ def parse_ts(ts: str) -> datetime:
71
+ """Parse a receipt timestamp (``Z`` suffix accepted on Python 3.10 too)."""
72
+ if ts.endswith("Z"):
73
+ ts = ts[:-1] + "+00:00"
74
+ dt = datetime.fromisoformat(ts)
75
+ if dt.tzinfo is None:
76
+ dt = dt.replace(tzinfo=timezone.utc)
77
+ return dt.astimezone(timezone.utc)
78
+
79
+
80
+ def new_receipt_id() -> str:
81
+ """A 16-byte random hex string."""
82
+ return secrets.token_hex(16)
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class Receipt:
87
+ """One payment, as stored by a ledger (spec section 4)."""
88
+
89
+ id: str
90
+ ts: str
91
+ origin: str
92
+ network: str
93
+ asset: str
94
+ amount: str
95
+ pay_to: str
96
+ scheme: str
97
+ x402_version: int
98
+ decision: Literal["allow", "ask"]
99
+ approved_by: Literal["policy", "human"]
100
+ status: Status = "pending"
101
+ transaction: str | None = None
102
+ v: int = 1
103
+
104
+ def to_dict(self) -> dict[str, Any]:
105
+ """The receipt in the spec's JSON shape (camelCase keys)."""
106
+ return {
107
+ "v": self.v,
108
+ "id": self.id,
109
+ "ts": self.ts,
110
+ "origin": self.origin,
111
+ "network": self.network,
112
+ "asset": self.asset,
113
+ "amount": self.amount,
114
+ "payTo": self.pay_to,
115
+ "scheme": self.scheme,
116
+ "x402Version": self.x402_version,
117
+ "decision": self.decision,
118
+ "approvedBy": self.approved_by,
119
+ "status": self.status,
120
+ "transaction": self.transaction,
121
+ }
122
+
123
+ @classmethod
124
+ def from_dict(cls, doc: dict[str, Any]) -> Receipt:
125
+ """Build a receipt from its JSON shape."""
126
+ return cls(
127
+ v=int(doc.get("v", 1)),
128
+ id=str(doc["id"]),
129
+ ts=str(doc["ts"]),
130
+ origin=str(doc["origin"]),
131
+ network=str(doc["network"]),
132
+ asset=str(doc["asset"]),
133
+ amount=str(doc["amount"]),
134
+ pay_to=str(doc["payTo"]),
135
+ scheme=str(doc["scheme"]),
136
+ x402_version=int(doc["x402Version"]),
137
+ decision=doc["decision"],
138
+ approved_by=doc["approvedBy"],
139
+ status=doc["status"],
140
+ transaction=doc.get("transaction"),
141
+ )
142
+
143
+ def with_status(self, status: Status, transaction: str | None = None) -> Receipt:
144
+ """A copy with a new status (and transaction, when given)."""
145
+ return dataclasses.replace(
146
+ self,
147
+ status=status,
148
+ transaction=transaction if transaction is not None else self.transaction,
149
+ )
150
+
151
+ @property
152
+ def time(self) -> datetime:
153
+ """``ts`` as an aware UTC datetime."""
154
+ return parse_ts(self.ts)
155
+
156
+
157
+ @runtime_checkable
158
+ class Ledger(Protocol):
159
+ """What plug402 needs from a ledger.
160
+
161
+ ``lock()`` must be held while the policy decides and the pending receipt is
162
+ written, so concurrent requests see each other's pending payments.
163
+ """
164
+
165
+ def put(self, receipt: Receipt) -> None:
166
+ """Insert a receipt, or replace the receipt with the same id."""
167
+
168
+ def get(self, receipt_id: str) -> Receipt | None:
169
+ """The current receipt with this id, if any."""
170
+
171
+ def receipts(self) -> list[Receipt]:
172
+ """Current receipts (the latest version of each id), oldest first."""
173
+
174
+ def state(self, network: str, asset: str, now: datetime | None = None) -> State:
175
+ """``spentToday`` for network + asset and ``paymentsLastMinute`` at ``now``."""
176
+
177
+ def lock(self) -> Any:
178
+ """A context manager that serialises decide-and-reserve."""
179
+
180
+
181
+ class _BaseLedger:
182
+ """Shared state computation; subclasses keep ``_by_id`` (insertion ordered)."""
183
+
184
+ def __init__(self) -> None:
185
+ self._by_id: dict[str, Receipt] = {}
186
+ self._lock = threading.RLock()
187
+
188
+ @contextmanager
189
+ def lock(self) -> Iterator[None]:
190
+ with self._lock:
191
+ yield
192
+
193
+ def get(self, receipt_id: str) -> Receipt | None:
194
+ with self._lock:
195
+ self._refresh()
196
+ return self._by_id.get(receipt_id)
197
+
198
+ def receipts(self) -> list[Receipt]:
199
+ with self._lock:
200
+ self._refresh()
201
+ return list(self._by_id.values())
202
+
203
+ def state(self, network: str, asset: str, now: datetime | None = None) -> State:
204
+ now = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
205
+ today = now.date()
206
+ minute_ago = now - timedelta(seconds=60)
207
+ spent = 0
208
+ recent = 0
209
+ with self._lock:
210
+ self._refresh()
211
+ for r in self._by_id.values():
212
+ if r.status == "failed":
213
+ continue
214
+ try:
215
+ t = r.time
216
+ except ValueError:
217
+ continue
218
+ if t > minute_ago:
219
+ recent += 1
220
+ if t.date() == today and r.network == network and same_address(network, r.asset, asset):
221
+ spent += parse_amount(r.amount) or 0
222
+ return State(spent_today=spent, payments_last_minute=recent)
223
+
224
+ def _refresh(self) -> None:
225
+ """Pick up changes made elsewhere (the file ledger reads new lines)."""
226
+
227
+
228
+ class MemoryLedger(_BaseLedger):
229
+ """The default ledger: receipts live in memory for the life of the process."""
230
+
231
+ def put(self, receipt: Receipt) -> None:
232
+ with self._lock:
233
+ self._by_id[receipt.id] = receipt
234
+
235
+
236
+ class JsonlLedger(_BaseLedger):
237
+ """Receipts appended to a JSON Lines file (spec section 4).
238
+
239
+ One JSON object per line. A status change appends the updated object with
240
+ the same ``id``; when reading, the last line for an ``id`` wins. Lines
241
+ appended by another process are picked up on the next read. A torn or
242
+ malformed line (for example after a crash) is skipped. The file is created
243
+ with mode ``0600``.
244
+ """
245
+
246
+ def __init__(self, path: str | os.PathLike[str]) -> None:
247
+ super().__init__()
248
+ self.path = os.fspath(path)
249
+ self._offset = 0
250
+ self._partial = b""
251
+ with self._lock:
252
+ self._refresh()
253
+
254
+ def put(self, receipt: Receipt) -> None:
255
+ line = json.dumps(receipt.to_dict(), separators=(",", ":"), ensure_ascii=False) + "\n"
256
+ data = line.encode("utf-8")
257
+ with self._lock:
258
+ self._refresh()
259
+ fd = os.open(self.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
260
+ try:
261
+ written = 0
262
+ while written < len(data):
263
+ written += os.write(fd, data[written:])
264
+ finally:
265
+ os.close(fd)
266
+ self._refresh()
267
+
268
+ def _refresh(self) -> None:
269
+ try:
270
+ with open(self.path, "rb") as f:
271
+ f.seek(0, os.SEEK_END)
272
+ size = f.tell()
273
+ if size < self._offset: # truncated or replaced: read from the start
274
+ self._offset = 0
275
+ self._partial = b""
276
+ self._by_id.clear()
277
+ if size == self._offset:
278
+ return
279
+ f.seek(self._offset)
280
+ chunk = f.read(size - self._offset)
281
+ self._offset = size
282
+ except FileNotFoundError:
283
+ return
284
+ data = self._partial + chunk
285
+ lines = data.split(b"\n")
286
+ self._partial = lines.pop() # incomplete last line, if any
287
+ for raw in lines:
288
+ if not raw.strip():
289
+ continue
290
+ try:
291
+ receipt = Receipt.from_dict(json.loads(raw.decode("utf-8")))
292
+ except (ValueError, KeyError, TypeError):
293
+ continue
294
+ self._by_id[receipt.id] = receipt