From e90dc1a44040b693c18a5df3882a0330f9985618 Mon Sep 17 00:00:00 2001 From: Nas Kavian Date: Sun, 15 Nov 2026 01:14:51 -0500 Subject: [PATCH] feat(sdk): expose request-local payment options and capability metadata --- README.md | 176 +++++++++++++++- conformance/adapter.py | 30 ++- conformance/inflow-specs.lock.json | 2 +- interop/node.lock.json | 2 +- pyproject.toml | 1 + scripts/interoperability.mjs | 2 + src/inflowpay/_runtime.py | 6 +- src/inflowpay/mpp/_controls.py | 129 ++++++++++++ src/inflowpay/mpp/buyer.py | 155 +++++++++++---- src/inflowpay/x402/_seller.py | 19 ++ src/inflowpay/x402/facilitator.py | 29 ++- tests/test_mpp_controls.py | 194 ++++++++++++++++++ tests/test_mpp_request_options.py | 265 +++++++++++++++++++++++++ tests/test_native_extensions.py | 247 +++++++++++++++++++++++ tests/test_native_frameworks.py | 91 +++++++++ tests/test_solana_versions.py | 182 +++++++++++++++++ tests/test_upstream_upgrade.py | 4 +- tests/test_x402_extension_responses.py | 76 +++++++ uv.lock | 70 +++++++ 19 files changed, 1622 insertions(+), 58 deletions(-) create mode 100644 src/inflowpay/mpp/_controls.py create mode 100644 tests/test_mpp_controls.py create mode 100644 tests/test_mpp_request_options.py create mode 100644 tests/test_native_extensions.py create mode 100644 tests/test_native_frameworks.py create mode 100644 tests/test_solana_versions.py create mode 100644 tests/test_x402_extension_responses.py diff --git a/README.md b/README.md index 4ca3e8d..39a1cdc 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,37 @@ fields through pympp's request retry. Plain pympp `PaymentRuntime` and `McpClien rebuild credentials using fixed-field models and can drop additional credential fields and an empty `source`. Their normal payment payload is retained. +### Select options for one request + +Pass `PaymentOptions` through HTTPX's `extensions` argument to override a buyer's +defaults for one request. Omit a field to inherit its constructor value, or set it +to `None` to clear that value. Clearing the instrument lets InFlow select the +funding source; clearing the subscription requests a new subscription payment +instead of authorizing an existing subscription. CARD payments still require +valid merchant details, so clearing the merchant fails before requesting payment. + +```python +from inflowpay.mpp.buyer import PaymentOptions + +response = await http.get( + resource_url, + extensions={"inflow.payment": PaymentOptions(instrument_id=instrument_id)}, +) +``` + +The options are local request metadata, not HTTP headers or a request body. They +are validated and copied before payment creation; concurrent requests do not +change each other's settings. Direct method calls accept the same options as +`CredentialParams(context=PaymentOptions(...), challenge=challenge)`. Cancelling +the request's asyncio task cancels that request's approval wait, not other requests +using the same buyer. + +To select among offered challenges, pass pympp's native `order_challenges` +callback to `payment_transport`. It receives supported challenge candidates and +may return them in a different order or filter them. Returning an empty sequence +rejects payment without creating an approval. The transport retains its one-paid- +attempt limit regardless of the callback. + | Constructor settings | Behavior | | --- | --- | | Defaults: `method="inflow", intent="charge"` | Pay an InFlow charge using the rail advertised by the seller. | @@ -242,14 +273,33 @@ fields and an empty `source`. Their normal payment payload is retained. | `intent="subscription"` | Purchase a subscription through the create-and-approve flow. | | `intent="subscription", subscription_id="..."` | Authorize access using that existing subscription and the current seller challenge; do not purchase another subscription. | -Instrument and subscription identifiers are UUID strings. They are fixed when the -method is constructed. This adapter rejects nonempty per-call `context`; configure -selectors on the constructor instead. -Use separate method instances for different selections; do not change +Instrument and subscription identifiers are UUID strings. Constructor values are +defaults; use `PaymentOptions` for request-specific selections. Do not mutate one instance's settings between concurrent requests. Do not register several methods with the same method/intent expecting pympp to choose a funding instrument: pympp selects the first matching method. Select the intended instance in your application. +### Limit automatic MPP payments + +`BuyerMethod` imposes no amount ceiling or allowlist unless you configure one. +For example, `BuyerMethod(options, max_amount="5.00", currencies=["USD"])` +accepts InFlow charges of at most five USD. Limits filter challenge selection and +are checked again before direct credential creation, before any approval request. +`PaymentOptions` cannot change or disable them. + +| Method | Optional limits | +| --- | --- | +| InFlow charge | `max_amount` in decimal currency units requires `currencies`; `expected_recipients` restricts recipient identifiers. | +| Tempo charge | `max_atomic_amount` limits smallest token units. `max_amount` requires explicit `max_amount_decimals`. Either amount limit requires `currencies` containing token addresses. `allowed_chain_ids` restricts chains; `expected_recipients` checks both the primary recipient and every split recipient. | +| CARD charge | `max_amount` is USD with at most two significant decimal places; `max_atomic_amount` is cents. | + +When both amount limits are supplied, both must pass. Empty allowlists reject all +payments for that field. Tempo addresses are compared case-insensitively; InFlow +currency and recipient identifiers are exact matches. Configuration is copied at +construction, so editing the caller's lists cannot relax a buyer's limits. Charge +limits are rejected on subscription methods rather than applied to recurring +payments with different approval semantics. + ### Pay with a linked Visa card Use `method="card"` for a merchant advertising CARD charge, not for an InFlow @@ -422,6 +472,11 @@ when application authentication uses `Authorization`; pympp then uses `Payment-Authorization` for the payment credential. The decorator does not implement your application's authentication or access-control policy. +For an entire ASGI application, pympp also provides +`PaymentMiddleware(app, payments.charge(**terms))` in `mpp.server.asgi`. +It protects every HTTP route in that application; mount it only around routes +that require payment, not around public health or discovery endpoints. + pympp's `pay` decorator returns HTTP `402` for payment errors, including a pending settlement whose Problem Details body has `status: 503`. The InFlow Seller preserves that problem; the HTTP status is chosen by pympp. Node's middleware uses the problem's @@ -979,6 +1034,108 @@ forces a refresh. `await seller.get_supported(refresh=True)` refreshes the Selle capability lookup, not a running Facilitator or resource server. Values returned by these methods can be modified without changing the client's cache. +### Native x402 extensions + +`Buyer` inherits upstream extension registration. Sellers register native +extensions on `x402ResourceServer` and attach declarations to `RouteConfig.extensions`. +There is no separate InFlow extension registry. For the examples below, install +`x402[extensions]` alongside `inflowpay[evm,fastapi]` in compatible versions. + +#### Wallet authentication for paid resources + +Sign-In-With-X lets an external wallet prove ownership of the address that paid +for a resource. Register the upstream client extension on your buyer: + +```python +from x402.extensions.sign_in_with_x import ( + CreateSIWxClientExtensionOptions, + create_siwx_client_extension, +) + +buyer.register_extension( + create_siwx_client_extension(CreateSIWxClientExtensionOptions(signers=[wallet])) +) +``` + +Here `wallet` is your external signing account, such as an `eth_account` account; +the InFlow managed wallet does not provide this message-signing interface. Use the +native `x402AsyncTransport` with the buyer so its HTTP authentication hooks run. +Calling `create_payment_payload` directly does not perform HTTP authentication. + +On the seller, configure the public origin and storage, then declare the extension +on each applicable route: + +```python +from x402.extensions.sign_in_with_x import ( + CreateSIWxResourceServerExtensionOptions, + DeclareSIWxOptions, + create_siwx_resource_server_extension, + declare_siwx_extension, +) + +resource_server.register_extension( + create_siwx_resource_server_extension( + CreateSIWxResourceServerExtensionOptions(origin="https://store.example", storage=storage) + ) +) +route = await seller.route("0.10 USDC", schemes=["exact"]) +route.extensions = declare_siwx_extension(DeclareSIWxOptions(expiration_seconds=300)) +``` + +Storage must implement paid-resource tracking. For replay detection, also provide +both `has_used_nonce` and `record_nonce`; upstream's `InMemorySIWxStorage` does not +implement those two methods. Choose persistence and concurrency handling suitable +for your deployment. The upstream hooks record access after successful settlement +and check wallet proofs before running the protected handler. Authentication can +avoid another payment for a resource whose access has already been recorded. +If authentication fails, upstream can fall back to payment; configure buyer payment +policies accordingly. Registering this extension does not enroll a user with AEP. + +#### Discovery metadata and explicit attribution + +Bazaar metadata describes a paid HTTP route. Attach its declaration to the same +route used by the middleware, including request-time route resolvers: + +```python +from x402.extensions.bazaar import declare_discovery_extension + +route = await seller.route("0.10 USDC") +route.extensions = declare_discovery_extension() +``` + +Native middleware enriches route templates and request path parameters. This does +not publish the service to the InFlow Directory or replace an ODP catalog. + +Builder attribution is opt-in. A seller can attach +`{"builder-code": declare_builder_code_extension("your_app")}` using +`x402.extensions.builder_code`. An external-wallet buyer can register +`BuilderCodeClientExtension("your_client")` from that module. The facilitator must +support builder-code settlement for those declarations to become on-chain +attribution. InFlow's facilitator does not promise that capability; attaching +metadata alone is not proof that a settlement transaction carries it. No InFlow +builder code is injected automatically. The installed Python x402 extension set +does not provide the signed-offer/signed-receipt extension available in Node. + +#### Browser paywalls + +The native paywall provider can be passed through the InFlow request-pricing +middleware. For an EVM USDC route: + +```python +from x402.http.paywall import create_paywall, evm_paywall +from inflowpay.x402.fastapi import payment_middleware + +paywall = create_paywall().with_network(evm_paywall).with_config(app_name="Reports").build() +app.middleware("http")( + payment_middleware({"GET /report": route}, resource_server, paywall_provider=paywall) +) +``` + +Browser requests accepting HTML receive the native payment page; API clients +receive the protocol's payment challenge. Configure a route and network the +paywall actually supports. The native EVM paywall is not an InFlow hosted-wallet, +balance, or CARD checkout interface. + ### Prices, payment methods, and metering `seller.offers()` accepts `"$0.01"`, `"0.01 USDC"`, or `"0.01"` with @@ -1086,6 +1243,17 @@ settlement require a Seller account. ## x402 facilitator capabilities +Verification and settlement results expose valid `EXTENSION-RESPONSES` header +metadata as `result.extension_responses` for seller hooks. Missing or malformed +metadata is ignored; it does not change whether verification or settlement +succeeded. Upstream response models exclude this field from serialized buyer +receipts. + +For Solana exact offers, seller configuration's matching supported capability +supplies `extra.transactionVersions`. The SDK preserves that value and does not +advertise version support when it is absent. The managed buyer forwards the +selected requirement unchanged; the wallet service constructs the transaction. + Facilitator capabilities describe the payment schemes, networks, and extensions the facilitator supports. InFlow fetches these capabilities asynchronously during adapter creation. Setup fails if that request fails, rather than returning an diff --git a/conformance/adapter.py b/conformance/adapter.py index 77baa83..36df6b9 100644 --- a/conformance/adapter.py +++ b/conformance/adapter.py @@ -14,7 +14,13 @@ from mpp.server.decorator import pay from mpp.server.method import ValidateContext, VerifyContext from starlette.responses import JSONResponse -from x402.schemas import PaymentPayload, PaymentRequirements, ResourceInfo +from x402.schemas import ( + PaymentPayload, + PaymentRequirements, + ResourceInfo, + SettleResponse, + VerifyResponse, +) from conformance.tap import tap_execute from inflowpay import ClientOptions, InflowApiError, mpp, x402 @@ -380,16 +386,26 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: ) as facilitator: payload = PaymentPayload.model_validate(data["payment_payload"]) requirement = PaymentRequirements.model_validate(data["payment_requirements"]) + + def observe(result: VerifyResponse | SettleResponse) -> Data: + # Metadata is observable by sellers but intentionally absent from wire serialization. + return { + **result.model_dump(exclude_none=True), + **( + {"extensionResponses": result.extension_responses} + if result.extension_responses is not None + else {} + ), + } + if operation == "x402.seller.settle": - return (await facilitator.settle(payload, requirement)).model_dump(exclude_none=True) + return observe(await facilitator.settle(payload, requirement)) verified = await facilitator.verify(payload, requirement) if operation == "x402.seller.verify": - return verified.model_dump(exclude_none=True) - observations = {"verification": verified.model_dump(exclude_none=True)} + return observe(verified) + observations = {"verification": observe(verified)} if verified.is_valid: - observations["settlement"] = ( - await facilitator.settle(payload, requirement) - ).model_dump(exclude_none=True) + observations["settlement"] = observe(await facilitator.settle(payload, requirement)) return observations diff --git a/conformance/inflow-specs.lock.json b/conformance/inflow-specs.lock.json index 9d3fe8f..3e513ed 100644 --- a/conformance/inflow-specs.lock.json +++ b/conformance/inflow-specs.lock.json @@ -1,4 +1,4 @@ { "repository": "inflowpayai/inflow-specs", - "revision": "20c518990672db7d29020ba22056a4c372d356c4" + "revision": "efdccacc338ed5397e2a37e1f12f6568f83b4811" } diff --git a/interop/node.lock.json b/interop/node.lock.json index b5d678a..1ed63fa 100644 --- a/interop/node.lock.json +++ b/interop/node.lock.json @@ -1,4 +1,4 @@ { "repository": "inflowpayai/inflow-node", - "revision": "309aab2650dcb06dd652a5076dc176d5c41196d7" + "revision": "c28b402ebdfc0f59efd84be21396f403768b3394" } diff --git a/pyproject.toml b/pyproject.toml index 0156418..3273591 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,6 +47,7 @@ dev = [ "ruff==0.17.5", "twine==7.0.0", "uvicorn==0.52.4", + "x402[extensions]==2.28.0", ] [tool.hatch.build.targets.sdist] diff --git a/scripts/interoperability.mjs b/scripts/interoperability.mjs index e107a75..e171a2b 100644 --- a/scripts/interoperability.mjs +++ b/scripts/interoperability.mjs @@ -249,6 +249,7 @@ async function runCase( problem: { type: "https://paymentauth.org/problems/verification-failed", title: "Rejected test payment", + detail: "The synthetic payment was rejected during validation.", status: 402, }, }); @@ -272,6 +273,7 @@ async function runCase( problem: { type: "https://paymentauth.org/problems/verification-failed", title: "Rejected test payment", + detail: "The synthetic payment was rejected during settlement.", status: 402, }, }); diff --git a/src/inflowpay/_runtime.py b/src/inflowpay/_runtime.py index 2864c8c..3c6eb2f 100644 --- a/src/inflowpay/_runtime.py +++ b/src/inflowpay/_runtime.py @@ -169,6 +169,7 @@ async def request( body: object = None, headers: Mapping[str, str] | None = None, retries: int = 0, + response_parser: Callable[[httpx.Response], object] = _parse, ) -> object: # Retry permission belongs to the protocol operation, not the HTTP method. if not path.startswith("/") or path.startswith("//") or "#" in path: @@ -181,7 +182,7 @@ async def request( content = None if body is None else json.dumps(body, allow_nan=False).encode() attempt = 0 while True: - error = await self._attempt(method, path, content, extra) + error = await self._attempt(method, path, content, extra, response_parser) if not isinstance(error, InflowApiError): return error if attempt >= min(retries, 3) or ( @@ -197,6 +198,7 @@ async def _attempt( path: str, content: bytes | None, extra: dict[str, str], + response_parser: Callable[[httpx.Response], object], ) -> object: await asyncio.sleep(0) token = self._options.api_key @@ -244,7 +246,7 @@ async def _attempt( endpoint=path, ) if response.is_success: - return _parse(response) + return response_parser(response) return _error(path, response, (token,) if token else ()) async def get_payment_status( diff --git a/src/inflowpay/mpp/_controls.py b/src/inflowpay/mpp/_controls.py new file mode 100644 index 0000000..26b34e6 --- /dev/null +++ b/src/inflowpay/mpp/_controls.py @@ -0,0 +1,129 @@ +import re +from collections.abc import Callable, Sequence +from typing import cast + +from ._wire import WireObject, object_value, string + + +def _decimal(value: str) -> tuple[str, str]: + if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)?", value): + raise ValueError("max_amount must be a nonnegative decimal string") + whole, _, fraction = value.partition(".") + return whole, fraction.rstrip("0") + + +def _atomic(value: str, decimals: int) -> int: + whole, fraction = _decimal(value) + if len(fraction) > decimals: + raise ValueError("max_amount exceeds currency precision") + return int(whole + fraction.ljust(decimals, "0")) + + +def _strings(values: Sequence[str] | None, *, lower: bool) -> tuple[str, ...] | None: + if values is None: + return None + if isinstance(values, (str, bytes)) or any( + not isinstance(value, str) or not value for value in values + ): + raise ValueError("Payment allowlists must be sequences of nonempty strings") + return tuple(value.lower() if lower else value for value in values) + + +def controls( + method: str, + intent: str, + *, + max_amount: str | None, + max_atomic_amount: int | str | None, + max_amount_decimals: int | None, + currencies: Sequence[str] | None, + expected_recipients: Sequence[str] | None, + allowed_chain_ids: Sequence[int] | None, +) -> Callable[[WireObject], None]: + configured = any( + value is not None + for value in ( + max_amount, + max_atomic_amount, + max_amount_decimals, + currencies, + expected_recipients, + allowed_chain_ids, + ) + ) + if intent != "charge" and configured: + raise ValueError("Payment limits apply only to charge intents") + if method != "tempo" and (max_amount_decimals is not None or allowed_chain_ids is not None): + raise ValueError("max_amount_decimals and allowed_chain_ids apply only to Tempo") + if method == "inflow" and max_atomic_amount is not None: + raise ValueError("InFlow amounts use decimal currency units; use max_amount") + if method == "card" and (currencies is not None or expected_recipients is not None): + raise ValueError("CARD supports amount limits only") + currency_set = _strings(currencies, lower=method == "tempo") + recipients = _strings(expected_recipients, lower=method == "tempo") + chains = None if allowed_chain_ids is None else tuple(allowed_chain_ids) + if chains is not None and any( + type(chain) is not int or not 0 <= chain <= 9007199254740991 for chain in chains + ): + raise ValueError("allowed_chain_ids must contain nonnegative safe integers") + if max_amount_decimals is not None and ( + type(max_amount_decimals) is not int or not 0 <= max_amount_decimals <= 255 + ): + raise ValueError("max_amount_decimals must be an integer from 0 to 255") + atomic_limit = None + if max_atomic_amount is not None: + if isinstance(max_atomic_amount, bool) or not re.fullmatch( + r"[0-9]+", str(max_atomic_amount) + ): + raise ValueError("max_atomic_amount must be a nonnegative integer or digit string") + atomic_limit = int(max_atomic_amount) + if ( + method == "tempo" + and (max_amount is not None or atomic_limit is not None) + and currency_set is None + ): + raise ValueError("Tempo amount limits require currencies") + token_limit = None + if max_amount is not None: + _decimal(max_amount) + if method == "inflow": + if currency_set is None: + raise ValueError("max_amount requires currencies") + else: + decimals = 2 if method == "card" else max_amount_decimals + if decimals is None: + raise ValueError("Tempo max_amount requires max_amount_decimals") + token_limit = _atomic(max_amount, decimals) + + def check(request: WireObject) -> None: + if currency_set is not None: + currency = string(request.get("currency")) + if (currency.lower() if method == "tempo" else currency) not in currency_set: + raise ValueError("MPP charge currency is not allowed") + details = object_value(request.get("methodDetails", {})) + if chains is not None and details.get("chainId") not in chains: + raise ValueError("MPP charge chain is not allowed") + if recipients is not None: + values = [request.get("recipient")] + if method == "tempo": + # Both callers run validate_request before applying limits. + splits = cast(list[WireObject], details.get("splits", [])) + values.extend(split.get("recipient") for split in splits) + for value in values: + recipient = string(value) + if (recipient.lower() if method == "tempo" else recipient) not in recipients: + raise ValueError("MPP charge recipient is not allowed") + if method == "inflow": + if max_amount is not None: + amount = string(request.get("amount")) + precision = max(len(_decimal(amount)[1]), len(_decimal(max_amount)[1])) + if _atomic(amount, precision) > _atomic(max_amount, precision): + raise ValueError("MPP charge amount exceeds max_amount") + elif token_limit is not None or atomic_limit is not None: + amount_atomic = int(string(request.get("amount"))) + if token_limit is not None and amount_atomic > token_limit: + raise ValueError("MPP charge amount exceeds max_amount") + if atomic_limit is not None and amount_atomic > atomic_limit: + raise ValueError("MPP charge amount exceeds max_atomic_amount") + + return check diff --git a/src/inflowpay/mpp/buyer.py b/src/inflowpay/mpp/buyer.py index 168c880..9a836fd 100644 --- a/src/inflowpay/mpp/buyer.py +++ b/src/inflowpay/mpp/buyer.py @@ -3,11 +3,11 @@ import asyncio import math import re -from collections.abc import Sequence +from collections.abc import Callable, Sequence from copy import deepcopy from dataclasses import dataclass, field from types import TracebackType -from typing import Self +from typing import Self, TypedDict from urllib.parse import quote from uuid import UUID @@ -15,10 +15,11 @@ from mpp import Challenge, Credential from mpp.client.transport import PaymentTransport from mpp.events import CHALLENGE_RECEIVED, EventDispatcher, EventPayload -from mpp.runtime import ClientMethod, CredentialParams +from mpp.runtime import ClientMethod, CredentialParams, OrderChallenges from .._runtime import Client from ..options import ClientOptions +from ._controls import controls from ._method import method_definition from ._pympp import from_pympp_challenge from ._requests import validate_payload, validate_request @@ -38,10 +39,19 @@ "MppPaymentExpiredError", "MppPaymentFailedError", "MppPaymentTimeoutError", + "PaymentOptions", "payment_transport", ] +class PaymentOptions(TypedDict, total=False): + """Omitted selectors inherit buyer defaults; None clears a selector.""" + + instrument_id: str | None + subscription_id: str | None + merchant: WireObject | None + + class MppMalformedCredentialError(ValueError): pass @@ -133,6 +143,34 @@ def _card_merchant(value: WireObject | None) -> WireObject: return {"name": name, "url": url, "countryCode": country} +def _validate_options( + method: str, + intent: str, + instrument_id: str | None, + subscription_id: str | None, + merchant: WireObject | None, +) -> WireObject | None: + for value in (instrument_id, subscription_id): + if value is not None: + UUID(value) + if instrument_id is not None and (method, intent) not in ( + ("inflow", "charge"), + ("card", "charge"), + ): + raise ValueError("instrument_id applies only to InFlow or CARD charge") + if ( + method == "card" + and instrument_id is not None + and not re.fullmatch(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", instrument_id) + ): + raise ValueError("CARD instrument_id must be a hyphenated UUID") + if merchant is not None and method != "card": + raise ValueError("merchant applies only to CARD charge") + if subscription_id is not None and intent != "subscription": + raise ValueError("subscription_id applies only to InFlow subscription") + return _card_merchant(merchant) if method == "card" else None + + class BuyerMethod(ClientMethod): def __init__( self, @@ -145,6 +183,12 @@ def __init__( merchant: WireObject | None = None, poll_interval: float = 5, pending_timeout: float = 900, + max_amount: str | None = None, + max_atomic_amount: int | str | None = None, + max_amount_decimals: int | None = None, + currencies: Sequence[str] | None = None, + expected_recipients: Sequence[str] | None = None, + allowed_chain_ids: Sequence[int] | None = None, ) -> None: if (method, intent) not in ( ("inflow", "charge"), @@ -153,33 +197,31 @@ def __init__( ("card", "charge"), ): raise ValueError("Unsupported MPP Buyer method or intent") - for value in (instrument_id, subscription_id): - if value is not None: - UUID(value) - if instrument_id is not None and (method, intent) not in ( - ("inflow", "charge"), - ("card", "charge"), - ): - raise ValueError("instrument_id applies only to InFlow or CARD charge") - if ( - method == "card" - and instrument_id is not None - and not re.fullmatch( - r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", instrument_id - ) - ): - raise ValueError("CARD instrument_id must be a hyphenated UUID") - if merchant is not None and method != "card": - raise ValueError("merchant applies only to CARD charge") object.__setattr__( - self, "_merchant", _card_merchant(merchant) if method == "card" else None + self, + "_merchant", + _validate_options(method, intent, instrument_id, subscription_id, merchant), ) - if subscription_id is not None and intent != "subscription": - raise ValueError("subscription_id applies only to InFlow subscription") if any(not math.isfinite(value) or value < 0 for value in (poll_interval, pending_timeout)): raise ValueError("Polling settings must be finite and nonnegative") + object.__setattr__( + self, + "_check_limits", + controls( + method, + intent, + max_amount=max_amount, + max_atomic_amount=max_atomic_amount, + max_amount_decimals=max_amount_decimals, + currencies=currencies, + expected_recipients=expected_recipients, + allowed_chain_ids=allowed_chain_ids, + ), + ) super().__init__( - method=method_definition(method, intent), create_credential=self._credential + method=method_definition(method, intent), + create_credential=self._credential, + can_handle_challenge=self._accepts, ) # Upstream methods are frozen; only private resource state changes over their lifetime. object.__setattr__(self, "_instrument_id", instrument_id) @@ -198,6 +240,16 @@ def __init__( _client: Client _active: set[asyncio.Task[Credential]] _closed: bool + _check_limits: Callable[[WireObject], None] + + def _accepts(self, challenge: Challenge) -> bool: + try: + self._check_limits( + validate_request(challenge.method, challenge.intent, decode(challenge.request_b64)) + ) + return True + except ValueError: + return False async def __aenter__(self) -> Self: return self @@ -239,37 +291,55 @@ async def _credential(self, params: CredentialParams) -> str: async def _credential_object(self, params: CredentialParams) -> Credential: if self._closed: raise RuntimeError("MPP Buyer method is closed") - if params.context is not None and params.context != {}: - raise ValueError("Per-call context is unsupported; configure selectors on BuyerMethod") + context = params.context + if context is None and isinstance(params.request, httpx.Request): + context = params.request.extensions.get("inflow.payment") + overrides = {} if context is None else object_value(context) + if overrides.keys() - {"instrument_id", "subscription_id", "merchant"}: + raise ValueError("Unknown per-request payment option") + instrument = overrides.get("instrument_id", self._instrument_id) + subscription = overrides.get("subscription_id", self._subscription_id) + merchant = overrides.get("merchant", self._merchant) + selected_merchant = _validate_options( + self.name, + self.intent, + None if instrument is None else string(instrument), + None if subscription is None else string(subscription), + None if merchant is None else object_value(merchant), + ) + options: WireObject = {} if instrument is None else {"instrumentId": instrument} + if selected_merchant is not None: + options["merchant"] = selected_merchant challenge = params.challenge wire = from_pympp_challenge(challenge) if challenge.method != self.name or challenge.intent != self.intent: raise ValueError("Challenge does not match this MPP Buyer method") - validate_request(challenge.method, challenge.intent, decode(challenge.request_b64)) - task = asyncio.create_task(self._create(wire)) + self._check_limits( + validate_request(challenge.method, challenge.intent, decode(challenge.request_b64)) + ) + task = asyncio.create_task( + self._create(wire, options, None if subscription is None else string(subscription)) + ) self._active.add(task) try: return await task finally: self._active.discard(task) - async def _create(self, challenge: WireObject) -> Credential: - if self._subscription_id is not None: + async def _create( + self, challenge: WireObject, options: WireObject, subscription_id: str | None + ) -> Credential: + if subscription_id is not None: response = _response( await self._client.request( "POST", - f"/v1/subscriptions/{quote(self._subscription_id, safe='')}/authorize", + f"/v1/subscriptions/{quote(subscription_id, safe='')}/authorize", body={"challenge": challenge}, ) ) if "problem" in response: raise MppPaymentFailedError(object_value(response["problem"])) return _credential(response, challenge) - options: WireObject = ( - {} if self._instrument_id is None else {"instrumentId": self._instrument_id} - ) - if self._merchant is not None: - options["merchant"] = deepcopy(self._merchant) response = _response( await self._client.request( "POST", @@ -345,7 +415,9 @@ async def emit(self, name: str, payload: EventPayload, *, first_result: bool = F if isinstance(method, BuyerMethod) and isinstance(challenge, Challenge): # Supply the wire-preserving object before pympp reparses its serialization. # Do not use a normal listener: its exceptions are swallowed, allowing a retry. - return await method._credential_object(CredentialParams(challenge=challenge)) + return await method._credential_object( + CredentialParams(challenge=challenge, request=payload.get("request")) + ) return supplied @@ -353,8 +425,13 @@ def payment_transport( methods: Sequence[ClientMethod], *, inner: httpx.AsyncBaseTransport | None = None, + order_challenges: OrderChallenges | None = None, ) -> PaymentTransport: # pympp creates another credential on each retry. Limit automatic payment to one attempt. return PaymentTransport( - methods=methods, inner=inner, events=_PaymentEvents(), max_payment_retries=1 + methods=methods, + inner=inner, + events=_PaymentEvents(), + max_payment_retries=1, + order_challenges=order_challenges, ) diff --git a/src/inflowpay/x402/_seller.py b/src/inflowpay/x402/_seller.py index e02553b..961628a 100644 --- a/src/inflowpay/x402/_seller.py +++ b/src/inflowpay/x402/_seller.py @@ -125,6 +125,25 @@ def include(scheme: str, network: str) -> bool: if not include(scheme, asset.network): continue extra: dict[str, Any] = {"assetName": asset.asset_name} + if scheme == "exact" and asset.network.startswith("solana:"): + supported = next( + ( + kind + for kind in config.supported + if kind.x402_version == 2 + and kind.scheme == scheme + and kind.network == asset.network + ), + None, + ) + if ( + supported is not None + and supported.extra is not None + and "transactionVersions" in supported.extra + ): + extra["transactionVersions"] = deepcopy( + supported.extra["transactionVersions"] + ) for key, value in ( ("name", asset.token_name), ("version", asset.token_version), diff --git a/src/inflowpay/x402/facilitator.py b/src/inflowpay/x402/facilitator.py index 9b3b621..5a54d90 100644 --- a/src/inflowpay/x402/facilitator.py +++ b/src/inflowpay/x402/facilitator.py @@ -7,6 +7,8 @@ from types import TracebackType from typing import Self +import httpx +from x402.http.extension_responses import extract_extension_responses_header from x402.schemas import ( PaymentPayload, PaymentPayloadV1, @@ -28,6 +30,20 @@ ) +def _verify_response(response: httpx.Response) -> VerifyResponse: + result = VerifyResponse.model_validate(response.json()) + return result.model_copy( + update={"extension_responses": extract_extension_responses_header(response)} + ) + + +def _settle_response(response: httpx.Response) -> SettleResponse: + result = SettleResponse.model_validate(response.json()) + return result.model_copy( + update={"extension_responses": extract_extension_responses_header(response)} + ) + + def _request( payload: PaymentPayload | PaymentPayloadV1, requirements: PaymentRequirements | PaymentRequirementsV1, @@ -109,7 +125,10 @@ async def verify( ) -> VerifyResponse: try: response = await self._client.request( - "POST", "/v1/x402/verify", body=_request(payload, requirements) + "POST", + "/v1/x402/verify", + body=_request(payload, requirements), + response_parser=_verify_response, ) except InflowApiError as error: body = error.body @@ -120,7 +139,9 @@ async def verify( and body.get("invalidReason") == "permit2_allowance_required" ): raise - response = body + response = VerifyResponse.model_validate(body).model_copy( + update={"extension_responses": extract_extension_responses_header(error)} + ) return VerifyResponse.model_validate(response) async def settle( @@ -132,7 +153,9 @@ async def settle( attempt = 1 while True: try: - response = await self._client.request("POST", "/v1/x402/settle", body=body) + response = await self._client.request( + "POST", "/v1/x402/settle", body=body, response_parser=_settle_response + ) return SettleResponse.model_validate(response) except InflowApiError as error: if not ( diff --git a/tests/test_mpp_controls.py b/tests/test_mpp_controls.py new file mode 100644 index 0000000..ab07518 --- /dev/null +++ b/tests/test_mpp_controls.py @@ -0,0 +1,194 @@ +import json +from typing import Any + +import httpx +import pytest +from mpp.runtime import CredentialParams + +from inflowpay import ClientOptions +from inflowpay.mpp import WireObject, encode, to_pympp_challenge +from inflowpay.mpp.buyer import BuyerMethod, payment_transport +from test_card_buyer import CHALLENGE, MERCHANT +from test_card_buyer import ready as card_ready +from test_card_seller import PAYLOAD +from test_mpp_buyer import ID, WIRE, ready + +TOKEN = "0x" + "ab" * 20 +RECIPIENT = "0x" + "cd" * 20 + + +def wire(method: str, amount: str, **extra: Any) -> WireObject: + if method == "card": + from inflowpay.mpp import decode + + request = decode(str(CHALLENGE["request"])) + assert isinstance(request, dict) + return {**CHALLENGE, "request": encode({**request, "amount": amount, **extra})} + request = {"amount": amount, "currency": "USD", "recipient": ID} + if method == "tempo": + request.update(currency=TOKEN, recipient=RECIPIENT) + return {**WIRE, "method": method, "request": encode({**request, **extra})} + + +@pytest.mark.parametrize( + "method,settings", + [ + ("inflow", {"max_amount": "1"}), + ("inflow", {"max_atomic_amount": 1}), + ("inflow", {"max_amount_decimals": 2}), + ("inflow", {"allowed_chain_ids": []}), + ("inflow", {"currencies": "USD"}), + ("inflow", {"currencies": [""]}), + ("inflow", {"currencies": [1]}), + ("inflow", {"max_amount": "-1", "currencies": ["USD"]}), + ("inflow", {"max_amount": "1e3", "currencies": ["USD"]}), + ("card", {"max_amount": "0.501"}), + ("card", {"currencies": ["usd"]}), + ("card", {"expected_recipients": []}), + ("card", {"max_atomic_amount": -1}), + ("card", {"max_atomic_amount": True}), + ("card", {"max_atomic_amount": "1.5"}), + ("tempo", {"max_atomic_amount": 1}), + ("tempo", {"max_amount": "1", "currencies": [TOKEN]}), + ("tempo", {"max_amount_decimals": -1}), + ("tempo", {"max_amount_decimals": 256}), + ("tempo", {"max_amount_decimals": True}), + ("tempo", {"allowed_chain_ids": [-1]}), + ("tempo", {"allowed_chain_ids": [True]}), + ("tempo", {"allowed_chain_ids": [9007199254740992]}), + ], +) +def test_invalid_limits_fail_at_construction(method: str, settings: dict[str, Any]) -> None: + with pytest.raises(ValueError): + BuyerMethod( + ClientOptions(), + method=method, + merchant=MERCHANT if method == "card" else None, + **settings, + ) + + +def test_subscription_does_not_silently_accept_charge_limits() -> None: + with pytest.raises(ValueError, match="charge intents"): + BuyerMethod(ClientOptions(), intent="subscription", currencies=["USD"]) + + +@pytest.mark.parametrize( + "method,amount,settings,extra,allowed", + [ + ("inflow", "1.000", {"max_amount": "1", "currencies": ["USD"]}, {}, True), + ("inflow", "1.00000000000000000001", {"max_amount": "1", "currencies": ["USD"]}, {}, False), + ("inflow", "0", {"max_amount": "0", "currencies": ["USD"]}, {}, True), + ("inflow", "1", {"currencies": []}, {}, False), + ("inflow", "1", {"expected_recipients": [ID]}, {}, True), + ("inflow", "1", {"expected_recipients": []}, {}, False), + ("inflow", "99999999999999999999999999999999999999", {}, {}, True), + ("card", "100", {"max_amount": "1.00"}, {}, True), + ("card", "101", {"max_amount": "1.00"}, {}, False), + ("card", "100", {"max_atomic_amount": "100"}, {}, True), + ("card", "101", {"max_atomic_amount": 100}, {}, False), + ( + "tempo", + "1000000", + {"max_amount": "1", "max_amount_decimals": 6, "currencies": [TOKEN.upper()]}, + {}, + True, + ), + ( + "tempo", + "1000001", + {"max_amount": "1", "max_amount_decimals": 6, "currencies": [TOKEN]}, + {}, + False, + ), + ("tempo", "1", {"max_atomic_amount": 1, "currencies": [TOKEN]}, {}, True), + ("tempo", "2", {"max_atomic_amount": 1, "currencies": [TOKEN]}, {}, False), + ("tempo", "1", {"allowed_chain_ids": [42431]}, {"methodDetails": {"chainId": 42431}}, True), + ("tempo", "1", {"allowed_chain_ids": [42431]}, {}, False), + ("tempo", "1", {"allowed_chain_ids": []}, {"methodDetails": {"chainId": 42431}}, False), + ("tempo", "1", {"expected_recipients": [RECIPIENT.upper()]}, {}, True), + ( + "tempo", + "1", + {"expected_recipients": [RECIPIENT]}, + {"methodDetails": {"splits": [{"amount": "1", "recipient": TOKEN}]}}, + False, + ), + ( + "tempo", + "1", + {"expected_recipients": [RECIPIENT, TOKEN]}, + {"methodDetails": {"splits": [{"amount": "1", "recipient": TOKEN}]}}, + True, + ), + ], +) +async def test_limits_apply_to_selection_and_direct_creation( + method: str, amount: str, settings: dict[str, Any], extra: dict[str, Any], allowed: bool +) -> None: + selected = wire(method, amount, **extra) + challenge = to_pympp_challenge(selected) + calls: list[httpx.Request] = [] + + def platform(request: httpx.Request) -> httpx.Response: + calls.append(request) + body = json.loads(request.content) + result = ( + card_ready({"challenge": body["challenge"], "payload": PAYLOAD}) + if method == "card" + else ready(body["challenge"]) + ) + return httpx.Response(200, json=result) + + async with BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)), + method=method, + merchant=MERCHANT if method == "card" else None, + **settings, + ) as buyer: + assert buyer.can_handle_challenge is not None + assert buyer.can_handle_challenge(challenge) is allowed + if allowed: + await buyer.create_credential(CredentialParams(challenge=challenge)) + else: + with pytest.raises(ValueError): + await buyer.create_credential(CredentialParams(challenge=challenge)) + assert len(calls) == int(allowed) + + +async def test_native_transport_selects_affordable_offer_and_snapshots_limits() -> None: + currencies = ["USD"] + selected: list[str] = [] + + def platform(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + selected.append(body["challenge"]["id"]) + return httpx.Response(200, json=ready(body["challenge"])) + + def seller(request: httpx.Request) -> httpx.Response: + if "authorization" in request.headers: + return httpx.Response(200) + return httpx.Response( + 402, + headers=[ + ( + "www-authenticate", + to_pympp_challenge( + {**wire("inflow", amount), "id": amount} + ).to_www_authenticate("seller.example"), + ) + for amount in ("10", "1") + ], + ) + + async with BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)), + max_amount="1", + currencies=currencies, + ) as buyer: + currencies.clear() + async with httpx.AsyncClient( + transport=payment_transport([buyer], inner=httpx.MockTransport(seller)) + ) as client: + assert (await client.get("https://seller.example")).status_code == 200 + assert selected == ["1"] diff --git a/tests/test_mpp_request_options.py b/tests/test_mpp_request_options.py new file mode 100644 index 0000000..d91e504 --- /dev/null +++ b/tests/test_mpp_request_options.py @@ -0,0 +1,265 @@ +import asyncio +import json +from collections.abc import Sequence + +import httpx +import pytest +from mpp.errors import NoMethodFoundError +from mpp.runtime import ChallengeCandidate, CredentialParams + +from inflowpay import ClientOptions +from inflowpay.mpp import decode_credential, to_pympp_challenge +from inflowpay.mpp.buyer import BuyerMethod, PaymentOptions, payment_transport +from test_card_buyer import CHALLENGE, MERCHANT +from test_card_buyer import ready as card_ready +from test_mpp_buyer import ID, WIRE, ready, subscription + + +async def test_request_options_are_isolated_through_native_transport() -> None: + challenge = to_pympp_challenge(WIRE) + received: list[dict[str, object]] = [] + arrived = asyncio.Event() + + async def platform(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + received.append(body["options"]) + if len(received) == 3: + arrived.set() + await arrived.wait() + return httpx.Response(200, json=ready()) + + def seller(request: httpx.Request) -> httpx.Response: + if "authorization" in request.headers: + return httpx.Response(200) + return httpx.Response( + 402, headers={"www-authenticate": challenge.to_www_authenticate("seller.example")} + ) + + alternate = "22222222-2222-4222-8222-222222222222" + override = PaymentOptions(instrument_id=alternate) + async with ( + BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)), instrument_id=ID + ) as buyer, + httpx.AsyncClient( + transport=payment_transport([buyer], inner=httpx.MockTransport(seller)) + ) as client, + ): + responses = await asyncio.gather( + client.get("https://seller.example/default"), + client.get("https://seller.example/override", extensions={"inflow.payment": override}), + client.get( + "https://seller.example/clear", + extensions={"inflow.payment": PaymentOptions(instrument_id=None)}, + ), + ) + assert all(response.status_code == 200 for response in responses) + assert {tuple(item.items()) for item in received} == { + (("instrumentId", ID),), + (("instrumentId", alternate),), + (), + } + assert override == {"instrument_id": alternate} + + +@pytest.mark.parametrize("clear", [False, True]) +async def test_subscription_default_can_be_cleared(clear: bool) -> None: + paths: list[str] = [] + challenge = subscription() + + def platform(request: httpx.Request) -> httpx.Response: + paths.append(request.url.path) + return httpx.Response(200, json=ready(json.loads(request.content)["challenge"])) + + async with BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)), + intent="subscription", + subscription_id=ID, + ) as buyer: + await buyer.create_credential( + CredentialParams( + challenge=challenge, + context=PaymentOptions(subscription_id=None) if clear else PaymentOptions(), + ) + ) + assert paths == ["/v1/transactions/mpp" if clear else f"/v1/subscriptions/{ID}/authorize"] + + +@pytest.mark.parametrize( + "options", + [ + {"unknown": True}, + {"instrument_id": "invalid"}, + {"instrument_id": 3}, + {"subscription_id": ID}, + {"merchant": {"name": "wrong method"}}, + [], + ], +) +async def test_invalid_options_fail_before_platform_request(options: object) -> None: + def platform(request: httpx.Request) -> httpx.Response: + pytest.fail("Invalid options must not start a payment") + + async with BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)) + ) as buyer: + with pytest.raises(ValueError): + await buyer.create_credential( + CredentialParams(challenge=to_pympp_challenge(WIRE), context=options) + ) + + +@pytest.mark.parametrize("reject", [False, True]) +async def test_native_ordering_and_alternate_payment_header(reject: bool) -> None: + wires = [{**WIRE, "id": value, "header": "Payment"} for value in ("first", "second")] + calls: list[str] = [] + + def platform(request: httpx.Request) -> httpx.Response: + challenge = json.loads(request.content)["challenge"] + calls.append(challenge["id"]) + assert challenge["header"] == "Payment" + return httpx.Response(200, json=ready(challenge)) + + def seller(request: httpx.Request) -> httpx.Response: + assert request.headers["authorization"] == "Bearer application-token" + if "payment" in request.headers: + credential = decode_credential(request.headers["payment"][8:]) + echoed = credential["challenge"] + assert isinstance(echoed, dict) + assert echoed["id"] == "second" + assert echoed["header"] == "Payment" + return httpx.Response(200) + return httpx.Response( + 402, + headers=[ + ("www-authenticate", to_pympp_challenge(wire).to_www_authenticate("seller.example")) + for wire in wires + ], + ) + + async def order(candidates: Sequence[ChallengeCandidate]) -> Sequence[ChallengeCandidate]: + return [] if reject else list(reversed(candidates)) + + async with ( + BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)) + ) as buyer, + httpx.AsyncClient( + transport=payment_transport( + [buyer], inner=httpx.MockTransport(seller), order_challenges=order + ) + ) as client, + ): + if reject: + with pytest.raises(NoMethodFoundError): + await client.get( + "https://seller.example", headers={"authorization": "Bearer application-token"} + ) + else: + assert ( + await client.get( + "https://seller.example", headers={"authorization": "Bearer application-token"} + ) + ).status_code == 200 + assert calls == ([] if reject else ["second"]) + + +async def test_request_cancellation_does_not_cancel_other_payment() -> None: + polling = asyncio.Event() + paths: list[str] = [] + challenge = to_pympp_challenge(WIRE) + + async def platform(request: httpx.Request) -> httpx.Response: + paths.append(request.url.path) + if request.url.path.endswith("/cancel"): + return httpx.Response(204) + if request.method == "POST": + if json.loads(request.content)["options"].get("instrumentId") == ID: + return httpx.Response( + 200, + json={ + "state": "pending", + "transactionId": "waiting", + "approvalId": "approval", + "retryAfterSeconds": 0, + }, + ) + await polling.wait() + return httpx.Response(200, json=ready()) + polling.set() + await asyncio.Event().wait() + raise AssertionError("Cancelled polling must not complete") + + def seller(request: httpx.Request) -> httpx.Response: + if "authorization" in request.headers: + return httpx.Response(200) + return httpx.Response( + 402, headers={"www-authenticate": challenge.to_www_authenticate("seller.example")} + ) + + async with ( + BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)) + ) as buyer, + httpx.AsyncClient( + transport=payment_transport([buyer], inner=httpx.MockTransport(seller)) + ) as client, + ): + waiting = asyncio.create_task( + client.get( + "https://seller.example/wait", + extensions={"inflow.payment": PaymentOptions(instrument_id=ID)}, + ) + ) + other = asyncio.create_task(client.get("https://seller.example/other")) + await asyncio.wait_for(polling.wait(), 2) + waiting.cancel() + with pytest.raises(asyncio.CancelledError): + await waiting + assert (await other).status_code == 200 + assert paths.count("/v1/approvals/approval/cancel") == 1 + + +async def test_card_request_merchant_is_copied_and_validated() -> None: + merchant = {**MERCHANT, "name": "Selected seller"} + started, release = asyncio.Event(), asyncio.Event() + + async def platform(request: httpx.Request) -> httpx.Response: + started.set() + await release.wait() + assert json.loads(request.content)["options"]["merchant"]["name"] == "Selected seller" + return httpx.Response(200, json=card_ready()) + + async with BuyerMethod( + ClientOptions(api_key="test", transport=httpx.MockTransport(platform)), + method="card", + merchant=MERCHANT, + ) as buyer: + task = asyncio.ensure_future( + buyer.create_credential( + CredentialParams( + challenge=to_pympp_challenge(CHALLENGE), + context=PaymentOptions(merchant=merchant), + ) + ) + ) + await asyncio.wait_for(started.wait(), 2) + merchant["name"] = "Mutated caller value" + release.set() + await task + for options in ( + PaymentOptions(merchant=None), + PaymentOptions(instrument_id=ID.replace("-", "")), + ): + with pytest.raises(ValueError): + await buyer.create_credential( + CredentialParams(challenge=to_pympp_challenge(CHALLENGE), context=options) + ) + + +async def test_subscription_rejects_instrument_override() -> None: + async with BuyerMethod(ClientOptions(), intent="subscription") as buyer: + with pytest.raises(ValueError, match="instrument_id applies"): + await buyer.create_credential( + CredentialParams(challenge=subscription(), context=PaymentOptions(instrument_id=ID)) + ) diff --git a/tests/test_native_extensions.py b/tests/test_native_extensions.py new file mode 100644 index 0000000..988ff5e --- /dev/null +++ b/tests/test_native_extensions.py @@ -0,0 +1,247 @@ +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from copy import deepcopy +from typing import cast + +import httpx +import pytest +from eth_account import Account +from fastapi import FastAPI +from x402 import x402ResourceServer +from x402.extensions.builder_code import ( + BuilderCodeClientExtension, + BuilderCodeFacilitatorExtension, + declare_builder_code_extension, + parse_builder_code_suffix_from_calldata, +) +from x402.extensions.sign_in_with_x import ( + CreateSIWxClientExtensionOptions, + CreateSIWxResourceServerExtensionOptions, + InMemorySIWxStorage, + create_siwx_client_extension, + create_siwx_resource_server_extension, + declare_siwx_extension, + encode_siwx_header, + parse_siwx_header, +) +from x402.http import x402HTTPClient +from x402.http.clients.httpx import x402AsyncTransport +from x402.http.types import RouteConfig +from x402.http.utils import ( + decode_payment_required_header, + decode_payment_response_header, + encode_payment_signature_header, +) +from x402.mechanisms.evm.exact import ExactEvmScheme +from x402.schemas import PaymentPayload, PaymentRequired +from x402.schemas.extensions import ClientExtension + +from inflowpay import ClientOptions +from inflowpay.x402.buyer import Buyer +from inflowpay.x402.facilitator import Facilitator +from inflowpay.x402.fastapi import payment_middleware +from inflowpay.x402.seller import Seller +from test_x402_upfront import FlowPlatform + +WALLET = Account.from_key("0x" + "11" * 32) +ORIGIN = "https://seller.example" +USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" + + +class NonceStorage(InMemorySIWxStorage): + # Exercise the upstream storage hooks; the supplied in-memory store has no nonce tracking. + def __init__(self) -> None: + super().__init__() + self.nonces: set[str] = set() + + def has_used_nonce(self, nonce: str) -> bool: + return nonce in self.nonces + + def record_nonce(self, nonce: str) -> None: + self.nonces.add(nonce) + + +@asynccontextmanager +async def merchant( + platform: FlowPlatform, storage: NonceStorage, *, dynamic: bool = False +) -> AsyncIterator[FastAPI]: + platform.config["assets"][0]["assetId"] = USDC + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + resource.register_extension( + create_siwx_resource_server_extension( + CreateSIWxResourceServerExtensionOptions(origin=ORIGIN, storage=storage) + ) + ) + route = await seller.route("0.10 USDC", schemes=["exact"]) + route.extensions = declare_siwx_extension() + + def resolve(_: object) -> RouteConfig: + return route + + app = FastAPI() + app.middleware("http")( + payment_middleware({"GET /report": resolve if dynamic else route}, resource) + ) + + @app.get("/report") + async def report() -> dict[str, bool]: + platform.events.append("handler") + return {"ok": True} + + yield app + + +@asynccontextmanager +async def external_buyer() -> AsyncIterator[Buyer]: + def platform(request: httpx.Request) -> httpx.Response: + assert request.url.path == "/v1/transactions/x402-supported" + return httpx.Response(200, json={"kinds": []}) + + async with await Buyer.create( + ClientOptions(api_key="synthetic", transport=httpx.MockTransport(platform)) + ) as buyer: + buyer.register("eip155:8453", ExactEvmScheme(WALLET)) + buyer.register_extension( + create_siwx_client_extension(CreateSIWxClientExtensionOptions(signers=[WALLET])) + ) + yield buyer + + +@pytest.mark.parametrize("dynamic", [False, True]) +async def test_native_siwx_http_authentication_without_payment(dynamic: bool) -> None: + storage = NonceStorage() + storage.record_payment("/report", WALLET.address) + platform = FlowPlatform() + async with merchant(platform, storage, dynamic=dynamic) as app, external_buyer() as buyer: + # A policy rejecting all payments still permits native wallet authentication. + buyer.register_policy(lambda version, requirements: []) + async with httpx.AsyncClient( + transport=x402AsyncTransport(buyer, httpx.ASGITransport(app)), base_url=ORIGIN + ) as client: + response = await client.get("/report") + assert response.status_code == 200 + assert platform.events == ["handler"] + assert len(storage.nonces) == 1 + + +async def test_siwx_origin_unpaid_wallet_and_nonce_replay() -> None: + platform = FlowPlatform() + storage = NonceStorage() + async with ( + merchant(platform, storage) as app, + external_buyer() as buyer, + httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url=ORIGIN) as client, + ): + response = await client.get("/report") + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + http = x402HTTPClient(buyer) + assert await http.handle_payment_required(required, "https://other.example/report") is None + headers = await http.handle_payment_required(required, ORIGIN + "/report") + assert headers + assert (await client.get("/report", headers=headers)).status_code == 402 + assert not storage.nonces + storage.record_payment("/report", WALLET.address) + assert (await client.get("/report", headers=headers)).status_code == 200 + assert (await client.get("/report", headers=headers)).status_code == 402 + assert platform.events == ["handler"] + + +@pytest.mark.parametrize("fault", ["signature", "origin", "expired"]) +async def test_siwx_rejects_invalid_proofs_without_handler(fault: str) -> None: + platform = FlowPlatform() + storage = NonceStorage() + storage.record_payment("/report", WALLET.address) + async with ( + merchant(platform, storage) as app, + external_buyer() as buyer, + httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url=ORIGIN) as client, + ): + response = await client.get("/report") + required = decode_payment_required_header(response.headers["payment-required"]) + headers = await x402HTTPClient(buyer).handle_payment_required(required, ORIGIN + "/report") + assert headers + proof = parse_siwx_header(headers["sign-in-with-x"]) + if fault == "signature": + proof.signature = "0x" + "00" * 65 + elif fault == "origin": + proof.domain = "other.example" + else: + proof.expiration_time = "2020-01-01T00:00:00Z" + response = await client.get( + "/report", headers={"sign-in-with-x": encode_siwx_header(proof)} + ) + assert response.status_code == 402 + assert not storage.nonces + assert not platform.events + + +@pytest.mark.parametrize("success", [False, True]) +async def test_only_successful_settlement_records_wallet_access(success: bool) -> None: + platform = FlowPlatform() + platform.settlement.update(payer=WALLET.address, success=success, network="eip155:8453") + if not success: + platform.settlement.update(transaction="", errorReason="invalid_payload") + storage = NonceStorage() + async with ( + merchant(platform, storage) as app, + external_buyer() as buyer, + httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url=ORIGIN) as client, + ): + response = await client.get("/report") + required = decode_payment_required_header(response.headers["payment-required"]) + payload = await buyer.create_payment_payload(required) + response = await client.get( + "/report", headers={"payment-signature": encode_payment_signature_header(payload)} + ) + assert response.status_code == (200 if success else 402) + assert storage.has_paid("/report", WALLET.address) is success + receipt = decode_payment_response_header(response.headers["payment-response"]) + assert receipt.success is success + assert platform.events == ["verify", "handler", "settle"] + + +async def test_builder_codes_with_native_external_signing_and_suffix_encoding() -> None: + platform = FlowPlatform() + async with merchant(platform, NonceStorage()) as app, external_buyer() as buyer: + async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url=ORIGIN) as client: + response = await client.get("/report") + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + required.extensions = { + "builder-code": declare_builder_code_extension("seller_app", ["seller_service"]) + } + before = deepcopy(required) + # Upstream's protocol requires hooks that its own builder extension omits; + # registration and execution use getattr for these optional hooks. + buyer.register_extension(cast(ClientExtension, BuilderCodeClientExtension("buyer_service"))) + payload = await buyer.create_payment_payload(required) + assert isinstance(payload, PaymentPayload) + assert payload.payload["signature"].startswith("0x") + assert payload.extensions is not None + assert payload.extensions["builder-code"]["info"] == { + "a": "seller_app", + "s": ["buyer_service", "seller_service"], + } + facilitator = BuilderCodeFacilitatorExtension( + builder_code="facilitator_wallet", service_code="facilitator_service" + ) + suffix = facilitator.build_data_suffix(payload, payload.accepted) + assert suffix is not None + decoded = parse_builder_code_suffix_from_calldata(suffix) + assert decoded is not None + assert decoded.a == "seller_app" + assert decoded.w == "facilitator_wallet" + assert decoded.s == ["buyer_service", "seller_service", "facilitator_service"] + assert required == before + required.extensions = {} + async with external_buyer() as plain_buyer: + plain = await plain_buyer.create_payment_payload(required) + assert isinstance(plain, PaymentPayload) + assert not (plain.extensions or {}).get("builder-code") diff --git a/tests/test_native_frameworks.py b/tests/test_native_frameworks.py new file mode 100644 index 0000000..05b44d6 --- /dev/null +++ b/tests/test_native_frameworks.py @@ -0,0 +1,91 @@ +import httpx +import pytest +from fastapi import FastAPI, Request +from mpp import Challenge, Credential +from mpp.server import Mpp +from mpp.server.asgi import PaymentMiddleware +from x402 import x402ResourceServer +from x402.http.paywall import create_paywall, evm_paywall +from x402.http.types import RouteConfig + +from inflowpay.mpp import decode +from inflowpay.mpp.seller import Seller as MppSeller +from inflowpay.x402.facilitator import Facilitator +from inflowpay.x402.fastapi import payment_middleware +from inflowpay.x402.seller import Seller +from test_mpp_seller import ID, RECEIPT, Platform, options +from test_x402_upfront import FlowPlatform + + +async def test_native_asgi_payment_preserves_application_authorization() -> None: + platform = Platform() + async with await MppSeller.create(options(platform)) as seller: + server = Mpp( + methods=[seller], + realm="seller.example", + secret_key="test-only-secret", + requires_auth=True, + ) + handler = server.charge(**seller.charge_request({"amount": "0.50", "currency": "USDC"})) + app = FastAPI() + calls: list[str] = [] + + @app.get("/paid") + async def paid(request: Request) -> dict[str, bool]: + calls.append(request.headers["authorization"]) + return {"ok": True} + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(PaymentMiddleware(app, handler)), + base_url="https://seller.example", + headers={"Authorization": "Bearer application"}, + ) as client: + response = await client.get("/paid") + assert response.status_code == 402 + assert not calls + challenge = Challenge.from_www_authenticate(response.headers["www-authenticate"]) + assert challenge.header == "Payment-Authorization" + credential = Credential(challenge=challenge.to_echo(), payload={"transactionId": ID}) + response = await client.get( + "/paid", headers={"Payment-Authorization": credential.to_authorization()} + ) + assert response.status_code == 200 + assert calls == ["Bearer application"] + assert decode(response.headers["payment-receipt"]) == RECEIPT + + +@pytest.mark.parametrize("dynamic", [False, True]) +async def test_native_evm_paywall_and_api_challenge(dynamic: bool) -> None: + platform = FlowPlatform() + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + route = await seller.route("0.10 USDC", schemes=["exact"]) + + def resolve(_: Request) -> RouteConfig: + return route + + app = FastAPI() + paywall = create_paywall().with_network(evm_paywall).with_config(app_name="Reports").build() + app.middleware("http")( + payment_middleware( + {"GET /report": resolve if dynamic else route}, resource, paywall_provider=paywall + ) + ) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + browser = await client.get( + "/report", headers={"Accept": "text/html", "User-Agent": "Mozilla/5.0"} + ) + assert browser.status_code == 402 + assert "text/html" in browser.headers["content-type"] + assert "Reports" in browser.text + api = await client.get("/report", headers={"Accept": "application/json"}) + assert api.status_code == 402 + assert "payment-required" in api.headers + assert not platform.events diff --git a/tests/test_solana_versions.py b/tests/test_solana_versions.py new file mode 100644 index 0000000..f0b3c6f --- /dev/null +++ b/tests/test_solana_versions.py @@ -0,0 +1,182 @@ +import base64 +import json +from typing import Any + +import pytest +from solders.hash import Hash +from solders.keypair import Keypair +from solders.message import to_bytes_versioned +from solders.signature import Signature +from solders.transaction import VersionedTransaction +from x402.mechanisms.svm.constants import TOKEN_PROGRAM_ADDRESS +from x402.mechanisms.svm.exact import ExactSvmScheme +from x402.mechanisms.svm.rpc import SvmRpcClient +from x402.mechanisms.svm.signers import KeypairSigner +from x402.mechanisms.svm.utils import get_transaction_version +from x402.schemas import PaymentPayload, PaymentRequired, PaymentRequirements, SupportedKind + +from inflowpay import ClientOptions +from inflowpay.x402._seller import SellerConfig, build_offers +from inflowpay.x402.buyer import Buyer +from test_x402_buyer import REQUIREMENT, RESOURCE, Platform +from test_x402_seller import CONFIG + + +@pytest.mark.parametrize("versions", [None, [0], [1], [0, 1]]) +async def test_managed_buyer_forwards_transaction_versions(versions: list[int] | None) -> None: + platform = Platform() + network = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" + platform.supported = {"kinds": [{"scheme": "exact", "network": network, "x402Version": 2}]} + requirement = REQUIREMENT.model_copy( + update={ + "scheme": "exact", + "network": network, + "extra": { + "feePayer": "payer", + **({} if versions is None else {"transactionVersions": versions}), + }, + }, + deep=True, + ) + before = requirement.model_copy(deep=True) + async with await Buyer.create(ClientOptions(api_key="test", transport=platform)) as buyer: + await buyer.prepare(requirement, RESOURCE) + submitted = next( + request for request in platform.requests if request.url.path == "/v1/transactions/x402" + ) + assert json.loads(submitted.content)["accept"] == requirement.model_dump( + by_alias=True, exclude_none=True + ) + assert requirement == before + + +@pytest.mark.parametrize("versions", [None, [0], [1], [0, 1]]) +@pytest.mark.parametrize("present", [False, True]) +def test_seller_only_advertises_matching_exact_versions( + versions: list[int] | None, present: bool +) -> None: + config = SellerConfig.model_validate(CONFIG) + network = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" + config.assets.append( + config.assets[0].model_copy(update={"network": network, "blockchain": "Solana"}) + ) + config.wallets.append( + config.wallets[0].model_copy(update={"blockchain": "Solana", "fee_payer": "payer"}) + ) + config.supported = [kind for kind in config.supported if kind.network != network] + config.supported.insert( + 0, + SupportedKind( + x402_version=2, scheme="upto", network=network, extra={"transactionVersions": [99]} + ), + ) + if present: + config.supported.append( + SupportedKind( + x402_version=2, + scheme="exact", + network=network, + extra={} if versions is None else {"transactionVersions": versions}, + ) + ) + before = config.model_copy(deep=True) + offers = build_offers(config, "1 USDC") + matched = [offer for offer in offers if offer.network == network] + assert matched + for offer in offers: + assert (offer.extra or {}).get("transactionVersions") == ( + versions if present and offer.network == network else None + ) + assert config == before + + +@pytest.mark.parametrize( + "versions,client_versions,expected", + [ + (None, None, 0), + ([0], None, 0), + ([1], None, 1), + ([0, 1], None, 1), + ([0, 1], [0], 0), + ([1], [0], None), + ([], None, None), + ([2], None, None), + ("1", None, None), + ], +) +async def test_external_solana_builds_and_signs_negotiated_version( + versions: Any, + client_versions: list[int] | None, + expected: int | None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + wallet = Keypair.from_seed(bytes([1]) * 32) + fee_payer = Keypair.from_seed(bytes([2]) * 32).pubkey() + recipient = Keypair.from_seed(bytes([3]) * 32).pubkey() + mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" + calls: list[str] = [] + + def rpc(_: SvmRpcClient, method: str, params: list[Any]) -> str: + calls.append(method) + assert method == "getAccountInfo" + assert params[0] == mint + data = bytearray(82) + data[44] = 6 + return json.dumps( + { + "jsonrpc": "2.0", + "id": 1, + "result": { + "context": {"slot": 1}, + "value": { + "data": [base64.b64encode(data).decode(), "base64"], + "executable": False, + "lamports": 1, + "owner": TOKEN_PROGRAM_ADDRESS, + "rentEpoch": 0, + }, + }, + } + ) + + # Only RPC account data is synthetic; upstream builds and signs the transaction. + monkeypatch.setattr(SvmRpcClient, "_call", rpc) + requirement = PaymentRequirements( + scheme="exact", + network="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", + asset=mint, + amount="100000", + pay_to=str(recipient), + max_timeout_seconds=60, + extra={ + "feePayer": str(fee_payer), + "recentBlockhash": str(Hash.default()), + **({} if versions is None else {"transactionVersions": versions}), + }, + ) + scheme = ExactSvmScheme(KeypairSigner(wallet), transaction_versions=client_versions) + platform = Platform() + platform.supported = {"kinds": []} + try: + async with await Buyer.create(ClientOptions(api_key="test", transport=platform)) as buyer: + buyer.register(requirement.network, scheme) + required = PaymentRequired(accepts=[requirement], resource=RESOURCE) + if expected is None: + with pytest.raises(ValueError, match="unsupported_transaction_version"): + await buyer.create_payment_payload(required) + assert not calls + return + result = await buyer.create_payment_payload(required) + assert isinstance(result, PaymentPayload) + transaction = VersionedTransaction.from_bytes( + base64.b64decode(result.payload["transaction"]) + ) + assert get_transaction_version(transaction.message) == expected + assert transaction.signatures[0] == Signature.default() + assert transaction.signatures[1].verify( + wallet.pubkey(), to_bytes_versioned(transaction.message) + ) + assert calls == ["getAccountInfo"] + finally: + for client in scheme._clients.values(): + client.close() diff --git a/tests/test_upstream_upgrade.py b/tests/test_upstream_upgrade.py index 2e6c4a6..8eed20e 100644 --- a/tests/test_upstream_upgrade.py +++ b/tests/test_upstream_upgrade.py @@ -44,7 +44,9 @@ def unexpected(request: httpx.Request) -> httpx.Response: pytest.fail("Unsupported context reached the payment service") async with BuyerMethod(ClientOptions(transport=httpx.MockTransport(unexpected))) as method: - with pytest.raises(ValueError, match="configure selectors"): + with pytest.raises( + ValueError, match=r"Unknown per-request payment option|Expected a JSON object" + ): await method.create_credential( CredentialParams(challenge=to_pympp_challenge(WIRE), context=context) ) diff --git a/tests/test_x402_extension_responses.py b/tests/test_x402_extension_responses.py new file mode 100644 index 0000000..e8bc7d3 --- /dev/null +++ b/tests/test_x402_extension_responses.py @@ -0,0 +1,76 @@ +import base64 +import json + +import httpx +import pytest + +from inflowpay import InflowApiError +from inflowpay.x402.facilitator import Facilitator +from test_x402_seller import PAYLOAD, REQUIREMENTS, Platform + + +@pytest.mark.parametrize("operation", ["verify", "settle"]) +@pytest.mark.parametrize( + "header", [None, "invalid", "W10=", "bnVsbA==", "e30=", "eyJ0ZXN0Ijp7Im9rIjp0cnVlfX0="] +) +async def test_extension_metadata_is_for_seller_not_buyer( + operation: str, header: str | None +) -> None: + platform = Platform() + body = platform.verification if operation == "verify" else platform.settlement + response = httpx.Response( + 200, json=body, headers={} if header is None else {"EXTENSION-RESPONSES": header} + ) + if operation == "verify": + platform.verification = response + else: + platform.settlement = response + async with await Facilitator.create(platform.options()) as facilitator: + result = await getattr(facilitator, operation)(PAYLOAD, REQUIREMENTS) + expected = ( + {} + if header == "e30=" + else {"test": {"ok": True}} + if header == "eyJ0ZXN0Ijp7Im9rIjp0cnVlfX0=" + else None + ) + assert result.extension_responses == expected + encoded = result.model_dump(by_alias=True, exclude_none=True) + assert "extensionResponses" not in encoded + assert "extension_responses" not in encoded + assert encoded == body + + +@pytest.mark.parametrize("operation", ["verify", "settle"]) +async def test_metadata_does_not_turn_failure_into_success(operation: str) -> None: + platform = Platform() + response = httpx.Response( + 403, + json={"code": "REJECTED"}, + headers={ + "EXTENSION-RESPONSES": base64.b64encode( + json.dumps({"test": {"ok": True}}).encode() + ).decode() + }, + ) + if operation == "verify": + platform.verification = response + else: + platform.settlement = response + async with await Facilitator.create(platform.options()) as facilitator: + with pytest.raises(InflowApiError) as failure: + await getattr(facilitator, operation)(PAYLOAD, REQUIREMENTS) + assert failure.value.http_status == 403 + + +@pytest.mark.parametrize("header", ["invalid", "eyJ0ZXN0Ijp7Im9rIjp0cnVlfX0="]) +async def test_allowance_required_keeps_seller_metadata(header: str) -> None: + platform = Platform() + body = {"isValid": False, "invalidReason": "permit2_allowance_required"} + platform.verification = httpx.Response(412, json=body, headers={"EXTENSION-RESPONSES": header}) + async with await Facilitator.create(platform.options()) as facilitator: + result = await facilitator.verify(PAYLOAD, REQUIREMENTS) + assert not result.is_valid + assert result.invalid_reason == "permit2_allowance_required" + assert result.extension_responses == (None if header == "invalid" else {"test": {"ok": True}}) + assert result.model_dump(by_alias=True, exclude_none=True) == body diff --git a/uv.lock b/uv.lock index bd91e98..432030d 100644 --- a/uv.lock +++ b/uv.lock @@ -10,6 +10,15 @@ resolution-markers = [ "(python_full_version < '3.12' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32')", ] +[[package]] +name = "abnf" +version = "2.9.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/27/09d5b2e8e0a83a1bb169e4b4382261f4dcf1d0cccaef6306d9962944223a/abnf-2.9.1.tar.gz", hash = "sha256:58dfcbec5362fbc25d210ff916c014bc75a5a89e274318c7e9b47c1e8c379c06", size = 1010171, upload-time = "2026-10-21T19:34:54.472Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/8f/bc07d154a9aee9181922d73a5be0c7854bd6e30c932ecc33e95af1ad960e/abnf-2.9.1-py3-none-any.whl", hash = "sha256:cdcac127b3693ded2b00565878d8ed2b96d34b29f0ee199c06d7b40baaf60917", size = 78103, upload-time = "2026-10-21T19:34:52.901Z" }, +] + [[package]] name = "aiohappyeyeballs" version = "2.7.1" @@ -1384,6 +1393,7 @@ dev = [ { name = "ruff" }, { name = "twine" }, { name = "uvicorn" }, + { name = "x402", extra = ["extensions"] }, ] [package.metadata] @@ -1412,6 +1422,7 @@ dev = [ { name = "ruff", specifier = "==0.17.5" }, { name = "twine", specifier = "==7.0.0" }, { name = "uvicorn", specifier = "==0.52.4" }, + { name = "x402", extras = ["extensions"], specifier = "==2.28.0" }, ] [[package]] @@ -2355,6 +2366,41 @@ mcp = [ { name = "yarl" }, ] +[[package]] +name = "pynacl" +version = "1.6.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/9a/4019b524b03a13438637b11538c82781a5eda427394380381af8f04f467a/pynacl-1.6.2.tar.gz", hash = "sha256:018494d6d696ae03c7e656e5e74cdfd8ea1326962cc401bcf018f1ed8436811c", size = 3511692, upload-time = "2026-01-01T17:48:10.851Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4b/79/0e3c34dc3c4671f67d251c07aa8eb100916f250ee470df230b0ab89551b4/pynacl-1.6.2-cp314-cp314t-macosx_10_10_universal2.whl", hash = "sha256:622d7b07cc5c02c666795792931b50c91f3ce3c2649762efb1ef0d5684c81594", size = 390064, upload-time = "2026-01-01T17:31:57.264Z" }, + { url = "https://files.pythonhosted.org/packages/eb/1c/23a26e931736e13b16483795c8a6b2f641bf6a3d5238c22b070a5112722c/pynacl-1.6.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d071c6a9a4c94d79eb665db4ce5cedc537faf74f2355e4d502591d850d3913c0", size = 809370, upload-time = "2026-01-01T17:31:59.198Z" }, + { url = "https://files.pythonhosted.org/packages/87/74/8d4b718f8a22aea9e8dcc8b95deb76d4aae380e2f5b570cc70b5fd0a852d/pynacl-1.6.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fe9847ca47d287af41e82be1dd5e23023d3c31a951da134121ab02e42ac218c9", size = 1408304, upload-time = "2026-01-01T17:32:01.162Z" }, + { url = "https://files.pythonhosted.org/packages/fd/73/be4fdd3a6a87fe8a4553380c2b47fbd1f7f58292eb820902f5c8ac7de7b0/pynacl-1.6.2-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:04316d1fc625d860b6c162fff704eb8426b1a8bcd3abacea11142cbd99a6b574", size = 844871, upload-time = "2026-01-01T17:32:02.824Z" }, + { url = "https://files.pythonhosted.org/packages/55/ad/6efc57ab75ee4422e96b5f2697d51bbcf6cdcc091e66310df91fbdc144a8/pynacl-1.6.2-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:44081faff368d6c5553ccf55322ef2819abb40e25afaec7e740f159f74813634", size = 1446356, upload-time = "2026-01-01T17:32:04.452Z" }, + { url = "https://files.pythonhosted.org/packages/78/b7/928ee9c4779caa0a915844311ab9fb5f99585621c5d6e4574538a17dca07/pynacl-1.6.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:a9f9932d8d2811ce1a8ffa79dcbdf3970e7355b5c8eb0c1a881a57e7f7d96e88", size = 826814, upload-time = "2026-01-01T17:32:06.078Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a9/1bdba746a2be20f8809fee75c10e3159d75864ef69c6b0dd168fc60e485d/pynacl-1.6.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:bc4a36b28dd72fb4845e5d8f9760610588a96d5a51f01d84d8c6ff9849968c14", size = 1411742, upload-time = "2026-01-01T17:32:07.651Z" }, + { url = "https://files.pythonhosted.org/packages/f3/2f/5e7ea8d85f9f3ea5b6b87db1d8388daa3587eed181bdeb0306816fdbbe79/pynacl-1.6.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3bffb6d0f6becacb6526f8f42adfb5efb26337056ee0831fb9a7044d1a964444", size = 801714, upload-time = "2026-01-01T17:32:09.558Z" }, + { url = "https://files.pythonhosted.org/packages/06/ea/43fe2f7eab5f200e40fb10d305bf6f87ea31b3bbc83443eac37cd34a9e1e/pynacl-1.6.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2fef529ef3ee487ad8113d287a593fa26f48ee3620d92ecc6f1d09ea38e0709b", size = 1372257, upload-time = "2026-01-01T17:32:11.026Z" }, + { url = "https://files.pythonhosted.org/packages/4d/54/c9ea116412788629b1347e415f72195c25eb2f3809b2d3e7b25f5c79f13a/pynacl-1.6.2-cp314-cp314t-win32.whl", hash = "sha256:a84bf1c20339d06dc0c85d9aea9637a24f718f375d861b2668b2f9f96fa51145", size = 231319, upload-time = "2026-01-01T17:32:12.46Z" }, + { url = "https://files.pythonhosted.org/packages/ce/04/64e9d76646abac2dccf904fccba352a86e7d172647557f35b9fe2a5ee4a1/pynacl-1.6.2-cp314-cp314t-win_amd64.whl", hash = "sha256:320ef68a41c87547c91a8b58903c9caa641ab01e8512ce291085b5fe2fcb7590", size = 244044, upload-time = "2026-01-01T17:32:13.781Z" }, + { url = "https://files.pythonhosted.org/packages/33/33/7873dc161c6a06f43cda13dec67b6fe152cb2f982581151956fa5e5cdb47/pynacl-1.6.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d29bfe37e20e015a7d8b23cfc8bd6aa7909c92a1b8f41ee416bbb3e79ef182b2", size = 188740, upload-time = "2026-01-01T17:32:15.083Z" }, + { url = "https://files.pythonhosted.org/packages/be/7b/4845bbf88e94586ec47a432da4e9107e3fc3ce37eb412b1398630a37f7dd/pynacl-1.6.2-cp38-abi3-macosx_10_10_universal2.whl", hash = "sha256:c949ea47e4206af7c8f604b8278093b674f7c79ed0d4719cc836902bf4517465", size = 388458, upload-time = "2026-01-01T17:32:16.829Z" }, + { url = "https://files.pythonhosted.org/packages/1e/b4/e927e0653ba63b02a4ca5b4d852a8d1d678afbf69b3dbf9c4d0785ac905c/pynacl-1.6.2-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8845c0631c0be43abdd865511c41eab235e0be69c81dc66a50911594198679b0", size = 800020, upload-time = "2026-01-01T17:32:18.34Z" }, + { url = "https://files.pythonhosted.org/packages/7f/81/d60984052df5c97b1d24365bc1e30024379b42c4edcd79d2436b1b9806f2/pynacl-1.6.2-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:22de65bb9010a725b0dac248f353bb072969c94fa8d6b1f34b87d7953cf7bbe4", size = 1399174, upload-time = "2026-01-01T17:32:20.239Z" }, + { url = "https://files.pythonhosted.org/packages/68/f7/322f2f9915c4ef27d140101dd0ed26b479f7e6f5f183590fd32dfc48c4d3/pynacl-1.6.2-cp38-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:46065496ab748469cdd999246d17e301b2c24ae2fdf739132e580a0e94c94a87", size = 835085, upload-time = "2026-01-01T17:32:22.24Z" }, + { url = "https://files.pythonhosted.org/packages/3e/d0/f301f83ac8dbe53442c5a43f6a39016f94f754d7a9815a875b65e218a307/pynacl-1.6.2-cp38-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8a66d6fb6ae7661c58995f9c6435bda2b1e68b54b598a6a10247bfcdadac996c", size = 1437614, upload-time = "2026-01-01T17:32:23.766Z" }, + { url = "https://files.pythonhosted.org/packages/c4/58/fc6e649762b029315325ace1a8c6be66125e42f67416d3dbd47b69563d61/pynacl-1.6.2-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:26bfcd00dcf2cf160f122186af731ae30ab120c18e8375684ec2670dccd28130", size = 818251, upload-time = "2026-01-01T17:32:25.69Z" }, + { url = "https://files.pythonhosted.org/packages/c9/a8/b917096b1accc9acd878819a49d3d84875731a41eb665f6ebc826b1af99e/pynacl-1.6.2-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:c8a231e36ec2cab018c4ad4358c386e36eede0319a0c41fed24f840b1dac59f6", size = 1402859, upload-time = "2026-01-01T17:32:27.215Z" }, + { url = "https://files.pythonhosted.org/packages/85/42/fe60b5f4473e12c72f977548e4028156f4d340b884c635ec6b063fe7e9a5/pynacl-1.6.2-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:68be3a09455743ff9505491220b64440ced8973fe930f270c8e07ccfa25b1f9e", size = 791926, upload-time = "2026-01-01T17:32:29.314Z" }, + { url = "https://files.pythonhosted.org/packages/fa/f9/e40e318c604259301cc091a2a63f237d9e7b424c4851cafaea4ea7c4834e/pynacl-1.6.2-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8b097553b380236d51ed11356c953bf8ce36a29a3e596e934ecabe76c985a577", size = 1363101, upload-time = "2026-01-01T17:32:31.263Z" }, + { url = "https://files.pythonhosted.org/packages/48/47/e761c254f410c023a469284a9bc210933e18588ca87706ae93002c05114c/pynacl-1.6.2-cp38-abi3-win32.whl", hash = "sha256:5811c72b473b2f38f7e2a3dc4f8642e3a3e9b5e7317266e4ced1fba85cae41aa", size = 227421, upload-time = "2026-01-01T17:32:33.076Z" }, + { url = "https://files.pythonhosted.org/packages/41/ad/334600e8cacc7d86587fe5f565480fde569dfb487389c8e1be56ac21d8ac/pynacl-1.6.2-cp38-abi3-win_amd64.whl", hash = "sha256:62985f233210dee6548c223301b6c25440852e13d59a8b81490203c3227c5ba0", size = 239754, upload-time = "2026-01-01T17:32:34.557Z" }, + { url = "https://files.pythonhosted.org/packages/29/7d/5945b5af29534641820d3bd7b00962abbbdfee84ec7e19f0d5b3175f9a31/pynacl-1.6.2-cp38-abi3-win_arm64.whl", hash = "sha256:834a43af110f743a754448463e8fd61259cd4ab5bbedcf70f9dabad1d28a394c", size = 184801, upload-time = "2026-01-01T17:32:36.309Z" }, +] + [[package]] name = "pyproject-hooks" version = "1.3.3" @@ -2844,6 +2890,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" }, ] +[[package]] +name = "signinwithethereum" +version = "5.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "abnf" }, + { name = "eth-account" }, + { name = "eth-utils" }, + { name = "pydantic" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "web3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3b/49/c2d40d20a64c1a4c07cd96659bcf81c5441e55313101cac9dffcd6bd979c/signinwithethereum-5.1.0.tar.gz", hash = "sha256:ecf76834aefd0d218e0abb8f4ab183041c1e634cc20094a885d129e08c882ec4", size = 166311, upload-time = "2026-11-09T18:30:44.139Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/f4/ef0d0169257eb7326f1f4f6ce27ab5e5e7388d6358eb58acf7dae13492de/signinwithethereum-5.1.0-py3-none-any.whl", hash = "sha256:c0b6d92083f1f059225004554b466146e0c7845a1df34c3f5d467d0f22370eee", size = 18939, upload-time = "2026-11-09T18:30:42.939Z" }, +] + [[package]] name = "solders" version = "0.29.0" @@ -3214,6 +3278,12 @@ evm = [ { name = "eth-utils" }, { name = "web3" }, ] +extensions = [ + { name = "idna" }, + { name = "jsonschema" }, + { name = "pynacl" }, + { name = "signinwithethereum" }, +] mcp = [ { name = "mcp" }, ]