AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(stripe-link): pay MPP merchants, and say which block to use when (#14066)
Nicholas Tindle32c3b335b8dd
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/mpp.py b/autogpt_platform/backend/backend/blocks/stripe_link/mpp.pynew file mode 100644index 0000000000..b6a50d865c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe_link/mpp.py@@ -0,0 +1,536 @@+"""+Stripe Link — Machine Payments Protocol (MPP) blocks.++MPP merchants answer an unauthenticated request with HTTP 402 and a+`WWW-Authenticate: Payment` challenge. The agent turns a Shared Payment Token+into a credential for that challenge and retries. No checkout form, no card+number, nothing for a human to type.++Pair these with the Create Token Spend Request block.+For ordinary merchants that need a card typed into a checkout form, use the+virtual-card flow instead — see `spend_request.py`.+"""++import base64+import json+import logging+import re+from typing import Any+from urllib.parse import quote++from backend.blocks._base import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+)+from backend.blocks.stripe_link._auth import (+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ StripeLinkCredentials,+ StripeLinkCredentialsField,+ StripeLinkCredentialsInput,+)+from backend.blocks.stripe_link.spend_request import link_api_request+from backend.data.model import SchemaField+from backend.util.request import Requests, Response++logger = logging.getLogger(__name__)+++class BlockedURLError(Exception):+ """`Requests` refused the URL (SSRF / private-range guard).++ Redacted at the point of refusal rather than by inspecting exception types+ later: `Requests` signals a refusal with a bare `ValueError`, and so does+ every other parse failure in this module, so a catch-all would report a+ merchant's malformed challenge as a blocked URL.+ """+++async def guarded_request(client: Requests, method: str, url: str, **kwargs: Any):+ """Make a request, converting a refusal into a message safe to surface.++ The rejection names the host or resolved IP, which belongs in the logs but+ not in an agent- and user-visible `error` output, where it turns a blocked+ request into a readout of what resolves on the internal network.+ """+ try:+ return await client.request(method, url, **kwargs)+ except ValueError as e:+ logger.warning("Blocked MPP request to %s: %s", url, e)+ raise BlockedURLError("Request blocked: the URL is not allowed.") from e+++PAYMENT_SCHEME = "Payment"+# Merchant-controlled data: bound what we decode and what we echo back.+# Bounds the base64 challenge blob we decode from a 402 header.+MAX_REQUEST_BLOB_BYTES = 16 * 1024+# Bounds a merchant response body before we deserialize it. Separate from the+# challenge bound so the two can move independently.+MAX_RESPONSE_BYTES = 256 * 1024+# How much of an oversized or unparseable body we keep for diagnostics.+MAX_TRUNCATED_BODY_CHARS = 1000+# A JSON number literal — no leading zeros, so identifiers survive as strings.+JSON_NUMBER_PATTERN = re.compile(r"^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$")+# Fields `mppx` keeps on the wire challenge; anything else the server sends is+# dropped rather than echoed back.+CHALLENGE_FIELDS = frozenset(+ {+ "description",+ "digest",+ "expires",+ "id",+ "intent",+ "method",+ "opaque",+ "realm",+ "request",+ }+)+++def parse_payment_challenges(header: str) -> list[dict[str, str]]:+ """Split a `WWW-Authenticate` value into its `Payment` challenges.++ A merchant may offer several (Stripe and an onchain method, say), so this+ returns all of them and the caller picks.+ """+ challenges: list[dict[str, str]] = []+ for chunk in re.split(r"(?i)(?=\bPayment\s+\w+=)", header):+ chunk = chunk.strip().rstrip(",")+ if not chunk.lower().startswith(PAYMENT_SCHEME.lower()):+ continue+ fields = dict(re.findall(r'(\w+)="([^"]*)"', chunk))+ if fields:+ challenges.append(fields)+ return challenges+++def decode_payment_request(encoded: str) -> dict[str, Any]:+ """Decode a challenge's base64url `request` blob.++ The blob comes from the merchant, so it is size-bounded and the result is+ type-checked — `json.loads` can return a list or a scalar just as easily.+ """+ if len(encoded) > MAX_REQUEST_BLOB_BYTES:+ raise ValueError("Payment challenge request blob is implausibly large")+ padded = encoded + "=" * (-len(encoded) % 4)+ decoded = json.loads(base64.urlsafe_b64decode(padded))+ if not isinstance(decoded, dict):+ raise ValueError("Payment challenge request must decode to an object")+ return decoded+++def build_credential(challenge: dict[str, str], spt: str) -> str:+ """Build the `Authorization: Payment ...` value for a challenge.++ Mirrors `Credential.serialize` in `mppx`: base64url (unpadded) of+ `{challenge, payload}`, with the challenge's `request` passed through+ exactly as the server sent it.+ """+ wire = {+ "challenge": {k: v for k, v in challenge.items() if k in CHALLENGE_FIELDS},+ "payload": {"spt": spt},+ }+ encoded = (+ base64.urlsafe_b64encode(json.dumps(wire, separators=(",", ":")).encode())+ .decode()+ .rstrip("=")+ )+ return f"{PAYMENT_SCHEME} {encoded}"+++def select_stripe_challenge(header: str) -> dict[str, str] | None:+ """Pick the Stripe challenge from a `WWW-Authenticate` value, if offered.++ Merchants may advertise several methods (an onchain one alongside Stripe);+ only the Stripe one is payable with a Link token.+ """+ return next(+ (c for c in parse_payment_challenges(header) if c.get("method") == "stripe"),+ None,+ )+++class StripeLinkGetPaymentChallengeBlock(Block):+ """Ask an MPP merchant what it wants paid, before creating a spend request."""++ class Input(BlockSchemaInput):+ url: str = SchemaField(description="The merchant endpoint to purchase from")+ method: str = SchemaField(+ description="HTTP method the purchase uses", default="POST"+ )+ body: dict[str, Any] = SchemaField(+ description="JSON body for the purchase request",+ default_factory=dict,+ )++ class Output(BlockSchemaOutput):+ supports_mpp: bool = SchemaField(+ description=(+ "True when the merchant answered 402 with a Stripe payment "+ "challenge, so a Shared Payment Token can pay it. False means "+ "it cannot be paid this way — check `payment_required` to see "+ "whether that is because nothing is owed or because the "+ "merchant only accepts a method this block cannot provide. A "+ "probe that got no answer at all raises instead, so it is "+ "never reported as False."+ )+ )+ payment_required: bool = SchemaField(+ description=(+ "True when the merchant demanded payment (HTTP 402) but not "+ "via Stripe — an onchain-only merchant, say. With "+ "`supports_mpp` false this distinguishes 'pays another way, "+ "unreachable from here' from 'served without charging', where "+ "the virtual-card flow is the sensible fallback."+ ),+ default=False,+ )+ network_id: str = SchemaField(+ description="Merchant network ID — pass this to Create Spend "+ "Request as `network_id`",+ default="",+ )+ amount: int = SchemaField(+ description="Amount the merchant wants, in the smallest currency unit",+ default=0,+ )+ currency: str = SchemaField(+ description="Three-letter currency code", default=""+ )+ description: str = SchemaField(+ description="What the merchant says the charge is for", default=""+ )+ error: str = SchemaField(description="Error message on failure", default="")++ def __init__(self):+ super().__init__(+ id="0518625e-5c08-40d4-b1fe-7953250cbe80",+ description=(+ "MPP step 1 of 3: read a merchant's HTTP 402 payment challenge "+ "to learn its network ID and amount. Step 2 is Create Spend "+ "Request with credential type 'shared_payment_token' and that "+ "network ID; step 3 is MPP Pay. Returns supports_mpp=false for "+ "ordinary merchants — use the virtual-card flow for those."+ ),+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={"url": "https://merchant.example/api/buy"},+ test_output=[+ ("supports_mpp", True),+ ("network_id", "profile_test"),+ ("amount", 100),+ ("currency", "usd"),+ ("description", "Test charge"),+ ],+ test_mock={+ "_probe": lambda *args, **kwargs: (+ 402,+ 'Payment id="ch_1", realm="merchant.example", method="stripe", '+ 'intent="charge", request="'+ + base64.urlsafe_b64encode(+ json.dumps(+ {+ "amount": "100",+ "currency": "usd",+ "methodDetails": {"networkId": "profile_test"},+ }+ ).encode()+ )+ .decode()+ .rstrip("=")+ + '", description="Test charge"',+ )+ },+ )++ # Instance method to match `_pay_with_token`, so both API seams patch+ # the same way in tests.+ async def _probe(+ self, url: str, method: str, body: dict[str, Any]+ ) -> tuple[int, str]:+ """Make the unauthenticated request and return (status, challenge header).++ Goes through `Requests`, which validates the URL before connecting. The+ URL comes from the agent, so a raw client here would be an SSRF hole.+ """+ response = await guarded_request(+ Requests(raise_for_status=False, retry_max_attempts=1),+ method,+ url,+ json=body or None,+ headers={"Content-Type": "application/json"},+ allow_redirects=False,+ )+ return response.status, response.headers.get("www-authenticate", "")++ async def run(self, input_data: Input, **kwargs: Any) -> BlockOutput:+ try:+ status, header = await self._probe(+ input_data.url, input_data.method, input_data.body+ )+ # "Not payable from here" and "the probe got no answer" are+ # different outcomes: only the first is a statement about the+ # merchant. Collapsing them would route an agent into the+ # virtual-card flow on a transient 503 as though the merchant had+ # been checked.+ if status == 402 and not header:+ # Wants payment, but offers no challenge we can read.+ yield "supports_mpp", False+ yield "payment_required", True+ return+ if status != 402:+ if 200 <= status < 300:+ # Served without demanding payment — a definitive answer.+ yield "supports_mpp", False+ return+ raise RuntimeError(+ f"Payment challenge probe failed with HTTP {status}; "+ "cannot tell whether this merchant supports MPP"+ )++ stripe_challenge = select_stripe_challenge(header)+ if not stripe_challenge:+ # 402 with challenges, but none we can pay — onchain-only+ # merchants are the common case. The virtual-card flow will+ # not help here either, so say so rather than implying it.+ yield "supports_mpp", False+ yield "payment_required", True+ return++ request = decode_payment_request(stripe_challenge.get("request", ""))+ yield "supports_mpp", True+ yield "network_id", request.get("methodDetails", {}).get("networkId", "")+ yield "amount", int(request.get("amount", 0))+ yield "currency", request.get("currency", "")+ yield "description", stripe_challenge.get("description", "")+ except Exception as e:+ yield "error", str(e)+++class StripeLinkMPPPayBlock(Block):+ """Complete a purchase at an MPP merchant using an approved spend request."""++ _link_api_request = staticmethod(link_api_request)++ class Input(BlockSchemaInput):+ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()+ spend_request_id: str = SchemaField(+ description="An approved spend request created with credential "+ "type 'shared_payment_token'"+ )+ url: str = SchemaField(description="The merchant endpoint to purchase from")+ method: str = SchemaField(description="HTTP method", default="POST")+ body: dict[str, Any] = SchemaField(+ description="JSON body for the purchase request", default_factory=dict+ )+ headers: dict[str, str] = SchemaField(+ description="Extra headers to send to the merchant",+ default_factory=dict,+ advanced=True,+ )++ class Output(BlockSchemaOutput):+ status_code: int = SchemaField(description="HTTP status the merchant returned")+ paid: bool = SchemaField(+ description=(+ "True when the merchant accepted the credential-bearing payment "+ "request (2xx)"+ )+ )+ response: dict[str, Any] = SchemaField(+ description="Merchant's JSON response, e.g. an order or receipt",+ default_factory=dict,+ )+ error: str = SchemaField(description="Error message on failure", default="")++ def __init__(self):+ super().__init__(+ id="b219415c-8b36-4f49-937b-f11b1bbddfb2",+ description=(+ "MPP step 3 of 3: spend an approved Shared Payment Token at "+ "the merchant's endpoint. Follows Get Payment Challenge (step "+ "1) and Create Token Spend Request (step 2). No card number and no "+ "checkout form. The token is single-use, so a failed payment "+ "needs a fresh spend request."+ ),+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "spend_request_id": "lsrq_test",+ "url": "https://merchant.example/api/buy",+ "body": {"amount": 100},+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("status_code", 200),+ ("paid", True),+ ("response", {"ok": True}),+ ],+ test_mock={+ "_link_api_request": lambda *args, **kwargs: {+ "status": "approved",+ "shared_payment_token": {"id": "spt_test"},+ },+ "_pay_with_token": lambda *args, **kwargs: (200, {"ok": True}, True),+ },+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: StripeLinkCredentials,+ **kwargs: Any,+ ) -> BlockOutput:+ try:+ spend_request = await self._link_api_request(+ credentials,+ "GET",+ # No `?include=` here. Link returns `shared_payment_token` on+ # the plain representation, and naming it as an include+ # *suppresses* the field instead of expanding it — the request+ # succeeds and the field is simply absent. `card` is a valid+ # include; this is not.+ f"/spend_requests/{quote(input_data.spend_request_id, safe='')}",+ )+ if spend_request.get("status") != "approved":+ yield "error", (+ f"Spend request {input_data.spend_request_id} is "+ f"{spend_request.get('status')}, not approved"+ )+ return++ spt = (spend_request.get("shared_payment_token") or {}).get("id")+ if not spt:+ yield "error", (+ "Spend request has no shared payment token — it was likely "+ "created for a virtual card. Use credential type "+ "'shared_payment_token' to pay an MPP merchant."+ )+ return++ status_code, payload, payment_attempted = await self._pay_with_token(+ spt,+ input_data.url,+ input_data.method,+ _coerce_numeric_strings(input_data.body),+ input_data.headers,+ )+ yield "status_code", status_code+ yield "paid", payment_attempted and 200 <= status_code < 300+ yield "response", payload+ except Exception as e:+ yield "error", str(e)++ async def _pay_with_token(+ self,+ spt: str,+ url: str,+ method: str,+ body: dict[str, Any],+ headers: dict[str, str],+ ) -> tuple[int, dict[str, Any], bool]:+ """Probe for a challenge, then retry the request carrying the token.++ Every hop goes through `Requests`. The URL is agent-supplied and the+ retry carries the SPT — a bearer credential that can authorize a charge+ — so an unvalidated client could be steered into handing a payment+ token to an arbitrary or internal host.+ """+ client = Requests(raise_for_status=False, retry_max_attempts=1)+ # Caller headers first, so they cannot displace Content-Type or, more+ # importantly, the Authorization we are about to attach.+ base_headers = {**headers, "Content-Type": "application/json"}+ # Strip any caller Authorization case-insensitively. Re-adding ours+ # under the canonical spelling would otherwise leave a lowercase+ # `authorization` in place and send the merchant two of them.+ base_headers = {+ k: v for k, v in base_headers.items() if k.lower() != "authorization"+ }+ # The probe must be unauthenticated — that is what elicits the 402+ # challenge.+ first = await guarded_request(+ client,+ method,+ url,+ json=body or None,+ headers=base_headers,+ allow_redirects=False,+ )+ if first.status != 402:+ # Nothing to pay — it either succeeded outright or failed for an+ # unrelated reason. Report what happened either way.+ return first.status, _json_or_text(first), False++ challenge = select_stripe_challenge(first.headers.get("www-authenticate", ""))+ if challenge is None:+ raise RuntimeError(+ "Merchant returned 402 without a Stripe payment challenge"+ )++ retry = await guarded_request(+ client,+ method,+ url,+ json=body or None,+ headers={**base_headers, "Authorization": build_credential(challenge, spt)},+ allow_redirects=False,+ )+ return retry.status, _json_or_text(retry), True+++def _coerce_numeric_strings(body: dict[str, Any]) -> dict[str, Any]:+ """Restore numbers the builder's key/value editor turned into strings.++ Only valid JSON number literals convert, so `"0012345"` stays a string.+ """+ return {+ key: _as_json_number(value) if isinstance(value, str) else value+ for key, value in body.items()+ }+++def _as_json_number(value: str) -> int | float | str:+ if not JSON_NUMBER_PATTERN.match(value):+ return value+ return float(value) if {".", "e", "E"} & set(value) else int(value)+++def _json_or_text(response: Response) -> dict[str, Any]:+ """Normalize a merchant response into a dict output, bounded in size.++ The size check happens *before* parsing. Deserializing JSON amplifies:+ a few hundred KB of text becomes far more as Python objects, so checking+ the parsed result would already have paid the cost this guards against.+ (The body has still been read into memory by the client — fully bounding+ that needs streaming support in `Requests`, which this cannot reach.)+ """+ try:+ raw = response.content+ except Exception:+ raw = b""++ if len(raw) > MAX_RESPONSE_BYTES:+ logger.warning(+ "Merchant response of %d bytes exceeds the %d-byte cap; truncating",+ len(raw),+ MAX_RESPONSE_BYTES,+ )+ return {+ "truncated": True,+ "body": raw[:MAX_TRUNCATED_BODY_CHARS].decode("utf-8", errors="replace"),+ }++ try:+ parsed = response.json()+ except Exception:+ return {"body": response.text()[:MAX_TRUNCATED_BODY_CHARS]}++ return parsed if isinstance(parsed, dict) else {"data": parsed}diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/mpp_test.py b/autogpt_platform/backend/backend/blocks/stripe_link/mpp_test.pynew file mode 100644index 0000000000..e95efb7a5a--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe_link/mpp_test.py@@ -0,0 +1,740 @@+"""Tests for the MPP challenge parsing and credential construction.++The credential format is not documented; it was derived from `Credential+.serialize` in `mppx` and confirmed against a live MPP merchant, which+accepted it and settled a real payment. These tests pin the shape so a+refactor cannot silently break it.+"""++import base64+import json++import pytest++from backend.blocks.stripe_link._auth import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.stripe_link.mpp import (+ StripeLinkGetPaymentChallengeBlock,+ StripeLinkMPPPayBlock,+ build_credential,+ decode_payment_request,+ parse_payment_challenges,+ select_stripe_challenge,+)++# Shape of a real climate.stripe.dev response: two challenges in one header.+TWO_CHALLENGE_HEADER = (+ 'Payment id="abc", realm="merchant.example", method="tempo", intent="charge", '+ 'request="eyJhIjoxfQ", description="Climate contribution", '+ 'expires="2026-08-18T04:05:32.228Z", '+ 'Payment id="def", realm="merchant.example", method="stripe", intent="charge", '+ 'request="eyJiIjoyfQ", description="Climate contribution", '+ 'expires="2026-08-18T04:05:32.231Z"'+)+++def test_both_challenges_are_parsed_from_one_header():+ """A merchant can offer several methods; picking the wrong one fails to pay."""+ challenges = parse_payment_challenges(TWO_CHALLENGE_HEADER)++ assert [c["method"] for c in challenges] == ["tempo", "stripe"]+ assert challenges[1]["id"] == "def"+ assert challenges[1]["realm"] == "merchant.example"+++def test_a_header_without_payment_challenges_yields_nothing():+ assert parse_payment_challenges('Bearer realm="example"') == []+ assert parse_payment_challenges("") == []+++def test_payment_request_decodes_without_padding():+ """The `request` blob is base64url with padding stripped."""+ payload = {+ "amount": "100",+ "currency": "usd",+ "methodDetails": {"networkId": "p_1"},+ }+ encoded = (+ base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")+ )++ assert decode_payment_request(encoded) == payload+++def test_credential_round_trips_to_the_expected_wire_shape():+ challenge = {+ "id": "def",+ "realm": "merchant.example",+ "method": "stripe",+ "intent": "charge",+ "request": "eyJiIjoyfQ",+ "description": "Climate contribution",+ "expires": "2026-08-18T04:05:32.231Z",+ }+ credential = build_credential(challenge, "spt_123")++ scheme, _, encoded = credential.partition(" ")+ assert scheme == "Payment"+ assert "=" not in encoded, "mppx emits unpadded base64url"++ decoded = json.loads(base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4)))+ assert decoded["payload"] == {"spt": "spt_123"}+ # `request` must survive byte-for-byte: the server HMAC-binds the challenge.+ assert decoded["challenge"]["request"] == "eyJiIjoyfQ"+ assert decoded["challenge"]["id"] == "def"+++def test_unknown_challenge_fields_are_not_echoed_back():+ """Only the fields mppx keeps travel back, or verification fails."""+ challenge = {+ "id": "def",+ "realm": "m",+ "method": "stripe",+ "intent": "charge",+ "request": "eyJiIjoyfQ",+ "vendor_extension": "should-be-dropped",+ }+ encoded = build_credential(challenge, "spt_1").split(" ", 1)[1]+ decoded = json.loads(base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4)))++ assert "vendor_extension" not in decoded["challenge"]+++async def run_pay(spend_request: dict) -> dict:+ block = StripeLinkMPPPayBlock()++ async def _fake_link(credentials, method, path, body=None):+ return spend_request++ block._link_api_request = _fake_link # type: ignore[method-assign]+ inp = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "spend_request_id": "lsrq_test",+ "url": "https://merchant.example/api/buy",+ }+ )+ return {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}+++async def test_paying_with_an_unapproved_request_is_refused():+ """The token does not exist yet; hitting the merchant would just fail."""+ outputs = await run_pay({"status": "pending_approval"})++ assert "not approved" in outputs["error"]+ assert "status_code" not in outputs+++async def test_paying_with_a_card_request_explains_the_mismatch():+ """A card spend request has no SPT — say so instead of failing obscurely."""+ outputs = await run_pay({"status": "approved", "card": {"number": "4242"}})++ assert "shared_payment_token" in outputs["error"]+++async def test_challenge_block_reports_non_mpp_merchants():+ block = StripeLinkGetPaymentChallengeBlock()++ async def _probe(*_a, **_kw):+ return 200, ""++ block._probe = _probe # type: ignore[method-assign]++ inp = block.Input.model_validate({"url": "https://shop.example/checkout"})+ outputs = {n: v async for n, v in block.run(inp)}++ assert outputs["supports_mpp"] is False+ assert "network_id" not in outputs+++async def test_challenge_block_ignores_a_402_without_a_stripe_method():+ """Onchain-only merchants answer 402 but we cannot pay them."""+ block = StripeLinkGetPaymentChallengeBlock()+ onchain_only = 'Payment id="abc", realm="m", method="tempo", intent="charge", request="eyJhIjoxfQ"'++ async def _probe(*_a, **_kw):+ return 402, onchain_only++ block._probe = _probe # type: ignore[method-assign]++ inp = block.Input.model_validate({"url": "https://shop.example/checkout"})+ outputs = {n: v async for n, v in block.run(inp)}++ assert outputs["supports_mpp"] is False+++class _FakeResponse:+ """Stands in for `backend.util.request.Response`."""++ def __init__(self, status: int, payload=None, headers=None, text=""):+ self.status = status+ self._payload = payload+ self.headers = headers or {}+ self._text = text++ @property+ def content(self) -> bytes:+ if self._payload is not None:+ return json.dumps(self._payload).encode()+ return self._text.encode()++ def json(self):+ if self._payload is None:+ raise ValueError("no json")+ return self._payload++ def text(self):+ return self._text+++class _RecordingClient:+ """Returns queued responses and records every request made."""++ def __init__(self, responses):+ self._responses = list(responses)+ self.calls: list[dict] = []++ async def request(+ self, method, url, *, json=None, headers=None, allow_redirects=True+ ):+ self.calls.append(+ {+ "method": method,+ "url": url,+ "json": json,+ "headers": headers or {},+ "allow_redirects": allow_redirects,+ }+ )+ return self._responses.pop(0)+++def _patch_requests(monkeypatch, client):+ from backend.blocks.stripe_link import mpp++ configurations = []++ def _factory(*args, **kwargs):+ configurations.append(kwargs)+ return client++ monkeypatch.setattr(mpp, "Requests", _factory)+ return configurations+++CHALLENGE_HEADER = (+ 'Payment id="ch_1", realm="merchant.example", method="stripe", '+ 'intent="charge", request="eyJhIjoxfQ"'+)+++async def test_pay_attaches_the_credential_on_the_retry(monkeypatch):+ """The heart of MPP: probe unauthenticated, then retry carrying the token."""+ client = _RecordingClient(+ [+ _FakeResponse(402, headers={"www-authenticate": CHALLENGE_HEADER}),+ _FakeResponse(200, payload={"contribution_id": "pi_1"}),+ ]+ )+ configurations = _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()+ status, payload, payment_attempted = await block._pay_with_token(+ "spt_abc", "https://merchant.example/buy", "POST", {"amount": 100}, {}+ )++ assert status == 200+ assert payload == {"contribution_id": "pi_1"}+ assert payment_attempted is True+ assert configurations == [{"raise_for_status": False, "retry_max_attempts": 1}]+ assert len(client.calls) == 2+ assert all(call["allow_redirects"] is False for call in client.calls)+ # First hop must be unauthenticated — that is what elicits the challenge.+ assert "Authorization" not in client.calls[0]["headers"]+ credential = client.calls[1]["headers"]["Authorization"]+ assert credential.startswith("Payment ")+ assert (+ "spt_abc"+ in base64.urlsafe_b64decode(credential.split(" ", 1)[1] + "==").decode()+ )+++async def test_challenge_probe_does_not_retry_or_follow_redirects(monkeypatch):+ client = _RecordingClient(+ [_FakeResponse(402, headers={"www-authenticate": CHALLENGE_HEADER})]+ )+ configurations = _patch_requests(monkeypatch, client)++ block = StripeLinkGetPaymentChallengeBlock()+ status, header = await block._probe(+ "https://merchant.example/buy", "POST", {"amount": 100}+ )++ assert status == 402+ assert header == CHALLENGE_HEADER+ assert configurations == [{"raise_for_status": False, "retry_max_attempts": 1}]+ assert client.calls[0]["allow_redirects"] is False+++async def test_pay_does_not_retry_when_the_merchant_did_not_ask_for_payment(+ monkeypatch,+):+ """A 200 on the first hop means nothing is owed; sending the token anyway+ would leak a bearer credential for no reason."""+ client = _RecordingClient([_FakeResponse(200, payload={"ok": True})])+ _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()+ status, payload, payment_attempted = await block._pay_with_token(+ "spt_abc", "https://merchant.example/buy", "POST", {}, {}+ )++ assert status == 200 and payload == {"ok": True}+ assert payment_attempted is False+ assert len(client.calls) == 1+++async def test_unauthenticated_success_is_not_reported_as_paid(monkeypatch):+ client = _RecordingClient([_FakeResponse(200, payload={"ok": True})])+ _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()++ async def _fake_link(credentials, method, path, body=None):+ return {+ "status": "approved",+ "shared_payment_token": {"id": "spt_abc"},+ }++ object.__setattr__(block, "_link_api_request", _fake_link)+ inp = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "spend_request_id": "lsrq_test",+ "url": "https://merchant.example/buy",+ }+ )++ outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}++ assert outputs == {"status_code": 200, "paid": False, "response": {"ok": True}}+ assert len(client.calls) == 1+++async def test_pay_raises_when_402_offers_no_stripe_method(monkeypatch):+ onchain_only = (+ 'Payment id="c", realm="m", method="tempo", intent="charge", request="e30"'+ )+ client = _RecordingClient(+ [_FakeResponse(402, headers={"www-authenticate": onchain_only})]+ )+ _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()+ with pytest.raises(RuntimeError, match="without a Stripe payment challenge"):+ await block._pay_with_token(+ "spt_abc", "https://merchant.example/buy", "POST", {}, {}+ )+++async def test_caller_headers_cannot_displace_the_credential(monkeypatch):+ """A caller-supplied Authorization must not survive into the paid retry."""+ client = _RecordingClient(+ [+ _FakeResponse(402, headers={"www-authenticate": CHALLENGE_HEADER}),+ _FakeResponse(200, payload={"ok": True}),+ ]+ )+ _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()+ await block._pay_with_token(+ "spt_abc",+ "https://merchant.example/buy",+ "POST",+ {},+ {"Authorization": "Bearer attacker", "Content-Type": "text/plain"},+ )++ retry_headers = client.calls[1]["headers"]+ assert retry_headers["Authorization"].startswith("Payment ")+ assert retry_headers["Content-Type"] == "application/json"+++def test_oversized_request_blob_is_refused():+ """The blob is merchant-controlled; decoding it unbounded is a DoS vector."""+ with pytest.raises(ValueError, match="implausibly large"):+ decode_payment_request("A" * (17 * 1024))+++def test_non_object_request_blob_is_refused():+ """`json.loads` can return a list; downstream `.get()` would explode."""+ encoded = base64.urlsafe_b64encode(b"[1,2,3]").decode().rstrip("=")+ with pytest.raises(ValueError, match="must decode to an object"):+ decode_payment_request(encoded)+++def test_challenges_parse_regardless_of_field_order():+ """RFC 7235 does not fix auth-param order; Link merely happens to send+ `id` first. Splitting on `id=` would have merged these into one."""+ header = (+ 'Payment realm="m", method="stripe", intent="charge", id="x", '+ 'request="eyJhIjoxfQ", '+ 'Payment method="tempo", id="y", realm="m", intent="charge", request="e30"'+ )+ challenges = parse_payment_challenges(header)++ assert [c["method"] for c in challenges] == ["stripe", "tempo"]+ assert challenges[0]["id"] == "x"+ assert select_stripe_challenge(header)["id"] == "x" # type: ignore[index]+++async def test_probe_drops_a_caller_supplied_authorization(monkeypatch):+ """The first hop must be unauthenticated — an Authorization header the+ caller passed through would suppress the 402 and break the flow."""+ client = _RecordingClient(+ [+ _FakeResponse(402, headers={"www-authenticate": CHALLENGE_HEADER}),+ _FakeResponse(200, payload={"ok": True}),+ ]+ )+ _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()+ await block._pay_with_token(+ "spt_abc",+ "https://merchant.example/buy",+ "POST",+ {},+ {"Authorization": "Bearer caller-token"},+ )++ assert "Authorization" not in client.calls[0]["headers"]+ assert client.calls[1]["headers"]["Authorization"].startswith("Payment ")+++async def test_a_declined_payment_is_reported_as_unpaid(monkeypatch):+ """The money-sensitive case: a decline must never read as `paid`.++ The retry carries the token, so a 402/4xx on the second hop means the+ merchant refused the credential. Reporting that as success would tell an+ agent a purchase completed when nothing was bought.+ """+ client = _RecordingClient(+ [+ _FakeResponse(402, headers={"www-authenticate": CHALLENGE_HEADER}),+ _FakeResponse(402, payload={"error": "card_declined"}),+ ]+ )+ _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()+ status, payload, payment_attempted = await block._pay_with_token(+ "spt_abc", "https://merchant.example/buy", "POST", {"amount": 100}, {}+ )++ assert status == 402+ assert payload == {"error": "card_declined"}+ assert payment_attempted is True+ assert not (200 <= status < 300)+++async def test_a_lowercase_caller_authorization_cannot_duplicate_the_header(+ monkeypatch,+):+ """Stripping only the canonical spelling left a second Authorization.++ The probe dropped `authorization` case-insensitively but the retry merged+ over `Authorization`, so a lowercase caller header survived and the+ merchant received two — defeating the guarantee that callers cannot+ displace the credential.+ """+ client = _RecordingClient(+ [+ _FakeResponse(402, headers={"www-authenticate": CHALLENGE_HEADER}),+ _FakeResponse(200, payload={"ok": True}),+ ]+ )+ _patch_requests(monkeypatch, client)++ block = StripeLinkMPPPayBlock()+ await block._pay_with_token(+ "spt_abc",+ "https://merchant.example/buy",+ "POST",+ {"amount": 100},+ {"authorization": "Bearer caller-token"},+ )++ retry_headers = client.calls[1]["headers"]+ auth_headers = [k for k in retry_headers if k.lower() == "authorization"]+ assert len(auth_headers) == 1+ assert retry_headers[auth_headers[0]].startswith("Payment ")+ assert "caller-token" not in str(retry_headers)+++def test_a_list_merchant_response_is_wrapped_into_a_dict():+ from backend.blocks.stripe_link.mpp import _json_or_text++ assert _json_or_text(_FakeResponse(200, payload=[1, 2, 3])) == {"data": [1, 2, 3]}+++def test_a_non_json_merchant_response_falls_back_to_bounded_text():+ from backend.blocks.stripe_link.mpp import _json_or_text++ out = _json_or_text(_FakeResponse(500, text="y" * 5000))++ assert len(out["body"]) == 1000+++async def test_a_failed_probe_is_not_reported_as_a_non_mpp_merchant():+ """A 503 or a typo'd URL used to yield supports_mpp=false, which routes the+ agent into the virtual-card flow as though the merchant had been checked."""++ async def _probe(url, method, body):+ return 503, ""++ block = StripeLinkGetPaymentChallengeBlock()+ block._probe = _probe # type: ignore[method-assign]++ inp = block.Input.model_validate({"url": "https://shop.example/checkout"})+ outputs = {n: v async for n, v in block.run(inp)}++ assert "supports_mpp" not in outputs+ assert "503" in outputs["error"]+++async def test_a_plain_success_still_reports_a_non_mpp_merchant():+ """A merchant that serves the request without demanding payment is a+ definitive 'not MPP', unlike a failed probe."""++ async def _probe(url, method, body):+ return 200, ""++ block = StripeLinkGetPaymentChallengeBlock()+ block._probe = _probe # type: ignore[method-assign]++ inp = block.Input.model_validate({"url": "https://shop.example/checkout"})+ outputs = {n: v async for n, v in block.run(inp)}++ assert outputs["supports_mpp"] is False+ assert "error" not in outputs+++async def test_the_pay_path_does_not_send_an_include_for_the_token():+ """Regression: `?include=shared_payment_token` SUPPRESSES the field.++ Link returns `shared_payment_token` on the plain spend-request+ representation. Naming it as an include does not expand it — Link+ silently returns a trimmed object with the field absent, so the pay block+ reported "Spend request has no shared payment token ... likely created for+ a virtual card" on a request that was correctly created as a token+ request. `card` IS a valid include, which is why Retrieve Card worked and+ hid the asymmetry. Found only by paying a live merchant; the mocked tests+ agreed with the wrong assumption.+ """+ seen: dict = {}++ async def _fake(credentials, method, path, body=None):+ seen["path"] = path+ return {+ "status": "approved",+ "shared_payment_token": {"id": "spt_live_abc"},+ }++ block = StripeLinkMPPPayBlock()+ object.__setattr__(block, "_link_api_request", _fake)++ captured = {}++ async def _pay(spt, url, method, body, headers):+ captured["spt"] = spt+ return 200, {"ok": True}, True++ object.__setattr__(block, "_pay_with_token", _pay)++ inp = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "spend_request_id": "lsrq_test",+ "url": "https://merchant.example/buy",+ }+ )+ outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}++ assert "include" not in seen["path"]+ assert captured["spt"] == "spt_live_abc"+ assert outputs["paid"] is True+++async def test_a_malformed_challenge_is_not_reported_as_a_blocked_url():+ """Redaction has to name the actual cause.++ `Requests` signals an SSRF refusal with a bare `ValueError`, and so does+ every parse failure here — so a catch-all reported a merchant's malformed+ challenge blob as "Request blocked: the URL is not allowed", which is both+ wrong and unactionable.+ """++ async def _probe(url, method, body):+ return (+ 402,+ 'Payment id="c", realm="m", method="stripe", request="!!!not-base64!!!"',+ )++ block = StripeLinkGetPaymentChallengeBlock()+ block._probe = _probe # type: ignore[method-assign]++ inp = block.Input.model_validate({"url": "https://shop.example/buy"})+ outputs = {n: v async for n, v in block.run(inp)}++ assert "not allowed" not in outputs.get("error", "")+++async def test_a_blocked_url_is_redacted(monkeypatch):+ """`Requests` names the host or resolved IP it refused. Useful in logs,+ but the `error` output is agent-visible and must not become a readout of+ what resolves on the internal network."""+ from backend.blocks.stripe_link import mpp++ class _Refusing:+ async def request(self, *a, **kw):+ raise ValueError(+ "Access to private IP 169.254.169.254 (metadata.internal) is blocked"+ )++ monkeypatch.setattr(mpp, "Requests", lambda *a, **kw: _Refusing())++ block = StripeLinkGetPaymentChallengeBlock()+ inp = block.Input.model_validate({"url": "https://metadata.internal/latest"})+ outputs = {n: v async for n, v in block.run(inp)}++ assert "169.254.169.254" not in outputs["error"]+ assert "metadata.internal" not in outputs["error"]+ assert "not allowed" in outputs["error"]+++async def test_a_402_without_any_challenge_header_is_payment_required():+ async def _probe(url, method, body):+ return 402, ""++ block = StripeLinkGetPaymentChallengeBlock()+ block._probe = _probe # type: ignore[method-assign]++ inp = block.Input.model_validate({"url": "https://shop.example/buy"})+ outputs = {n: v async for n, v in block.run(inp)}++ assert outputs["supports_mpp"] is False+ # Wants payment, just not one we can make — the card flow is no fallback.+ assert outputs["payment_required"] is True+++async def test_an_onchain_only_merchant_is_distinguished_from_a_free_one():+ """Both yield supports_mpp=false; only one is a candidate for the card flow."""++ async def _onchain(url, method, body):+ return 402, 'Payment id="c", realm="m", method="tempo", request="eyJhIjoxfQ"'++ async def _free(url, method, body):+ return 200, ""++ block = StripeLinkGetPaymentChallengeBlock()+ inp = block.Input.model_validate({"url": "https://shop.example/buy"})++ block._probe = _onchain # type: ignore[method-assign]+ onchain = {n: v async for n, v in block.run(inp)}+ block._probe = _free # type: ignore[method-assign]+ free = {n: v async for n, v in block.run(inp)}++ assert onchain["supports_mpp"] is False and onchain["payment_required"] is True+ assert (+ free["supports_mpp"] is False and free.get("payment_required", False) is False+ )+++def test_an_oversized_body_is_not_parsed():+ """The cap has to apply before deserialization, not after."""+ from backend.blocks.stripe_link.mpp import MAX_RESPONSE_BYTES, _json_or_text++ huge = _FakeResponse(200, payload={"blob": "x" * (MAX_RESPONSE_BYTES + 1024)})+ out = _json_or_text(huge)++ assert out["truncated"] is True+ assert len(out["body"]) <= 1000+++# ---------------------------------------------------------------------------+# Body values reach the merchant with their JSON types intact+# ---------------------------------------------------------------------------+async def run_pay_against(+ responses: list[dict],+ *,+ body: dict | None = None,+) -> tuple[dict, list[dict], dict]:+ """Run the pay block against a scripted sequence of Link responses.++ Returns the block's outputs, what it sent to the merchant, and the call+ log, so a test can assert on the wire rather than on internals.+ """+ from backend.blocks.stripe_link.mpp import StripeLinkMPPPayBlock++ calls: list[dict] = []+ sent: dict = {}++ async def _fake_link(credentials, method, path, body=None):+ calls.append({"path": path})+ return responses[min(len(calls) - 1, len(responses) - 1)]++ async def _fake_pay(spt, url, method, body, headers):+ sent.update({"spt": spt, "body": body})+ return 200, {"ok": True}, True++ block = StripeLinkMPPPayBlock()+ object.__setattr__(block, "_link_api_request", _fake_link)+ object.__setattr__(block, "_pay_with_token", _fake_pay)++ payload = {+ "credentials": TEST_CREDENTIALS_INPUT,+ "spend_request_id": "lsrq_test",+ "url": "https://merchant.example/api/buy",+ }+ if body is not None:+ payload["body"] = body+ inp = block.Input.model_validate(payload)++ outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}+ return outputs, calls, sent+++async def test_number_shaped_body_values_are_sent_as_numbers():+ """The builder's key/value editor stringifies every value; merchants 400."""+ _, _, sent = await run_pay_against(+ [{"status": "approved", "shared_payment_token": {"id": "spt_x"}}],+ body={"amount": "100", "rate": "1.5", "sku": "0012345", "name": "board"},+ )++ assert sent["body"]["amount"] == 100+ assert isinstance(sent["body"]["amount"], int)+ assert sent["body"]["rate"] == 1.5+ assert sent["body"]["sku"] == "0012345", "leading zeros are not a number"+ assert sent["body"]["name"] == "board"diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.pyindex e21f723318..73c0433a76 100644--- a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py+++ b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py@@ -148,7 +148,11 @@ class StripeLinkListPaymentMethodsBlock(Block):def __init__(self):super().__init__(id="6eacc954-2218-4dc7-a485-5bf21549ecbe",- description="List payment methods from a Stripe Link wallet",+ description=(+ "List the cards and bank accounts in the user's Link wallet. "+ "Use this first to pick a payment method ID for Create Spend "+ "Request."+ ),categories={BlockCategory.DATA},input_schema=self.Input,output_schema=self.Output,@@ -531,9 +535,11 @@ class StripeLinkCreateTokenSpendRequestBlock(Block):super().__init__(id="b12877be-06cd-4a96-bf79-438bb4cb5517",description=(- "MPP step 2 of 3: create a Stripe Link spend request for a "- "Shared Payment Token, using the network ID from the "- "merchant's 402 challenge. Step 3 is MPP Pay."+ "MPP step 2 of 3: ask the user to authorize a payment to a "+ "merchant that answers HTTP 402, and provision a Shared "+ "Payment Token for it. Takes the network ID from the Get "+ "Payment Challenge block; step 3 is MPP Pay. For an ordinary "+ "checkout form, use Create Card Spend Request instead."),categories={BlockCategory.DATA},input_schema=self.Input,@@ -654,7 +660,11 @@ class StripeLinkGetSpendRequestStatusBlock(Block):id="b5ef8aa2-f0bc-424f-b613-c1961ec0028d",description=("Check whether a Stripe Link spend request has been approved "- "yet. Poll this after creating a request and before spending."+ "yet. Poll this after creating a request and before spending, "+ "for both the card and the Shared Payment Token flows. If the "+ "status is 'requires_action' the payment method needs "+ "attention first — keep polling when `auto_resumes` is true, "+ "otherwise resolve the action and create a new request."),categories={BlockCategory.DATA},input_schema=self.Input,@@ -791,11 +801,12 @@ class StripeLinkRetrieveCardBlock(Block):super().__init__(id="1aff59ef-e8a2-413e-9410-4ce7e4849337",description=(- "Get the one-time virtual card for an approved Stripe Link "- "spend request. The card number and CVC are stored in clear "- "text with the execution record — do not use this where PCI "- "compliance matters. Self-hosted only; on AutoGPT Cloud use "- "the Shared Payment Token flow with the MPP blocks instead."+ "Get the one-time virtual card number and CVC for an approved "+ "spend request, to type into a normal checkout form. Both are "+ "stored in clear text with the execution record — do not use "+ "this where PCI compliance matters. Self-hosted only; on "+ "AutoGPT Cloud use the Shared Payment Token flow with the MPP "+ "blocks instead."),categories={BlockCategory.DATA},disabled=CARD_FLOW_DISABLED,diff --git a/autogpt_platform/backend/scripts/generate_block_docs.py b/autogpt_platform/backend/scripts/generate_block_docs.pyindex 978b456ee1..c37acf5180 100644--- a/autogpt_platform/backend/scripts/generate_block_docs.py+++ b/autogpt_platform/backend/scripts/generate_block_docs.py@@ -228,6 +228,7 @@ def file_path_to_title(file_path: str) -> str:"Ci": "CI","Pr": "PR","Gmb": "GMB", # Google My Business+ "Mpp": "MPP", # Machine Payments Protocol"Hubspot": "HubSpot","Allquiet": "All Quiet","Linkedin": "LinkedIn",diff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex 376b8173b2..c4556aa19d 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -186,12 +186,14 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [SQL Query](block-integrations/data.md#sql-query) | Execute a SQL query || [Screenshot Web Page](block-integrations/data.md#screenshot-web-page) | Takes a screenshot of a specified website using ScreenshotOne API || [Stripe Link Create Card Spend Request](block-integrations/stripe_link/spend_request.md#stripe-link-create-card-spend-request) | Create a Stripe Link spend request for a one-time virtual card |-| [Stripe Link Create Token Spend Request](block-integrations/stripe_link/spend_request.md#stripe-link-create-token-spend-request) | MPP step 2 of 3: create a Stripe Link spend request for a Shared Payment Token, using the network ID from the merchant's 402 challenge |+| [Stripe Link Create Token Spend Request](block-integrations/stripe_link/spend_request.md#stripe-link-create-token-spend-request) | MPP step 2 of 3: ask the user to authorize a payment to a merchant that answers HTTP 402, and provision a Shared Payment Token for it |+| [Stripe Link Get Payment Challenge](block-integrations/stripe_link/mpp.md#stripe-link-get-payment-challenge) | MPP step 1 of 3: read a merchant's HTTP 402 payment challenge to learn its network ID and amount || [Stripe Link Get Shipping Address](block-integrations/stripe_link/profile.md#stripe-link-get-shipping-address) | Get the delivery addresses saved on the user's Link wallet, with the default one resolved for you || [Stripe Link Get Spend Request Status](block-integrations/stripe_link/spend_request.md#stripe-link-get-spend-request-status) | Check whether a Stripe Link spend request has been approved yet || [Stripe Link Get User Info](block-integrations/stripe_link/profile.md#stripe-link-get-user-info) | Get the Link account holder's name, email and phone |-| [Stripe Link List Payment Methods](block-integrations/stripe_link/spend_request.md#stripe-link-list-payment-methods) | List payment methods from a Stripe Link wallet |-| [Stripe Link Retrieve Card](block-integrations/stripe_link/spend_request.md#stripe-link-retrieve-card) | Get the one-time virtual card for an approved Stripe Link spend request |+| [Stripe Link List Payment Methods](block-integrations/stripe_link/spend_request.md#stripe-link-list-payment-methods) | List the cards and bank accounts in the user's Link wallet |+| [Stripe Link MPP Pay](block-integrations/stripe_link/mpp.md#stripe-link-mpp-pay) | MPP step 3 of 3: spend an approved Shared Payment Token at the merchant's endpoint |+| [Stripe Link Retrieve Card](block-integrations/stripe_link/spend_request.md#stripe-link-retrieve-card) | Get the one-time virtual card number and CVC for an approved spend request, to type into a normal checkout form || [Stripe Subscription Trigger](block-integrations/stripe/triggers.md#stripe-subscription-trigger) | Triggers on Stripe subscription events (new, upgrade, cancel) |## Text Processingdiff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.mdindex b422ed59da..8307702c4f 100644--- a/docs/integrations/SUMMARY.md+++ b/docs/integrations/SUMMARY.md@@ -122,6 +122,7 @@* [Smartlead Campaign](block-integrations/smartlead/campaign.md)* [Stagehand Blocks](block-integrations/stagehand/blocks.md)* [Stripe Triggers](block-integrations/stripe/triggers.md)+* [Stripe Link MPP](block-integrations/stripe_link/mpp.md)* [Stripe Link Profile](block-integrations/stripe_link/profile.md)* [Stripe Link Spend Request](block-integrations/stripe_link/spend_request.md)* [System Library Operations](block-integrations/system/library_operations.md)diff --git a/docs/integrations/block-integrations/stripe_link/mpp.md b/docs/integrations/block-integrations/stripe_link/mpp.mdnew file mode 100644index 0000000000..1f9ce65840--- /dev/null+++ b/docs/integrations/block-integrations/stripe_link/mpp.md@@ -0,0 +1,77 @@+# Stripe Link MPP+<!-- MANUAL: file_description -->+_Add a description of this category of blocks._+<!-- END MANUAL -->++## Stripe Link Get Payment Challenge++### What it is+MPP step 1 of 3: read a merchant's HTTP 402 payment challenge to learn its network ID and amount. Step 2 is Create Spend Request with credential type 'shared_payment_token' and that network ID; step 3 is MPP Pay. Returns supports_mpp=false for ordinary merchants — use the virtual-card flow for those.++### How it works+<!-- MANUAL: how_it_works -->+_Add technical explanation here._+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| url | The merchant endpoint to purchase from | str | Yes |+| method | HTTP method the purchase uses | str | No |+| body | JSON body for the purchase request | Dict[str, Any] | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message on failure | str |+| supports_mpp | True when the merchant answered 402 with a Stripe payment challenge, so a Shared Payment Token can pay it. False means it cannot be paid this way — check `payment_required` to see whether that is because nothing is owed or because the merchant only accepts a method this block cannot provide. A probe that got no answer at all raises instead, so it is never reported as False. | bool |+| payment_required | True when the merchant demanded payment (HTTP 402) but not via Stripe — an onchain-only merchant, say. With `supports_mpp` false this distinguishes 'pays another way, unreachable from here' from 'served without charging', where the virtual-card flow is the sensible fallback. | bool |+| network_id | Merchant network ID — pass this to Create Spend Request as `network_id` | str |+| amount | Amount the merchant wants, in the smallest currency unit | int |+| currency | Three-letter currency code | str |+| description | What the merchant says the charge is for | str |++### Possible use case+<!-- MANUAL: use_case -->+_Add practical use case examples here._+<!-- END MANUAL -->++---++## Stripe Link MPP Pay++### What it is+MPP step 3 of 3: spend an approved Shared Payment Token at the merchant's endpoint. Follows Get Payment Challenge (step 1) and Create Token Spend Request (step 2). No card number and no checkout form. The token is single-use, so a failed payment needs a fresh spend request.++### How it works+<!-- MANUAL: how_it_works -->+_Add technical explanation here._+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| spend_request_id | An approved spend request created with credential type 'shared_payment_token' | str | Yes |+| url | The merchant endpoint to purchase from | str | Yes |+| method | HTTP method | str | No |+| body | JSON body for the purchase request | Dict[str, Any] | No |+| headers | Extra headers to send to the merchant | Dict[str, str] | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message on failure | str |+| status_code | HTTP status the merchant returned | int |+| paid | True when the merchant accepted the credential-bearing payment request (2xx) | bool |+| response | Merchant's JSON response, e.g. an order or receipt | Dict[str, Any] |++### Possible use case+<!-- MANUAL: use_case -->+_Add practical use case examples here._+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/stripe_link/spend_request.md b/docs/integrations/block-integrations/stripe_link/spend_request.mdindex 3d0a0379a3..31238f7ab6 100644--- a/docs/integrations/block-integrations/stripe_link/spend_request.md+++ b/docs/integrations/block-integrations/stripe_link/spend_request.md@@ -48,7 +48,7 @@ _Add practical use case examples here._## Stripe Link Create Token Spend Request### What it is-MPP step 2 of 3: create a Stripe Link spend request for a Shared Payment Token, using the network ID from the merchant's 402 challenge. Step 3 is MPP Pay.+MPP step 2 of 3: ask the user to authorize a payment to a merchant that answers HTTP 402, and provision a Shared Payment Token for it. Takes the network ID from the Get Payment Challenge block; step 3 is MPP Pay. For an ordinary checkout form, use Create Card Spend Request instead.### How it works<!-- MANUAL: how_it_works -->@@ -89,7 +89,7 @@ _Add practical use case examples here._## Stripe Link Get Spend Request Status### What it is-Check whether a Stripe Link spend request has been approved yet. Poll this after creating a request and before spending.+Check whether a Stripe Link spend request has been approved yet. Poll this after creating a request and before spending, for both the card and the Shared Payment Token flows. If the status is 'requires_action' the payment method needs attention first — keep polling when `auto_resumes` is true, otherwise resolve the action and create a new request.### How it works<!-- MANUAL: how_it_works -->@@ -123,7 +123,7 @@ _Add practical use case examples here._## Stripe Link List Payment Methods### What it is-List payment methods from a Stripe Link wallet+List the cards and bank accounts in the user's Link wallet. Use this first to pick a payment method ID for Create Spend Request.### How it works<!-- MANUAL: how_it_works -->@@ -147,7 +147,7 @@ _Add practical use case examples here._## Stripe Link Retrieve Card### What it is-Get the one-time virtual card for an approved Stripe Link spend request. The card number and CVC are stored in clear text with the execution record — do not use this where PCI compliance matters. Self-hosted only; on AutoGPT Cloud use the Shared Payment Token flow with the MPP blocks instead.+Get the one-time virtual card number and CVC for an approved spend request, to type into a normal checkout form. Both are stored in clear text with the execution record — do not use this where PCI compliance matters. Self-hosted only; on AutoGPT Cloud use the Shared Payment Token flow with the MPP blocks instead.### How it works<!-- MANUAL: how_it_works -->