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/policy.py ADDED
@@ -0,0 +1,527 @@
1
+ """The plug402 spend policy (spec section 3). Pure Python, no third-party dependencies.
2
+
3
+ A :class:`Policy` decides one ``PaymentRequirements`` entry at a time
4
+ (:meth:`Policy.decide`, spec 3.1). :func:`evaluate` decides every entry of
5
+ ``accepts`` in the server's order and :func:`choose` picks the one to pay
6
+ (spec 3.2). Amounts are arbitrary-precision ``int`` values, never floats.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, Literal
17
+ from urllib.parse import urlsplit
18
+
19
+ __all__ = [
20
+ "ApprovalRequest",
21
+ "Approve",
22
+ "Choice",
23
+ "Decision",
24
+ "LimitRule",
25
+ "Policy",
26
+ "PolicyError",
27
+ "Requirement",
28
+ "State",
29
+ "V1_NETWORKS",
30
+ "choose",
31
+ "evaluate",
32
+ "is_insecure_origin",
33
+ "normalize_requirement",
34
+ "parse_amount",
35
+ "same_address",
36
+ ]
37
+
38
+ #: v1 network names plug402 v0.1 supports, mapped to CAIP-2 (spec section 2).
39
+ V1_NETWORKS: Mapping[str, str] = {
40
+ "base": "eip155:8453",
41
+ "base-sepolia": "eip155:84532",
42
+ "solana": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
43
+ "solana-devnet": "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
44
+ }
45
+
46
+ _AMOUNT = re.compile(r"(0|[1-9][0-9]*)")
47
+ #: Payment flows x402 defines (spec 3.1, step 1a); clients must not pay others.
48
+ PAYMENT_FLOWS = frozenset({"authorization", "upfront", "escrow"})
49
+ #: Hosts that count as loopback for ``http:`` origins (spec 3.2, step 0).
50
+ LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
51
+ _RULE_NETWORK = re.compile(r"(\*|[-a-z0-9]{3,8}:(\*|[-_a-zA-Z0-9]{1,32}))")
52
+
53
+ DecisionKind = Literal["allow", "ask", "deny"]
54
+
55
+
56
+ class PolicyError(ValueError):
57
+ """The policy document does not match ``spec/policy.schema.json``."""
58
+
59
+
60
+ def parse_amount(value: object) -> int | None:
61
+ """Parse a spec amount: a decimal string of a non-negative integer, no leading zeros.
62
+
63
+ Returns ``None`` for anything else (numbers, ``"1e5"``, ``"010"``, ``" 1"``, ``""``).
64
+ """
65
+ if not isinstance(value, str) or _AMOUNT.fullmatch(value) is None:
66
+ return None
67
+ return int(value)
68
+
69
+
70
+ def _namespace(network: str) -> str:
71
+ return network.split(":", 1)[0]
72
+
73
+
74
+ def same_address(network: str, a: str, b: str) -> bool:
75
+ """Compare two addresses or asset ids the way the spec does for ``network``.
76
+
77
+ EVM (``eip155:*``) compares case-insensitively; every other namespace
78
+ (Solana included) compares exactly.
79
+ """
80
+ if _namespace(network) == "eip155":
81
+ return a.lower() == b.lower()
82
+ return a == b
83
+
84
+
85
+ # ----------------------------------------------------------------------------
86
+ # Policy document
87
+ # ----------------------------------------------------------------------------
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class LimitRule:
92
+ """One entry of ``limits`` (spec section 3)."""
93
+
94
+ network: str
95
+ asset: str
96
+ max_per_request: int
97
+ max_per_day: int | None = None
98
+ ask_above: int | None = None
99
+
100
+ def matches(self, network: str, asset: str) -> bool:
101
+ """Whether this rule covers ``network`` + ``asset``."""
102
+ if self.network != "*" and self.network != network:
103
+ if not (self.network.endswith(":*") and _namespace(network) == self.network[:-2]):
104
+ return False
105
+ return self.asset == "*" or same_address(network, self.asset, asset)
106
+
107
+
108
+ _POLICY_KEYS = {"version", "networks", "schemes", "payTo", "limits", "maxPaymentsPerMinute", "allowHttp"}
109
+ _RULE_KEYS = {"network", "asset", "maxPerRequest", "maxPerDay", "askAbove"}
110
+
111
+
112
+ def _string_list(value: object, name: str, *, min_length: int = 0, unique: bool = False) -> list[str]:
113
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
114
+ raise PolicyError(f"{name} must be an array of strings")
115
+ if any(len(v) < min_length for v in value):
116
+ raise PolicyError(f"{name} entries must be at least {min_length} characters long")
117
+ if unique and len(set(value)) != len(value):
118
+ raise PolicyError(f"{name} entries must be unique")
119
+ return list(value)
120
+
121
+
122
+ def _rule_amount(raw: Mapping[str, Any], key: str, index: int, required: bool) -> int | None:
123
+ if key not in raw:
124
+ if required:
125
+ raise PolicyError(f"limits[{index}].{key} is required")
126
+ return None
127
+ value = parse_amount(raw[key])
128
+ if value is None:
129
+ raise PolicyError(
130
+ f"limits[{index}].{key} must be a decimal string of a non-negative integer without leading zeros"
131
+ )
132
+ return value
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class Policy:
137
+ """A validated spend policy (``spec/policy.schema.json``).
138
+
139
+ Build one with :meth:`from_dict`, :meth:`from_file`, :meth:`from_json` or
140
+ :meth:`load`. Default deny: a payment that no limit rule covers is refused.
141
+ """
142
+
143
+ networks: tuple[str, ...]
144
+ limits: tuple[LimitRule, ...]
145
+ schemes: tuple[str, ...] = ("exact",)
146
+ pay_to: tuple[str, ...] | None = None
147
+ max_payments_per_minute: int | None = None
148
+ allow_http: bool = False
149
+ raw: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
150
+
151
+ # -- loading ---------------------------------------------------------------
152
+
153
+ @classmethod
154
+ def from_dict(cls, doc: Mapping[str, Any]) -> Policy:
155
+ """Validate a policy object and build a :class:`Policy`."""
156
+ if not isinstance(doc, Mapping):
157
+ raise PolicyError("a policy must be a JSON object")
158
+ extra = set(doc) - _POLICY_KEYS
159
+ if extra:
160
+ raise PolicyError(f"unknown policy field(s): {', '.join(sorted(extra))}")
161
+ if doc.get("version") != 1 or isinstance(doc.get("version"), bool):
162
+ raise PolicyError("version must be 1")
163
+ if "networks" not in doc:
164
+ raise PolicyError("networks is required")
165
+ networks = _string_list(doc["networks"], "networks", min_length=3, unique=True)
166
+
167
+ schemes: list[str] = ["exact"]
168
+ if "schemes" in doc:
169
+ schemes = _string_list(doc["schemes"], "schemes", unique=True)
170
+
171
+ pay_to: list[str] | None = None
172
+ if doc.get("payTo") is not None:
173
+ pay_to = _string_list(doc["payTo"], "payTo", min_length=1)
174
+
175
+ if "limits" not in doc:
176
+ raise PolicyError("limits is required (it may be empty)")
177
+ if not isinstance(doc["limits"], list):
178
+ raise PolicyError("limits must be an array")
179
+ rules: list[LimitRule] = []
180
+ for i, raw in enumerate(doc["limits"]):
181
+ if not isinstance(raw, Mapping):
182
+ raise PolicyError(f"limits[{i}] must be an object")
183
+ extra = set(raw) - _RULE_KEYS
184
+ if extra:
185
+ raise PolicyError(f"unknown field(s) in limits[{i}]: {', '.join(sorted(extra))}")
186
+ network = raw.get("network")
187
+ if not isinstance(network, str) or _RULE_NETWORK.fullmatch(network) is None:
188
+ raise PolicyError(
189
+ f"limits[{i}].network must be a CAIP-2 id, a namespace wildcard "
190
+ "such as 'eip155:*', or '*'"
191
+ )
192
+ asset = raw.get("asset")
193
+ if not isinstance(asset, str) or not asset:
194
+ raise PolicyError(f"limits[{i}].asset must be a non-empty string")
195
+ rules.append(
196
+ LimitRule(
197
+ network=network,
198
+ asset=asset,
199
+ max_per_request=_rule_amount(raw, "maxPerRequest", i, True), # type: ignore[arg-type]
200
+ max_per_day=_rule_amount(raw, "maxPerDay", i, False),
201
+ ask_above=_rule_amount(raw, "askAbove", i, False),
202
+ )
203
+ )
204
+
205
+ rate: int | None = None
206
+ if "maxPaymentsPerMinute" in doc:
207
+ rate = doc["maxPaymentsPerMinute"]
208
+ if not isinstance(rate, int) or isinstance(rate, bool) or rate < 1:
209
+ raise PolicyError("maxPaymentsPerMinute must be an integer >= 1")
210
+
211
+ allow_http = doc.get("allowHttp", False)
212
+ if not isinstance(allow_http, bool):
213
+ raise PolicyError("allowHttp must be true or false")
214
+
215
+ return cls(
216
+ networks=tuple(networks),
217
+ limits=tuple(rules),
218
+ schemes=tuple(schemes),
219
+ pay_to=None if pay_to is None else tuple(pay_to),
220
+ max_payments_per_minute=rate,
221
+ allow_http=allow_http,
222
+ raw=json.loads(json.dumps(doc)),
223
+ )
224
+
225
+ @classmethod
226
+ def from_json(cls, text: str) -> Policy:
227
+ """Parse and validate a policy from JSON text."""
228
+ try:
229
+ doc = json.loads(text)
230
+ except json.JSONDecodeError as e:
231
+ raise PolicyError(f"policy is not valid JSON: {e}") from None
232
+ return cls.from_dict(doc)
233
+
234
+ @classmethod
235
+ def from_file(cls, path: str | os.PathLike[str]) -> Policy:
236
+ """Load and validate a policy from a JSON file."""
237
+ with open(path, encoding="utf-8") as f:
238
+ return cls.from_json(f.read())
239
+
240
+ @classmethod
241
+ def load(cls, source: Policy | Mapping[str, Any] | str | os.PathLike[str]) -> Policy:
242
+ """Accept a :class:`Policy`, a policy object, or a path to a JSON file."""
243
+ if isinstance(source, Policy):
244
+ return source
245
+ if isinstance(source, Mapping):
246
+ return cls.from_dict(source)
247
+ if isinstance(source, (str, os.PathLike)):
248
+ return cls.from_file(source)
249
+ raise TypeError("policy must be a Policy, a dict, or a path to a JSON file")
250
+
251
+ def to_dict(self) -> dict[str, Any]:
252
+ """The policy as a JSON-ready object (as it was loaded)."""
253
+ return json.loads(json.dumps(self.raw))
254
+
255
+ # -- decision (spec 3.1) ---------------------------------------------------
256
+
257
+ def find_rule(self, network: str, asset: str) -> LimitRule | None:
258
+ """The first limit rule that covers ``network`` + ``asset``, or ``None``."""
259
+ for rule in self.limits:
260
+ if rule.matches(network, asset):
261
+ return rule
262
+ return None
263
+
264
+ def decide(
265
+ self,
266
+ requirement: Mapping[str, Any],
267
+ state: State | None = None,
268
+ x402_version: int = 2,
269
+ ) -> Decision:
270
+ """Decide one ``PaymentRequirements`` entry (spec 3.1, steps 0 to 9, with 1a).
271
+
272
+ Args:
273
+ requirement: The entry as the server sent it (a JSON object; v1
274
+ entries use ``maxAmountRequired`` and v1 network names).
275
+ state: ``spentToday`` for this entry's network + asset and
276
+ ``paymentsLastMinute``; defaults to nothing spent.
277
+ x402_version: ``1`` or ``2``; selects the field names.
278
+ """
279
+ state = state or State()
280
+ req = normalize_requirement(requirement, x402_version)
281
+ if req is None: # step 0
282
+ return Decision("deny", "invalid-requirement")
283
+ if req.scheme not in self.schemes: # step 1
284
+ return Decision("deny", "scheme-not-allowed", req)
285
+ unsupported = _unsupported_extra(req.extra) # step 1a
286
+ if unsupported is not None:
287
+ return Decision("deny", "unsupported", req, detail=unsupported)
288
+ if req.network is None or req.network not in self.networks: # step 2
289
+ return Decision("deny", "network-not-allowed", req)
290
+ network = req.network
291
+ if self.pay_to is not None: # step 3: payTo and every split recipient
292
+ allowed = self.pay_to
293
+ recipients = [req.pay_to, *_split_recipients(req.extra)]
294
+ if not all(
295
+ isinstance(r, str) and any(same_address(network, a, r) for a in allowed) for r in recipients
296
+ ):
297
+ return Decision("deny", "payto-not-allowed", req)
298
+ rule = self.find_rule(network, req.asset)
299
+ if rule is None: # step 4
300
+ return Decision("deny", "no-limit", req)
301
+ if req.amount > rule.max_per_request: # step 5
302
+ return Decision("deny", "over-per-request", req, rule)
303
+ if rule.max_per_day is not None and state.spent_today + req.amount > rule.max_per_day:
304
+ return Decision("deny", "over-daily", req, rule) # step 6
305
+ if (
306
+ self.max_payments_per_minute is not None
307
+ and state.payments_last_minute >= self.max_payments_per_minute
308
+ ):
309
+ return Decision("deny", "rate-limited", req, rule) # step 7
310
+ if rule.ask_above is not None and req.amount > rule.ask_above:
311
+ return Decision("ask", "needs-approval", req, rule) # step 8
312
+ return Decision("allow", "within-policy", req, rule) # step 9
313
+
314
+
315
+ # ----------------------------------------------------------------------------
316
+ # Requirements, state, decisions
317
+ # ----------------------------------------------------------------------------
318
+
319
+
320
+ @dataclass(frozen=True)
321
+ class Requirement:
322
+ """One ``accepts`` entry after mapping v1 fields to v2 names.
323
+
324
+ ``network`` is the CAIP-2 id, or ``None`` for an unknown v1 network name.
325
+ """
326
+
327
+ scheme: str
328
+ network: str | None
329
+ asset: str
330
+ amount: int
331
+ pay_to: str
332
+ x402_version: int
333
+ raw_network: str
334
+ max_timeout_seconds: int = 0
335
+ extra: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
336
+
337
+
338
+ def _extra_of(raw: Mapping[str, Any]) -> Mapping[str, Any]:
339
+ extra = raw.get("extra")
340
+ if isinstance(extra, str): # some v1 servers send extra as a JSON string
341
+ try:
342
+ extra = json.loads(extra)
343
+ except ValueError:
344
+ return {}
345
+ return extra if isinstance(extra, Mapping) else {}
346
+
347
+
348
+ def _unsupported_extra(extra: Mapping[str, Any]) -> str | None:
349
+ """Spec 3.1 step 1a: a transfer method or payment flow plug402 v0.1 does not pay.
350
+
351
+ A JSON ``null`` counts as absent, as in the official TypeScript SDK.
352
+ """
353
+ method = extra.get("assetTransferMethod")
354
+ if method is not None and method != "eip3009":
355
+ return f"transfer method {method!r} is not in v0.1"
356
+ flow = extra.get("paymentFlow")
357
+ if flow is not None and flow not in PAYMENT_FLOWS:
358
+ return f"unknown payment flow {flow!r}"
359
+ return None
360
+
361
+
362
+ def _split_recipients(extra: Mapping[str, Any]) -> list[object]:
363
+ """``extra.splits[].payTo``; an unreadable split yields ``None`` (never allowlisted).
364
+
365
+ Absent or JSON ``null`` splits mean no extra recipients.
366
+ """
367
+ splits = extra.get("splits")
368
+ if splits is None:
369
+ return []
370
+ if not isinstance(splits, list):
371
+ return [None]
372
+ return [s.get("payTo") if isinstance(s, Mapping) else None for s in splits]
373
+
374
+
375
+ def normalize_requirement(raw: Mapping[str, Any], x402_version: int = 2) -> Requirement | None:
376
+ """Map one entry to v2 names; ``None`` when it fails spec step 0.
377
+
378
+ Step 0: ``scheme``, ``network``, ``asset`` and ``payTo`` must be non-empty
379
+ strings, ``maxTimeoutSeconds`` a positive integer, and the amount
380
+ (``amount``, or ``maxAmountRequired`` in v1) a valid amount string.
381
+ """
382
+ if not isinstance(raw, Mapping):
383
+ return None
384
+ fields = {}
385
+ for key in ("scheme", "network", "asset", "payTo"):
386
+ value = raw.get(key)
387
+ if not isinstance(value, str) or not value:
388
+ return None
389
+ fields[key] = value
390
+ timeout = raw.get("maxTimeoutSeconds")
391
+ if not isinstance(timeout, int) or isinstance(timeout, bool) or timeout <= 0:
392
+ return None
393
+ amount = parse_amount(raw.get("maxAmountRequired" if x402_version == 1 else "amount"))
394
+ if amount is None:
395
+ return None
396
+ raw_network = fields["network"]
397
+ network: str | None = raw_network
398
+ if x402_version == 1:
399
+ network = V1_NETWORKS.get(raw_network)
400
+ return Requirement(
401
+ scheme=fields["scheme"],
402
+ network=network,
403
+ asset=fields["asset"],
404
+ amount=amount,
405
+ pay_to=fields["payTo"],
406
+ x402_version=x402_version,
407
+ raw_network=raw_network,
408
+ max_timeout_seconds=timeout,
409
+ extra=_extra_of(raw),
410
+ )
411
+
412
+
413
+ @dataclass(frozen=True)
414
+ class State:
415
+ """Ledger state for one decision (spec 3.3)."""
416
+
417
+ spent_today: int = 0
418
+ payments_last_minute: int = 0
419
+
420
+ @classmethod
421
+ def from_dict(cls, doc: Mapping[str, Any]) -> State:
422
+ """Build from the vector format ``{"spentToday": "0", "paymentsLastMinute": 0}``."""
423
+ spent = parse_amount(doc.get("spentToday", "0"))
424
+ if spent is None:
425
+ raise ValueError("spentToday must be an amount string")
426
+ return cls(spent_today=spent, payments_last_minute=int(doc.get("paymentsLastMinute", 0)))
427
+
428
+
429
+ @dataclass(frozen=True)
430
+ class Decision:
431
+ """The answer for one entry: ``decision`` plus a spec reason code.
432
+
433
+ ``detail`` is optional free text for ``unsupported`` (spec 3.2, step 1).
434
+ """
435
+
436
+ decision: DecisionKind
437
+ reason: str
438
+ requirement: Requirement | None = None
439
+ rule: LimitRule | None = None
440
+ detail: str | None = None
441
+
442
+
443
+ StateFor = Callable[[str, str], State]
444
+
445
+
446
+ def is_insecure_origin(origin: str, policy: Policy) -> bool:
447
+ """Spec 3.2 step 0: a non-loopback ``http:`` origin the policy does not allow."""
448
+ parts = urlsplit(origin)
449
+ if parts.scheme.lower() != "http" or policy.allow_http:
450
+ return False
451
+ return (parts.hostname or "").lower() not in LOOPBACK_HOSTS
452
+
453
+
454
+ def evaluate(
455
+ policy: Policy,
456
+ accepts: Sequence[Mapping[str, Any]],
457
+ x402_version: int = 2,
458
+ state_for: StateFor | None = None,
459
+ origin: str | None = None,
460
+ ) -> list[Decision]:
461
+ """Decide every entry of ``accepts``, in the server's order (spec 3.2, steps 0 and 1).
462
+
463
+ ``state_for(network, asset)`` returns the :class:`State` for that pair;
464
+ without it nothing counts as spent. With ``origin``, a non-loopback
465
+ ``http:`` origin denies every entry with ``insecure-origin`` unless the
466
+ policy sets ``allowHttp``.
467
+ """
468
+ if origin is not None and is_insecure_origin(origin, policy):
469
+ return [Decision("deny", "insecure-origin") for _ in accepts]
470
+ out: list[Decision] = []
471
+ for raw in accepts:
472
+ req = normalize_requirement(raw, x402_version)
473
+ state = State()
474
+ if state_for is not None and req is not None and req.network is not None:
475
+ state = state_for(req.network, req.asset)
476
+ out.append(policy.decide(raw, state, x402_version))
477
+ return out
478
+
479
+
480
+ @dataclass(frozen=True)
481
+ class Choice:
482
+ """What to do with an ``accepts`` list (spec 3.2).
483
+
484
+ ``action`` is ``"pay"`` (pay entry ``index`` as the policy allows it),
485
+ ``"ask"`` (entry ``index`` needs the approval callback) or ``"deny"``
486
+ (nothing can be paid; ``index`` is ``None``).
487
+ """
488
+
489
+ action: Literal["pay", "ask", "deny"]
490
+ index: int | None
491
+
492
+
493
+ def choose(decisions: Sequence[Decision]) -> Choice:
494
+ """The first ``allow``; else the first ``ask``; else deny (spec 3.2, steps 2 to 4)."""
495
+ for i, d in enumerate(decisions):
496
+ if d.decision == "allow":
497
+ return Choice("pay", i)
498
+ for i, d in enumerate(decisions):
499
+ if d.decision == "ask":
500
+ return Choice("ask", i)
501
+ return Choice("deny", None)
502
+
503
+
504
+ # ----------------------------------------------------------------------------
505
+ # Approval callback
506
+ # ----------------------------------------------------------------------------
507
+
508
+
509
+ @dataclass(frozen=True)
510
+ class ApprovalRequest:
511
+ """Read-only data handed to the approval callback (spec 3.2, step 3).
512
+
513
+ ``amount`` is the atomic amount as a decimal string; ``network`` is CAIP-2;
514
+ ``origin`` is scheme, host and port only.
515
+ """
516
+
517
+ network: str
518
+ asset: str
519
+ amount: str
520
+ pay_to: str
521
+ scheme: str
522
+ origin: str
523
+
524
+
525
+ #: The approval callback: return ``True`` to approve (anything else rejects).
526
+ #: Async callbacks are supported by the async httpx client.
527
+ Approve = Callable[[ApprovalRequest], bool | Awaitable[bool]]
plug402/py.typed ADDED
File without changes
plug402/requests.py ADDED
@@ -0,0 +1,146 @@
1
+ """requests add-on: an ``HTTPAdapter`` and a session helper that pay ``402`` responses.
2
+
3
+ ::
4
+
5
+ from plug402.requests import x402_session
6
+
7
+ session = x402_session(account, policy="policy.json")
8
+ r = session.get("https://api.example.com/paid")
9
+
10
+ :class:`X402Adapter` subclasses the official ``x402.http.clients.requests.
11
+ x402HTTPAdapter``: it keeps the official adapter's set-up (the official
12
+ ``x402HTTPClientSync`` for the header wire format) and its handling of
13
+ streamed and capped ``402`` bodies, and replaces the payment step so the
14
+ plug402 spend policy runs before anything is signed. Signing is done by the
15
+ official ``x402ClientSync`` and exact schemes.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Mapping
21
+ from typing import Any
22
+
23
+ import requests
24
+ from requests.adapters import HTTPAdapter
25
+ from x402.http.clients.requests import x402HTTPAdapter
26
+ from x402.http.utils import read_limited_body
27
+
28
+ from ._engine import Engine, has_payment_header
29
+ from .errors import PaymentFailed
30
+ from .ledger import Ledger, origin_of
31
+ from .policy import Approve, Policy
32
+
33
+ __all__ = ["X402Adapter", "x402_session"]
34
+
35
+
36
+ def _read_capped(resp: requests.Response) -> bytes:
37
+ """Read a 402 body with the official size cap and keep it on the response."""
38
+ if resp._content_consumed: # type: ignore[attr-defined]
39
+ return resp.content or b""
40
+ try:
41
+ raw = resp.raw
42
+ stream = getattr(raw, "stream", None)
43
+ content = read_limited_body(stream(decode_content=True) if callable(stream) else raw)
44
+ finally:
45
+ resp.close()
46
+ resp._content = content # type: ignore[attr-defined]
47
+ resp._content_consumed = True # type: ignore[attr-defined]
48
+ for name in ("content-encoding", "content-length"):
49
+ resp.headers.pop(name, None)
50
+ return content
51
+
52
+
53
+ class X402Adapter(x402HTTPAdapter):
54
+ """A requests transport adapter that pays ``402`` responses under a spend policy.
55
+
56
+ Mount it on a session (``session.mount("https://", adapter)``) or use
57
+ :func:`x402_session`. Same arguments and errors as
58
+ :class:`plug402.httpx.X402Auth`; extra keyword arguments go to
59
+ ``requests.adapters.HTTPAdapter``. The approval callback must be sync.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ signers: Any,
65
+ policy: Policy | Mapping[str, Any] | str,
66
+ ledger: Ledger | None = None,
67
+ approve: Approve | None = None,
68
+ *,
69
+ svm_rpc_url: str | None = None,
70
+ **adapter_kwargs: Any,
71
+ ) -> None:
72
+ engine = Engine(signers, policy, ledger, approve, svm_rpc_url=svm_rpc_url)
73
+ super().__init__(engine.http, **adapter_kwargs)
74
+ self.engine = engine
75
+
76
+ @property
77
+ def ledger(self) -> Ledger:
78
+ """The ledger receipts are written to."""
79
+ return self.engine.ledger
80
+
81
+ @property
82
+ def policy(self) -> Policy:
83
+ """The spend policy in force."""
84
+ return self.engine.policy
85
+
86
+ def send(self, request: requests.PreparedRequest, **kwargs: Any) -> requests.Response: # type: ignore[override]
87
+ """Send; on a ``402``, decide, sign with the official client, retry once."""
88
+ if has_payment_header(request.headers.get):
89
+ return HTTPAdapter.send(self, request, **kwargs)
90
+
91
+ caller_wants_stream = kwargs.pop("stream", False)
92
+ send_kwargs = {**kwargs, "stream": True}
93
+
94
+ def finalize(resp: requests.Response) -> requests.Response:
95
+ if not caller_wants_stream:
96
+ _ = resp.content
97
+ return resp
98
+
99
+ response = HTTPAdapter.send(self, request, **send_kwargs)
100
+ if response.status_code != 402:
101
+ return finalize(response)
102
+
103
+ body = _read_capped(response)
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 response
107
+
108
+ paid_request = request.copy()
109
+ paid_request.headers.update(payment.headers)
110
+ try:
111
+ paid = HTTPAdapter.send(self, paid_request, **send_kwargs)
112
+ except BaseException:
113
+ payment.fail() # transport error before any response
114
+ raise
115
+ payment.complete(paid.status_code, paid.headers.get)
116
+ if paid.status_code == 402:
117
+ _read_capped(paid)
118
+ raise PaymentFailed(
119
+ "the paid request was answered with 402 again; it is not paid twice",
120
+ status_code=paid.status_code,
121
+ receipt_id=payment.receipt.id,
122
+ response=paid,
123
+ )
124
+ return finalize(paid)
125
+
126
+
127
+ def x402_session(
128
+ signers: Any,
129
+ policy: Policy | Mapping[str, Any] | str,
130
+ ledger: Ledger | None = None,
131
+ approve: Approve | None = None,
132
+ *,
133
+ session: requests.Session | None = None,
134
+ svm_rpc_url: str | None = None,
135
+ **adapter_kwargs: Any,
136
+ ) -> requests.Session:
137
+ """A ``requests.Session`` (new, or the one given) with :class:`X402Adapter` mounted.
138
+
139
+ The adapter is mounted for ``https://`` and ``http://``; it is reachable as
140
+ ``session.get_adapter("https://")``.
141
+ """
142
+ session = session if session is not None else requests.Session()
143
+ adapter = X402Adapter(signers, policy, ledger, approve, svm_rpc_url=svm_rpc_url, **adapter_kwargs)
144
+ session.mount("https://", adapter)
145
+ session.mount("http://", adapter)
146
+ return session