Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
192 changes: 73 additions & 119 deletions README.md

Large diffs are not rendered by default.

67 changes: 46 additions & 21 deletions conformance/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
from fastapi import FastAPI, Request
from mpp import Challenge, Credential, Receipt
from mpp.errors import InvalidChallengeError
from mpp.runtime import CredentialParams
from mpp.server import Mpp, ServerMethod
from mpp.server.decorator import pay
from mpp.server.intent import broadcast_credential
from mpp.server.method import ValidateContext, VerifyContext
from starlette.responses import JSONResponse
from x402.schemas import PaymentPayload, PaymentRequirements, ResourceInfo

Expand Down Expand Up @@ -142,7 +144,7 @@ async def mpp_execute(operation: str, data: Data) -> object:
return mpp.parse_challenge_headers(data["headers"])
if operation in ("mpp.buyer.fulfil", "mpp.buyer.cancel"):
challenge = mpp.to_pympp_challenge(data["challenge"])
payment: asyncio.Task[Credential]
payment: asyncio.Future[str]

class Observe(httpx.AsyncHTTPTransport):
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
Expand All @@ -164,8 +166,10 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
subscription_id=data["context"].get("subscriptionId"),
merchant=data["context"].get("merchant"),
) as buyer:
payment = asyncio.create_task(buyer.create_credential(challenge))
return mpp.decode_credential((await payment).to_authorization()[8:])
payment = asyncio.ensure_future(
buyer.create_credential(CredentialParams(challenge=challenge))
)
return mpp.decode_credential((await payment)[8:])
allowed = (
"mpp.seller.prepare",
"mpp.seller.validate",
Expand All @@ -185,16 +189,28 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
)
if operation == "mpp.seller.route-binding":
return await route_binding(seller, data)
assert wire is not None
credential = Credential.from_authorization("Payment " + mpp.encode(wire))
request = mpp.decode(credential.challenge.request)
if not isinstance(request, dict):
raise RuntimeError("Expected an object request")
if operation == "mpp.seller.verify":
receipt = await broadcast_credential(
intent=seller, credential=credential, request=request
receipt, _ = await seller.settle(
VerifyContext(
credential=credential,
request=request,
challenge=mpp.to_pympp_challenge(wire["challenge"]),
)
)
return mpp.decode_receipt(receipt.to_payment_receipt())
value = await seller.validate(credential, request)
assert seller.validate is not None
value = await seller.validate(
ValidateContext(
credential=credential,
request=request,
challenge=mpp.to_pympp_challenge(wire["challenge"]),
)
)
observed = mpp.decode_credential(value.credential.to_authorization()[8:])
observed.setdefault("source", "")
return {
Expand All @@ -212,17 +228,24 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
async def route_binding(seller: MppSeller, data: Data, *, prepare_only: bool = False) -> object:
app = FastAPI()
prepare = {"stripe": seller.stripe_request, "card": seller.card_request}.get(
seller.method, seller.charge_request
seller.name, seller.charge_request
)
terms = prepare(data["request"])

@app.get("/test")
@pay(
intent=seller,
method=seller.method,
request=lambda _: terms,
realm="seller.example",
secret_key="test-only-binding-secret-at-least-32-bytes",
Mpp(
methods=[
ServerMethod(
method=seller.method,
validate=seller.validate,
broadcast=seller.broadcast,
resolve_request=lambda _: terms,
)
],
realm="seller.example",
secret_key="test-only-binding-secret-at-least-32-bytes",
).charge()
)
async def handler(request: Request, credential: Credential, receipt: Receipt) -> JSONResponse:
return JSONResponse({"ok": True})
Expand Down Expand Up @@ -374,14 +397,16 @@ async def runtime_call(product: str, config: ClientOptions) -> None:
if product == "mpp-buyer":
async with BuyerMethod(config) as buyer:
await buyer.create_credential(
mpp.to_pympp_challenge(
{
"id": "test",
"realm": "seller.example",
"method": "inflow",
"intent": "charge",
"request": mpp.encode({"amount": "1", "currency": "USD"}),
}
CredentialParams(
challenge=mpp.to_pympp_challenge(
{
"id": "test",
"realm": "seller.example",
"method": "inflow",
"intent": "charge",
"request": mpp.encode({"amount": "1", "currency": "USD"}),
}
)
)
)
elif product == "mpp-seller":
Expand Down
5 changes: 2 additions & 3 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,8 @@ method and reference decoded from the Seller's `Payment-Receipt`.

The Buyer obtains a payment credential through InFlow and retries the resource
once. The Seller verifies and broadcasts the payment before its widgets handler
runs. This example uses one charge offer. MPP Seller subscriptions and composed
InFlow offers are not supported by this integration; see the
[upstream limitations](../README.md#seller-route-limitations).
runs. This example uses one charge offer. The InFlow Seller implements charge
payments; it does not implement subscription Seller routes.

### Stripe Seller

Expand Down
9 changes: 2 additions & 7 deletions examples/mpp_seller.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import uvicorn
from fastapi import FastAPI, Request
from mpp import Credential, Receipt
from mpp.server import Mpp
from mpp.server.decorator import pay
from starlette.responses import JSONResponse

Expand All @@ -30,13 +31,7 @@ async def application(
app = FastAPI()

@app.get("/api/widgets")
@pay(
intent=seller,
method=seller.method,
request=terms,
realm="localhost",
secret_key=secret,
)
@pay(Mpp(methods=[seller], realm="localhost", secret_key=secret).charge(**terms))
async def widgets(
request: Request, credential: Credential, receipt: Receipt
) -> JSONResponse:
Expand Down
5 changes: 2 additions & 3 deletions interop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,8 @@ MPP broadcasts before calling the protected handler. x402 verifies before the
handler and settles after a successful handler response. The assertions reflect
these different lifecycles rather than treating them as interchangeable.

Python MPP Seller subscriptions are excluded because pympp's Seller routes lack
the required terms; see [pympp #269](https://github.com/tempoxyz/pympp/issues/269).
The standalone Python MPP decorator does not set private cache headers on the
Python MPP Seller subscriptions are excluded because the InFlow Seller implements
charge payments only. The Python MPP decorator does not set private cache headers on the
handler's response; the application owns those headers. Cache assertions apply
to Node MPP and both x402 middleware implementations.

Expand Down
11 changes: 6 additions & 5 deletions interop/peer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import uvicorn
from fastapi import FastAPI, Request
from mpp import Credential, Receipt
from mpp.server import Mpp
from mpp.server.decorator import pay
from starlette.middleware.base import RequestResponseEndpoint
from starlette.responses import JSONResponse, Response
Expand Down Expand Up @@ -148,11 +149,11 @@ async def handle() -> None:

@app.get("/paid")
@pay(
intent=seller,
method=seller.method,
request=terms,
realm="interop",
secret_key="test-only-binding-secret-at-least-32-bytes",
Mpp(
methods=[seller],
realm="interop",
secret_key="test-only-binding-secret-at-least-32-bytes",
).charge(**terms)
)
async def paid(
request: Request, credential: Credential, receipt: Receipt
Expand Down
19 changes: 10 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,24 @@ Issues = "https://github.com/inflowpayai/inflow-python/issues"
Repository = "https://github.com/inflowpayai/inflow-python"

[project.optional-dependencies]
evm = ["x402[evm]>=2.25.0,<3"]
evm = ["x402[evm]>=2.28.0,<3"]
fastapi = ["fastapi>=0.142.2,<1"]
mcp = ["mcp>=1.30.0,<2", "pympp[mcp]>=0.11.0,<0.12", "x402[mcp]>=2.25.0,<3"]
mpp = ["pympp>=0.11.0,<0.12", "rfc8785>=0.1.4,<0.2"]
svm = ["x402[svm]>=2.25.0,<3"]
mcp = ["mcp>=1.30.0,<2", "pympp[mcp]>=0.22.0,<0.23", "x402[mcp]>=2.28.0,<3"]
mpp = ["pympp>=0.22.0,<0.23", "rfc8785>=0.1.4,<0.2"]
svm = ["x402[svm]>=2.28.0,<3"]
tap = ["cryptography>=50.0.2,<51"]
x402 = ["x402>=2.25.0,<3"]
x402 = ["x402>=2.28.0,<3"]

[dependency-groups]
dev = [
"build==1.6.1",
"mypy==2.4.0",
"mypy==2.4.1",
"pytest==9.2.0",
"pytest-asyncio==1.4.1",
"pytest-asyncio==1.5.0",
"pytest-cov==7.1.0",
"ruff==0.17.4",
"ruff==0.17.5",
"twine==7.0.0",
"uvicorn==0.54.0",
"uvicorn==0.52.4",
]

[tool.hatch.build.targets.sdist]
Expand All @@ -73,6 +73,7 @@ addopts = [
"--strict-markers",
]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
pythonpath = ["."]
testpaths = ["tests"]

Expand Down
82 changes: 2 additions & 80 deletions scripts/conformance.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,50 +21,6 @@ export function checkContract(path, revision) {
)
throw new Error(`Use a clean contract checkout at ${revision}`);
}
const descriptionIssue = "https://github.com/tempoxyz/pympp/issues/272";
const descriptionCase = "mpp.card.verify-reference";

export function acceptsDescriptionFailure(report, diagnostic) {
const failures = report.results.filter((item) => item.status !== "passed");
return (
report.completed === true &&
!report.runner_error &&
!report.passed &&
report.implementation.dependencies.pympp === "0.11.0" &&
failures.length === 1 &&
failures[0].case_id === descriptionCase &&
failures[0].suite === "mpp-seller" &&
failures[0].status === "failed" &&
failures[0].message === "Unexpected platform request at exchange 2" &&
diagnostic?.completed === true &&
diagnostic.passed === true &&
!diagnostic.runner_error &&
diagnostic.results.length === 1 &&
diagnostic.results[0].case_id === descriptionCase &&
diagnostic.results[0].status === "passed"
);
}

export function descriptionDiagnostic(index) {
const item = structuredClone(
index.cases.find((item) => item.id === descriptionCase),
);
if (!item?.input.credential.challenge.description)
throw new Error("Description fixture changed; review pympp#272 allowance");
// Keep the caller's complete credential; the platform echoes the received credential.
for (const exchange of item.platform.exchanges) {
if (exchange.request.json?.credential) {
exchange.request = structuredClone(exchange.request);
delete exchange.request.json.credential.challenge.description;
}
if (exchange.response?.json?.credential) {
exchange.response = structuredClone(exchange.response);
delete exchange.response.json.credential.challenge.description;
delete exchange.response.json.challenge.description;
}
}
return { ...index, cases: [item] };
}
async function main() {
const { values } = parseArgs({
options: {
Expand Down Expand Up @@ -157,7 +113,7 @@ async function main() {
{
id: "mpp-seller-subscriptions",
reason:
"pympp Seller routes do not expose subscription terms; see tempoxyz/pympp#269.",
"The InFlow Seller implements charge routes only; Buyer subscriptions are supported.",
},
]
: [],
Expand All @@ -173,41 +129,7 @@ async function main() {
console.log(
`${suite}: ${report.results.filter((r) => r.status === "passed").length}/${report.results.length} passed`,
);
let accepted = false;
if (suite === "card") {
const diagnostic = await run({
...configuration,
index: descriptionDiagnostic(configuration.index),
capabilities: {
...configuration.capabilities,
suites: ["mpp-seller"],
},
});
const diagnosticOutput = await open(
join(outputDirectory, "card-description-diagnostic.json"),
"wx",
0o600,
);
try {
await diagnosticOutput.writeFile(
JSON.stringify(diagnostic, null, 2) + "\n",
);
} finally {
await diagnosticOutput.close();
}
accepted = acceptsDescriptionFailure(report, diagnostic);
if (accepted)
console.warn(
`Known failed case ${descriptionCase}: ${descriptionIssue}`,
);
else {
process.exitCode = 1;
console.error(
`Review or remove the pympp#272 allowance: ${descriptionIssue}`,
);
}
}
if (!report.passed && !accepted) {
if (!report.passed) {
process.exitCode = 1;
console.error(
report.runner_error ??
Expand Down
Loading
Loading